-
Notifications
You must be signed in to change notification settings - Fork 336
/
Copy pathCombToAIG.cpp
648 lines (562 loc) · 24.4 KB
/
CombToAIG.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
//===- CombToAIG.cpp - Comb to AIG Conversion Pass --------------*- 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 is the main Comb to AIG Conversion Pass Implementation.
//
//===----------------------------------------------------------------------===//
#include "circt/Conversion/CombToAIG.h"
#include "circt/Dialect/AIG/AIGOps.h"
#include "circt/Dialect/Comb/CombOps.h"
#include "circt/Dialect/HW/HWOps.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
namespace circt {
#define GEN_PASS_DEF_CONVERTCOMBTOAIG
#include "circt/Conversion/Passes.h.inc"
} // namespace circt
using namespace circt;
using namespace comb;
//===----------------------------------------------------------------------===//
// Utility Functions
//===----------------------------------------------------------------------===//
// A wrapper for comb::extractBits that returns a SmallVector<Value>.
static SmallVector<Value> extractBits(OpBuilder &builder, Value val) {
SmallVector<Value> bits;
comb::extractBits(builder, val, bits);
return bits;
}
// Construct a mux tree for shift operations. `isLeftShift` controls the
// direction of the shift operation and is used to determine order of the
// padding and extracted bits. Callbacks `getPadding` and `getExtract` are used
// to get the padding and extracted bits for each shift amount. `getPadding`
// could return a nullptr as i0 value but except for that, these callbacks must
// return a valid value for each shift amount in the range [0, maxShiftAmount].
// The value for `maxShiftAmount` is used as the out-of-bounds value.
template <bool isLeftShift>
static Value createShiftLogic(ConversionPatternRewriter &rewriter, Location loc,
Value shiftAmount, int64_t maxShiftAmount,
llvm::function_ref<Value(int64_t)> getPadding,
llvm::function_ref<Value(int64_t)> getExtract) {
// Extract individual bits from shift amount
auto bits = extractBits(rewriter, shiftAmount);
// Create nodes for each possible shift amount
SmallVector<Value> nodes;
nodes.reserve(maxShiftAmount);
for (int64_t i = 0; i < maxShiftAmount; ++i) {
Value extract = getExtract(i);
Value padding = getPadding(i);
if (!padding) {
nodes.push_back(extract);
continue;
}
// Concatenate extracted bits with padding
if (isLeftShift)
nodes.push_back(
rewriter.createOrFold<comb::ConcatOp>(loc, extract, padding));
else
nodes.push_back(
rewriter.createOrFold<comb::ConcatOp>(loc, padding, extract));
}
// Create out-of-bounds value
auto outOfBoundsValue = getPadding(maxShiftAmount);
assert(outOfBoundsValue && "outOfBoundsValue must be valid");
// Construct mux tree for shift operation
auto result =
comb::constructMuxTree(rewriter, loc, bits, nodes, outOfBoundsValue);
// Add bounds checking
auto inBound = rewriter.createOrFold<comb::ICmpOp>(
loc, ICmpPredicate::ult, shiftAmount,
rewriter.create<hw::ConstantOp>(loc, shiftAmount.getType(),
maxShiftAmount));
return rewriter.createOrFold<comb::MuxOp>(loc, inBound, result,
outOfBoundsValue);
}
//===----------------------------------------------------------------------===//
// Conversion patterns
//===----------------------------------------------------------------------===//
namespace {
/// Lower a comb::AndOp operation to aig::AndInverterOp
struct CombAndOpConversion : OpConversionPattern<AndOp> {
using OpConversionPattern<AndOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(AndOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
SmallVector<bool> nonInverts(adaptor.getInputs().size(), false);
rewriter.replaceOpWithNewOp<aig::AndInverterOp>(op, adaptor.getInputs(),
nonInverts);
return success();
}
};
/// Lower a comb::OrOp operation to aig::AndInverterOp with invert flags
struct CombOrOpConversion : OpConversionPattern<OrOp> {
using OpConversionPattern<OrOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(OrOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
// Implement Or using And and invert flags: a | b = ~(~a & ~b)
SmallVector<bool> allInverts(adaptor.getInputs().size(), true);
auto andOp = rewriter.create<aig::AndInverterOp>(
op.getLoc(), adaptor.getInputs(), allInverts);
rewriter.replaceOpWithNewOp<aig::AndInverterOp>(op, andOp,
/*invert=*/true);
return success();
}
};
/// Lower a comb::XorOp operation to AIG operations
struct CombXorOpConversion : OpConversionPattern<XorOp> {
using OpConversionPattern<XorOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(XorOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
if (op.getNumOperands() != 2)
return failure();
// Xor using And with invert flags: a ^ b = (a | b) & (~a | ~b)
// (a | b) = ~(~a & ~b)
// (~a | ~b) = ~(a & b)
auto inputs = adaptor.getInputs();
SmallVector<bool> allInverts(inputs.size(), true);
SmallVector<bool> allNotInverts(inputs.size(), false);
auto notAAndNotB =
rewriter.create<aig::AndInverterOp>(op.getLoc(), inputs, allInverts);
auto aAndB =
rewriter.create<aig::AndInverterOp>(op.getLoc(), inputs, allNotInverts);
rewriter.replaceOpWithNewOp<aig::AndInverterOp>(op, notAAndNotB, aAndB,
/*lhs_invert=*/true,
/*rhs_invert=*/true);
return success();
}
};
template <typename OpTy>
struct CombLowerVariadicOp : OpConversionPattern<OpTy> {
using OpConversionPattern<OpTy>::OpConversionPattern;
using OpAdaptor = typename OpConversionPattern<OpTy>::OpAdaptor;
LogicalResult
matchAndRewrite(OpTy op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto result = lowerFullyAssociativeOp(op, op.getOperands(), rewriter);
rewriter.replaceOp(op, result);
return success();
}
static Value lowerFullyAssociativeOp(OpTy op, OperandRange operands,
ConversionPatternRewriter &rewriter) {
Value lhs, rhs;
switch (operands.size()) {
case 0:
assert(false && "cannot be called with empty operand range");
break;
case 1:
return operands[0];
case 2:
lhs = operands[0];
rhs = operands[1];
return rewriter.create<OpTy>(op.getLoc(), ValueRange{lhs, rhs}, true);
default:
auto firstHalf = operands.size() / 2;
lhs =
lowerFullyAssociativeOp(op, operands.take_front(firstHalf), rewriter);
rhs =
lowerFullyAssociativeOp(op, operands.drop_front(firstHalf), rewriter);
return rewriter.create<OpTy>(op.getLoc(), ValueRange{lhs, rhs}, true);
}
}
};
// Lower comb::MuxOp to AIG operations.
struct CombMuxOpConversion : OpConversionPattern<MuxOp> {
using OpConversionPattern<MuxOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(MuxOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
// Implement: c ? a : b = (replicate(c) & a) | (~replicate(c) & b)
Value cond = op.getCond();
auto trueVal = op.getTrueValue();
auto falseVal = op.getFalseValue();
if (!op.getType().isInteger()) {
// If the type of the mux is not integer, bitcast the operands first.
auto widthType = rewriter.getIntegerType(hw::getBitWidth(op.getType()));
trueVal =
rewriter.create<hw::BitcastOp>(op->getLoc(), widthType, trueVal);
falseVal =
rewriter.create<hw::BitcastOp>(op->getLoc(), widthType, falseVal);
}
// Replicate condition if needed
if (!trueVal.getType().isInteger(1))
cond = rewriter.create<comb::ReplicateOp>(op.getLoc(), trueVal.getType(),
cond);
// c ? a : b => (replicate(c) & a) | (~replicate(c) & b)
auto lhs = rewriter.create<aig::AndInverterOp>(op.getLoc(), cond, trueVal);
auto rhs = rewriter.create<aig::AndInverterOp>(op.getLoc(), cond, falseVal,
true, false);
Value result = rewriter.create<comb::OrOp>(op.getLoc(), lhs, rhs);
// Insert the bitcast if the type of the mux is not integer.
if (result.getType() != op.getType())
result =
rewriter.create<hw::BitcastOp>(op.getLoc(), op.getType(), result);
rewriter.replaceOp(op, result);
return success();
}
};
struct CombAddOpConversion : OpConversionPattern<AddOp> {
using OpConversionPattern<AddOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(AddOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto inputs = adaptor.getInputs();
// Lower only when there are two inputs.
// Variadic operands must be lowered in a different pattern.
if (inputs.size() != 2)
return failure();
auto width = op.getType().getIntOrFloatBitWidth();
// Skip a zero width value.
if (width == 0) {
rewriter.replaceOpWithNewOp<hw::ConstantOp>(op, op.getType(), 0);
return success();
}
// Implement a naive Ripple-carry full adder.
Value carry;
auto aBits = extractBits(rewriter, inputs[0]);
auto bBits = extractBits(rewriter, inputs[1]);
SmallVector<Value> results;
results.resize(width);
for (int64_t i = 0; i < width; ++i) {
SmallVector<Value> xorOperands = {aBits[i], bBits[i]};
if (carry)
xorOperands.push_back(carry);
// sum[i] = xor(carry[i-1], a[i], b[i])
// NOTE: The result is stored in reverse order.
results[width - i - 1] =
rewriter.create<comb::XorOp>(op.getLoc(), xorOperands, true);
// If this is the last bit, we are done.
if (i == width - 1) {
break;
}
// carry[i] = (carry[i-1] & (a[i] ^ b[i])) | (a[i] & b[i])
Value nextCarry = rewriter.create<comb::AndOp>(
op.getLoc(), ValueRange{aBits[i], bBits[i]}, true);
if (!carry) {
// This is the first bit, so the carry is the next carry.
carry = nextCarry;
continue;
}
auto aXnorB = rewriter.create<comb::XorOp>(
op.getLoc(), ValueRange{aBits[i], bBits[i]}, true);
auto andOp = rewriter.create<comb::AndOp>(
op.getLoc(), ValueRange{carry, aXnorB}, true);
carry = rewriter.create<comb::OrOp>(op.getLoc(),
ValueRange{andOp, nextCarry}, true);
}
rewriter.replaceOpWithNewOp<comb::ConcatOp>(op, results);
return success();
}
};
struct CombSubOpConversion : OpConversionPattern<SubOp> {
using OpConversionPattern<SubOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(SubOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto lhs = op.getLhs();
auto rhs = op.getRhs();
// Since `-rhs = ~rhs + 1` holds, rewrite `sub(lhs, rhs)` to:
// sub(lhs, rhs) => add(lhs, -rhs) => add(lhs, add(~rhs, 1))
// => add(lhs, ~rhs, 1)
auto notRhs = rewriter.create<aig::AndInverterOp>(op.getLoc(), rhs,
/*invert=*/true);
auto one = rewriter.create<hw::ConstantOp>(op.getLoc(), op.getType(), 1);
rewriter.replaceOpWithNewOp<comb::AddOp>(op, ValueRange{lhs, notRhs, one},
true);
return success();
}
};
struct CombMulOpConversion : OpConversionPattern<MulOp> {
using OpConversionPattern<MulOp>::OpConversionPattern;
using OpAdaptor = typename OpConversionPattern<MulOp>::OpAdaptor;
LogicalResult
matchAndRewrite(MulOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
if (adaptor.getInputs().size() != 2)
return failure();
// FIXME: Currently it's lowered to a really naive implementation that
// chains add operations.
// a_{n}a_{n-1}...a_0 * b
// = sum_{i=0}^{n} a_i * 2^i * b
// = sum_{i=0}^{n} (a_i ? b : 0) << i
int64_t width = op.getType().getIntOrFloatBitWidth();
auto aBits = extractBits(rewriter, adaptor.getInputs()[0]);
SmallVector<Value> results;
auto rhs = op.getInputs()[1];
auto zero = rewriter.create<hw::ConstantOp>(op.getLoc(),
llvm::APInt::getZero(width));
for (int64_t i = 0; i < width; ++i) {
auto aBit = aBits[i];
auto andBit =
rewriter.createOrFold<comb::MuxOp>(op.getLoc(), aBit, rhs, zero);
auto upperBits = rewriter.createOrFold<comb::ExtractOp>(
op.getLoc(), andBit, 0, width - i);
if (i == 0) {
results.push_back(upperBits);
continue;
}
auto lowerBits =
rewriter.create<hw::ConstantOp>(op.getLoc(), APInt::getZero(i));
auto shifted = rewriter.createOrFold<comb::ConcatOp>(
op.getLoc(), op.getType(), ValueRange{upperBits, lowerBits});
results.push_back(shifted);
}
rewriter.replaceOpWithNewOp<comb::AddOp>(op, results, true);
return success();
}
};
struct CombICmpOpConversion : OpConversionPattern<ICmpOp> {
using OpConversionPattern<ICmpOp>::OpConversionPattern;
static Value constructUnsignedCompare(ICmpOp op, ArrayRef<Value> aBits,
ArrayRef<Value> bBits, bool isLess,
bool includeEq,
ConversionPatternRewriter &rewriter) {
// Construct following unsigned comparison expressions.
// a <= b ==> (~a[n] & b[n]) | (a[n] == b[n] & a[n-1:0] <= b[n-1:0])
// a < b ==> (~a[n] & b[n]) | (a[n] == b[n] & a[n-1:0] < b[n-1:0])
// a >= b ==> ( a[n] & ~b[n]) | (a[n] == b[n] & a[n-1:0] >= b[n-1:0])
// a > b ==> ( a[n] & ~b[n]) | (a[n] == b[n] & a[n-1:0] > b[n-1:0])
Value acc =
rewriter.create<hw::ConstantOp>(op.getLoc(), op.getType(), includeEq);
for (auto [aBit, bBit] : llvm::zip(aBits, bBits)) {
auto aBitXorBBit =
rewriter.createOrFold<comb::XorOp>(op.getLoc(), aBit, bBit, true);
auto aEqualB = rewriter.createOrFold<aig::AndInverterOp>(
op.getLoc(), aBitXorBBit, true);
auto pred = rewriter.createOrFold<aig::AndInverterOp>(
op.getLoc(), aBit, bBit, isLess, !isLess);
auto aBitAndBBit = rewriter.createOrFold<comb::AndOp>(
op.getLoc(), ValueRange{aEqualB, acc}, true);
acc = rewriter.createOrFold<comb::OrOp>(op.getLoc(), pred, aBitAndBBit,
true);
}
return acc;
}
LogicalResult
matchAndRewrite(ICmpOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto lhs = adaptor.getLhs();
auto rhs = adaptor.getRhs();
switch (op.getPredicate()) {
default:
return failure();
case ICmpPredicate::eq:
case ICmpPredicate::ceq: {
// a == b ==> ~(a[n] ^ b[n]) & ~(a[n-1] ^ b[n-1]) & ...
auto xorOp = rewriter.createOrFold<comb::XorOp>(op.getLoc(), lhs, rhs);
auto xorBits = extractBits(rewriter, xorOp);
SmallVector<bool> allInverts(xorBits.size(), true);
rewriter.replaceOpWithNewOp<aig::AndInverterOp>(op, xorBits, allInverts);
return success();
}
case ICmpPredicate::ne:
case ICmpPredicate::cne: {
// a != b ==> (a[n] ^ b[n]) | (a[n-1] ^ b[n-1]) | ...
auto xorOp = rewriter.createOrFold<comb::XorOp>(op.getLoc(), lhs, rhs);
rewriter.replaceOpWithNewOp<comb::OrOp>(op, extractBits(rewriter, xorOp),
true);
return success();
}
case ICmpPredicate::uge:
case ICmpPredicate::ugt:
case ICmpPredicate::ule:
case ICmpPredicate::ult: {
bool isLess = op.getPredicate() == ICmpPredicate::ult ||
op.getPredicate() == ICmpPredicate::ule;
bool includeEq = op.getPredicate() == ICmpPredicate::uge ||
op.getPredicate() == ICmpPredicate::ule;
auto aBits = extractBits(rewriter, lhs);
auto bBits = extractBits(rewriter, rhs);
rewriter.replaceOp(op, constructUnsignedCompare(op, aBits, bBits, isLess,
includeEq, rewriter));
return success();
}
case ICmpPredicate::slt:
case ICmpPredicate::sle:
case ICmpPredicate::sgt:
case ICmpPredicate::sge: {
if (lhs.getType().getIntOrFloatBitWidth() == 0)
return rewriter.notifyMatchFailure(
op.getLoc(), "i0 signed comparison is unsupported");
bool isLess = op.getPredicate() == ICmpPredicate::slt ||
op.getPredicate() == ICmpPredicate::sle;
bool includeEq = op.getPredicate() == ICmpPredicate::sge ||
op.getPredicate() == ICmpPredicate::sle;
auto aBits = extractBits(rewriter, lhs);
auto bBits = extractBits(rewriter, rhs);
// Get a sign bit
auto signA = aBits.back();
auto signB = bBits.back();
// Compare magnitudes (all bits except sign)
auto sameSignResult = constructUnsignedCompare(
op, ArrayRef(aBits).drop_back(), ArrayRef(bBits).drop_back(), isLess,
includeEq, rewriter);
// XOR of signs: true if signs are different
auto signsDiffer =
rewriter.create<comb::XorOp>(op.getLoc(), signA, signB);
// Result when signs are different
Value diffSignResult = isLess ? signA : signB;
// Final result: choose based on whether signs differ
rewriter.replaceOpWithNewOp<comb::MuxOp>(op, signsDiffer, diffSignResult,
sameSignResult);
return success();
}
}
}
};
struct CombParityOpConversion : OpConversionPattern<ParityOp> {
using OpConversionPattern<ParityOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(ParityOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
// Parity is the XOR of all bits.
rewriter.replaceOpWithNewOp<comb::XorOp>(
op, extractBits(rewriter, adaptor.getInput()), true);
return success();
}
};
struct CombShlOpConversion : OpConversionPattern<comb::ShlOp> {
using OpConversionPattern<comb::ShlOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(comb::ShlOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto width = op.getType().getIntOrFloatBitWidth();
auto lhs = adaptor.getLhs();
auto result = createShiftLogic</*isLeftShift=*/true>(
rewriter, op.getLoc(), adaptor.getRhs(), width,
/*getPadding=*/
[&](int64_t index) {
// Don't create zero width value.
if (index == 0)
return Value();
// Padding is 0 for left shift.
return rewriter.createOrFold<hw::ConstantOp>(
op.getLoc(), rewriter.getIntegerType(index), 0);
},
/*getExtract=*/
[&](int64_t index) {
assert(index < width && "index out of bounds");
// Exract the bits from LSB.
return rewriter.createOrFold<comb::ExtractOp>(op.getLoc(), lhs, 0,
width - index);
});
rewriter.replaceOp(op, result);
return success();
}
};
struct CombShrUOpConversion : OpConversionPattern<comb::ShrUOp> {
using OpConversionPattern<comb::ShrUOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(comb::ShrUOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto width = op.getType().getIntOrFloatBitWidth();
auto lhs = adaptor.getLhs();
auto result = createShiftLogic</*isLeftShift=*/false>(
rewriter, op.getLoc(), adaptor.getRhs(), width,
/*getPadding=*/
[&](int64_t index) {
// Don't create zero width value.
if (index == 0)
return Value();
// Padding is 0 for right shift.
return rewriter.createOrFold<hw::ConstantOp>(
op.getLoc(), rewriter.getIntegerType(index), 0);
},
/*getExtract=*/
[&](int64_t index) {
assert(index < width && "index out of bounds");
// Exract the bits from MSB.
return rewriter.createOrFold<comb::ExtractOp>(op.getLoc(), lhs, index,
width - index);
});
rewriter.replaceOp(op, result);
return success();
}
};
struct CombShrSOpConversion : OpConversionPattern<comb::ShrSOp> {
using OpConversionPattern<comb::ShrSOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(comb::ShrSOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto width = op.getType().getIntOrFloatBitWidth();
if (width == 0)
return rewriter.notifyMatchFailure(op.getLoc(),
"i0 signed shift is unsupported");
auto lhs = adaptor.getLhs();
// Get the sign bit.
auto sign =
rewriter.createOrFold<comb::ExtractOp>(op.getLoc(), lhs, width - 1, 1);
// NOTE: The max shift amount is width - 1 because the sign bit is already
// shifted out.
auto result = createShiftLogic</*isLeftShift=*/false>(
rewriter, op.getLoc(), adaptor.getRhs(), width - 1,
/*getPadding=*/
[&](int64_t index) {
return rewriter.createOrFold<comb::ReplicateOp>(op.getLoc(), sign,
index + 1);
},
/*getExtract=*/
[&](int64_t index) {
return rewriter.createOrFold<comb::ExtractOp>(op.getLoc(), lhs, index,
width - index - 1);
});
rewriter.replaceOp(op, result);
return success();
}
};
} // namespace
//===----------------------------------------------------------------------===//
// Convert Comb to AIG pass
//===----------------------------------------------------------------------===//
namespace {
struct ConvertCombToAIGPass
: public impl::ConvertCombToAIGBase<ConvertCombToAIGPass> {
void runOnOperation() override;
using ConvertCombToAIGBase<ConvertCombToAIGPass>::ConvertCombToAIGBase;
using ConvertCombToAIGBase<ConvertCombToAIGPass>::additionalLegalOps;
};
} // namespace
static void populateCombToAIGConversionPatterns(RewritePatternSet &patterns) {
patterns.add<
// Bitwise Logical Ops
CombAndOpConversion, CombOrOpConversion, CombXorOpConversion,
CombMuxOpConversion, CombParityOpConversion,
// Arithmetic Ops
CombAddOpConversion, CombSubOpConversion, CombMulOpConversion,
CombICmpOpConversion,
// Shift Ops
CombShlOpConversion, CombShrUOpConversion, CombShrSOpConversion,
// Variadic ops that must be lowered to binary operations
CombLowerVariadicOp<XorOp>, CombLowerVariadicOp<AddOp>,
CombLowerVariadicOp<MulOp>>(patterns.getContext());
}
void ConvertCombToAIGPass::runOnOperation() {
ConversionTarget target(getContext());
// Comb is source dialect.
target.addIllegalDialect<comb::CombDialect>();
// Keep data movement operations like Extract, Concat and Replicate.
target.addLegalOp<comb::ExtractOp, comb::ConcatOp, comb::ReplicateOp,
hw::BitcastOp, hw::ConstantOp>();
// Treat array operations as illegal. Strictly speaking, other than array get
// operation with non-const index are legal in AIG but array types prevent a
// bunch of optimizations so just lower them to integer operations. It's
// required to run HWAggregateToComb pass before this pass.
target.addIllegalOp<hw::ArrayGetOp, hw::ArrayCreateOp, hw::ArrayConcatOp,
hw::AggregateConstantOp>();
// AIG is target dialect.
target.addLegalDialect<aig::AIGDialect>();
// This is a test only option to add logical ops.
if (!additionalLegalOps.empty())
for (const auto &opName : additionalLegalOps)
target.addLegalOp(OperationName(opName, &getContext()));
RewritePatternSet patterns(&getContext());
populateCombToAIGConversionPatterns(patterns);
if (failed(mlir::applyPartialConversion(getOperation(), target,
std::move(patterns))))
return signalPassFailure();
}