[llvm] [IndVarSimplify] Fix Masking Issue by Adding nsw/nuw Flags to Trunc Instruction (PR #150179)

via llvm-commits llvm-commits at lists.llvm.org
Thu Jul 24 02:48:20 PDT 2025


================
@@ -1049,9 +1049,28 @@ linearFunctionTestReplace(Loop *L, BasicBlock *ExitingBB,
     if (Extended) {
       bool Discard;
       L->makeLoopInvariant(ExitCnt, Discard);
-    } else
+    } else{
       CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
                                       "lftr.wideiv");
+
+      // Set the correct wrap flag to avoid the masking issue.
+      Instruction *TruncInst = dyn_cast<Instruction>(CmpIndVar);
+      
+      // The TruncatedIV is incrementing.
+      if (const SCEVAddRecExpr *TruncAR =
+              dyn_cast<SCEVAddRecExpr>(TruncatedIV)) {
----------------
buggfg wrote:

> Because it's an induction variable, is `TruncatedIV` always guaranteed to be a SCEVAddRecExpr? Does it work if we do a cast instead?

For safety, I prefer using `dyn_cast` (even though in the `genLoopLimit` function of this file, it directly uses `cast<SCEVAddRecExpr>(SE->getSCEV(IndVar))`)

https://github.com/llvm/llvm-project/pull/150179


More information about the llvm-commits mailing list