407 if (sourceElementType == targetElementType)
410 auto targetIntType = dyn_cast<IntegerType>(targetElementType);
417 if (
auto sourceFloatType = dyn_cast<FloatType>(sourceElementType)) {
418 if (sourceFloatType.getWidth() != targetIntType.getWidth())
427 if (!isa<IndexType>(sourceElementType))
431 unsigned width = targetIntType.getWidth();
433 if (
auto intAttr = dyn_cast<IntegerAttr>(attr))
434 return IntegerAttr::get(targetIntType,
435 intAttr.getValue().sextOrTrunc(width));
438 return values.mapValues(targetIntType, [&](
const APInt &value) {
439 return value.sextOrTrunc(width);
443 if (
auto denseAttr = dyn_cast<DenseIntElementsAttr>(attr))
444 return retypeValues(denseAttr);
446 if (
auto sparseAttr = dyn_cast<SparseElementsAttr>(attr))
447 return SparseElementsAttr::get(
448 cast<ShapedType>(attr.getType()).clone(targetIntType),
449 sparseAttr.getIndices(),
450 retypeValues(cast<DenseIntElementsAttr>(sparseAttr.getValues())));
456 if (
auto resourceAttr = dyn_cast<DenseResourceElementsAttr>(attr)) {
457 if (width != IndexType::kInternalStorageBitWidth)
459 return DenseResourceElementsAttr::get(
460 cast<ShapedType>(attr.getType()).clone(targetIntType),
461 resourceAttr.getRawHandle());
468ConstantOpLowering::matchAndRewrite(arith::ConstantOp op, OpAdaptor adaptor,
469 ConversionPatternRewriter &rewriter)
const {
470 Type resultType = getTypeConverter()->convertType(op.getType());
472 return rewriter.notifyMatchFailure(op,
"failed to convert result type");
476 return rewriter.notifyMatchFailure(
477 op,
"failed to convert value attribute to the converted result type");
482 DictionaryAttr discardableAttrs = op->getDiscardableAttrDictionary();
484 LLVM::ConstantOp::create(rewriter, op.getLoc(), resultType, value);
485 constantOp->setDiscardableAttrs(discardableAttrs);
486 rewriter.replaceOp(op, constantOp);
494template <
typename OpTy,
typename ExtCastTy>
495LogicalResult IndexCastOpLowering<OpTy, ExtCastTy>::matchAndRewrite(
496 OpTy op,
typename OpTy::Adaptor adaptor,
497 ConversionPatternRewriter &rewriter)
const {
498 Type resultType = op.getResult().getType();
499 Type targetElementType =
501 Type sourceElementType =
506 if (targetBits == sourceBits) {
507 rewriter.replaceOp(op, adaptor.getIn());
514 if (isa<MemRefType>(op.getIn().getType())) {
515 rewriter.replaceOp(op, adaptor.getIn());
519 bool isNonNeg =
false;
520 if constexpr (std::is_same_v<ExtCastTy, LLVM::ZExtOp>)
521 isNonNeg = op.getNonNeg();
524 Type operandType = adaptor.getIn().getType();
525 if (!isa<LLVM::LLVMArrayType>(operandType)) {
526 Type targetType = this->typeConverter->convertType(resultType);
527 if (targetBits < sourceBits) {
528 rewriter.replaceOpWithNewOp<LLVM::TruncOp>(op, targetType,
531 auto extOp = rewriter.replaceOpWithNewOp<ExtCastTy>(op, targetType,
533 if constexpr (std::is_same_v<ExtCastTy, LLVM::ZExtOp>)
534 extOp.setNonNeg(isNonNeg);
539 if (!isa<VectorType>(resultType))
540 return rewriter.notifyMatchFailure(op,
"expected vector result type");
543 op.getOperation(), adaptor.getOperands(), *(
this->getTypeConverter()),
544 [&](Type llvm1DVectorTy,
ValueRange operands) -> Value {
545 typename OpTy::Adaptor adaptor(operands);
546 if (targetBits < sourceBits) {
547 return LLVM::TruncOp::create(rewriter, op.getLoc(), llvm1DVectorTy,
550 auto extOp = ExtCastTy::create(rewriter, op.getLoc(), llvm1DVectorTy,
552 if constexpr (std::is_same_v<ExtCastTy, LLVM::ZExtOp>) {
554 extOp.setNonNeg(
true);
565LogicalResult AddUIExtendedOpLowering::matchAndRewrite(
566 arith::AddUIExtendedOp op, OpAdaptor adaptor,
567 ConversionPatternRewriter &rewriter)
const {
568 Type operandType = adaptor.getLhs().getType();
569 Type sumResultType = op.getSum().getType();
570 Type overflowResultType = op.getOverflow().getType();
575 MLIRContext *ctx = rewriter.getContext();
576 Location loc = op.getLoc();
579 if (!isa<LLVM::LLVMArrayType>(operandType)) {
580 Type newSumType = typeConverter->convertType(sumResultType);
581 Type newOverflowType = typeConverter->convertType(overflowResultType);
583 LLVM::LLVMStructType::getLiteral(ctx, {newSumType, newOverflowType});
584 Value addOverflow = LLVM::UAddWithOverflowOp::create(
585 rewriter, loc, structType, adaptor.getLhs(), adaptor.getRhs());
587 LLVM::ExtractValueOp::create(rewriter, loc, addOverflow, 0);
588 Value overflowExtracted =
589 LLVM::ExtractValueOp::create(rewriter, loc, addOverflow, 1);
590 rewriter.replaceOp(op, {sumExtracted, overflowExtracted});
594 if (!isa<VectorType>(sumResultType))
595 return rewriter.notifyMatchFailure(loc,
"expected vector result types");
597 return rewriter.notifyMatchFailure(loc,
598 "ND vector types are not supported yet");
605LogicalResult SubUIExtendedOpLowering::matchAndRewrite(
606 arith::SubUIExtendedOp op, OpAdaptor adaptor,
607 ConversionPatternRewriter &rewriter)
const {
608 Type operandType = adaptor.getLhs().getType();
609 Type diffResultType = op.getDiff().getType();
610 Type borrowResultType = op.getBorrow().getType();
615 MLIRContext *ctx = rewriter.getContext();
616 Location loc = op.getLoc();
619 if (!isa<LLVM::LLVMArrayType>(operandType)) {
620 Type newBorrowType = typeConverter->convertType(borrowResultType);
622 LLVM::LLVMStructType::getLiteral(ctx, {diffResultType, newBorrowType});
623 Value subOverflow = LLVM::USubWithOverflowOp::create(
624 rewriter, loc, structType, adaptor.getLhs(), adaptor.getRhs());
625 Value diffExtracted =
626 LLVM::ExtractValueOp::create(rewriter, loc, subOverflow, 0);
627 Value borrowExtracted =
628 LLVM::ExtractValueOp::create(rewriter, loc, subOverflow, 1);
629 rewriter.replaceOp(op, {diffExtracted, borrowExtracted});
633 if (!isa<VectorType>(diffResultType))
634 return rewriter.notifyMatchFailure(loc,
"expected vector result types");
636 return rewriter.notifyMatchFailure(loc,
637 "ND vector types are not supported yet");
644template <
typename ArithMulOp,
bool IsSigned>
645LogicalResult MulIExtendedOpLowering<ArithMulOp, IsSigned>::matchAndRewrite(
646 ArithMulOp op,
typename ArithMulOp::Adaptor adaptor,
647 ConversionPatternRewriter &rewriter)
const {
648 Type resultType = adaptor.getLhs().getType();
653 Location loc = op.getLoc();
659 if (!isa<LLVM::LLVMArrayType>(resultType)) {
661 TypedAttr shiftValAttr;
663 if (
auto intTy = dyn_cast<IntegerType>(resultType)) {
664 unsigned resultBitwidth = intTy.getWidth();
665 auto attrTy = rewriter.getIntegerType(resultBitwidth * 2);
666 shiftValAttr = rewriter.getIntegerAttr(attrTy, resultBitwidth);
668 auto vecTy = cast<VectorType>(resultType);
669 unsigned resultBitwidth = vecTy.getElementTypeBitWidth();
670 auto attrTy = VectorType::get(
671 vecTy.getShape(), rewriter.getIntegerType(resultBitwidth * 2));
672 shiftValAttr = SplatElementsAttr::get(
673 attrTy, APInt(resultBitwidth * 2, resultBitwidth));
675 Type wideType = shiftValAttr.getType();
677 "LLVM dialect should support all signless integer types");
679 using LLVMExtOp = std::conditional_t<IsSigned, LLVM::SExtOp, LLVM::ZExtOp>;
680 Value lhsExt = LLVMExtOp::create(rewriter, loc, wideType, adaptor.getLhs());
681 Value rhsExt = LLVMExtOp::create(rewriter, loc, wideType, adaptor.getRhs());
682 Value mulExt = LLVM::MulOp::create(rewriter, loc, wideType, lhsExt, rhsExt);
685 Value low = LLVM::TruncOp::create(rewriter, loc, resultType, mulExt);
686 Value shiftVal = LLVM::ConstantOp::create(rewriter, loc, shiftValAttr);
687 Value highExt = LLVM::LShrOp::create(rewriter, loc, mulExt, shiftVal);
688 Value high = LLVM::TruncOp::create(rewriter, loc, resultType, highExt);
690 rewriter.replaceOp(op, {low, high});
694 if (!isa<VectorType>(resultType))
695 return rewriter.notifyMatchFailure(op,
"expected vector result type");
697 return rewriter.notifyMatchFailure(op,
698 "ND vector types are not supported yet");
707template <
typename LLVMPredType,
typename PredType>
709 return static_cast<LLVMPredType
>(pred);
713CmpIOpLowering::matchAndRewrite(arith::CmpIOp op, OpAdaptor adaptor,
714 ConversionPatternRewriter &rewriter)
const {
715 Type operandType = adaptor.getLhs().getType();
716 Type resultType = op.getResult().getType();
719 if (!isa<LLVM::LLVMArrayType>(operandType)) {
720 rewriter.replaceOpWithNewOp<LLVM::ICmpOp>(
721 op, typeConverter->convertType(resultType),
723 adaptor.getLhs(), adaptor.getRhs());
727 if (!isa<VectorType>(resultType))
728 return rewriter.notifyMatchFailure(op,
"expected vector result type");
731 op.getOperation(), adaptor.getOperands(), *getTypeConverter(),
732 [&](Type llvm1DVectorTy,
ValueRange operands) {
733 OpAdaptor adaptor(operands);
734 return LLVM::ICmpOp::create(
735 rewriter, op.getLoc(), llvm1DVectorTy,
737 adaptor.getLhs(), adaptor.getRhs());
747CmpFOpLowering::matchAndRewrite(arith::CmpFOp op, OpAdaptor adaptor,
748 ConversionPatternRewriter &rewriter)
const {
750 op.getLhs().getType()))
751 return rewriter.notifyMatchFailure(op,
"unsupported floating point type");
753 Type operandType = adaptor.getLhs().getType();
754 Type resultType = op.getResult().getType();
755 LLVM::FastmathFlags fmf =
756 arith::convertArithFastMathFlagsToLLVM(op.getFastmath());
759 if (!isa<LLVM::LLVMArrayType>(operandType)) {
760 rewriter.replaceOpWithNewOp<LLVM::FCmpOp>(
761 op, typeConverter->convertType(resultType),
763 adaptor.getLhs(), adaptor.getRhs(), fmf);
767 if (!isa<VectorType>(resultType))
768 return rewriter.notifyMatchFailure(op,
"expected vector result type");
771 op.getOperation(), adaptor.getOperands(), *getTypeConverter(),
772 [&](Type llvm1DVectorTy,
ValueRange operands) {
773 OpAdaptor adaptor(operands);
774 return LLVM::FCmpOp::create(
775 rewriter, op.getLoc(), llvm1DVectorTy,
777 adaptor.getLhs(), adaptor.getRhs(), fmf);
789LogicalResult SelectOpOneToNLowering::matchAndRewrite(
790 arith::SelectOp op, Adaptor adaptor,
791 ConversionPatternRewriter &rewriter)
const {
793 if (llvm::hasSingleElement(adaptor.getTrueValue()))
794 return rewriter.notifyMatchFailure(
795 op,
"not a 1:N conversion, 1:1 pattern will match");
796 if (!op.getCondition().getType().isInteger(1))
797 return rewriter.notifyMatchFailure(op,
798 "non-i1 conditions are not supported");
799 SmallVector<Value> results;
800 for (
auto [trueValue, falseValue] :
801 llvm::zip_equal(adaptor.getTrueValue(), adaptor.getFalseValue()))
802 results.push_back(arith::SelectOp::create(
803 rewriter, op.getLoc(), op.getCondition(), trueValue, falseValue));
804 rewriter.replaceOpWithMultiple(op, {results});
813struct ArithToLLVMConversionPass
814 :
public impl::ArithToLLVMConversionPassBase<ArithToLLVMConversionPass> {
817 void runOnOperation()
override {
821 const auto &dataLayoutAnalysis = getAnalysis<DataLayoutAnalysis>();
823 dataLayoutAnalysis.getAtOrAbove(getOperation()));
825 options.overrideIndexBitwidth(indexBitwidth);
828 arith::populateCeilFloorDivExpandOpsPatterns(patterns);
829 arith::populateArithToLLVMConversionPatterns(converter, patterns);
831 if (
failed(applyPartialConversion(getOperation(),
target,
832 std::move(patterns))))
844struct ArithToLLVMDialectInterface :
public ConvertToLLVMPatternInterface {
845 ArithToLLVMDialectInterface(Dialect *dialect)
846 : ConvertToLLVMPatternInterface(dialect) {}
848 void loadDependentDialects(MLIRContext *context)
const final {
849 context->loadDialect<LLVM::LLVMDialect>();
854 void populateConvertToLLVMConversionPatterns(
855 ConversionTarget &
target, LLVMTypeConverter &typeConverter,
856 RewritePatternSet &patterns)
const final {
857 arith::populateCeilFloorDivExpandOpsPatterns(patterns);
858 arith::populateArithToLLVMConversionPatterns(typeConverter, patterns);
866 dialect->addInterfaces<ArithToLLVMDialectInterface>();
879 patterns.
add<IdentityBitcastLowering>(converter, patterns.
getContext(),
885 ConstrainedAddFOpLowering,
888 AddUIExtendedOpLowering,
889 SubUIExtendedOpLowering,
895 ConstrainedDivFOpLowering,
904 IndexCastOpSILowering,
905 IndexCastOpUILowering,
908 MaximumNumFOpLowering,
913 MinimumNumFOpLowering,
917 ConstrainedMulFOpLowering,
919 MulSIExtendedOpLowering,
920 MulUIExtendedOpLowering,
927 SelectOpOneToNLowering,
933 ConstrainedSubFOpLowering,
936 ConstrainedTruncFOpLowering,