forked from EPFL-LAP/dynamatic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHandshakeOptimizeBitwidths.cpp
1666 lines (1452 loc) · 69.5 KB
/
HandshakeOptimizeBitwidths.cpp
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
//===- HandshakeOptimizeBitwidths.cpp - Optimize channel widths -*- C++ -*-===//
//
// Dynamatic is 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
//
//===----------------------------------------------------------------------===//
//
// Implements a fairly standard bitwidth optimization pass using two set of
// rewrite patterns that are applied greedily and recursively on the IR until it
// converges. In addition to classical arithmetic optimizations presented, for
// example, in this paper
// (https://ieeexplore.ieee.org/abstract/document/959864), Handshake operations
// are also bitwidth-optimized according to their specific semantics. The end
// goal of the pass is to reduce the area taken up by the circuit modeled at the
// Handhshake level.
//
// Note on shift operation handling (forward and backward): the logic of
// truncating a value only to extend it again immediately may seem unnecessary,
// but it in fact allows the rest of the rewrite patterns to understand that
// a value fits on less bits than what the original value suggests. This is
// slightly convoluted but we are forced to do this like that since shift
// operations enforce that all their operands are of the same type. Ideally, we
// would have a Handshake version of shift operations that accept varrying
// bitwidths between its operands and results.
//
//===----------------------------------------------------------------------===//
#include "dynamatic/Transforms/HandshakeOptimizeBitwidths.h"
#include "dynamatic/Analysis/NameAnalysis.h"
#include "dynamatic/Dialect/Handshake/HandshakeInterfaces.h"
#include "dynamatic/Dialect/Handshake/HandshakeOps.h"
#include "dynamatic/Dialect/Handshake/HandshakeTypes.h"
#include "dynamatic/Support/CFG.h"
#include "dynamatic/Transforms/HandshakeMinimizeCstWidth.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/Value.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include <functional>
#include <iterator>
using namespace mlir;
using namespace dynamatic;
namespace {
/// Extension type. When backtracing through extension operations, serves to
/// remember the type of any extension we may have encountered along the
/// way.getMinimalValue Then, when modifying a value's bitwidth, serves to guide
/// the determination of which extension operation to use.
/// - UNKNOWN when no extension has been encountered / when a value's signedness
/// should determine its extension type.
/// - LOGICAL when only logical extensions have been encountered / when a value
/// should be logically extended.
/// - ARITHMETIC when only arithmaric extensions have been encountered / when a
/// value should be arithmetically extended.
/// - CONFLICT when both logical and arithmetic extensions have been encountered
/// when it's not possible to accurately determine what type of extension to
/// use for a value.
enum class ExtType { UNKNOWN, LOGICAL, ARITHMETIC, CONFLICT };
/// A channel-typed value.
using ChannelVal = TypedValue<handshake::ChannelType>;
/// Shortcut for a value accompanied by its corresponding extension type.
using ExtValue = std::pair<ChannelVal, ExtType>;
/// Holds a set of operations that were already visisted during backtracking.
using VisitedOps = SmallPtrSet<Operation *, 4>;
} // namespace
//===----------------------------------------------------------------------===//
// Utility functions
//===----------------------------------------------------------------------===//
/// Returns the input value has a channel-typed value if it is
/// bitwidth-optimizable.
static ChannelVal asTypedIfLegal(Value val) {
if (auto channelType = dyn_cast<handshake::ChannelType>(val.getType())) {
if (isa<IntegerType>(channelType.getDataType()))
return cast<ChannelVal>(val);
}
return nullptr;
}
/// Backtracks through defining operations of the value as long as they are
/// extension operations. Returns the "minimal value", i.e., the potentially
/// different value that represents the same number as the originally provided
/// one but without all bits added by extension operations. During the forward
/// pass, the returned value gives an indication of how many bits of the
/// original value can be safely discarded. If an extension type is provided and
/// the function is able to backtrack through any extension operation, updates
/// the extension type with respect to the latter.
static ChannelVal getMinimalValue(ChannelVal val, ExtType *ext = nullptr) {
// Ignore values whose type isn't optimizable
if (!asTypedIfLegal(val))
return val;
// Only backtrack through values that were produced by extension operations
while (Operation *defOp = val.getDefiningOp()) {
if (!isa<handshake::ExtSIOp, handshake::ExtUIOp>(defOp))
return val;
// Update the extension type using the nature of the current extension
// operation and the current type
if (ext) {
switch (*ext) {
case ExtType::UNKNOWN:
*ext = isa<handshake::ExtSIOp>(defOp) ? ExtType::ARITHMETIC
: ExtType::LOGICAL;
break;
case ExtType::LOGICAL:
if (isa<handshake::ExtSIOp>(defOp))
*ext = ExtType::CONFLICT;
break;
case ExtType::ARITHMETIC:
if (isa<handshake::ExtUIOp>(defOp))
*ext = ExtType::CONFLICT;
break;
default:
break;
}
}
// Backtrack through the extension operation
val = cast<ChannelVal>(defOp->getOperand(0));
}
return val;
}
// Backtracks through defining operations of the given value as long as they are
// "single data input data-forwarders" (i.e., Handshake operations which forward
// one their single "data input" to one of their outputs).
static ChannelVal backtrack(ChannelVal val) {
VisitedOps visitedOps;
while (Operation *defOp = val.getDefiningOp()) {
// Stop when reaching an operation that was already backtracked through
if (auto [_, isNewOp] = visitedOps.insert(defOp); !isNewOp)
return val;
if (isa<handshake::BufferOp, handshake::ForkOp, handshake::LazyForkOp,
handshake::BranchOp>(defOp))
val = cast<ChannelVal>(defOp->getOperand(0));
if (auto condOp = dyn_cast<handshake::ConditionalBranchOp>(defOp))
val = cast<ChannelVal>(condOp.getDataOperand());
else if (auto mergeLikeOp =
dyn_cast<handshake::MergeLikeOpInterface>(defOp)) {
if (auto dataOpr = mergeLikeOp.getDataOperands(); dataOpr.size() == 1)
val = cast<ChannelVal>(dataOpr[0]);
} else
return val;
}
// Stop backtracking when reaching function arguments
return val;
}
static ChannelVal backtrackToMinimalValue(ChannelVal val,
ExtType *ext = nullptr) {
ChannelVal newVal;
while ((newVal = getMinimalValue(backtrack(val), ext)) != val)
val = newVal;
return newVal;
}
/// Returns the maximum number of bits that are used by any of the value's
/// users. If the value has no users, returns 0. During the backward pass, the
/// returned value gives an indication of how many high-significant bits can be
/// safely truncated away from the value during optimization.
static unsigned getUsefulResultWidth(ChannelVal val) {
std::optional<unsigned> maxWidth;
for (Operation *user : val.getUsers()) {
if (isa<handshake::SinkOp>(user))
continue;
auto truncOp = dyn_cast<handshake::TruncIOp>(user);
if (!truncOp)
return val.getType().getDataBitWidth();
unsigned truncWidth = truncOp.getOut().getType().getDataBitWidth();
maxWidth = std::max(maxWidth.value_or(0), truncWidth);
}
return maxWidth.value_or(0);
}
/// Produces a value that matches the content of the passed value but whose
/// bitwidth is modified to equal the target width. Inserts an extension or
/// truncation operation in the IR after the original value if necessary. If an
/// extension operation is required, the provided extension type determines
/// which type of extension operation is inserted. If the extension type is
/// unknown, the value's signedness determines whether the extension should be
/// logical or arithmetic.
static ChannelVal modBitWidth(ExtValue extVal, unsigned targetWidth,
PatternRewriter &rewriter) {
auto &[val, ext] = extVal;
// Return the original value when it already has the target width
unsigned width = val.getType().getDataBitWidth();
if (width == targetWidth)
return val;
// Otherwise, insert a bitwidth modification operation to create a value of
// the target width
Operation *newOp = nullptr;
Location loc = val.getLoc();
Type newDataType = rewriter.getIntegerType(targetWidth);
Type dstChannelType = val.getType().withDataType(newDataType);
rewriter.setInsertionPointAfterValue(val);
if (width < targetWidth) {
if (ext == ExtType::CONFLICT) {
// If the extension type is conflicting, just emit a warning and hope for
// the best
Operation *defOp = val.getDefiningOp();
std::string origin;
if (defOp)
origin = "operation result";
else {
defOp = val.getParentBlock()->getParentOp();
origin = "function argument";
}
defOp->emitWarning()
<< "Conflicting extension type given for " << origin
<< ", optimization result may change circuit semantics.";
}
if (ext == ExtType::LOGICAL ||
(ext == ExtType::UNKNOWN &&
val.getType().getDataType().isUnsignedInteger())) {
newOp = rewriter.create<handshake::ExtUIOp>(loc, dstChannelType, val);
} else {
newOp = rewriter.create<handshake::ExtSIOp>(loc, dstChannelType, val);
}
} else {
newOp = rewriter.create<handshake::TruncIOp>(loc, dstChannelType, val);
}
inheritBBFromValue(val, newOp);
return cast<ChannelVal>(newOp->getResult(0));
}
/// Recursive version of isOperandInCycle which includes an additional
/// parameter to keep track of which operations were already visited during
/// backtracking to avoid looping forever. See overload's documentation for more
/// details.
static bool isOperandInCycle(Value val, Value res,
DenseSet<Value> &mergedValues,
VisitedOps &visitedOps) {
// Stop when we've reached the result of the merge-like operation
if (val == res)
return true;
// Stop when reaching function arguments
Operation *defOp = val.getDefiningOp();
if (!defOp)
return false;
// Stop when reaching an operation that was already backtracked through
if (auto [_, isNewOp] = visitedOps.insert(defOp); !isNewOp)
return true;
// Backtrack through operations that end up "forwarding" one of their
// inputs to the output
if (isa<handshake::BufferOp, handshake::ForkOp, handshake::LazyForkOp,
handshake::BranchOp, handshake::ExtSIOp, handshake::ExtUIOp>(defOp))
return isOperandInCycle(defOp->getOperand(0), res, mergedValues,
visitedOps);
if (auto condOp = dyn_cast<handshake::ConditionalBranchOp>(defOp))
return isOperandInCycle(condOp.getDataOperand(), res, mergedValues,
visitedOps);
auto recurseMergeLike = [&](ValueRange dataOperands) -> bool {
bool oneOprInCycle = false;
SmallVector<Value> mergeOperands;
for (Value mergeLikeOpr : dataOperands) {
VisitedOps nestedVisitedOps(visitedOps);
if (isOperandInCycle(mergeLikeOpr, res, mergedValues, nestedVisitedOps))
oneOprInCycle = true;
else
mergeOperands.push_back(mergeLikeOpr);
}
// If the merge-like operation is part of the cycle through one of its data
// operands, add other data operands not part of the cycle to the merged
// values
if (oneOprInCycle)
for (Value &outOfCycleOpr : mergeOperands)
mergedValues.insert(outOfCycleOpr);
return oneOprInCycle;
};
// Recursively explore data operands of merge-like operations to find cycles
if (auto mergeLikeOp = dyn_cast<handshake::MergeLikeOpInterface>(defOp))
return recurseMergeLike(mergeLikeOp.getDataOperands());
if (auto selectOp = dyn_cast<handshake::SelectOp>(defOp))
return recurseMergeLike(
ValueRange{selectOp.getTrueValue(), selectOp.getFalseValue()});
return false;
}
/// Determines whether it is possible to backtrack the value to the result by
/// only going through defining Handshake operations that act as "data
/// forwarders" i.e, operations that forward one of their data inputs to one of
/// their outputs without modification. If yes, then we say the value and result
/// are in the same cycle and the function returns true; otherwise, the function
/// returns false. When the function returns true, mergedValues represents the
/// set of values that are fed inside the cycle through operands of merge-like
/// operations that are on the path between value and result. When the function
/// returns false, the value of mergedValues is undefined.
static bool isOperandInCycle(Value val, Value res,
DenseSet<Value> &mergedValues) {
VisitedOps visitedOps;
return isOperandInCycle(val, res, mergedValues, visitedOps);
}
/// Replaces an operation with two operands and one result of the same integer
/// or floating type with an operation of the same type but whose operands and
/// result bitwidths have been modified to match the provided optimized
/// bitwidth. Extension and truncation operations are inserted as necessary to
/// satisfy the IR and bitwidth constraints.
template <typename Op>
static void modArithOp(Op op, ExtValue lhs, ExtValue rhs, unsigned optWidth,
ExtType extRes, PatternRewriter &rewriter,
NameAnalysis &namer) {
ChannelVal channelVal = asTypedIfLegal(op->getResult(0));
assert(channelVal && "result must have valid type");
unsigned resWidth = channelVal.getType().getDataBitWidth();
// Create a new operation as well as appropriate bitwidth
// modification operations to keep the IR valid
Value newLhs = modBitWidth(lhs, optWidth, rewriter);
Value newRhs = modBitWidth(rhs, optWidth, rewriter);
rewriter.setInsertionPoint(op);
auto newOp = rewriter.create<Op>(op.getLoc(), newLhs, newRhs);
Value newRes = modBitWidth({newOp.getResult(), extRes}, resWidth, rewriter);
namer.replaceOp(op, newOp);
inheritBB(op, newOp);
// Replace uses of the original operation's result with
// the result of the optimized operation we just created
rewriter.replaceOp(op, newRes);
}
//===----------------------------------------------------------------------===//
// Transfer functions for arith operations
//===----------------------------------------------------------------------===//
/// Transfer function for add/sub operations or alike.
static inline unsigned addWidth(unsigned lhs, unsigned rhs) {
return std::max(lhs, rhs) + 1;
}
/// Transfer function for mul operations or alike.
static inline unsigned mulWidth(unsigned lhs, unsigned rhs) {
return lhs + rhs;
}
/// Transfer function for div/rem operations or alike.
static inline unsigned divWidth(unsigned lhs, unsigned _) { return lhs + 1; }
/// Transfer function for and operations or alike.
static inline unsigned andWidth(unsigned lhs, unsigned rhs) {
return std::min(lhs, rhs);
}
/// Transfer function for or/xor operations or alike.
static inline unsigned orWidth(unsigned lhs, unsigned rhs) {
return std::max(lhs, rhs);
}
//===----------------------------------------------------------------------===//
// Configurations for data optimization of Handshake operations
//===----------------------------------------------------------------------===//
namespace {
/// Holds overridable methods called from the HandshakeOptData rewrite pattern
/// The template parameter of this class is meant to hold a Handshake operation
/// type. Subclassing this class allows to specify, for a specific operation
/// type, the operations/results that carry the data value whose bitwidth may be
/// optimized as well as to tweak the creation process of new operation
/// instances. The default configuration works for Handshake operations whose
/// operands and results all represent the data value (e.g., merge).
template <typename Op>
class OptDataConfig {
public:
/// Constructs the configuration from the specific operation being
/// transformed.
OptDataConfig(Op op) : op(op) {};
/// Returns the list of operands that carry data. The method must return at
/// least one operand. If multiple operands are returned, they must all have
/// the same data type, which must also be shared by all results returned by
/// getDataResults.
virtual SmallVector<Value> getDataOperands() { return op->getOperands(); }
/// Returns the list of results that carry data. The method must return at
/// least one result. If multiple results are returned, they must all have
/// the same data type, which must also be shared by all operands returned by
/// getDataOperands.
virtual SmallVector<Value> getDataResults() { return op->getResults(); }
/// Determines the list of operands that will be given to the builder of the
/// optimized operation from the optimized data width, extension type, and
/// list of minimal data operands of the original operation. The vector given
/// as last argument is filled with the new operands.
virtual void getNewOperands(unsigned optWidth, ExtType ext,
ArrayRef<ChannelVal> minDataOperands,
PatternRewriter &rewriter,
SmallVector<Value> &newOperands) {
llvm::transform(minDataOperands, std::back_inserter(newOperands),
[&](ChannelVal val) {
return modBitWidth({val, ext}, optWidth, rewriter);
});
}
/// Determines the list of result types that will be given to the builder of
/// the optimized operation. The dataType is the type shared by all data
/// results. The vector given as last argument is filled with the new result
/// types.
virtual void getResultTypes(Type dataType, SmallVector<Type> &newResTypes) {
for (size_t i = 0, numResults = op->getNumResults(); i < numResults; ++i)
newResTypes.push_back(dataType);
}
/// Creates and returns the optimized operation from its result types and
/// operands. The default builder for the operation must be available for the
/// default implementation of this function.
virtual Op createOp(ArrayRef<Type> newResTypes, ArrayRef<Value> newOperands,
PatternRewriter &rewriter) {
return rewriter.create<Op>(op.getLoc(), newResTypes, newOperands);
}
/// Determines the list of values that the original operation will be replaced
/// with. These are the results of the newly inserted optimized operations
/// whose bitwidth is modified to match those of the original operation. The
/// width is the width that was shared by all data operands in the original
/// operation. The vector given as last argument is filled with the new
/// values.
virtual void modResults(Op newOp, unsigned width, ExtType ext,
PatternRewriter &rewriter,
SmallVector<Value> &newResults) {
llvm::transform(
newOp->getResults(), std::back_inserter(newResults), [&](OpResult res) {
return modBitWidth({cast<ChannelVal>(res), ext}, width, rewriter);
});
}
/// Default destructor declared virtual because of virtual methods.
virtual ~OptDataConfig() = default;
protected:
/// The operation currently being transformed.
Op op;
};
/// Special configuration for control merges required because of the index
/// result which does not carry data.
class CMergeDataConfig : public OptDataConfig<handshake::ControlMergeOp> {
public:
CMergeDataConfig(handshake::ControlMergeOp op) : OptDataConfig(op) {};
SmallVector<Value> getDataResults() override {
return SmallVector<Value>{op.getResult()};
}
void getResultTypes(Type dataType, SmallVector<Type> &newResTypes) override {
for (size_t i = 0, numResults = op->getNumResults() - 1; i < numResults;
++i)
newResTypes.push_back(dataType);
newResTypes.push_back(op.getIndex().getType());
}
void modResults(handshake::ControlMergeOp newOp, unsigned width, ExtType ext,
PatternRewriter &rewriter,
SmallVector<Value> &newResults) override {
newResults.push_back(modBitWidth({cast<ChannelVal>(newOp.getResult()), ext},
width, rewriter));
newResults.push_back(newOp.getIndex());
}
};
/// Special configuration for muxes required because of the select operand
/// which does not carry data.
class MuxDataConfig : public OptDataConfig<handshake::MuxOp> {
public:
MuxDataConfig(handshake::MuxOp op) : OptDataConfig(op) {};
SmallVector<Value> getDataOperands() override { return op.getDataOperands(); }
void getNewOperands(unsigned optWidth, ExtType ext,
ArrayRef<ChannelVal> minDataOperands,
PatternRewriter &rewriter,
SmallVector<Value> &newOperands) override {
newOperands.push_back(op.getSelectOperand());
llvm::transform(
minDataOperands, std::back_inserter(newOperands), [&](Value val) {
return modBitWidth({cast<ChannelVal>(val), ext}, optWidth, rewriter);
});
}
};
/// Special configuration for conditional branches required because of the
/// condition operand which does not carry data.
class CBranchDataConfig : public OptDataConfig<handshake::ConditionalBranchOp> {
public:
CBranchDataConfig(handshake::ConditionalBranchOp op) : OptDataConfig(op) {};
SmallVector<Value> getDataOperands() override {
return SmallVector<Value>{op.getDataOperand()};
}
void getNewOperands(unsigned optWidth, ExtType ext,
ArrayRef<ChannelVal> minDataOperands,
PatternRewriter &rewriter,
SmallVector<Value> &newOperands) override {
newOperands.push_back(op.getConditionOperand());
newOperands.push_back(
modBitWidth({minDataOperands[0], ext}, optWidth, rewriter));
}
};
/// Special configuration for buffers required because of the buffer type
/// attribute and custom builder.
class BufferDataConfig : public OptDataConfig<handshake::BufferOp> {
public:
BufferDataConfig(handshake::BufferOp op)
: OptDataConfig<handshake::BufferOp>(op) {};
SmallVector<Value> getDataOperands() override {
return SmallVector<Value>{this->op.getOperand()};
}
void getNewOperands(unsigned optWidth, ExtType ext,
ArrayRef<ChannelVal> minDataOperands,
PatternRewriter &rewriter,
SmallVector<Value> &newOperands) override {
newOperands.push_back(
modBitWidth({minDataOperands[0], ext}, optWidth, rewriter));
}
handshake::BufferOp createOp(ArrayRef<Type> newResTypes,
ArrayRef<Value> newOperands,
PatternRewriter &rewriter) override {
return rewriter.create<handshake::BufferOp>(
op.getLoc(), newOperands[0].getType(), newOperands[0],
op->getAttrDictionary().getValue());
}
};
} // namespace
//===----------------------------------------------------------------------===//
// Patterns for Handshake operations
//===----------------------------------------------------------------------===//
namespace {
/// Generic rewrite pattern for Handshake operations forwarding a "data value"
/// from their operand(s) to their result(s). The first template parameter is
/// meant to hold a Handshake operation type on which to apply the pattern,
/// while the second is meant to hold a subclass of OptDataConfig (or the class
/// itself) that specifies how the transformation may be performed on that
/// specific operation type. We use the latter as a way to reduce code
/// duplication, since a number of Handshake operations do not purely follow
/// this "data forwarding" behavior (e.g., they may have a separate operand,
/// like the index operand for muxes) yet their "data-carrying" operands/results
/// can be optimized in the same way as "pure data-forwarding" operations (e.g.,
/// merges). If possible, the pattern replaces the matched operation with one
/// whose bitwidth has been optimized.
///
/// The "data-carrying" operands/results are optimized in the standard way
/// during both the forward and backward passes. In forward mode, the largest
/// "minimal" data operand width is used to potentially reduce the bitwidth of
/// data results. In backward mode, the maximum number of bits used from any of
/// the data results drives a potential reduction in the number of bits in the
/// data operands.
template <typename Op, typename Cfg>
struct HandshakeOptData : public OpRewritePattern<Op> {
using OpRewritePattern<Op>::OpRewritePattern;
HandshakeOptData(bool forward, MLIRContext *ctx, NameAnalysis &namer)
: OpRewritePattern<Op>(ctx), forward(forward), namer(namer) {}
LogicalResult matchAndRewrite(Op op,
PatternRewriter &rewriter) const override {
Cfg cfg(op);
SmallVector<Value> dataOperands = cfg.getDataOperands();
SmallVector<Value> dataResults = cfg.getDataResults();
assert(!dataOperands.empty() && "op must have at least one data operand");
assert(!dataResults.empty() && "op must have at least one data result");
ChannelVal channelVal = asTypedIfLegal(dataResults[0]);
if (!channelVal)
return failure();
// Get the operation's data operands actual widths
SmallVector<ChannelVal> minDataOperands;
ExtType ext = ExtType::UNKNOWN;
llvm::transform(dataOperands, std::back_inserter(minDataOperands),
[&](Value val) {
return getMinimalValue(cast<ChannelVal>(val), &ext);
});
// Check whether we can reduce the bitwidth of the operation
unsigned optWidth = 0;
if (forward) {
for (ChannelVal oprd : minDataOperands)
optWidth = std::max(optWidth, oprd.getType().getDataBitWidth());
} else {
for (Value res : dataResults)
optWidth =
std::max(optWidth, getUsefulResultWidth(cast<ChannelVal>(res)));
}
unsigned dataWidth = channelVal.getType().getDataBitWidth();
if (optWidth >= dataWidth)
return failure();
// Create a new operation as well as appropriate bitwidth modification
// operations to keep the IR valid
SmallVector<Value> newOperands;
SmallVector<Value> newResults;
SmallVector<Type> newResTypes;
Type newDataType = rewriter.getIntegerType(optWidth);
Type newChannelType = channelVal.getType().withDataType(newDataType);
cfg.getNewOperands(optWidth, ext, minDataOperands, rewriter, newOperands);
cfg.getResultTypes(newChannelType, newResTypes);
rewriter.setInsertionPoint(op);
Op newOp = cfg.createOp(newResTypes, newOperands, rewriter);
inheritBB(op, newOp);
namer.replaceOp(op, newOp);
cfg.modResults(newOp, dataWidth, ext, rewriter, newResults);
// Replace uses of the original operation's results with the results of the
// optimized operation we just created
rewriter.replaceOp(op, newResults);
return success();
}
private:
/// Indicates whether this pattern is part of the forward or backward pass.
bool forward;
/// A reference to the pass's name analysis.
NameAnalysis &namer;
};
/// Optimizes the bitwidth of muxes' select operand so that it is just wide
/// enough to support indexing into the number of data operands. This pattern
/// can be applied as part of a single greedy rewriting pass; it doesn't need to
/// be part of the forward/backward process.
struct HandshakeMuxSelect : public OpRewritePattern<handshake::MuxOp> {
HandshakeMuxSelect(NameAnalysis &namer, MLIRContext *ctx)
: OpRewritePattern<handshake::MuxOp>(ctx), namer(namer) {}
LogicalResult matchAndRewrite(handshake::MuxOp muxOp,
PatternRewriter &rewriter) const override {
// Compute the number of bits required to index into the mux data operands
unsigned optWidth = std::max(
1U, APInt(APInt::APINT_BITS_PER_WORD, muxOp.getDataOperands().size())
.ceilLogBase2());
// Check whether we can reduce the bitwidth of the operation
ChannelVal selectOperand = muxOp.getSelectOperand();
handshake::ChannelType selectType = selectOperand.getType();
unsigned selectWidth = selectType.getDataBitWidth();
if (optWidth >= selectWidth)
return failure();
// Create a new mux whose select operand is optimized
SmallVector<Value, 3> newOperands;
newOperands.push_back(
modBitWidth({selectOperand, ExtType::LOGICAL}, optWidth, rewriter));
auto dataOprds = muxOp.getDataOperands();
newOperands.append(dataOprds.begin(), dataOprds.end());
auto newMuxOp = rewriter.create<handshake::MuxOp>(
muxOp.getLoc(), muxOp->getResultTypes(), newOperands,
muxOp->getAttrs());
namer.replaceOp(muxOp, newMuxOp);
rewriter.replaceOp(muxOp, newMuxOp);
return success();
}
protected:
/// A reference to the pass's name analysis.
NameAnalysis &namer;
};
/// Optimizes the bitwidth of control merges' index result so that it is just
/// wide enough to support indexing into the number of data operands. This
/// pattern can be applied as part of a single greedy rewriting pass; it doesn't
/// need to be part of the forward/backward process.
struct HandshakeCMergeIndex
: public OpRewritePattern<handshake::ControlMergeOp> {
HandshakeCMergeIndex(NameAnalysis &namer, MLIRContext *ctx)
: OpRewritePattern<handshake::ControlMergeOp>(ctx), namer(namer) {}
LogicalResult matchAndRewrite(handshake::ControlMergeOp cmergeOp,
PatternRewriter &rewriter) const override {
// Compute the number of bits required to index into the mux data operands
unsigned optWidth = std::max(
1U, APInt(APInt::APINT_BITS_PER_WORD, cmergeOp->getNumOperands())
.ceilLogBase2());
// Check whether we can reduce the bitwidth of the operation
ChannelVal indexResult = cmergeOp.getIndex();
handshake::ChannelType indexType = indexResult.getType();
unsigned indexWidth = indexType.getDataBitWidth();
if (optWidth >= indexWidth)
return failure();
// Create a new control merge whose index result is optimized
SmallVector<Type, 2> newResultTypes{
cmergeOp->getOperandTypes().front(),
indexType.withDataType(rewriter.getIntegerType(optWidth))};
rewriter.setInsertionPoint(cmergeOp);
auto newCmergeOp = rewriter.create<handshake::ControlMergeOp>(
cmergeOp.getLoc(), newResultTypes, cmergeOp.getDataOperands(),
cmergeOp->getAttrs());
namer.replaceOp(cmergeOp, newCmergeOp);
Value modIndex = modBitWidth({newCmergeOp.getIndex(), ExtType::LOGICAL},
indexWidth, rewriter);
rewriter.replaceOp(cmergeOp, {newCmergeOp.getResult(), modIndex});
return success();
}
protected:
/// A reference to the pass's name analysis.
NameAnalysis &namer;
};
/// Optimizes the bitwidth of memory interfaces' address-carrying channels so
/// that they are just wide enough to support indexing into the memory region
/// attached to the interface. This pattern can be applied as part of a single
/// greedy rewriting pass; it doesn't need to be part of the forward/backward
/// process.
struct MemInterfaceAddrOpt
: public OpInterfaceRewritePattern<handshake::MemoryOpInterface> {
MemInterfaceAddrOpt(NameAnalysis &namer, MLIRContext *ctx)
: OpInterfaceRewritePattern<handshake::MemoryOpInterface>(ctx),
namer(namer) {}
LogicalResult matchAndRewrite(handshake::MemoryOpInterface memOp,
PatternRewriter &rewriter) const override {
unsigned optWidth = APInt(APInt::APINT_BITS_PER_WORD,
memOp.getMemRef().getType().getDimSize(0))
.ceilLogBase2();
FuncMemoryPorts ports = getMemoryPorts(memOp);
if (ports.addrWidth == 0 || optWidth >= ports.addrWidth)
return failure();
ValueRange operands = memOp->getOperands();
TypeRange resultTypes = memOp->getResultTypes();
// Optimizes the bitwidth of the address channel currently being pointed to
// by inputIdx, and increment inputIdx before returning the optimized value
auto getOptAddrInput = [&](unsigned inputIdx) {
return modBitWidth({getMinimalValue(cast<ChannelVal>(operands[inputIdx])),
ExtType::LOGICAL},
optWidth, rewriter);
};
// Replace new operands and result types with the narrrower address type by
// iterating over the memory interface's ports
SmallVector<Value> newOperands(operands);
SmallVector<Type> newResultTypes(resultTypes);
SmallVector<unsigned, 2> addrResultIndices;
// First iterate over regular load/store ports directly connecting to the
// memory interface
for (GroupMemoryPorts &blockPorts : ports.groups) {
for (MemoryPort &port : blockPorts.accessPorts) {
if (std::optional<LoadPort> loadPort = dyn_cast<LoadPort>(port)) {
unsigned addrIdx = loadPort->getAddrInputIndex();
newOperands[addrIdx] = getOptAddrInput(addrIdx);
} else {
std::optional<StorePort> storePort = dyn_cast<StorePort>(port);
assert(storePort && "port must be load or store");
unsigned addrIdx = storePort->getAddrInputIndex();
newOperands[addrIdx] = getOptAddrInput(addrIdx);
}
}
}
// Then iterate over ports connecting this memory interface to another one
// that references the same memory region
for (MemoryPort &port : ports.interfacePorts) {
if (std::optional<MCLoadStorePort> mcPort =
dyn_cast<MCLoadStorePort>(port)) {
// Load address and store address results are modified
Type optAddrType =
handshake::ChannelType::get(rewriter.getIntegerType(optWidth));
unsigned ldAddrIdx = mcPort->getLoadAddrOutputIndex();
addrResultIndices.push_back(ldAddrIdx);
newResultTypes[ldAddrIdx] = optAddrType;
unsigned stAddrIdx = mcPort->getStoreAddrOutputIndex();
addrResultIndices.push_back(stAddrIdx);
newResultTypes[stAddrIdx] = optAddrType;
} else {
std::optional<LSQLoadStorePort> lsqPort =
dyn_cast<LSQLoadStorePort>(port);
// Load address and store address operands are modified
assert(lsqPort && "interface port must be to MC or LSQ");
unsigned ldAddrIdx = lsqPort->getLoadAddrInputIndex();
newOperands[ldAddrIdx] = getOptAddrInput(ldAddrIdx);
unsigned stAddrIdx = lsqPort->getStoreAddrInputIndex();
newOperands[stAddrIdx] = getOptAddrInput(stAddrIdx);
}
}
// Replace the memory interface
rewriter.setInsertionPoint(memOp);
auto newMemOp = cast<handshake::MemoryOpInterface>(rewriter.create(
memOp->getLoc(),
StringAttr::get(getContext(), memOp->getName().getStringRef()),
newOperands, newResultTypes, memOp->getAttrs()));
SmallVector<Value> replacementValues(newMemOp->getResults());
for (unsigned resIdx : addrResultIndices) {
replacementValues[resIdx] = modBitWidth(
{cast<ChannelVal>(replacementValues[resIdx]), ExtType::LOGICAL},
ports.addrWidth, rewriter);
}
inheritBB(memOp, newMemOp);
namer.replaceOp(memOp, newMemOp);
rewriter.replaceOp(memOp, replacementValues);
return success();
}
protected:
/// A reference to the pass's name analysis.
NameAnalysis &namer;
};
/// Optimizes the bitwidth of memory ports's address-carrying channels so that
/// they are just wide enough to support indexing into the memory region these
/// ports ultimately talk to. This pattern can be applied as part of a single
/// greedy rewriting pass; it doesn't need to be part of the forward/backward
/// process.
struct MemPortAddrOpt
: public OpInterfaceRewritePattern<handshake::MemPortOpInterface> {
MemPortAddrOpt(NameAnalysis &namer, MLIRContext *ctx)
: OpInterfaceRewritePattern<handshake::MemPortOpInterface>(ctx),
namer(namer) {}
LogicalResult matchAndRewrite(handshake::MemPortOpInterface portOp,
PatternRewriter &rewriter) const override {
// Check whether we can optimize the address bitwidth
ChannelVal addrRes = portOp.getAddressOutput();
unsigned addrWidth = addrRes.getType().getDataBitWidth();
unsigned optWidth = getUsefulResultWidth(addrRes);
if (optWidth >= addrWidth)
return failure();
// Derive new operands and result types with the narrrower address type
Value newAddr = modBitWidth(
{getMinimalValue(portOp.getAddressInput()), ExtType::LOGICAL}, optWidth,
rewriter);
Value dataIn = portOp.getDataInput();
SmallVector<Value, 2> newOperands{newAddr, dataIn};
SmallVector<Type, 2> newResultTypes{newAddr.getType(), dataIn.getType()};
// Replace the memory port
rewriter.setInsertionPoint(portOp);
auto newPortOp = cast<handshake::MemPortOpInterface>(rewriter.create(
portOp.getLoc(),
StringAttr::get(getContext(), portOp->getName().getStringRef()),
newOperands, newResultTypes, portOp->getAttrs()));
namer.replaceOp(portOp, newPortOp);
inheritBB(portOp, newPortOp);
Value newAddrRes = modBitWidth(
{newPortOp.getAddressOutput(), ExtType::LOGICAL}, addrWidth, rewriter);
rewriter.replaceOp(portOp, {newAddrRes, newPortOp.getDataOutput()});
return success();
}
protected:
/// A reference to the pass's name analysis.
NameAnalysis &namer;
};
/// Optimizes the bitwidth of channels contained inside "forwarding cycles".
/// These are values that generally circulate between branch-like and merge-like
/// operations without modification (i.e., in a block that branches to itself).
/// These require special treatment to be optimized as the rest of the rewrite
/// patterns only look at the operation they are matched on when optimizing,
/// whereas this pattern attempts to backtracks through operands of merge-like
/// operations to identify whether it was produced by the operation itself. If
/// an operand is identified as being part of a cycle, all other out-of-cycle
/// merged values incoming to the cycle through merge-like operation operands
/// are considered to determine the optimized width that can be given to the
/// in-cycle operand.
///
/// The first template parameter is meant to be a merge-like operation i.e., a
/// Handshake operation implementing the MergeLikeOpInterface trait on which to
/// apply the rewrite pattern. The second template parameter is meant to hold a
/// subclass of OptDataConfig (or the class itself) that specifies how the
/// transformation may be performed on that specific operation type.
template <typename Op, typename Cfg>
struct ForwardCycleOpt : public OpRewritePattern<Op> {
using OpRewritePattern<Op>::OpRewritePattern;
ForwardCycleOpt(MLIRContext *ctx, NameAnalysis &namer)
: OpRewritePattern<Op>(ctx), namer(namer) {}
LogicalResult matchAndRewrite(Op op,
PatternRewriter &rewriter) const override {
// This pattern only works for merge-like operations with a valid data type
auto mergeLikeOp =
dyn_cast<handshake::MergeLikeOpInterface>((Operation *)op);
if (!mergeLikeOp)
return failure();
ChannelVal channelVal = asTypedIfLegal(op->getResult(0));
if (!channelVal)
return failure();
// For each operand, determine whether it is in a forwarding cycle. If yes,
// keep track of other values coming in the cycle through merge-like ops
OperandRange dataOperands = mergeLikeOp.getDataOperands();
SmallVector<bool> operandInCycle;
DenseSet<ChannelVal> allMergedValues;
DenseSet<Value> mergedValues;
for (Value oprd : dataOperands) {
mergedValues.clear();
bool inCycle = isOperandInCycle(oprd, channelVal, mergedValues);
operandInCycle.push_back(inCycle);
if (inCycle) {
for (Value &val : mergedValues)
allMergedValues.insert(cast<ChannelVal>(val));
} else {
allMergedValues.insert(cast<ChannelVal>(oprd));
}
}
// Determine the achievable optimized width for operands inside the cycle
unsigned optWidth = 0;
ExtType ext = ExtType::UNKNOWN;
for (ChannelVal mergedVal : allMergedValues) {
optWidth = std::max(
optWidth,
backtrackToMinimalValue(mergedVal, &ext).getType().getDataBitWidth());
}
// Check whether we managed to optimize anything
unsigned dataWidth = channelVal.getType().getDataBitWidth();
if (optWidth >= dataWidth)
return failure();
// Get the minimal valuue of all data operands
SmallVector<ChannelVal> minDataOperands;
for (Value oprd : dataOperands)
minDataOperands.push_back(getMinimalValue(cast<ChannelVal>(oprd)));
// Create a new operation as well as appropriate bitwidth modification
// operations to keep the IR valid
Cfg cfg(op);
SmallVector<Value> newOperands;
SmallVector<Value> newResults;
SmallVector<Type> newResTypes;
Type newDataType = rewriter.getIntegerType(optWidth);
Type newChannelType = channelVal.getType().withDataType(newDataType);
cfg.getNewOperands(optWidth, ext, minDataOperands, rewriter, newOperands);
cfg.getResultTypes(newChannelType, newResTypes);
rewriter.setInsertionPoint(op);
Op newOp = cfg.createOp(newResTypes, newOperands, rewriter);
namer.replaceOp(op, newOp);
inheritBB(op, newOp);
cfg.modResults(newOp, dataWidth, ext, rewriter, newResults);
// Replace uses of the original operation's results with the results of the
// optimized operation we just created
rewriter.replaceOp(op, newResults);
return success();
}
protected:
/// A reference to the pass's name analysis.
NameAnalysis &namer;
};
/// Template specialization of forward cycle optimization rewrite pattern for
/// Handshake operations that do not require a specific configuration.
template <typename Op>
using ForwardCycleOptNoCfg = ForwardCycleOpt<Op, OptDataConfig<Op>>;
} // namespace
//===----------------------------------------------------------------------===//
// Patterns for arith operations
//===----------------------------------------------------------------------===//
namespace {
/// Transfer function type for arithmetic operations with two operands and a
/// single result of the same type. Returns the result bitwidth required to
/// achieve the operation behavior given the two operands' respective bitwidths.
using FTransfer = std::function<unsigned(unsigned, unsigned)>;
/// Generic rewrite pattern for arith operations that have two operands and a