21#include "mlir/IR/AttrTypeSubElements.h"
22#include "mlir/Pass/Pass.h"
24#include "mlir/Transforms/DialectConversion.h"
25#include "llvm/ADT/TypeSwitch.h"
28#define GEN_PASS_DEF_HWARITHTOHW
29#include "circt/Conversion/Passes.h.inc"
46 llvm::function_ref<std::string(StringRef)> namehintCallback) {
47 if (
auto *sourceOp = oldValue.getDefiningOp()) {
49 sourceOp->getAttrOfType<mlir::StringAttr>(
"sv.namehint")) {
50 auto newNamehint = namehintCallback(namehint.strref());
51 newOp->setAttr(
"sv.namehint",
52 StringAttr::get(oldValue.getContext(), newNamehint));
58static Value
extractBits(OpBuilder &builder, Location loc, Value value,
59 unsigned startBit,
unsigned bitWidth) {
60 Value extractedValue =
62 Operation *definingOp = extractedValue.getDefiningOp();
63 if (extractedValue != value && definingOp) {
66 return (oldNamehint +
"_" + std::to_string(startBit) +
"_to_" +
67 std::to_string(startBit + bitWidth))
71 return extractedValue;
77 unsigned targetWidth,
bool signExtension) {
78 unsigned sourceWidth = value.getType().getIntOrFloatBitWidth();
79 unsigned extensionLength = targetWidth - sourceWidth;
81 if (extensionLength == 0)
91 builder.createOrFold<comb::ReplicateOp>(loc, highBit, extensionLength);
96 builder.getIntegerType(extensionLength), 0)
100 auto extOp = comb::ConcatOp::create(builder, loc, extensionBits, value);
102 return (oldNamehint +
"_" + (signExtension ?
"sext_" :
"zext_") +
103 std::to_string(targetWidth))
107 return extOp->getOpResult(0);
112 llvm::TypeSwitch<Type, bool>(type)
113 .Case<IntegerType>([](
auto type) {
return !type.isSignless(); })
114 .Case<hw::ArrayType>(
116 .Case<hw::UnpackedArrayType>(
118 .Case<hw::StructType>([](
auto type) {
119 return llvm::any_of(type.getElements(), [](
auto element) {
120 return isSignednessType(element.type);
123 .Case<hw::UnionType>([](
auto type) {
124 return llvm::any_of(type.getElements(), [](
auto element) {
125 return isSignednessType(element.type);
128 .Case<hw::InOutType>(
134 .Case<hw::TypeAliasType>(
136 .Default([](
auto type) {
return false; });
142 if (
auto typeAttr = dyn_cast<TypeAttr>(attr))
150 if (
auto funcOp = dyn_cast<FunctionOpInterface>(op)) {
153 llvm::none_of(funcOp.getFunctionBody().getArgumentTypes(),
157 if (
auto modOp = dyn_cast<hw::HWModuleLike>(op)) {
159 llvm::none_of(modOp.getModuleBody().getArgumentTypes(),
163 auto attrs = llvm::map_range(op->getAttrs(), [](
const NamedAttribute &attr) {
164 return attr.getValue();
170 return operandsOK && resultsOK && attrsOK;
179 using OpConversionPattern<ConstantOp>::OpConversionPattern;
182 matchAndRewrite(ConstantOp constOp, OpAdaptor adaptor,
183 ConversionPatternRewriter &rewriter)
const override {
186 Type resultType = getTypeConverter()->convertType(constOp.getType());
189 auto valueAttr = rewriter.getIntegerAttr(
190 hw::type_cast<IntegerType>(resultType), constOp.getConstantValue());
191 rewriter.replaceOpWithNewOp<hw::ConstantOp>(constOp, resultType, valueAttr);
196struct AggregateConstantOpLowering
198 using OpConversionPattern<hw::AggregateConstantOp>::OpConversionPattern;
201 matchAndRewrite(hw::AggregateConstantOp op, OpAdaptor adaptor,
202 ConversionPatternRewriter &rewriter)
const override {
203 auto fields = op.getFieldsAttr().replace([&](IntegerType type) {
204 return getTypeConverter()->convertType(type);
207 return rewriter.notifyMatchFailure(op,
208 "attribute type conversion failed");
209 rewriter.modifyOpInPlace(
210 op, [&] { op.setFieldsAttr(cast<ArrayAttr>(fields)); });
217 using OpConversionPattern<DivOp>::OpConversionPattern;
220 matchAndRewrite(DivOp op, OpAdaptor adaptor,
221 ConversionPatternRewriter &rewriter)
const override {
222 auto loc = op.getLoc();
223 auto isLhsTypeSigned =
224 cast<IntegerType>(op.getOperand(0).getType()).isSigned();
225 auto rhsType = cast<IntegerType>(op.getOperand(1).getType());
226 auto targetType = cast<IntegerType>(op.getResult().getType());
237 bool signedDivision = targetType.isSigned();
238 unsigned extendSize = std::max(
239 targetType.getWidth(),
240 rhsType.getWidth() + (signedDivision && !rhsType.isSigned() ? 1 : 0));
243 Value lhsValue =
extendTypeWidth(rewriter, loc, adaptor.getInputs()[0],
244 extendSize, isLhsTypeSigned);
245 Value rhsValue =
extendTypeWidth(rewriter, loc, adaptor.getInputs()[1],
246 extendSize, rhsType.isSigned());
250 divResult = comb::DivSOp::create(rewriter, loc, lhsValue, rhsValue,
false)
253 divResult = comb::DivUOp::create(rewriter, loc, lhsValue, rhsValue,
false)
257 auto *divOp = divResult.getDefiningOp();
258 rewriter.modifyOpInPlace(
259 divOp, [&]() { divOp->setDialectAttrs(op->getDialectAttrs()); });
262 Value truncateResult =
extractBits(rewriter, loc, divResult, 0,
263 targetType.getWidth());
264 rewriter.replaceOp(op, truncateResult);
273 using OpConversionPattern<CastOp>::OpConversionPattern;
276 matchAndRewrite(CastOp op, OpAdaptor adaptor,
277 ConversionPatternRewriter &rewriter)
const override {
278 auto sourceType = cast<IntegerType>(op.getIn().getType());
279 auto sourceWidth = sourceType.getWidth();
280 bool isSourceTypeSigned = sourceType.isSigned();
281 auto targetWidth = cast<IntegerType>(op.getOut().getType()).getWidth();
284 if (sourceWidth == targetWidth) {
287 replaceValue = adaptor.getIn();
288 }
else if (sourceWidth < targetWidth) {
292 targetWidth, isSourceTypeSigned);
295 replaceValue =
extractBits(rewriter, op.getLoc(), adaptor.getIn(),
298 rewriter.replaceOp(op, replaceValue);
310static comb::ICmpPredicate lowerPredicate(ICmpPredicate pred,
bool isSigned) {
312 case ICmpPredicate::eq:
313 return comb::ICmpPredicate::eq;
314 case ICmpPredicate::ne:
315 return comb::ICmpPredicate::ne;
316 case ICmpPredicate::lt:
317 return isSigned ? comb::ICmpPredicate::slt : comb::ICmpPredicate::ult;
318 case ICmpPredicate::ge:
319 return isSigned ? comb::ICmpPredicate::sge : comb::ICmpPredicate::uge;
320 case ICmpPredicate::le:
321 return isSigned ? comb::ICmpPredicate::sle : comb::ICmpPredicate::ule;
322 case ICmpPredicate::gt:
323 return isSigned ? comb::ICmpPredicate::sgt : comb::ICmpPredicate::ugt;
327 "Missing hwarith::ICmpPredicate to comb::ICmpPredicate lowering");
328 return comb::ICmpPredicate::eq;
332 using OpConversionPattern<ICmpOp>::OpConversionPattern;
335 matchAndRewrite(ICmpOp op, OpAdaptor adaptor,
336 ConversionPatternRewriter &rewriter)
const override {
337 auto lhsType = cast<IntegerType>(op.getLhs().getType());
338 auto rhsType = cast<IntegerType>(op.getRhs().getType());
339 IntegerType::SignednessSemantics cmpSignedness;
340 const unsigned cmpWidth =
343 ICmpPredicate pred = op.getPredicate();
344 comb::ICmpPredicate combPred = lowerPredicate(
345 pred, cmpSignedness == IntegerType::SignednessSemantics::Signed);
347 const auto loc = op.getLoc();
348 Value lhsValue =
extendTypeWidth(rewriter, loc, adaptor.getLhs(), cmpWidth,
350 Value rhsValue =
extendTypeWidth(rewriter, loc, adaptor.getRhs(), cmpWidth,
353 auto newOp = comb::ICmpOp::create(rewriter, op->getLoc(), combPred,
354 lhsValue, rhsValue,
false);
355 rewriter.modifyOpInPlace(
356 newOp, [&]() { newOp->setDialectAttrs(op->getDialectAttrs()); });
357 rewriter.replaceOp(op, newOp);
363template <
class BinOp,
class ReplaceOp>
365 using OpConversionPattern<BinOp>::OpConversionPattern;
366 using OpAdaptor =
typename OpConversionPattern<BinOp>::OpAdaptor;
369 matchAndRewrite(BinOp op, OpAdaptor adaptor,
370 ConversionPatternRewriter &rewriter)
const override {
371 auto loc = op.getLoc();
372 auto isLhsTypeSigned =
373 cast<IntegerType>(op.getOperand(0).getType()).isSigned();
374 auto isRhsTypeSigned =
375 cast<IntegerType>(op.getOperand(1).getType()).isSigned();
376 auto targetWidth = cast<IntegerType>(op.getResult().getType()).getWidth();
378 Value lhsValue =
extendTypeWidth(rewriter, loc, adaptor.getInputs()[0],
379 targetWidth, isLhsTypeSigned);
380 Value rhsValue =
extendTypeWidth(rewriter, loc, adaptor.getInputs()[1],
381 targetWidth, isRhsTypeSigned);
383 ReplaceOp::create(rewriter, op.getLoc(), lhsValue, rhsValue,
false);
384 rewriter.modifyOpInPlace(
385 newOp, [&]() { newOp->setDialectAttrs(op->getDialectAttrs()); });
386 rewriter.replaceOp(op, newOp);
400 [](IntegerType type) -> std::optional<Type> {
401 if (type.isSignless())
403 return IntegerType::get(type.getContext(), type.getWidth());
409 addTargetMaterialization([&](mlir::OpBuilder &builder, mlir::Type resultType,
410 mlir::ValueRange inputs,
411 mlir::Location loc) -> mlir::Value {
412 if (inputs.size() != 1)
414 return UnrealizedConversionCastOp::create(builder, loc, resultType,
419 addSourceMaterialization([&](mlir::OpBuilder &builder, mlir::Type resultType,
420 mlir::ValueRange inputs,
421 mlir::Location loc) -> mlir::Value {
422 if (inputs.size() != 1)
424 return UnrealizedConversionCastOp::create(builder, loc, resultType,
436 patterns.add<ConstantOpLowering, AggregateConstantOpLowering, CastOpLowering,
437 ICmpOpLowering, BinaryOpLowering<AddOp, comb::AddOp>,
438 BinaryOpLowering<SubOp, comb::SubOp>,
439 BinaryOpLowering<MulOp, comb::MulOp>, DivOpLowering>(
440 typeConverter,
patterns.getContext());
445class HWArithToHWPass :
public circt::impl::HWArithToHWBase<HWArithToHWPass> {
447 void runOnOperation()
override {
448 ModuleOp module = getOperation();
451 target.markUnknownOpDynamicallyLegal(
isLegalOp);
452 RewritePatternSet
patterns(&getContext());
454 target.addIllegalDialect<HWArithDialect>();
467 if (failed(applyFullConversion(module, target, std::move(
patterns))))
468 return signalPassFailure();
478 return std::make_unique<HWArithToHWPass>();
static bool isLegalOp(Operation *op)
Returns true if the given op is considered as legal - i.e.
static bool isSignednessAttr(Attribute attr)
static bool isLegalOp(Operation *op)
Returns true if the given op is considered as legal for HWArith conversion.
static void improveNamehint(Value oldValue, Operation *newOp, llvm::function_ref< std::string(StringRef)> namehintCallback)
static Value extractBits(OpBuilder &builder, Location loc, Value value, unsigned startBit, unsigned bitWidth)
static bool isSignednessType(Type type)
static Value extendTypeWidth(OpBuilder &builder, Location loc, Value value, unsigned targetWidth, bool signExtension)
false return failure()
Parse an optional keyword or string and set instance into 'result'.
A helper type converter class that automatically populates the relevant materializations and type con...
mlir::AttrTypeReplacer signednessReplacer
mlir::Type removeSignedness(mlir::Type type)
HWArithToHWTypeConverter()
unsigned inferAddResultType(IntegerType::SignednessSemantics &signedness, IntegerType lhs, IntegerType rhs)
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
void populateHWArithToHWConversionPatterns(HWArithToHWTypeConverter &typeConverter, RewritePatternSet &patterns)
Get the HWArith to HW conversion patterns.
std::unique_ptr< mlir::Pass > createHWArithToHWPass()
LogicalResult doTypeConversion(Operation *op, ValueRange operands, ConversionPatternRewriter &rewriter, const TypeConverter *typeConverter)
Generic pattern which replaces an operation by one of the same operation name, but with converted att...