[llvm] [CGP]: Optimize mul.overflow. (PR #148343)
David Green via llvm-commits
llvm-commits at lists.llvm.org
Wed Oct 1 03:45:23 PDT 2025
================
@@ -6389,6 +6395,235 @@ bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
return true;
}
+// Rewrite the mul_with_overflow intrinsic by checking if both of the
+// operands' value range is within the legal type. If so, we can optimize the
+// multiplication algorithm. This code is supposed to be written during the step
+// of type legalization, but given that we need to reconstruct the IR which is
+// not doable there, we do it here.
+bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
+ ModifyDT &ModifiedDT) {
+ if (!TLI->shouldOptimizeMulOverflowIntrinsic())
+ return false;
+
+ if (TLI->getTypeAction(
+ I->getContext(),
+ TLI->getValueType(*DL, I->getType()->getContainedType(0))) !=
+ TargetLowering::TypeExpandInteger)
+ return false;
+
+ Value *LHS = I->getOperand(0);
+ Value *RHS = I->getOperand(1);
+ Type *Ty = LHS->getType();
+ unsigned VTBitWidth = Ty->getScalarSizeInBits();
+ unsigned VTHalfBitWidth = VTBitWidth / 2;
+ IntegerType *LegalTy =
+ IntegerType::getIntNTy(I->getContext(), VTHalfBitWidth);
+
+ // Skip the optimization if the type with HalfBitWidth is not legal for the
+ // target.
+ if (TLI->getTypeAction(I->getContext(), TLI->getValueType(*DL, LegalTy)) !=
+ TargetLowering::TypeLegal)
+ return false;
+
+ // Make sure that the I->getType() is a struct type with two elements.
+ if (!I->getType()->isStructTy() || I->getType()->getStructNumElements() != 2)
+ return false;
+
+ // Keep track of the instruction to stop reoptimizing it again.
+ InsertedInsts.insert(I);
+ // ----------------------------
+
+ // For the simple case where IR just checks the overflow flag, new blocks
+ // should be:
+ // entry:
+ // if signed:
+ // (lhs_lo ^ lhs_hi) || (rhs_lo ^ rhs_hi) ? overflow, overflow_no
----------------
davemgreen wrote:
Does there needs to be a `>> BW-1` on the lhs_lo/rhs_lo?
https://github.com/llvm/llvm-project/pull/148343
More information about the llvm-commits
mailing list