-
Notifications
You must be signed in to change notification settings - Fork 444
Expand file tree
/
Copy pathMooreToCore.cpp
More file actions
3303 lines (2818 loc) · 123 KB
/
MooreToCore.cpp
File metadata and controls
3303 lines (2818 loc) · 123 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
//===----------------------------------------------------------------------===//
//
// 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/Conversion/MooreToCore.h"
#include "circt/Dialect/Comb/CombOps.h"
#include "circt/Dialect/Debug/DebugOps.h"
#include "circt/Dialect/HW/HWOps.h"
#include "circt/Dialect/HW/HWTypes.h"
#include "circt/Dialect/LLHD/LLHDOps.h"
#include "circt/Dialect/LTL/LTLOps.h"
#include "circt/Dialect/Moore/MooreOps.h"
#include "circt/Dialect/Sim/SimOps.h"
#include "circt/Dialect/Verif/VerifOps.h"
#include "circt/Support/ConversionPatternSet.h"
#include "circt/Transforms/Passes.h"
#include "mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/Dialect/ControlFlow/Transforms/StructuralTypeConversions.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
#include "mlir/Dialect/Math/IR/Math.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/IR/BuiltinDialect.h"
#include "mlir/IR/Iterators.h"
#include "mlir/Interfaces/SideEffectInterfaces.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
#include "mlir/Transforms/RegionUtils.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/IR/DerivedTypes.h"
namespace circt {
#define GEN_PASS_DEF_CONVERTMOORETOCORE
#include "circt/Conversion/Passes.h.inc"
} // namespace circt
using namespace mlir;
using namespace circt;
using namespace moore;
using comb::ICmpPredicate;
using llvm::SmallDenseSet;
namespace {
/// Cache for identified structs and field GEP paths keyed by class symbol.
struct ClassTypeCache {
struct ClassStructInfo {
LLVM::LLVMStructType classBody;
// field name -> GEP path inside ident (excluding the leading pointer index)
DenseMap<StringRef, SmallVector<unsigned, 2>> propertyPath;
// TODO: Add classVTable in here.
/// Record/overwrite the field path to a single property for a class.
void setFieldPath(StringRef propertyName, ArrayRef<unsigned> path) {
this->propertyPath[propertyName] =
SmallVector<unsigned, 2>(path.begin(), path.end());
}
/// Lookup the full GEP path for a (class, field).
std::optional<ArrayRef<unsigned>>
getFieldPath(StringRef propertySym) const {
if (auto prop = this->propertyPath.find(propertySym);
prop != this->propertyPath.end())
return ArrayRef<unsigned>(prop->second);
return std::nullopt;
}
};
/// Record the identified struct body for a class.
/// Implicitly finalizes the class to struct conversion.
void setClassInfo(SymbolRefAttr classSym, const ClassStructInfo &info) {
auto &dst = classToStructMap[classSym];
dst = info;
}
/// Lookup the identified struct body for a class.
std::optional<ClassStructInfo> getStructInfo(SymbolRefAttr classSym) const {
if (auto it = classToStructMap.find(classSym); it != classToStructMap.end())
return it->second;
return std::nullopt;
}
private:
// Keyed by the SymbolRefAttr of the class.
// Kept private so all accesses are done with helpers which preserve
// invariants
DenseMap<Attribute, ClassStructInfo> classToStructMap;
};
/// Ensure we have `declare i8* @malloc(i64)` (opaque ptr prints as !llvm.ptr).
static LLVM::LLVMFuncOp getOrCreateMalloc(ModuleOp mod, OpBuilder &b) {
if (auto f = mod.lookupSymbol<LLVM::LLVMFuncOp>("malloc"))
return f;
OpBuilder::InsertionGuard g(b);
b.setInsertionPointToStart(mod.getBody());
auto i64Ty = IntegerType::get(mod.getContext(), 64);
auto ptrTy = LLVM::LLVMPointerType::get(mod.getContext()); // opaque pointer
auto fnTy = LLVM::LLVMFunctionType::get(ptrTy, {i64Ty}, false);
auto fn = LLVM::LLVMFuncOp::create(b, mod.getLoc(), "malloc", fnTy);
// Link this in from somewhere else.
fn.setLinkage(LLVM::Linkage::External);
return fn;
}
/// Helper function to create an opaque LLVM Struct Type which corresponds
/// to the sym
static LLVM::LLVMStructType getOrCreateOpaqueStruct(MLIRContext *ctx,
SymbolRefAttr className) {
return LLVM::LLVMStructType::getIdentified(ctx, className.getRootReference());
}
static LogicalResult resolveClassStructBody(ClassDeclOp op,
TypeConverter const &typeConverter,
ClassTypeCache &cache) {
auto classSym = SymbolRefAttr::get(op.getSymNameAttr());
auto structInfo = cache.getStructInfo(classSym);
if (structInfo)
// We already have a resolved class struct body.
return success();
// Otherwise we need to resolve.
ClassTypeCache::ClassStructInfo structBody;
SmallVector<Type> structBodyMembers;
// Base-first (prefix) layout for single inheritance.
unsigned derivedStartIdx = 0;
if (auto baseClass = op.getBaseAttr()) {
ModuleOp mod = op->getParentOfType<ModuleOp>();
auto *opSym = mod.lookupSymbol(baseClass);
auto classDeclOp = cast<ClassDeclOp>(opSym);
if (failed(resolveClassStructBody(classDeclOp, typeConverter, cache)))
return failure();
// Process base class' struct layout first
auto baseClassStruct = cache.getStructInfo(baseClass);
structBodyMembers.push_back(baseClassStruct->classBody);
derivedStartIdx = 1;
// Inherit base field paths with a leading 0.
for (auto &kv : baseClassStruct->propertyPath) {
SmallVector<unsigned, 2> path;
path.push_back(0); // into base subobject
path.append(kv.second.begin(), kv.second.end());
structBody.setFieldPath(kv.first, path);
}
}
// Properties in source order.
unsigned iterator = derivedStartIdx;
auto &block = op.getBody().front();
for (Operation &child : block) {
if (auto prop = dyn_cast<ClassPropertyDeclOp>(child)) {
Type mooreTy = prop.getPropertyType();
Type llvmTy = typeConverter.convertType(mooreTy);
if (!llvmTy)
return prop.emitOpError()
<< "failed to convert property type " << mooreTy;
structBodyMembers.push_back(llvmTy);
// Derived field path: either {i} or {1+i} if base is present.
SmallVector<unsigned, 2> path{iterator};
structBody.setFieldPath(prop.getSymName(), path);
++iterator;
}
}
// TODO: Handle vtable generation over ClassMethodDeclOp here.
auto llvmStructTy = getOrCreateOpaqueStruct(op.getContext(), classSym);
// Empty structs may be kept opaque
if (!structBodyMembers.empty() &&
failed(llvmStructTy.setBody(structBodyMembers, false)))
return op.emitOpError() << "Failed to set LLVM Struct body";
structBody.classBody = llvmStructTy;
cache.setClassInfo(classSym, structBody);
return success();
}
/// Convenience overload that looks up ClassDeclOp
static LogicalResult resolveClassStructBody(ModuleOp mod, SymbolRefAttr op,
TypeConverter const &typeConverter,
ClassTypeCache &cache) {
auto classDeclOp = cast<ClassDeclOp>(*mod.lookupSymbol(op));
return resolveClassStructBody(classDeclOp, typeConverter, cache);
}
/// Returns the passed value if the integer width is already correct.
/// Zero-extends if it is too narrow.
/// Truncates if the integer is too wide and the truncated part is zero, if it
/// is not zero it returns the max value integer of target-width.
static Value adjustIntegerWidth(OpBuilder &builder, Value value,
uint32_t targetWidth, Location loc) {
uint32_t intWidth = value.getType().getIntOrFloatBitWidth();
if (intWidth == targetWidth)
return value;
if (intWidth < targetWidth) {
Value zeroExt = hw::ConstantOp::create(
builder, loc, builder.getIntegerType(targetWidth - intWidth), 0);
return comb::ConcatOp::create(builder, loc, ValueRange{zeroExt, value});
}
Value hi = comb::ExtractOp::create(builder, loc, value, targetWidth,
intWidth - targetWidth);
Value zero = hw::ConstantOp::create(
builder, loc, builder.getIntegerType(intWidth - targetWidth), 0);
Value isZero = comb::ICmpOp::create(builder, loc, comb::ICmpPredicate::eq, hi,
zero, false);
Value lo = comb::ExtractOp::create(builder, loc, value, 0, targetWidth);
Value max = hw::ConstantOp::create(builder, loc,
builder.getIntegerType(targetWidth), -1);
return comb::MuxOp::create(builder, loc, isZero, lo, max, false);
}
/// Get the ModulePortInfo from a SVModuleOp.
static FailureOr<hw::ModulePortInfo>
getModulePortInfo(const TypeConverter &typeConverter, SVModuleOp op) {
size_t inputNum = 0;
size_t resultNum = 0;
auto moduleTy = op.getModuleType();
SmallVector<hw::PortInfo> ports;
ports.reserve(moduleTy.getNumPorts());
for (auto port : moduleTy.getPorts()) {
Type portTy = typeConverter.convertType(port.type);
if (!portTy) {
return op.emitOpError("port '")
<< port.name << "' has unsupported type " << port.type
<< " that cannot be converted to hardware type";
}
if (port.dir == hw::ModulePort::Direction::Output) {
ports.push_back(
hw::PortInfo({{port.name, portTy, port.dir}, resultNum++, {}}));
} else {
// FIXME: Once we support net<...>, ref<...> type to represent type of
// special port like inout or ref port which is not a input or output
// port. It can change to generate corresponding types for direction of
// port or do specified operation to it. Now inout and ref port is treated
// as input port.
ports.push_back(
hw::PortInfo({{port.name, portTy, port.dir}, inputNum++, {}}));
}
}
return hw::ModulePortInfo(ports);
}
struct DpiArrayCastInfo {
bool isRef = false;
bool isOpen = false;
bool isPacked = false;
Type elementType;
};
static std::optional<DpiArrayCastInfo> getDpiArrayCastInfo(Type type) {
DpiArrayCastInfo info;
if (auto refType = dyn_cast<RefType>(type)) {
info.isRef = true;
type = refType.getNestedType();
}
if (auto arrayType = dyn_cast<ArrayType>(type)) {
info.isPacked = true;
info.elementType = arrayType.getElementType();
return info;
}
if (auto arrayType = dyn_cast<OpenArrayType>(type)) {
info.isOpen = true;
info.isPacked = true;
info.elementType = arrayType.getElementType();
return info;
}
if (auto arrayType = dyn_cast<UnpackedArrayType>(type)) {
info.elementType = arrayType.getElementType();
return info;
}
if (auto arrayType = dyn_cast<OpenUnpackedArrayType>(type)) {
info.isOpen = true;
info.elementType = arrayType.getElementType();
return info;
}
return std::nullopt;
}
static bool hasOpenArrayBoundaryType(Type type) {
if (isa<OpenArrayType, OpenUnpackedArrayType>(type))
return true;
if (auto refType = dyn_cast<RefType>(type))
return isa<OpenArrayType, OpenUnpackedArrayType>(refType.getNestedType());
return false;
}
static bool isSupportedDpiOpenArrayCast(Type source, Type target) {
auto sourceInfo = getDpiArrayCastInfo(source);
auto targetInfo = getDpiArrayCastInfo(target);
if (!sourceInfo || !targetInfo)
return false;
// note: We currently don't support converting from open array to non-open
// array, even if the element types match, because there is no size
// information for the open array.
return sourceInfo->isRef == targetInfo->isRef &&
sourceInfo->isPacked == targetInfo->isPacked &&
sourceInfo->elementType == targetInfo->elementType &&
(targetInfo->isOpen && !sourceInfo->isOpen);
}
//===----------------------------------------------------------------------===//
// Structural Conversion
//===----------------------------------------------------------------------===//
struct SVModuleOpConversion : public OpConversionPattern<SVModuleOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(SVModuleOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
rewriter.setInsertionPoint(op);
// Create the hw.module to replace moore.module
auto portInfo = getModulePortInfo(*typeConverter, op);
if (failed(portInfo))
return failure();
auto hwModuleOp = hw::HWModuleOp::create(rewriter, op.getLoc(),
op.getSymNameAttr(), *portInfo);
// Make hw.module have the same visibility as the moore.module.
// The entry/top level module is public, otherwise is private.
SymbolTable::setSymbolVisibility(hwModuleOp,
SymbolTable::getSymbolVisibility(op));
rewriter.eraseBlock(hwModuleOp.getBodyBlock());
if (failed(
rewriter.convertRegionTypes(&op.getBodyRegion(), *typeConverter)))
return failure();
rewriter.inlineRegionBefore(op.getBodyRegion(), hwModuleOp.getBodyRegion(),
hwModuleOp.getBodyRegion().end());
// Erase the original op
rewriter.eraseOp(op);
return success();
}
};
struct OutputOpConversion : public OpConversionPattern<OutputOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(OutputOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOpWithNewOp<hw::OutputOp>(op, adaptor.getOperands());
return success();
}
};
struct InstanceOpConversion : public OpConversionPattern<InstanceOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(InstanceOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto instName = op.getInstanceNameAttr();
auto moduleName = op.getModuleNameAttr();
// Create the new hw instanceOp to replace the original one.
rewriter.setInsertionPoint(op);
auto instOp = hw::InstanceOp::create(
rewriter, op.getLoc(), op.getResultTypes(), instName, moduleName,
op.getInputs(), op.getInputNamesAttr(), op.getOutputNamesAttr(),
/*Parameter*/ rewriter.getArrayAttr({}), /*InnerSymbol*/ nullptr,
/*doNotPrint*/ nullptr);
// Replace uses chain and erase the original op.
op.replaceAllUsesWith(instOp.getResults());
rewriter.eraseOp(op);
return success();
}
};
static void getValuesToObserve(Region *region,
function_ref<void(Value)> setInsertionPoint,
const TypeConverter *typeConverter,
ConversionPatternRewriter &rewriter,
SmallVector<Value> &observeValues) {
SmallDenseSet<Value> alreadyObserved;
Location loc = region->getLoc();
auto probeIfSignal = [&](Value value) -> Value {
if (!isa<llhd::RefType>(value.getType()))
return value;
return llhd::ProbeOp::create(rewriter, loc, value);
};
region->getParentOp()->walk<WalkOrder::PreOrder, ForwardDominanceIterator<>>(
[&](Operation *operation) {
for (auto value : operation->getOperands()) {
if (isa<BlockArgument>(value))
value = rewriter.getRemappedValue(value);
if (region->isAncestor(value.getParentRegion()))
continue;
if (auto *defOp = value.getDefiningOp();
defOp && defOp->hasTrait<OpTrait::ConstantLike>())
continue;
if (!alreadyObserved.insert(value).second)
continue;
OpBuilder::InsertionGuard g(rewriter);
if (auto remapped = rewriter.getRemappedValue(value)) {
setInsertionPoint(remapped);
observeValues.push_back(probeIfSignal(remapped));
} else {
setInsertionPoint(value);
auto type = typeConverter->convertType(value.getType());
auto converted = typeConverter->materializeTargetConversion(
rewriter, loc, type, value);
observeValues.push_back(probeIfSignal(converted));
}
}
});
}
struct ProcedureOpConversion : public OpConversionPattern<ProcedureOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(ProcedureOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
// Collect values to observe before we do any modifications to the region.
SmallVector<Value> observedValues;
if (op.getKind() == ProcedureKind::AlwaysComb ||
op.getKind() == ProcedureKind::AlwaysLatch) {
auto setInsertionPoint = [&](Value value) {
rewriter.setInsertionPoint(op);
};
getValuesToObserve(&op.getBody(), setInsertionPoint, typeConverter,
rewriter, observedValues);
}
auto loc = op.getLoc();
if (failed(rewriter.convertRegionTypes(&op.getBody(), *typeConverter)))
return failure();
// Handle initial and final procedures. These lower to a corresponding
// `llhd.process` or `llhd.final` op that executes the body and then halts.
if (op.getKind() == ProcedureKind::Initial ||
op.getKind() == ProcedureKind::Final) {
Operation *newOp;
if (op.getKind() == ProcedureKind::Initial)
newOp = llhd::ProcessOp::create(rewriter, loc, TypeRange{});
else
newOp = llhd::FinalOp::create(rewriter, loc);
auto &body = newOp->getRegion(0);
rewriter.inlineRegionBefore(op.getBody(), body, body.end());
for (auto returnOp :
llvm::make_early_inc_range(body.getOps<ReturnOp>())) {
rewriter.setInsertionPoint(returnOp);
rewriter.replaceOpWithNewOp<llhd::HaltOp>(returnOp, ValueRange{});
}
rewriter.eraseOp(op);
return success();
}
// All other procedures lower to a an `llhd.process`.
auto newOp = llhd::ProcessOp::create(rewriter, loc, TypeRange{});
// We need to add an empty entry block because it is not allowed in MLIR to
// branch back to the entry block. Instead we put the logic in the second
// block and branch to that.
rewriter.createBlock(&newOp.getBody());
auto *block = &op.getBody().front();
cf::BranchOp::create(rewriter, loc, block);
rewriter.inlineRegionBefore(op.getBody(), newOp.getBody(),
newOp.getBody().end());
// Add special handling for `always_comb` and `always_latch` procedures.
// These run once at simulation startup and then implicitly wait for any of
// the values they access to change before running again. To implement this,
// we create another basic block that contains the implicit wait, and make
// all `moore.return` ops branch to that wait block instead of immediately
// jumping back up to the body.
if (op.getKind() == ProcedureKind::AlwaysComb ||
op.getKind() == ProcedureKind::AlwaysLatch) {
Block *waitBlock = rewriter.createBlock(&newOp.getBody());
llhd::WaitOp::create(rewriter, loc, ValueRange{}, Value(), observedValues,
ValueRange{}, block);
block = waitBlock;
}
// Make all `moore.return` ops branch back up to the beginning of the
// process, or the wait block created above for `always_comb` and
// `always_latch` procedures.
for (auto returnOp : llvm::make_early_inc_range(newOp.getOps<ReturnOp>())) {
rewriter.setInsertionPoint(returnOp);
cf::BranchOp::create(rewriter, loc, block);
rewriter.eraseOp(returnOp);
}
rewriter.eraseOp(op);
return success();
}
};
//===----------------------------------------------------------------------===//
// Coroutine Conversion
//===----------------------------------------------------------------------===//
struct CoroutineOpConversion : public OpConversionPattern<CoroutineOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(CoroutineOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto funcType = op.getFunctionType();
TypeConverter::SignatureConversion sigConversion(funcType.getNumInputs());
for (auto [i, type] : llvm::enumerate(funcType.getInputs())) {
auto converted = typeConverter->convertType(type);
if (!converted)
return failure();
sigConversion.addInputs(i, converted);
}
SmallVector<Type> resultTypes;
if (failed(typeConverter->convertTypes(funcType.getResults(), resultTypes)))
return failure();
auto newFuncType = FunctionType::get(
rewriter.getContext(), sigConversion.getConvertedTypes(), resultTypes);
auto newOp = llhd::CoroutineOp::create(rewriter, op.getLoc(),
op.getSymName(), newFuncType);
newOp.setSymVisibilityAttr(op.getSymVisibilityAttr());
rewriter.inlineRegionBefore(op.getBody(), newOp.getBody(),
newOp.getBody().end());
if (failed(rewriter.convertRegionTypes(&newOp.getBody(), *typeConverter,
&sigConversion)))
return failure();
// Replace moore.return with llhd.return inside the coroutine body.
for (auto returnOp :
llvm::make_early_inc_range(newOp.getBody().getOps<ReturnOp>())) {
rewriter.setInsertionPoint(returnOp);
rewriter.replaceOpWithNewOp<llhd::ReturnOp>(returnOp, ValueRange{});
}
rewriter.eraseOp(op);
return success();
}
};
struct CallCoroutineOpConversion : public OpConversionPattern<CallCoroutineOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(CallCoroutineOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
SmallVector<Type> convResTypes;
if (failed(typeConverter->convertTypes(op.getResultTypes(), convResTypes)))
return failure();
rewriter.replaceOpWithNewOp<llhd::CallCoroutineOp>(
op, convResTypes, adaptor.getCallee(), adaptor.getOperands());
return success();
}
};
struct WaitEventOpConversion : public OpConversionPattern<WaitEventOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(WaitEventOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
// In order to convert the `wait_event` op we need to create three separate
// blocks at the location of the op:
//
// - A "wait" block that reads the current state of any values used to
// detect events and then waits until any of those values change. When a
// change occurs, control transfers to the "check" block.
// - A "check" block which is executed after any interesting signal has
// changed. This is where any `detect_event` ops read the current state of
// interesting values and compare them against their state before the wait
// in order to detect an event. If any events were detected, control
// transfers to the "resume" block; otherwise control goes back to the
// "wait" block.
// - A "resume" block which holds any ops after the `wait_event` op. This is
// where control is expected to resume after an event has happened.
//
// Block structure before:
// opA
// moore.wait_event { ... }
// opB
//
// Block structure after:
// opA
// cf.br ^wait
// ^wait:
// <read "before" values>
// llhd.wait ^check, ...
// ^check:
// <read "after" values>
// <detect edges>
// cf.cond_br %event, ^resume, ^wait
// ^resume:
// opB
auto *resumeBlock =
rewriter.splitBlock(op->getBlock(), ++Block::iterator(op));
// If the 'wait_event' op is empty, we can lower it to a 'llhd.wait' op
// without any observed values, but since the process will never wake up
// from suspension anyway, we can also just terminate it using the
// 'llhd.halt' op.
if (op.getBody().front().empty()) {
// Let the cleanup iteration after the dialect conversion clean up all
// remaining unreachable blocks.
rewriter.replaceOpWithNewOp<llhd::HaltOp>(op, ValueRange{});
return success();
}
auto *waitBlock = rewriter.createBlock(resumeBlock);
auto *checkBlock = rewriter.createBlock(resumeBlock);
auto loc = op.getLoc();
rewriter.setInsertionPoint(op);
cf::BranchOp::create(rewriter, loc, waitBlock);
// We need to inline two copies of the `wait_event`'s body region: one is
// used to determine the values going into `detect_event` ops before the
// `llhd.wait`, and one will do the actual event detection after the
// `llhd.wait`.
//
// Create a copy of the entire `wait_event` op in the wait block, which also
// creates a copy of its region. Take note of all inputs to `detect_event`
// ops and delete the `detect_event` ops in this copy.
SmallVector<Value> valuesBefore;
rewriter.setInsertionPointToEnd(waitBlock);
auto clonedOp = cast<WaitEventOp>(rewriter.clone(*op));
bool allDetectsAreAnyChange = true;
for (auto detectOp :
llvm::make_early_inc_range(clonedOp.getOps<DetectEventOp>())) {
if (detectOp.getEdge() != Edge::AnyChange || detectOp.getCondition())
allDetectsAreAnyChange = false;
valuesBefore.push_back(detectOp.getInput());
rewriter.eraseOp(detectOp);
}
// Determine the values used during event detection that are defined outside
// the `wait_event`'s body region. We want to wait for a change on these
// signals before we check if any interesting event happened.
SmallVector<Value> observeValues;
auto setInsertionPointAfterDef = [&](Value value) {
if (auto *op = value.getDefiningOp())
rewriter.setInsertionPointAfter(op);
if (auto arg = dyn_cast<BlockArgument>(value))
rewriter.setInsertionPointToStart(value.getParentBlock());
};
getValuesToObserve(&clonedOp.getBody(), setInsertionPointAfterDef,
typeConverter, rewriter, observeValues);
// Create the `llhd.wait` op that suspends the current process and waits for
// a change in the interesting values listed in `observeValues`. When a
// change is detected, execution resumes in the "check" block.
auto waitOp = llhd::WaitOp::create(rewriter, loc, ValueRange{}, Value(),
observeValues, ValueRange{}, checkBlock);
rewriter.inlineBlockBefore(&clonedOp.getBody().front(), waitOp);
rewriter.eraseOp(clonedOp);
// Collect a list of all detect ops and inline the `wait_event` body into
// the check block.
SmallVector<DetectEventOp> detectOps(op.getBody().getOps<DetectEventOp>());
rewriter.inlineBlockBefore(&op.getBody().front(), checkBlock,
checkBlock->end());
rewriter.eraseOp(op);
// Helper function to detect if a certain change occurred between a value
// before the `llhd.wait` and after.
auto computeTrigger = [&](Value before, Value after, Edge edge) -> Value {
assert(before.getType() == after.getType() &&
"mismatched types after clone op");
auto beforeType = cast<IntType>(before.getType());
// 9.4.2 IEEE 1800-2017: An edge event shall be detected only on the LSB
// of the expression
if (beforeType.getWidth() != 1 && edge != Edge::AnyChange) {
constexpr int LSB = 0;
beforeType =
IntType::get(rewriter.getContext(), 1, beforeType.getDomain());
before =
moore::ExtractOp::create(rewriter, loc, beforeType, before, LSB);
after = moore::ExtractOp::create(rewriter, loc, beforeType, after, LSB);
}
auto intType = rewriter.getIntegerType(beforeType.getWidth());
before = typeConverter->materializeTargetConversion(rewriter, loc,
intType, before);
after = typeConverter->materializeTargetConversion(rewriter, loc, intType,
after);
if (edge == Edge::AnyChange)
return comb::ICmpOp::create(rewriter, loc, ICmpPredicate::ne, before,
after, true);
SmallVector<Value> disjuncts;
Value trueVal = hw::ConstantOp::create(rewriter, loc, APInt(1, 1));
if (edge == Edge::PosEdge || edge == Edge::BothEdges) {
Value notOldVal =
comb::XorOp::create(rewriter, loc, before, trueVal, true);
Value posedge =
comb::AndOp::create(rewriter, loc, notOldVal, after, true);
disjuncts.push_back(posedge);
}
if (edge == Edge::NegEdge || edge == Edge::BothEdges) {
Value notCurrVal =
comb::XorOp::create(rewriter, loc, after, trueVal, true);
Value posedge =
comb::AndOp::create(rewriter, loc, before, notCurrVal, true);
disjuncts.push_back(posedge);
}
return rewriter.createOrFold<comb::OrOp>(loc, disjuncts, true);
};
// Convert all `detect_event` ops into a check for the corresponding event
// between the value before and after the `llhd.wait`. The "before" value
// has been collected into `valuesBefore` in the "wait" block; the "after"
// value corresponds to the detect op's input.
SmallVector<Value> triggers;
for (auto [detectOp, before] : llvm::zip(detectOps, valuesBefore)) {
if (!allDetectsAreAnyChange) {
if (!isa<IntType>(before.getType()))
return detectOp->emitError() << "requires int operand";
rewriter.setInsertionPoint(detectOp);
auto trigger =
computeTrigger(before, detectOp.getInput(), detectOp.getEdge());
if (detectOp.getCondition()) {
auto condition = typeConverter->materializeTargetConversion(
rewriter, loc, rewriter.getI1Type(), detectOp.getCondition());
trigger =
comb::AndOp::create(rewriter, loc, trigger, condition, true);
}
triggers.push_back(trigger);
}
rewriter.eraseOp(detectOp);
}
rewriter.setInsertionPointToEnd(checkBlock);
if (triggers.empty()) {
// If there are no triggers to check, we always branch to the resume
// block. If there are no detect_event operations in the wait event, the
// 'llhd.wait' operation will not have any observed values and thus the
// process will hang there forever.
cf::BranchOp::create(rewriter, loc, resumeBlock);
} else {
// If any `detect_event` op detected an event, branch to the "resume"
// block which contains any code after the `wait_event` op. If no events
// were detected, branch back to the "wait" block to wait for the next
// change on the interesting signals.
auto triggered = rewriter.createOrFold<comb::OrOp>(loc, triggers, true);
cf::CondBranchOp::create(rewriter, loc, triggered, resumeBlock,
waitBlock);
}
return success();
}
};
// moore.wait_delay -> llhd.wait
static LogicalResult convert(WaitDelayOp op, WaitDelayOp::Adaptor adaptor,
ConversionPatternRewriter &rewriter) {
auto *resumeBlock =
rewriter.splitBlock(op->getBlock(), ++Block::iterator(op));
rewriter.setInsertionPoint(op);
rewriter.replaceOpWithNewOp<llhd::WaitOp>(op, ValueRange{},
adaptor.getDelay(), ValueRange{},
ValueRange{}, resumeBlock);
rewriter.setInsertionPointToStart(resumeBlock);
return success();
}
// moore.unreachable -> llhd.halt
static LogicalResult convert(UnreachableOp op, UnreachableOp::Adaptor adaptor,
ConversionPatternRewriter &rewriter) {
rewriter.replaceOpWithNewOp<llhd::HaltOp>(op, ValueRange{});
return success();
}
//===----------------------------------------------------------------------===//
// Declaration Conversion
//===----------------------------------------------------------------------===//
static Value createZeroValue(Type type, Location loc,
ConversionPatternRewriter &rewriter) {
// Handle pointers.
if (isa<mlir::LLVM::LLVMPointerType>(type))
return mlir::LLVM::ZeroOp::create(rewriter, loc, type);
// Handle time values.
if (isa<llhd::TimeType>(type)) {
auto timeAttr =
llhd::TimeAttr::get(type.getContext(), 0U, llvm::StringRef("ns"), 0, 0);
return llhd::ConstantTimeOp::create(rewriter, loc, timeAttr);
}
// Handle real values.
if (auto floatType = dyn_cast<FloatType>(type)) {
auto floatAttr = rewriter.getFloatAttr(floatType, 0.0);
return mlir::arith::ConstantOp::create(rewriter, loc, floatAttr);
}
// Handle dynamic strings
if (auto strType = dyn_cast<sim::DynamicStringType>(type))
return sim::StringConstantOp::create(rewriter, loc, strType, "");
// Handle queues
if (auto queueType = dyn_cast<sim::QueueType>(type))
return sim::QueueEmptyOp::create(rewriter, loc, queueType);
// Otherwise try to create a zero integer and bitcast it to the result type.
int64_t width = hw::getBitWidth(type);
if (width == -1)
return {};
// TODO: Once the core dialects support four-valued integers, this code
// will additionally need to generate an all-X value for four-valued
// variables.
Value constZero = hw::ConstantOp::create(rewriter, loc, APInt(width, 0));
return rewriter.createOrFold<hw::BitcastOp>(loc, type, constZero);
}
struct ClassPropertyRefOpConversion
: public OpConversionPattern<circt::moore::ClassPropertyRefOp> {
ClassPropertyRefOpConversion(TypeConverter &tc, MLIRContext *ctx,
ClassTypeCache &cache)
: OpConversionPattern(tc, ctx), cache(cache) {}
LogicalResult
matchAndRewrite(circt::moore::ClassPropertyRefOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
Location loc = op.getLoc();
MLIRContext *ctx = rewriter.getContext();
// Convert result type; we expect !llhd.ref<someT>.
Type dstTy = getTypeConverter()->convertType(op.getPropertyRef().getType());
// Operand is a !llvm.ptr
Value instRef = adaptor.getInstance();
// Resolve identified struct from cache.
auto classRefTy =
cast<circt::moore::ClassHandleType>(op.getInstance().getType());
SymbolRefAttr classSym = classRefTy.getClassSym();
ModuleOp mod = op->getParentOfType<ModuleOp>();
if (failed(resolveClassStructBody(mod, classSym, *typeConverter, cache)))
return rewriter.notifyMatchFailure(op,
"Could not resolve class struct for " +
classSym.getRootReference().str());
auto structInfo = cache.getStructInfo(classSym);
assert(structInfo && "class struct info must exist");
auto structTy = structInfo->classBody;
// Look up cached GEP path for the property.
auto propSym = op.getProperty();
auto pathOpt = structInfo->getFieldPath(propSym);
if (!pathOpt)
return rewriter.notifyMatchFailure(op,
"no GEP path for property " + propSym);
auto i32Ty = IntegerType::get(ctx, 32);
SmallVector<Value> idxVals;
for (unsigned idx : *pathOpt)
idxVals.push_back(LLVM::ConstantOp::create(
rewriter, loc, i32Ty, rewriter.getI32IntegerAttr(idx)));
// GEP to the field (opaque ptr mode requires element type).
auto ptrTy = LLVM::LLVMPointerType::get(ctx);
auto gep =
LLVM::GEPOp::create(rewriter, loc, ptrTy, structTy, instRef, idxVals);
// Wrap pointer back to !llhd.ref<someT>.
Value fieldRef = UnrealizedConversionCastOp::create(rewriter, loc, dstTy,
gep.getResult())
.getResult(0);
rewriter.replaceOp(op, fieldRef);
return success();
}
private:
ClassTypeCache &cache;
};
struct ClassUpcastOpConversion : public OpConversionPattern<ClassUpcastOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(ClassUpcastOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
// Expect lowered types like !llvm.ptr
Type dstTy = getTypeConverter()->convertType(op.getResult().getType());
Type srcTy = adaptor.getInstance().getType();
if (!dstTy)
return rewriter.notifyMatchFailure(op, "failed to convert result type");
// If the types are already identical (opaque pointer mode), just forward.
if (dstTy == srcTy && isa<LLVM::LLVMPointerType>(srcTy)) {
rewriter.replaceOp(op, adaptor.getInstance());
return success();
}
return rewriter.notifyMatchFailure(
op, "Upcast applied to non-opaque pointers!");
}
};
/// moore.class.new lowering: heap-allocate storage for the class object.
struct ClassNewOpConversion : public OpConversionPattern<ClassNewOp> {
ClassNewOpConversion(TypeConverter &tc, MLIRContext *ctx,
ClassTypeCache &cache)
: OpConversionPattern<ClassNewOp>(tc, ctx), cache(cache) {}
LogicalResult
matchAndRewrite(ClassNewOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
Location loc = op.getLoc();
MLIRContext *ctx = rewriter.getContext();
auto handleTy = cast<ClassHandleType>(op.getResult().getType());
auto sym = handleTy.getClassSym();
ModuleOp mod = op->getParentOfType<ModuleOp>();
if (failed(resolveClassStructBody(mod, sym, *typeConverter, cache)))
return op.emitError() << "Could not resolve class struct for " << sym;
auto structTy = cache.getStructInfo(sym)->classBody;
// Check that all struct members have data layout support. Types like
// !sim.dstring or !sim.queue don't have a known size, which would cause
// a fatal error in DataLayout::getTypeSize below.
for (auto memberTy : structTy.getBody()) {
if (!LLVM::isCompatibleType(memberTy) &&
!memberTy.hasTrait<DataLayoutTypeInterface::Trait>()) {
return op.emitError()
<< "class struct has member types with no data layout";
}
}
DataLayout dl(mod);
// DataLayout::getTypeSize gives a byte count for LLVM types.
uint64_t byteSize = dl.getTypeSize(structTy);
auto i64Ty = IntegerType::get(ctx, 64);
auto cSize = LLVM::ConstantOp::create(rewriter, loc, i64Ty,
rewriter.getI64IntegerAttr(byteSize));
// Get or declare malloc and call it.
auto mallocFn = getOrCreateMalloc(mod, rewriter);
auto ptrTy = LLVM::LLVMPointerType::get(ctx); // opaque pointer result
auto call =
LLVM::CallOp::create(rewriter, loc, TypeRange{ptrTy},
SymbolRefAttr::get(mallocFn), ValueRange{cSize});
// Replace the new op with the malloc pointer (no cast needed with opaque
// ptrs).
rewriter.replaceOp(op, call.getResult());
return success();
}
private:
ClassTypeCache &cache; // shared, owned by the pass
};
struct ClassDeclOpConversion : public OpConversionPattern<ClassDeclOp> {
ClassDeclOpConversion(TypeConverter &tc, MLIRContext *ctx,
ClassTypeCache &cache)
: OpConversionPattern<ClassDeclOp>(tc, ctx), cache(cache) {}
LogicalResult
matchAndRewrite(ClassDeclOp op, OpAdaptor,
ConversionPatternRewriter &rewriter) const override {
if (failed(resolveClassStructBody(op, *typeConverter, cache)))
return failure();
// The declaration itself is a no-op
rewriter.eraseOp(op);