-
Notifications
You must be signed in to change notification settings - Fork 473
Expand file tree
/
Copy pathLowerState.cpp
More file actions
1328 lines (1163 loc) · 49.3 KB
/
LowerState.cpp
File metadata and controls
1328 lines (1163 loc) · 49.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- LowerState.cpp -----------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "circt/Dialect/Arc/ArcOps.h"
#include "circt/Dialect/Arc/ArcPasses.h"
#include "circt/Dialect/Comb/CombDialect.h"
#include "circt/Dialect/Comb/CombOps.h"
#include "circt/Dialect/HW/HWOps.h"
#include "circt/Dialect/LLHD/LLHDOps.h"
#include "circt/Dialect/Seq/SeqOps.h"
#include "circt/Dialect/Sim/SimOps.h"
#include "circt/Support/BackedgeBuilder.h"
#include "mlir/Analysis/TopologicalSortUtils.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/LLVMIR/LLVMAttrs.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/IR/IRMapping.h"
#include "mlir/IR/ImplicitLocOpBuilder.h"
#include "mlir/IR/SymbolTable.h"
#include "mlir/Interfaces/SideEffectInterfaces.h"
#include "mlir/Pass/Pass.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/Debug.h"
#define DEBUG_TYPE "arc-lower-state"
namespace circt {
namespace arc {
#define GEN_PASS_DEF_LOWERSTATEPASS
#include "circt/Dialect/Arc/ArcPasses.h.inc"
} // namespace arc
} // namespace circt
using namespace circt;
using namespace arc;
using namespace hw;
using namespace mlir;
using llvm::SmallDenseSet;
namespace {
enum class Phase { Initial, Old, New, Final };
template <class OS>
OS &operator<<(OS &os, Phase phase) {
switch (phase) {
case Phase::Initial:
return os << "initial";
case Phase::Old:
return os << "old";
case Phase::New:
return os << "new";
case Phase::Final:
return os << "final";
}
}
struct ModuleLowering;
/// All state associated with lowering a single operation. Instances of this
/// struct are kept on a worklist to perform a depth-first traversal of the
/// module being lowered.
///
/// The actual lowering occurs in `lower()`. This function is called exactly
/// twice. A first time with `initial` being true, where other values and
/// operations that have to be lowered first may be marked with `addPending`. No
/// actual lowering or error reporting should occur when `initial` is true. The
/// worklist then ensures that all `pending` ops are lowered before `lower()` is
/// called a second time with `initial` being false. At this point the actual
/// lowering and error reporting should occur.
///
/// The `initial` variable is used to allow for a single block of code to mark
/// values and ops as dependencies and actually do the lowering based on them.
struct OpLowering {
Operation *op;
Phase phase;
ModuleLowering &module;
bool initial = true;
SmallVector<std::pair<Operation *, Phase>, 2> pending;
OpLowering(Operation *op, Phase phase, ModuleLowering &module)
: op(op), phase(phase), module(module) {}
// Operation Lowering.
LogicalResult lower();
LogicalResult lowerDefault();
LogicalResult lower(StateOp op);
LogicalResult lower(sim::DPICallOp op);
LogicalResult
lowerStateful(Value clock, Value enable, Value reset, ValueRange inputs,
ResultRange results,
llvm::function_ref<ValueRange(ValueRange)> createMapping);
LogicalResult lower(MemoryOp op);
LogicalResult lower(TapOp op);
LogicalResult lower(InstanceOp op);
LogicalResult lower(hw::OutputOp op);
LogicalResult lower(seq::InitialOp op);
LogicalResult lower(llhd::FinalOp op);
LogicalResult lower(llhd::CurrentTimeOp op);
LogicalResult lower(sim::ClockedTerminateOp op);
scf::IfOp createIfClockOp(Value clock);
// Value Lowering. These functions are called from the `lower()` functions
// above. They handle values used by the `op`. This can generate reads from
// state and memory storage on-the-fly, or mark other ops as dependencies to
// be lowered first.
Value lowerValue(Value value, Phase phase);
Value lowerValue(InstanceOp op, OpResult result, Phase phase);
Value lowerValue(StateOp op, OpResult result, Phase phase);
Value lowerValue(sim::DPICallOp op, OpResult result, Phase phase);
Value lowerValue(MemoryReadPortOp op, OpResult result, Phase phase);
Value lowerValue(seq::InitialOp op, OpResult result, Phase phase);
Value lowerValue(seq::FromImmutableOp op, OpResult result, Phase phase);
void addPending(Value value, Phase phase);
void addPending(Operation *op, Phase phase);
};
/// All state associated with lowering a single module.
struct ModuleLowering {
/// The module being lowered.
HWModuleOp moduleOp;
/// The builder for the main body of the model.
OpBuilder builder;
/// The builder for state allocation ops.
OpBuilder allocBuilder;
/// The builder for the initial phase.
OpBuilder initialBuilder;
/// The builder for the final phase.
OpBuilder finalBuilder;
/// The storage value that can be used for `arc.alloc_state` and friends.
Value storageArg;
/// A worklist of pending op lowerings.
SmallVector<OpLowering> opsWorklist;
/// The set of ops currently in the worklist. Used to detect cycles.
SmallDenseSet<std::pair<Operation *, Phase>> opsSeen;
/// The ops that have already been lowered.
DenseSet<std::pair<Operation *, Phase>> loweredOps;
/// The values that have already been lowered.
DenseMap<std::pair<Value, Phase>, Value> loweredValues;
/// The allocated input ports.
SmallVector<Value> allocatedInputs;
/// The allocated states as a mapping from op results to `arc.alloc_state`
/// results.
DenseMap<Value, Value> allocatedStates;
/// The allocated storage for instance inputs and top module outputs.
DenseMap<OpOperand *, Value> allocatedOutputs;
/// The allocated storage for values computed during the initial phase.
DenseMap<Value, Value> allocatedInitials;
/// The allocated storage for taps.
DenseMap<Operation *, Value> allocatedTaps;
/// A mapping from unlowered clocks to a value indicating a posedge. This is
/// used to not create an excessive number of posedge detectors.
DenseMap<Value, Value> loweredPosedges;
/// The previous enable and the value it was lowered to. This is used to reuse
/// previous if ops for the same enable value.
std::pair<Value, Value> prevEnable;
/// The previous reset and the value it was lowered to. This is used to reuse
/// previous if ops for the same reset value.
std::pair<Value, Value> prevReset;
ModuleLowering(HWModuleOp moduleOp)
: moduleOp(moduleOp), builder(moduleOp), allocBuilder(moduleOp),
initialBuilder(moduleOp), finalBuilder(moduleOp) {}
LogicalResult run();
LogicalResult lowerOp(Operation *op);
Value getAllocatedState(OpResult result);
Value detectPosedge(Value clock);
OpBuilder &getBuilder(Phase phase);
Value requireLoweredValue(Value value, Phase phase, Location useLoc);
};
} // namespace
//===----------------------------------------------------------------------===//
// Module Lowering
//===----------------------------------------------------------------------===//
LogicalResult ModuleLowering::run() {
LLVM_DEBUG(llvm::dbgs() << "Lowering module `" << moduleOp.getModuleName()
<< "`\n");
// Create the replacement `ModelOp`.
auto modelOp =
ModelOp::create(builder, moduleOp.getLoc(), moduleOp.getModuleNameAttr(),
TypeAttr::get(moduleOp.getModuleType()),
FlatSymbolRefAttr{}, FlatSymbolRefAttr{}, ArrayAttr{});
auto &modelBlock = modelOp.getBody().emplaceBlock();
storageArg = modelBlock.addArgument(
StorageType::get(builder.getContext(), {}), modelOp.getLoc());
builder.setInsertionPointToStart(&modelBlock);
// Reset the next wakeup slot to `UINT64_MAX` ("no wakeup pending") at the
// start of every eval. Process suspension code lowers the value to the
// earliest scheduled wakeup over the course of the evaluation.
auto noWakeup = hw::ConstantOp::create(builder, moduleOp.getLoc(),
builder.getI64Type(), -1);
SetNextWakeupOp::create(builder, moduleOp.getLoc(), storageArg, noWakeup);
// Create the `arc.initial` op to contain the ops for the initialization
// phase.
auto initialOp = InitialOp::create(builder, moduleOp.getLoc());
initialBuilder.setInsertionPointToStart(&initialOp.getBody().emplaceBlock());
// Create the `arc.final` op to contain the ops for the finalization phase.
auto finalOp = FinalOp::create(builder, moduleOp.getLoc());
finalBuilder.setInsertionPointToStart(&finalOp.getBody().emplaceBlock());
// Position the alloc builder such that allocation ops get inserted above the
// initial op.
allocBuilder.setInsertionPoint(initialOp);
// Allocate storage for the inputs.
for (auto arg : moduleOp.getBodyBlock()->getArguments()) {
auto name = moduleOp.getArgName(arg.getArgNumber());
auto state =
RootInputOp::create(allocBuilder, arg.getLoc(),
StateType::get(arg.getType()), name, storageArg);
allocatedInputs.push_back(state);
}
// Lower the ops.
for (auto &op : moduleOp.getOps()) {
if (mlir::isMemoryEffectFree(&op) &&
!isa<hw::OutputOp, sim::ClockedTerminateOp>(op))
continue;
if (isa<MemoryReadPortOp, MemoryWritePortOp>(op))
continue; // handled as part of `MemoryOp`
if (failed(lowerOp(&op)))
return failure();
}
// Clean up any dead ops. The lowering inserts a few defensive
// `arc.state_read` ops that may remain unused. This cleans them up.
for (auto &op : llvm::make_early_inc_range(llvm::reverse(modelBlock)))
if (mlir::isOpTriviallyDead(&op))
op.erase();
return success();
}
/// Lower an op and its entire fan-in cone.
LogicalResult ModuleLowering::lowerOp(Operation *op) {
LLVM_DEBUG(llvm::dbgs() << "- Handling " << *op << "\n");
// Pick in which phases the given operation has to perform some work.
SmallVector<Phase, 2> phases = {Phase::New};
if (isa<seq::InitialOp>(op))
phases = {Phase::Initial};
if (isa<llhd::FinalOp>(op))
phases = {Phase::Final};
if (isa<StateOp>(op))
phases = {Phase::Initial, Phase::New};
for (auto phase : phases) {
if (loweredOps.contains({op, phase}))
return success();
opsWorklist.push_back(OpLowering(op, phase, *this));
opsSeen.insert({op, phase});
}
auto dumpWorklist = [&] {
for (auto &opLowering : llvm::reverse(opsWorklist))
opLowering.op->emitRemark()
<< "computing " << opLowering.phase << " phase here";
};
while (!opsWorklist.empty()) {
auto &opLowering = opsWorklist.back();
// Collect an initial list of operands that need to be lowered.
if (opLowering.initial) {
if (failed(opLowering.lower())) {
dumpWorklist();
return failure();
}
std::reverse(opLowering.pending.begin(), opLowering.pending.end());
opLowering.initial = false;
}
// Push operands onto the worklist.
if (!opLowering.pending.empty()) {
auto [defOp, phase] = opLowering.pending.pop_back_val();
if (loweredOps.contains({defOp, phase}))
continue;
if (!opsSeen.insert({defOp, phase}).second) {
defOp->emitOpError("is on a combinational loop");
dumpWorklist();
return failure();
}
opsWorklist.push_back(OpLowering(defOp, phase, *this));
continue;
}
// At this point all operands are available and the op itself can be
// lowered.
LLVM_DEBUG(llvm::dbgs() << " - Lowering " << opLowering.phase << " "
<< *opLowering.op << "\n");
if (failed(opLowering.lower())) {
dumpWorklist();
return failure();
}
loweredOps.insert({opLowering.op, opLowering.phase});
opsSeen.erase({opLowering.op, opLowering.phase});
opsWorklist.pop_back();
}
return success();
}
/// Return the `arc.alloc_state` associated with the given state op result.
/// Creates the allocation op if it does not yet exist.
Value ModuleLowering::getAllocatedState(OpResult result) {
if (auto alloc = allocatedStates.lookup(result))
return alloc;
// Handle memories.
if (auto memOp = dyn_cast<MemoryOp>(result.getOwner())) {
auto alloc =
AllocMemoryOp::create(allocBuilder, memOp.getLoc(), memOp.getType(),
storageArg, memOp->getAttrs());
allocatedStates.insert({result, alloc});
return alloc;
}
// Create the allocation op.
auto alloc =
AllocStateOp::create(allocBuilder, result.getLoc(),
StateType::get(result.getType()), storageArg);
allocatedStates.insert({result, alloc});
// HACK: If the result comes from an instance op, add the instance and port
// name as an attribute to the allocation. This will make it show up in the C
// headers later. Get rid of this once we have proper debug dialect support.
if (auto instOp = dyn_cast<InstanceOp>(result.getOwner()))
alloc->setAttr(
"name", builder.getStringAttr(
instOp.getInstanceName() + "/" +
instOp.getOutputName(result.getResultNumber()).getValue()));
// HACK: If the result comes from an op that has a "names" attribute, use that
// as a name for the allocation. This should no longer be necessary once we
// properly support the Debug dialect.
if (isa<StateOp, sim::DPICallOp>(result.getOwner()))
if (auto names = result.getOwner()->getAttrOfType<ArrayAttr>("names"))
if (result.getResultNumber() < names.size())
alloc->setAttr("name", names[result.getResultNumber()]);
return alloc;
}
/// Allocate the necessary storage, reads, writes, and comparisons to detect a
/// rising edge on a clock value.
Value ModuleLowering::detectPosedge(Value clock) {
auto loc = clock.getLoc();
if (isa<seq::ClockType>(clock.getType()))
clock = seq::FromClockOp::create(builder, loc, clock);
// Allocate storage to store the previous clock value.
auto oldStorage = AllocStateOp::create(
allocBuilder, loc, StateType::get(builder.getI1Type()), storageArg);
// Read the old clock value from storage and write the new clock value to
// storage.
auto oldClock = StateReadOp::create(builder, loc, oldStorage);
StateWriteOp::create(builder, loc, oldStorage, clock);
// Detect a rising edge.
auto edge = comb::XorOp::create(builder, loc, oldClock, clock);
return comb::AndOp::create(builder, loc, edge, clock);
}
/// Get the builder appropriate for the given phase.
OpBuilder &ModuleLowering::getBuilder(Phase phase) {
switch (phase) {
case Phase::Initial:
return initialBuilder;
case Phase::Old:
case Phase::New:
return builder;
case Phase::Final:
return finalBuilder;
}
}
/// Get the lowered value, or emit a diagnostic and return null.
Value ModuleLowering::requireLoweredValue(Value value, Phase phase,
Location useLoc) {
if (auto lowered = loweredValues.lookup({value, phase}))
return lowered;
auto d = emitError(value.getLoc()) << "value has not been lowered";
d.attachNote(useLoc) << "value used here";
return {};
}
//===----------------------------------------------------------------------===//
// Operation Lowering
//===----------------------------------------------------------------------===//
/// Create a new `scf.if` operation with the given builder, or reuse a previous
/// `scf.if` if the builder's insertion point is located right after it.
static scf::IfOp createOrReuseIf(OpBuilder &builder, Value condition,
bool withElse) {
if (auto ip = builder.getInsertionPoint(); ip != builder.getBlock()->begin())
if (auto ifOp = dyn_cast<scf::IfOp>(*std::prev(ip)))
if (ifOp.getCondition() == condition)
return ifOp;
return scf::IfOp::create(builder, condition.getLoc(), condition, withElse);
}
/// This function is called from the lowering worklist in order to perform a
/// depth-first traversal of the surrounding module. These functions call
/// `lowerValue` to mark their operands as dependencies in the depth-first
/// traversal, and to map them to the lowered value in one go.
LogicalResult OpLowering::lower() {
return TypeSwitch<Operation *, LogicalResult>(op)
// Operations with special lowering.
.Case<StateOp, sim::DPICallOp, MemoryOp, TapOp, InstanceOp, hw::OutputOp,
seq::InitialOp, llhd::FinalOp, llhd::CurrentTimeOp,
sim::ClockedTerminateOp>([&](auto op) { return lower(op); })
// Operations that should be skipped entirely and never land on the
// worklist to be lowered.
.Case<MemoryWritePortOp, MemoryReadPortOp>([&](auto op) {
assert(false && "ports must be lowered by memory op");
return failure();
})
// All other ops are simply cloned into the lowered model.
.Default([&](auto) { return lowerDefault(); });
}
/// Called for all operations for which there is no special lowering. Simply
/// clones the operation.
LogicalResult OpLowering::lowerDefault() {
// Make sure that all operand values are lowered first.
IRMapping mapping;
auto anyFailed = false;
op->walk([&](Operation *nestedOp) {
for (auto operand : nestedOp->getOperands()) {
if (op->isAncestor(operand.getParentBlock()->getParentOp()))
continue;
auto lowered = lowerValue(operand, phase);
if (!lowered)
anyFailed = true;
mapping.map(operand, lowered);
}
});
if (initial)
return success();
if (anyFailed)
return failure();
// Clone the operation.
auto *clonedOp = module.getBuilder(phase).clone(*op, mapping);
// Keep track of the results.
for (auto [oldResult, newResult] :
llvm::zip(op->getResults(), clonedOp->getResults()))
module.loweredValues[{oldResult, phase}] = newResult;
return success();
}
/// Lower a state to a corresponding storage allocation and `write` of the
/// state's new value to it. This function uses the `Old` phase to get the
/// values at the state input before the current update, and then uses them to
/// compute the `New` value.
LogicalResult OpLowering::lower(StateOp op) {
// Handle initialization.
if (phase == Phase::Initial) {
// Ensure the initial values of the register have been lowered before.
if (initial) {
for (auto initial : op.getInitials())
lowerValue(initial, Phase::Initial);
return success();
}
// Write the initial values to the allocated storage in the initial block.
if (op.getInitials().empty())
return success();
for (auto [initial, result] :
llvm::zip(op.getInitials(), op.getResults())) {
auto value = lowerValue(initial, Phase::Initial);
if (!value)
return failure();
auto state = module.getAllocatedState(result);
if (!state)
return failure();
StateWriteOp::create(module.initialBuilder, value.getLoc(), state, value);
}
return success();
}
assert(phase == Phase::New);
if (!initial) {
if (!op.getClock())
return op.emitOpError() << "must have a clock";
if (op.getLatency() > 1)
return op.emitOpError("latencies > 1 not supported yet");
}
return lowerStateful(op.getClock(), op.getEnable(), op.getReset(),
op.getInputs(), op.getResults(), [&](ValueRange inputs) {
return CallOp::create(module.builder, op.getLoc(),
op.getResultTypes(), op.getArc(),
inputs)
.getResults();
});
}
/// Lower a DPI call to a corresponding storage allocation and write of the
/// state's new value to it. This function uses the `Old` phase to get the
/// values at the state input before the current update, and then uses them to
/// compute the `New` value.
LogicalResult OpLowering::lower(sim::DPICallOp op) {
// Handle unclocked DPI calls.
if (!op.getClock()) {
// Make sure that all operands have been lowered.
SmallVector<Value> inputs;
for (auto operand : op.getInputs())
inputs.push_back(lowerValue(operand, phase));
if (initial)
return success();
if (llvm::is_contained(inputs, Value{}))
return failure();
if (op.getEnable())
return op.emitOpError() << "without clock cannot have an enable";
// Lower the op to a regular function call.
auto callOp =
func::CallOp::create(module.getBuilder(phase), op.getLoc(),
op.getCalleeAttr(), op.getResultTypes(), inputs);
for (auto [oldResult, newResult] :
llvm::zip(op.getResults(), callOp.getResults()))
module.loweredValues[{oldResult, phase}] = newResult;
return success();
}
assert(phase == Phase::New);
return lowerStateful(op.getClock(), op.getEnable(), /*reset=*/{},
op.getInputs(), op.getResults(), [&](ValueRange inputs) {
return func::CallOp::create(
module.builder, op.getLoc(),
op.getCalleeAttr(), op.getResultTypes(),
inputs)
.getResults();
});
}
/// Lower a state to a corresponding storage allocation and `write` of the
/// state's new value to it. This function uses the `Old` phase to get the
/// values at the state input before the current update, and then uses them to
/// compute the `New` value.
LogicalResult OpLowering::lowerStateful(
Value clock, Value enable, Value reset, ValueRange inputs,
ResultRange results,
llvm::function_ref<ValueRange(ValueRange)> createMapping) {
// Ensure all operands are lowered before we lower the op itself. State ops
// are special in that they require the "old" value of their inputs and
// enable, in order to compute the updated "new" value. The clock needs to be
// the "new" value though, such that other states can act as a clock source.
if (initial) {
lowerValue(clock, Phase::New);
if (enable)
lowerValue(enable, Phase::Old);
if (reset)
lowerValue(reset, Phase::Old);
for (auto input : inputs)
lowerValue(input, Phase::Old);
return success();
}
// Check if we're inserting right after an `if` op for the same clock edge, in
// which case we can reuse that op. Otherwise, create the new `if` op.
auto ifClockOp = createIfClockOp(clock);
if (!ifClockOp)
return failure();
OpBuilder::InsertionGuard guard(module.builder);
module.builder.setInsertionPoint(ifClockOp.thenYield());
// Make sure we have the state storage available such that we can read and
// write from and to them.
SmallVector<Value> states;
for (auto result : results) {
auto state = module.getAllocatedState(result);
if (!state)
return failure();
states.push_back(state);
}
// Handle the reset.
if (reset) {
// Check if we can reuse a previous reset value.
auto &[unloweredReset, loweredReset] = module.prevReset;
if (unloweredReset != reset ||
loweredReset.getParentBlock() != module.builder.getBlock()) {
unloweredReset = reset;
loweredReset = lowerValue(reset, Phase::Old);
if (!loweredReset)
return failure();
}
// Check if we're inserting right after an if op for the same reset, in
// which case we can reuse that op. Otherwise create the new if op.
auto ifResetOp = createOrReuseIf(module.builder, loweredReset, true);
module.builder.setInsertionPoint(ifResetOp.thenYield());
// Generate the zero value writes.
for (auto state : states) {
auto type = cast<StateType>(state.getType()).getType();
Value value = ConstantOp::create(
module.builder, loweredReset.getLoc(),
module.builder.getIntegerType(hw::getBitWidth(type)), 0);
if (value.getType() != type)
value = BitcastOp::create(module.builder, loweredReset.getLoc(), type,
value);
StateWriteOp::create(module.builder, loweredReset.getLoc(), state, value);
}
module.builder.setInsertionPoint(ifResetOp.elseYield());
}
// Handle the enable.
if (enable) {
// Check if we can reuse a previous enable value.
auto &[unloweredEnable, loweredEnable] = module.prevEnable;
if (unloweredEnable != enable ||
loweredEnable.getParentBlock() != module.builder.getBlock()) {
unloweredEnable = enable;
loweredEnable = lowerValue(enable, Phase::Old);
if (!loweredEnable)
return failure();
}
// Check if we're inserting right after an if op for the same enable, in
// which case we can reuse that op. Otherwise create the new if op.
auto ifEnableOp = createOrReuseIf(module.builder, loweredEnable, false);
module.builder.setInsertionPoint(ifEnableOp.thenYield());
}
// Get the transfer function inputs. This potentially inserts read ops.
SmallVector<Value> loweredInputs;
for (auto input : inputs) {
auto lowered = lowerValue(input, Phase::Old);
if (!lowered)
return failure();
loweredInputs.push_back(lowered);
}
// Compute the transfer function and write its results to the state's storage.
auto loweredResults = createMapping(loweredInputs);
for (auto [state, value] : llvm::zip(states, loweredResults))
StateWriteOp::create(module.builder, value.getLoc(), state, value);
// Since we just wrote the new state value to storage, insert read ops just
// before the if op that keep the old value around for any later ops that
// still need it.
module.builder.setInsertionPoint(ifClockOp);
for (auto [state, result] : llvm::zip(states, results)) {
auto oldValue = StateReadOp::create(module.builder, result.getLoc(), state);
module.loweredValues[{result, Phase::Old}] = oldValue;
}
return success();
}
/// Lower a memory and its read and write ports to corresponding
/// `arc.memory_write` operations. Reads are also executed at this point and
/// stored in `loweredValues` for later operations to pick up.
LogicalResult OpLowering::lower(MemoryOp op) {
assert(phase == Phase::New);
// Collect all the reads and writes.
SmallVector<MemoryReadPortOp> reads;
SmallVector<MemoryWritePortOp> writes;
for (auto *user : op->getUsers()) {
if (auto read = dyn_cast<MemoryReadPortOp>(user)) {
reads.push_back(read);
} else if (auto write = dyn_cast<MemoryWritePortOp>(user)) {
writes.push_back(write);
} else {
auto d = op.emitOpError()
<< "users must all be memory read or write port ops";
d.attachNote(user->getLoc())
<< "but found " << user->getName() << " user here";
return d;
}
}
// Ensure all operands are lowered before we lower the memory itself.
if (initial) {
for (auto read : reads)
lowerValue(read, Phase::Old);
for (auto write : writes) {
if (write.getClock())
lowerValue(write.getClock(), Phase::New);
for (auto input : write.getInputs())
lowerValue(input, Phase::Old);
}
return success();
}
// Get the allocated storage for the memory.
auto state = module.getAllocatedState(op->getResult(0));
// Since we are going to write new values into storage, insert read ops that
// keep the old values around for any later ops that still need them.
for (auto read : reads) {
auto oldValue = lowerValue(read, Phase::Old);
if (!oldValue)
return failure();
module.loweredValues[{read, Phase::Old}] = oldValue;
}
// Lower the writes.
for (auto write : writes) {
if (!write.getClock())
return write.emitOpError() << "must have a clock";
if (write.getLatency() > 1)
return write.emitOpError("latencies > 1 not supported yet");
// Create the if op for the clock edge.
auto ifClockOp = createIfClockOp(write.getClock());
if (!ifClockOp)
return failure();
OpBuilder::InsertionGuard guard(module.builder);
module.builder.setInsertionPoint(ifClockOp.thenYield());
// Call the arc that computes the address, data, and enable.
SmallVector<Value> inputs;
for (auto input : write.getInputs()) {
auto lowered = lowerValue(input, Phase::Old);
if (!lowered)
return failure();
inputs.push_back(lowered);
}
auto callOp =
CallOp::create(module.builder, write.getLoc(),
write.getArcResultTypes(), write.getArc(), inputs);
// If the write has an enable, wrap the remaining logic in an if op.
if (write.getEnable()) {
auto ifEnableOp = createOrReuseIf(
module.builder, callOp.getResult(write.getEnableIdx()), false);
module.builder.setInsertionPoint(ifEnableOp.thenYield());
}
// If the write is masked, read the current
// value in the memory and merge it with the updated value.
auto address = callOp.getResult(write.getAddressIdx());
auto data = callOp.getResult(write.getDataIdx());
if (write.getMask()) {
auto mask = callOp.getResult(write.getMaskIdx(write.getEnable()));
auto maskInv = module.builder.createOrFold<comb::XorOp>(
write.getLoc(), mask,
ConstantOp::create(module.builder, write.getLoc(), mask.getType(),
-1),
true);
auto oldData =
MemoryReadOp::create(module.builder, write.getLoc(), state, address);
auto oldMasked = comb::AndOp::create(module.builder, write.getLoc(),
maskInv, oldData, true);
auto newMasked =
comb::AndOp::create(module.builder, write.getLoc(), mask, data, true);
data = comb::OrOp::create(module.builder, write.getLoc(), oldMasked,
newMasked, true);
}
// Actually write to the memory.
MemoryWriteOp::create(module.builder, write.getLoc(), state, address, data);
}
return success();
}
/// Lower a tap by allocating state storage for it and writing the current value
/// observed by the tap to it.
LogicalResult OpLowering::lower(TapOp op) {
assert(phase == Phase::New);
auto value = lowerValue(op.getValue(), phase);
if (initial)
return success();
if (!value)
return failure();
auto &state = module.allocatedTaps[op];
if (!state) {
auto alloc = AllocStateOp::create(module.allocBuilder, op.getLoc(),
StateType::get(value.getType()),
module.storageArg, true);
alloc->setAttr("names", op.getNamesAttr());
state = alloc;
}
StateWriteOp::create(module.builder, op.getLoc(), state, value);
return success();
}
/// Lower an instance by allocating state storage for each of its inputs and
/// writing the current value into that storage. This makes instance inputs
/// behave like outputs of the top-level module.
LogicalResult OpLowering::lower(InstanceOp op) {
assert(phase == Phase::New);
// Get the current values flowing into the instance's inputs.
SmallVector<Value> values;
for (auto operand : op.getOperands())
values.push_back(lowerValue(operand, Phase::New));
if (initial)
return success();
if (llvm::is_contained(values, Value{}))
return failure();
// Then allocate storage for each instance input and assign the corresponding
// value.
for (auto [value, name] : llvm::zip(values, op.getArgNames())) {
auto state = AllocStateOp::create(module.allocBuilder, value.getLoc(),
StateType::get(value.getType()),
module.storageArg);
state->setAttr("name", module.builder.getStringAttr(
op.getInstanceName() + "/" +
cast<StringAttr>(name).getValue()));
StateWriteOp::create(module.builder, value.getLoc(), state, value);
}
// HACK: Also ensure that storage has been allocated for all outputs.
// Otherwise only the actually used instance outputs would be allocated, which
// would make the optimization user-visible. Remove this once we use the debug
// dialect.
for (auto result : op.getResults())
module.getAllocatedState(result);
return success();
}
/// Lower the main module's outputs by allocating storage for each and then
/// writing the current value into that storage.
LogicalResult OpLowering::lower(hw::OutputOp op) {
assert(phase == Phase::New);
// First get the current value of all outputs.
SmallVector<Value> values;
for (auto operand : op.getOperands())
values.push_back(lowerValue(operand, Phase::New));
if (initial)
return success();
if (llvm::is_contained(values, Value{}))
return failure();
// Then allocate storage for each output and assign the corresponding value.
for (auto [value, name] :
llvm::zip(values, module.moduleOp.getOutputNames())) {
auto state = RootOutputOp::create(
module.allocBuilder, value.getLoc(), StateType::get(value.getType()),
cast<StringAttr>(name), module.storageArg);
StateWriteOp::create(module.builder, value.getLoc(), state, value);
}
return success();
}
/// Lower `seq.initial` ops by inlining them into the `arc.initial` op.
LogicalResult OpLowering::lower(seq::InitialOp op) {
assert(phase == Phase::Initial);
// First get the initial value of all operands.
SmallVector<Value> operands;
for (auto operand : op.getOperands())
operands.push_back(lowerValue(operand, Phase::Initial));
if (initial)
return success();
if (llvm::is_contained(operands, Value{}))
return failure();
// Expose the `seq.initial` operands as values for the block arguments.
for (auto [arg, operand] : llvm::zip(op.getBody().getArguments(), operands))
module.loweredValues[{arg, Phase::Initial}] = operand;
// Lower each op in the body. We maintain a mapping from original values
// defined in the body to their cloned counterparts.
IRMapping bodyMapping;
auto *initialBlock = module.initialBuilder.getBlock();
// Pre-lower all llhd.current_time ops inside the body. This reuses the
// existing lower(llhd::CurrentTimeOp) logic which handles Phase::Initial
// by replacing with constant 0 time.
auto result = op.walk([&](llhd::CurrentTimeOp timeOp) {
if (failed(lower(timeOp)))
return WalkResult::interrupt();
auto loweredTime = module.loweredValues.lookup({timeOp.getResult(), phase});
timeOp.replaceAllUsesWith(loweredTime);
timeOp.erase();
return WalkResult::advance();
});
if (result.wasInterrupted())
return failure();
for (auto &bodyOp : op.getOps()) {
if (isa<seq::YieldOp>(bodyOp))
continue;
// Clone the operation.
auto *clonedOp = module.initialBuilder.clone(bodyOp, bodyMapping);
auto result = clonedOp->walk([&](Operation *nestedClonedOp) {
for (auto &operand : nestedClonedOp->getOpOperands()) {
// Skip operands defined within the cloned tree.
if (clonedOp->isAncestor(operand.get().getParentBlock()->getParentOp()))
continue;
// Skip operands defined within the initial block (e.g., results of
// previously lowered ops like our zeroTime).
if (auto *defOp = operand.get().getDefiningOp())
if (defOp->getBlock() == initialBlock)
continue;
auto value = module.requireLoweredValue(operand.get(), Phase::Initial,
nestedClonedOp->getLoc());
if (!value)
return WalkResult::interrupt();
operand.set(value);
}
return WalkResult::advance();
});
if (result.wasInterrupted())
return failure();
// Keep track of the results in both mappings.
for (auto [result, lowered] :
llvm::zip(bodyOp.getResults(), clonedOp->getResults())) {
bodyMapping.map(result, lowered);
module.loweredValues[{result, Phase::Initial}] = lowered;
}
}
// Expose the operands of `seq.yield` as results from the initial op.
auto *terminator = op.getBodyBlock()->getTerminator();
for (auto [result, operand] :
llvm::zip(op.getResults(), terminator->getOperands())) {
auto value = module.requireLoweredValue(operand, Phase::Initial,
terminator->getLoc());
if (!value)
return failure();
module.loweredValues[{result, Phase::Initial}] = value;
}
return success();
}
/// Lower `llhd.final` ops into `scf.execute_region` ops in the `arc.final` op.
LogicalResult OpLowering::lower(llhd::FinalOp op) {
assert(phase == Phase::Final);
// Determine the uses of values defined outside the op.
SmallVector<Value> externalOperands;
op.walk([&](Operation *nestedOp) {
for (auto value : nestedOp->getOperands())
if (!op->isAncestor(value.getParentBlock()->getParentOp()))
externalOperands.push_back(value);
});
// Make sure that all uses of external values are lowered first.
IRMapping mapping;
for (auto operand : externalOperands) {
auto lowered = lowerValue(operand, Phase::Final);
if (!initial && !lowered)
return failure();
mapping.map(operand, lowered);
}
if (initial)
return success();
// Pre-lower all llhd.current_time ops inside the body. This reuses the
// existing lower(llhd::CurrentTimeOp) logic which handles Phase::Final
// by replacing with arc.current_time.
auto result = op.walk([&](llhd::CurrentTimeOp timeOp) {
if (failed(lower(timeOp)))
return WalkResult::interrupt();
auto loweredTime = module.loweredValues.lookup({timeOp.getResult(), phase});
timeOp.replaceAllUsesWith(loweredTime);
timeOp.erase();
return WalkResult::advance();
});
if (result.wasInterrupted())
return failure();
// Handle the simple case where the final op contains only one block, which we
// can inline directly.
if (op.getBody().hasOneBlock()) {
for (auto &bodyOp : op.getBody().front().without_terminator())
module.finalBuilder.clone(bodyOp, mapping);