-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathHandshakeOps.cpp
More file actions
1988 lines (1714 loc) · 73.4 KB
/
HandshakeOps.cpp
File metadata and controls
1988 lines (1714 loc) · 73.4 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
//===- HandshakeOps.cpp - Handshake operations ------------------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file originates from the CIRCT project (https://github.com/llvm/circt).
// It includes modifications made as part of Dynamatic.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the Handshake operations struct.
//
//===----------------------------------------------------------------------===//
#include "dynamatic/Dialect/Handshake/HandshakeOps.h"
#include "dynamatic/Dialect/Handshake/HandshakeAttributes.h"
#include "dynamatic/Dialect/Handshake/HandshakeDialect.h"
#include "dynamatic/Dialect/Handshake/HandshakeInterfaces.h"
#include "dynamatic/Dialect/Handshake/HandshakeTypes.h"
#include "dynamatic/Support/CFG.h"
#include "dynamatic/Support/LLVM.h"
#include "dynamatic/Support/Utils/Utils.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinAttributeInterfaces.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/IR/OpDefinition.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/Value.h"
#include "mlir/IR/ValueRange.h"
#include "mlir/Interfaces/FunctionImplementation.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/InliningUtils.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>
using namespace mlir;
using namespace dynamatic;
using namespace dynamatic::handshake;
static ParseResult parseHandshakeType(OpAsmParser &parser, Type &type) {
return parser.parseCustomTypeWithFallback(type, [&](Type &ty) -> ParseResult {
if ((ty = handshake::detail::jointHandshakeTypeParser(parser)))
return success();
return failure();
});
}
static ParseResult parseHandshakeTypes(OpAsmParser &parser,
SmallVectorImpl<Type> &types) {
do {
if (parseHandshakeType(parser, types.emplace_back()))
return failure();
} while (!parser.parseOptionalComma());
return success();
}
/// Parser for the `custom<SimpleControl>` Tablegen directive.
static ParseResult parseSimpleControl(OpAsmParser &parser, Type &type) {
// No parsing needed.
// Make ControlType without any extra signals
type = ControlType::get(parser.getContext());
return success();
}
static void printHandshakeType(OpAsmPrinter &printer, Operation * /*op*/,
Type type) {
if (auto controlType = dyn_cast<handshake::ControlType>(type)) {
controlType.print(printer);
} else if (auto channelType = dyn_cast<handshake::ChannelType>(type)) {
channelType.print(printer);
} else {
llvm_unreachable("not a handshake type");
}
}
static void printHandshakeTypes(OpAsmPrinter &printer, Operation * /*op*/,
TypeRange types) {
if (types.empty())
return;
for (Type ty : types.drop_back()) {
printHandshakeType(printer, nullptr, ty);
printer << ", ";
}
printHandshakeType(printer, nullptr, types.back());
}
/// Printer for the `custom<SimpleControl>` Tablegen directive.
static void printSimpleControl(OpAsmPrinter &, Operation *, Type) {
// No printing needed.
}
static void printHandshakeType(OpAsmPrinter &printer, Type type) {
printHandshakeType(printer, nullptr, type);
}
static ParseResult parseSingleTypedHandshakeOp(
OpAsmParser &parser, OpAsmParser::UnresolvedOperand &operand,
NamedAttrList &attributes, Type &type, SmallVectorImpl<Type> &resTypes) {
// Parse the operation's size between square brackets
unsigned size;
if (parser.parseLSquare() || parser.parseInteger(size) ||
parser.parseRSquare())
return failure();
// Parse the single operand and attribute dictionnary
if (parser.parseOperand(operand) || parser.parseOptionalAttrDict(attributes))
return failure();
// Parse the single handshake type common to all operands and results
if (parser.parseColon() || parseHandshakeType(parser, type))
return failure();
resTypes.assign(size, type);
return success();
}
static void printSingleTypedHandshakeOp(OpAsmPrinter &printer, Operation *op,
Value operand,
DictionaryAttr attributes, Type type,
TypeRange resTypes) {
printer << "[" << resTypes.size() << "] " << operand;
printer.printOptionalAttrDict(attributes.getValue());
printer << " : ";
printHandshakeType(printer, type);
}
/// Verifies whether an indexing value is wide enough to index into a provided
/// number of operands.
static LogicalResult verifyIndexWideEnough(Operation *op, Value indexVal,
uint64_t numOperands) {
auto idxType = dyn_cast<handshake::ChannelType>(indexVal.getType());
if (!idxType) {
return op->emitError() << "expected index value to be of type "
"handshake::ChannelType, but got "
<< indexVal.getType();
}
unsigned idxWidth = idxType.getDataBitWidth();
// Check whether the bitwidth can support the provided number of operands
if (idxWidth < 64) {
uint64_t maxNumOperands = (uint64_t)1 << idxWidth;
if (numOperands > maxNumOperands) {
return op->emitError()
<< "bitwidth of indexing value is " << idxWidth
<< ", which can index into " << maxNumOperands
<< " operands, but found " << numOperands << " operands";
}
}
return success();
}
static bool isControlCheckTypeAndOperand(Type dataType, Value operand) {
// The operation is a control operation if its operand data type is a
// control-only channel
if (isa<handshake::ControlType>(dataType))
return true;
// Otherwise, the operation is a control operation if the operation's
// operand originates from the control network
auto *defOp = operand.getDefiningOp();
return isa_and_nonnull<ControlMergeOp>(defOp) &&
operand == defOp->getResult(0);
}
IntegerType
dynamatic::handshake::getOptimizedIndexValType(OpBuilder &builder,
unsigned numToIndex) {
return builder.getIntegerType(std::max(
1U, APInt(APInt::APINT_BITS_PER_WORD, numToIndex).ceilLogBase2()));
}
//===----------------------------------------------------------------------===//
// TableGen'd canonicalization patterns
//===----------------------------------------------------------------------===//
static unsigned getDataBitWidth(Value val) {
return cast<handshake::ChannelType>(val.getType()).getDataBitWidth();
}
static IntegerAttr constantFoldExt(Operation *op, Attribute attr) {
auto integerAttr = cast<IntegerAttr>(attr);
if (auto extUI = dyn_cast<ExtUIOp>(op))
return IntegerAttr::get(
extUI.getType().getDataType(),
integerAttr.getValue().zext(extUI.getType().getDataBitWidth()));
if (auto extSI = dyn_cast<ExtSIOp>(op))
return IntegerAttr::get(
extSI.getType().getDataType(),
integerAttr.getValue().sext(extSI.getType().getDataBitWidth()));
llvm_unreachable("only expected extui and extsi");
}
namespace {
#include "lib/Dialect/Handshake/HandshakeCanonicalization.inc"
} // namespace
//===----------------------------------------------------------------------===//
// MergeOp
//===----------------------------------------------------------------------===//
OpResult MergeOp::getDataResult() { return cast<OpResult>(getResult()); }
//===----------------------------------------------------------------------===//
// MuxOp
//===----------------------------------------------------------------------===//
bool MuxOp::isControl() {
return isa<handshake::ControlType>(getResult().getType());
}
ParseResult MuxOp::parse(OpAsmParser &parser, OperationState &result) {
OpAsmParser::UnresolvedOperand selectOperand;
SmallVector<OpAsmParser::UnresolvedOperand, 4> dataOperands;
handshake::ChannelType selectType;
llvm::SMLoc allOperandLoc = parser.getCurrentLocation();
// Parse until the type of the select operand
if (parser.parseOperand(selectOperand) || parser.parseLSquare() ||
parser.parseOperandList(dataOperands) || parser.parseRSquare() ||
parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
parser.parseCustomTypeWithFallback(selectType) || parser.parseComma() ||
parser.parseLSquare())
return failure();
int numDataOperands = dataOperands.size();
// Parse the data operands types
SmallVector<Type> dataOperandsTypes(numDataOperands);
for (int i = 0; i < numDataOperands; i++) {
if (i > 0) {
if (parser.parseComma())
return failure();
}
if (parseHandshakeType(parser, dataOperandsTypes[i]))
return failure();
}
// Parse the result type
Type resultType;
if (parser.parseRSquare() || parser.parseKeyword("to") ||
parseHandshakeType(parser, resultType))
return failure();
result.addTypes(resultType);
// Fill the result.operands
return parser.resolveOperands(
llvm::concat<const OpAsmParser::UnresolvedOperand>(
ArrayRef<OpAsmParser::UnresolvedOperand>(selectOperand),
dataOperands),
llvm::concat<const Type>(ArrayRef<Type>(selectType), dataOperandsTypes),
allOperandLoc, result.operands);
}
void MuxOp::print(OpAsmPrinter &p) {
OperandRange operands = getOperands();
p << ' ' << operands.front();
p << " [";
p.printOperands(operands.drop_front());
p << "]";
p.printOptionalAttrDict((*this)->getAttrs());
p << " : ";
p.printStrippedAttrOrType(getSelectOperand().getType());
p << ", [";
int i = 0;
for (auto op : getDataOperands()) {
if (i > 0) {
p << ", ";
}
printHandshakeType(p, op.getType());
i++;
}
p << "] to ";
printHandshakeType(p, getResult().getType());
}
LogicalResult MuxOp::verify() {
return verifyIndexWideEnough(*this, getSelectOperand(),
getDataOperands().size());
}
OpResult MuxOp::getDataResult() { return cast<OpResult>(getResult()); }
//===----------------------------------------------------------------------===//
// ControlMergeOp
//===----------------------------------------------------------------------===//
ParseResult ControlMergeOp::parse(OpAsmParser &parser, OperationState &result) {
SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
llvm::SMLoc allOperandLoc = parser.getCurrentLocation();
// Parse until just before the operand types
if (parser.parseLSquare() || parser.parseOperandList(operands) ||
parser.parseRSquare() ||
parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
parser.parseLSquare())
return failure();
int numOperands = operands.size();
// Parse the operand types
SmallVector<Type> operandTypes(numOperands);
for (int i = 0; i < numOperands; i++) {
if (i > 0) {
if (parser.parseComma())
return failure();
}
if (parseHandshakeType(parser, operandTypes[i]))
return failure();
}
// Parse the return data type
Type resultDataType;
if (parser.parseRSquare() || parser.parseKeyword("to") ||
parseHandshakeType(parser, resultDataType))
return failure();
handshake::ChannelType indexType;
// Parse the index type
if (parser.parseComma() || parser.parseCustomTypeWithFallback(indexType))
return failure();
// Register the result types
result.addTypes({resultDataType, indexType});
// Fill the result.operands
return parser.resolveOperands(operands, operandTypes, allOperandLoc,
result.operands);
}
void ControlMergeOp::print(OpAsmPrinter &p) {
p << " [" << getOperands() << "] ";
p.printOptionalAttrDict((*this)->getAttrs());
p << " : [";
int i = 0;
for (auto op : getOperands()) {
if (i > 0) {
p << ", ";
}
printHandshakeType(p, op.getType());
i++;
}
p << "] to ";
printHandshakeType(p, getResult().getType());
p << ", ";
p.printStrippedAttrOrType(getIndex().getType());
}
LogicalResult ControlMergeOp::verify() {
return verifyIndexWideEnough(*this, getIndex(), getNumOperands());
}
OpResult ControlMergeOp::getDataResult() { return cast<OpResult>(getResult()); }
LogicalResult FuncOp::verify() {
// If this function is external there is nothing to do.
if (isExternal())
return success();
// Verify that the argument list of the function and the arg list of the
// entry block line up. The trait already verified that the number of
// arguments is the same between the signature and the block.
auto fnInputTypes = getArgumentTypes();
Block &entryBlock = front();
for (unsigned i = 0, e = entryBlock.getNumArguments(); i != e; ++i)
if (fnInputTypes[i] != entryBlock.getArgument(i).getType())
return emitOpError("type of entry block argument #")
<< i << '(' << entryBlock.getArgument(i).getType()
<< ") must match the type of the corresponding argument in "
<< "function signature(" << fnInputTypes[i] << ')';
// Verify that we have a name for each argument and result of this function.
auto verifyPortNameAttr = [&](StringRef attrName,
unsigned numIOs) -> LogicalResult {
auto portNamesAttr = (*this)->getAttrOfType<ArrayAttr>(attrName);
if (!portNamesAttr)
return emitOpError() << "expected attribute '" << attrName << "'.";
auto portNames = portNamesAttr.getValue();
if (portNames.size() != numIOs)
return emitOpError() << "attribute '" << attrName << "' has "
<< portNames.size()
<< " entries but is expected to have " << numIOs
<< ".";
if (llvm::any_of(portNames,
[&](Attribute attr) { return !attr.isa<StringAttr>(); }))
return emitOpError() << "expected all entries in attribute '" << attrName
<< "' to be strings.";
return success();
};
if (failed(verifyPortNameAttr("argNames", getNumArguments())))
return failure();
if (failed(verifyPortNameAttr("resNames", getNumResults())))
return failure();
return success();
}
LogicalResult BufferOp::verify() {
// this is additional verification
// so both attributes have already been verified as present
int numSlots = getNumSlots();
BufferType bufferType = getBufferType();
if ((bufferType == BufferType::ONE_SLOT_BREAK_DV ||
bufferType == BufferType::ONE_SLOT_BREAK_R ||
bufferType == BufferType::ONE_SLOT_BREAK_DVR) &&
numSlots != 1) {
return emitOpError("buffer type '")
<< stringifyEnum(bufferType) << "' requires NUM_SLOTS = 1, but got "
<< numSlots;
}
return success();
}
/// Parses a FuncOp signature using
/// mlir::function_interface_impl::parseFunctionSignature while getting access
/// to the parsed SSA names to store as attributes.
static ParseResult
parseFuncOpArgs(OpAsmParser &parser,
SmallVectorImpl<OpAsmParser::Argument> &entryArgs,
SmallVectorImpl<Type> &resTypes,
SmallVectorImpl<DictionaryAttr> &resAttrs) {
bool isVariadic;
if (mlir::function_interface_impl::parseFunctionSignature(
parser, /*allowVariadic=*/true, entryArgs, isVariadic, resTypes,
resAttrs)
.failed())
return failure();
return success();
}
/// Generates names for a handshake.func input and output arguments, based on
/// the number of args as well as a prefix.
static SmallVector<Attribute> getFuncOpNames(Builder &builder, unsigned cnt,
StringRef prefix) {
SmallVector<Attribute> resNames;
for (unsigned i = 0; i < cnt; ++i)
resNames.push_back(builder.getStringAttr(prefix + std::to_string(i)));
return resNames;
}
void handshake::FuncOp::build(OpBuilder &builder, OperationState &state,
StringRef name, FunctionType type,
ArrayRef<NamedAttribute> attrs) {
state.addAttribute(SymbolTable::getSymbolAttrName(),
builder.getStringAttr(name));
state.addAttribute(FuncOp::getFunctionTypeAttrName(state.name),
TypeAttr::get(type));
state.attributes.append(attrs.begin(), attrs.end());
if (const auto *argNamesAttrIt = llvm::find_if(
attrs, [&](auto attr) { return attr.getName() == "argNames"; });
argNamesAttrIt == attrs.end())
state.addAttribute("argNames", builder.getArrayAttr({}));
if (llvm::find_if(attrs, [&](auto attr) {
return attr.getName() == "resNames";
}) == attrs.end())
state.addAttribute("resNames", builder.getArrayAttr({}));
state.addRegion();
}
ParseResult FuncOp::parse(OpAsmParser &parser, OperationState &result) {
auto &builder = parser.getBuilder();
StringAttr nameAttr;
SmallVector<OpAsmParser::Argument> args;
SmallVector<Type> resTypes;
SmallVector<DictionaryAttr> resAttributes;
SmallVector<Attribute> argNames;
// Parse visibility.
(void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
// Parse signature
if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
result.attributes) ||
parseFuncOpArgs(parser, args, resTypes, resAttributes))
return failure();
mlir::function_interface_impl::addArgAndResultAttrs(
builder, result, args, resAttributes,
handshake::FuncOp::getArgAttrsAttrName(result.name),
handshake::FuncOp::getResAttrsAttrName(result.name));
// Set function type
SmallVector<Type> argTypes;
for (auto arg : args)
argTypes.push_back(arg.type);
result.addAttribute(
handshake::FuncOp::getFunctionTypeAttrName(result.name),
TypeAttr::get(builder.getFunctionType(argTypes, resTypes)));
// Determine the names of the arguments. If no SSA values are present, use
// fallback names.
bool noSSANames =
llvm::any_of(args, [](auto arg) { return arg.ssaName.name.empty(); });
if (noSSANames) {
argNames = getFuncOpNames(builder, args.size(), "in");
} else {
llvm::transform(args, std::back_inserter(argNames), [&](auto arg) {
return builder.getStringAttr(arg.ssaName.name.drop_front());
});
}
// Parse attributes
if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
return failure();
// If argNames and resNames wasn't provided manually, infer argNames attribute
// from the parsed SSA names and resNames from our naming convention.
if (!result.attributes.get("argNames"))
result.addAttribute("argNames", builder.getArrayAttr(argNames));
if (!result.attributes.get("resNames")) {
auto resNames = getFuncOpNames(builder, resTypes.size(), "out");
result.addAttribute("resNames", builder.getArrayAttr(resNames));
}
// Parse the optional function body. The printer will not print the body if
// its empty, so disallow parsing of empty body in the parser.
auto *body = result.addRegion();
llvm::SMLoc loc = parser.getCurrentLocation();
auto parseResult = parser.parseOptionalRegion(*body, args,
/*enableNameShadowing=*/false);
if (!parseResult.has_value())
return success();
if (failed(*parseResult))
return failure();
// Function body was parsed, make sure its not empty.
if (body->empty())
return parser.emitError(loc, "expected non-empty function body");
// If a body was parsed, the arg and res names need to be resolved
return success();
}
void FuncOp::print(OpAsmPrinter &p) {
mlir::function_interface_impl::printFunctionOp(
p, *this, /*isVariadic=*/true, getFunctionTypeAttrName(),
getArgAttrsAttrName(), getResAttrsAttrName());
}
bool ConditionalBranchOp::isControl() {
return isControlCheckTypeAndOperand(getDataOperand().getType(),
getDataOperand());
}
LogicalResult ConstantOp::inferReturnTypes(
MLIRContext *context, std::optional<Location> location, ValueRange operands,
DictionaryAttr attributes, mlir::OpaqueProperties properties,
mlir::RegionRange regions,
SmallVectorImpl<mlir::Type> &inferredReturnTypes) {
OperationName opName = OperationName(getOperationName(), context);
StringAttr attrName = getValueAttrName(opName);
auto attr = cast<TypedAttr>(attributes.get(attrName));
auto controlType = cast<ControlType>(operands[0].getType());
// The return type is a ChannelType with:
// - dataType as specified by the attribute
// - extra signals matching the input control type
inferredReturnTypes.push_back(handshake::ChannelType::get(
attr.getType(), controlType.getExtraSignals()));
return success();
}
LogicalResult ConstantOp::verify() {
// Verify that the type of the provided value is equal to the result channel's
// data type
auto typedValue = dyn_cast<mlir::TypedAttr>(getValue());
if (!typedValue)
return emitOpError("constant value must be a typed attribute; value is ")
<< getValue();
if (typedValue.getType() != getResult().getType().getDataType())
return emitOpError() << "constant value type " << typedValue.getType()
<< " differs from result channel's data type "
<< getResult().getType();
return success();
}
bool JoinOp::isControl() { return true; }
/// Based on mlir::func::CallOp::verifySymbolUses
LogicalResult InstanceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
// Check that the module attribute was specified.
auto fnAttr = this->getModuleAttr();
assert(fnAttr && "requires a 'module' symbol reference attribute");
FuncOp fn = symbolTable.lookupNearestSymbolFrom<FuncOp>(*this, fnAttr);
if (!fn)
return emitOpError() << "'" << fnAttr.getValue()
<< "' does not reference a valid handshake function";
// Verify that the operand and result types match the callee.
auto fnType = fn.getFunctionType();
if (fnType.getNumInputs() != getNumOperands())
return emitOpError(
"incorrect number of operands for the referenced handshake function");
for (unsigned i = 0, e = fnType.getNumInputs(); i != e; ++i)
if (getOperand(i).getType() != fnType.getInput(i))
return emitOpError("operand type mismatch: expected operand type ")
<< fnType.getInput(i) << ", but provided "
<< getOperand(i).getType() << " for operand number " << i;
if (fnType.getNumResults() != getNumResults())
return emitOpError(
"incorrect number of results for the referenced handshake function");
for (unsigned i = 0, e = fnType.getNumResults(); i != e; ++i)
if (getResult(i).getType() != fnType.getResult(i))
return emitOpError("result type mismatch: expected result type ")
<< fnType.getResult(i) << ", but provided "
<< getResult(i).getType() << " for result number " << i;
return success();
}
FunctionType InstanceOp::getModuleType() {
return FunctionType::get(getContext(), getOperandTypes(), getResultTypes());
}
/// Finds the type of operation that produces the input by backtracking the
/// def-use chain through potential bitwidth modification and/or fork
/// operations.
static Operation *backtrackToMemInput(Value input) {
Operation *inputOp = input.getDefiningOp();
while (isa_and_present<handshake::ExtSIOp, handshake::ExtUIOp,
handshake::TruncIOp, handshake::ForkOp>(inputOp))
inputOp = inputOp->getOperand(0).getDefiningOp();
return inputOp;
}
/// Common verification logic for memory controllers and LSQs.
static LogicalResult verifyMemOp(FuncMemoryPorts &ports) {
// At most we can connect to a single other memory interface
if (ports.interfacePorts.size() > 1)
return ports.memOp.emitError() << "Interface may have at most one port to "
"other memory interfaces, but has "
<< ports.interfacePorts.size() << ".";
return success();
}
/// During construction of a memory interface's ports information, checks
/// whether bitwidths are consistent between all signals of the same nature
/// (e.g., address signals). A width of 0 is understood as "uninitialized", in
/// which case the first encountered signal determines the "reference" for that
/// signal type's width. Fails when the memory input's bitwidth doesn't match
/// the previously established bitwidth.
static LogicalResult checkAndSetBitwidth(Value memInput, unsigned &width) {
// Determine the signal's width
Type inType = memInput.getType();
if (!isa<handshake::ControlType, handshake::ChannelType>(inType)) {
return memInput.getUsers().begin()->emitError()
<< "Invalid input type, expected !handshake.control or "
"!handshake.channel";
}
unsigned inputWidth = getHandshakeTypeBitWidth(inType);
if (width == 0) {
// This is the first time we encounter a signal of this type, consider its
// width as the reference one for its category
width = inputWidth;
return success();
}
if (width != inputWidth) {
return memInput.getUsers().begin()->emitError()
<< "Inconsistent bitwidths in inputs, expected signal with " << width
<< " bits but got signal with " << inputWidth << " bits.";
}
return success();
}
//===----------------------------------------------------------------------===//
// MemoryControllerOp
//===----------------------------------------------------------------------===//
static handshake::ChannelType wrapChannel(Type type) {
assert(ChannelType::isSupportedSignalType(type) && "unsupported data type");
return handshake::ChannelType::get(type);
}
void MemoryControllerOp::build(OpBuilder &odsBuilder, OperationState &odsState,
Value memRef, Value memStart, ValueRange inputs,
Value ctrlEnd, ArrayRef<unsigned> blocks,
unsigned numLoads) {
// Memory operands
odsState.addOperands({memRef, memStart});
odsState.addOperands(inputs);
odsState.addOperands(ctrlEnd);
// Data outputs (get their type from memref)
MemRefType memrefType = memRef.getType().cast<MemRefType>();
MLIRContext *ctx = odsBuilder.getContext();
odsState.types.append(numLoads, wrapChannel(memrefType.getElementType()));
odsState.types.push_back(handshake::ControlType::get(ctx));
// Set "connectedBlocks" attribute
SmallVector<int> blocksAttribute;
for (unsigned size : blocks)
blocksAttribute.push_back(size);
odsState.addAttribute("connectedBlocks",
odsBuilder.getI32ArrayAttr(blocksAttribute));
}
/// Attempts to derive the ports for a memory controller. Fails if some of the
/// ports fails to be identified.
static LogicalResult getMCPorts(MCPorts &mcPorts) {
unsigned nextBlockIdx = 0, resIdx = 0;
std::optional<unsigned> currentBlockID;
GroupMemoryPorts *currentGroup = nullptr;
ValueRange memResults = mcPorts.memOp->getResults();
SmallVector<unsigned> blocks = mcPorts.getMCOp().getMCBlocks();
// Moves forward in our list of blocks, checking that we do not overflow it.
auto getNextBlockID = [&]() -> LogicalResult {
if (nextBlockIdx == blocks.size())
return mcPorts.memOp.emitError()
<< "MC connects to more blocks than it declares.";
currentBlockID = blocks[nextBlockIdx++];
return success();
};
// Iterate over all memory inputs and figure out which ports are connected to
// the memory controller
auto inputIter = llvm::enumerate(mcPorts.memOp->getOperands());
auto currentIt = inputIter.begin();
// Skip the memref and memory start signals as well as the control end signal
++(++currentIt);
unsigned lastIterOprd = mcPorts.memOp->getNumOperands() - 1;
for (; currentIt != inputIter.end(); ++currentIt) {
auto input = *currentIt;
if (input.index() == lastIterOprd)
break;
Operation *portOp = backtrackToMemInput(input.value());
// Identify the block the input operation belongs to
unsigned portOpBlock = 0;
if (portOp) {
auto ctrlBlock =
dyn_cast_if_present<IntegerAttr>(portOp->getAttr(BB_ATTR_NAME));
if (ctrlBlock) {
portOpBlock = ctrlBlock.getUInt();
} else if (isa<handshake::LoadOp, handshake::StoreOp>(portOp)) {
return portOp->emitError() << "Input operation of memory interface "
"does not belong to any basic block.";
}
}
// Checks wheter an access port belongs to the correct block
auto checkAccessPort = [&]() -> LogicalResult {
if (portOpBlock != *currentBlockID)
return mcPorts.memOp->emitError()
<< "Access port belongs to block " << portOpBlock
<< ", but expected it to be part of block " << *currentBlockID;
return success();
};
auto handleLoad = [&](handshake::LoadOp loadOp) -> LogicalResult {
if (failed(checkAndSetBitwidth(input.value(), mcPorts.addrWidth)) ||
failed(checkAndSetBitwidth(memResults[resIdx], mcPorts.dataWidth)))
return failure();
if (!currentGroup || portOpBlock != *currentBlockID) {
// If this is the first input or if the load belongs to a different
// block, allocate a new data stucture for the block's memory ports
// (without control)
if (failed(getNextBlockID()))
return failure();
mcPorts.groups.emplace_back();
currentGroup = &mcPorts.groups.back();
}
if (failed(checkAccessPort()))
return failure();
// Add a load port to the group
currentGroup->accessPorts.push_back(
LoadPort(loadOp, input.index(), resIdx++));
return success();
};
auto handleStore = [&](handshake::StoreOp storeOp) -> LogicalResult {
auto dataInput = *(++currentIt);
if (failed(checkAndSetBitwidth(input.value(), mcPorts.addrWidth)) ||
failed(checkAndSetBitwidth(dataInput.value(), mcPorts.dataWidth)))
return failure();
// All basic blocks with at least one store access must have a control
// input, so the block's memory ports must already be defined and point to
// the same block
if (!currentGroup)
return storeOp.emitError() << "Store port must be preceeded by control "
"port.";
if (failed(checkAccessPort()))
return failure();
// Add a store port to the block
currentGroup->accessPorts.push_back(StorePort(storeOp, input.index()));
return success();
};
auto handleLSQ = [&](handshake::LSQOp lsqOp) -> LogicalResult {
auto stAddrInput = *(++currentIt);
auto stDataInput = *(++currentIt);
if (failed(checkAndSetBitwidth(input.value(), mcPorts.addrWidth)) ||
failed(checkAndSetBitwidth(memResults[resIdx], mcPorts.dataWidth)) ||
failed(checkAndSetBitwidth(stAddrInput.value(), mcPorts.addrWidth)) ||
failed(checkAndSetBitwidth(stDataInput.value(), mcPorts.dataWidth)))
return failure();
// Add the port to the list of ports from other memory
// interfaces
mcPorts.interfacePorts.push_back(
LSQLoadStorePort(lsqOp, input.index(), resIdx++));
return success();
};
auto handleControl = [&](Operation *ctrlOp) -> LogicalResult {
if (failed(checkAndSetBitwidth(input.value(), mcPorts.ctrlWidth)) ||
failed(getNextBlockID()))
return failure();
// Allocate a new data stucture for the group's memory ports
mcPorts.groups.emplace_back(ControlPort(ctrlOp, input.index()));
currentGroup = &mcPorts.groups.back();
return success();
};
LogicalResult res = failure();
if (!portOp) {
// Control signal may come directly from function arguments
res = handleControl(portOp);
} else {
res = llvm::TypeSwitch<Operation *, LogicalResult>(portOp)
.Case<handshake::LoadOp>(handleLoad)
.Case<handshake::StoreOp>(handleStore)
.Case<handshake::LSQOp>(handleLSQ)
.Default(handleControl);
}
// Forward failure when parsing parts
if (failed(res))
return failure();
}
// Check that all blocks have been accounted for
if (nextBlockIdx != blocks.size())
return mcPorts.memOp->emitError()
<< "MC declares more blocks than it connects to.";
// Check that all memory results have been accounted for
if (resIdx != memResults.size() - 1)
return mcPorts.memOp->emitError()
<< "When identifying memory ports, some memory results were "
"unnacounted for, this is not normal!";
return success();
}
LogicalResult MemoryControllerOp::verify() {
// Blocks must be unique
SmallVector<unsigned> blocks = getMCBlocks();
if (blocks.empty())
return emitError() << "Memory controller must have at least one block.";
DenseSet<unsigned> uniqueBlocks;
for (unsigned blockID : blocks) {
if (auto [_, newBlock] = uniqueBlocks.insert(blockID); !newBlock)
return emitError() << "Block IDs must be unique but ID " << blockID
<< " was found at least twice in the list.";
}
// Try to get the memort ports: this will catch most issues
MCPorts mcPorts(*this);
if (failed(getMCPorts(mcPorts)) || failed(verifyMemOp(mcPorts)))
return failure();
// If there is a port to another memory interface it must be to an LSQ
if (!mcPorts.interfacePorts.empty()) {
if (!isa<LSQLoadStorePort>(mcPorts.interfacePorts.front()))
return emitError()
<< "The only memory interface port the memory controller "
"supports is to an LSQ.";
}
return success();
}
dynamatic::MCPorts MemoryControllerOp::getPorts() {
MCPorts mcPorts(*this);
if (failed(getMCPorts(mcPorts)))
assert(false && "failed to identify memory ports");
return mcPorts;
}
//===----------------------------------------------------------------------===//
// LSQOp
//===----------------------------------------------------------------------===//
static void buildLSQGroupSizes(OpBuilder &odsBuilder, OperationState &odsState,
ArrayRef<unsigned> groupSizes) {
SmallVector<int> sizesAttribute;
for (unsigned size : groupSizes)
sizesAttribute.push_back(size);
odsState.addAttribute(LSQOp::getGroupSizesAttrName(odsState.name).strref(),
odsBuilder.getI32ArrayAttr(sizesAttribute));
}
void LSQOp::build(OpBuilder &odsBuilder, OperationState &odsState, Value memref,
Value memStart, ValueRange inputs, Value ctrlEnd,
ArrayRef<unsigned> groupSizes, unsigned numLoads) {
// Memory operands
odsState.addOperands({memref, memStart});
odsState.addOperands(inputs);
odsState.addOperands(ctrlEnd);
// Data outputs (get their type from memref)
MemRefType memrefType = memref.getType().cast<MemRefType>();
MLIRContext *ctx = odsBuilder.getContext();
odsState.types.append(numLoads, wrapChannel(memrefType.getElementType()));
odsState.types.push_back(handshake::ControlType::get(ctx));
buildLSQGroupSizes(odsBuilder, odsState, groupSizes);
}
void LSQOp::build(OpBuilder &odsBuilder, OperationState &odsState,
handshake::MemoryControllerOp mcOp, ValueRange inputs,
ArrayRef<unsigned> groupSizes, unsigned numLoads) {
// Memory operands
odsState.addOperands(inputs);
// Data outputs (get their type from memref)
MemRefType memrefType = mcOp.getMemRefType();
MLIRContext *ctx = odsBuilder.getContext();
Type dataType = wrapChannel(memrefType.getElementType());
odsState.types.append(numLoads, dataType);
// Add results for load/store address and store data
Type addrType = handshake::ChannelType::getAddrChannel(ctx);
odsState.types.append(2, addrType);
odsState.types.push_back(dataType);
// The LSQ is a slave interface in this case (the MC is the master), so it
// doesn't produce a completion signal
buildLSQGroupSizes(odsBuilder, odsState, groupSizes);
}
ParseResult LSQOp::parse(OpAsmParser &parser, OperationState &result) {
SmallVector<OpAsmParser::UnresolvedOperand> operands;
SmallVector<Type> resultTypes, operandTypes;
llvm::SMLoc allOperandLoc = parser.getCurrentLocation();
// Parse reference to memory region
if (parser.parseLSquare())
return failure();
if (parser.parseOptionalKeyword("MC")) {
// We expect something of the form "memref operand : memref type"
OpAsmParser::UnresolvedOperand memrefOperand;
Type memrefType;
if (parser.parseOperand(memrefOperand) || parser.parseColon() ||
parser.parseType(memrefType))
return failure();
operands.push_back(memrefOperand);
operandTypes.push_back(memrefType);
}
if (parser.parseRSquare())
return failure();
// Parse memory operands
if (parser.parseLParen() || parser.parseOperandList(operands) ||
parser.parseRParen())
return failure();
// Parse group sizes and other attributes
if (parser.parseOptionalAttrDict(result.attributes))
return failure();
// Parse operand and result types (function type)
FunctionType funType;
if (parser.parseColonType(funType))