[llvm] Only fold `trunc X` to `(X & Mask)` if `Mask == getLowBitsSet(bit width of original operands)` (PR #176589)

Tirthankar Mazumder via llvm-commits llvm-commits at lists.llvm.org
Sat Jan 17 11:56:12 PST 2026


https://github.com/wermos created https://github.com/llvm/llvm-project/pull/176589

Implements the refinement mentioned in https://github.com/llvm/llvm-project/pull/171195#pullrequestreview-3647121183.

We only perform the fold if the resultant mask is equal to `getLowBitsSet(bit width of original operands)`.

>From 0265ec0e3971b01abaf92453132796968e140644 Mon Sep 17 00:00:00 2001
From: Tirthankar Mazumder <tmazumder.github at gmail.com>
Date: Sat, 17 Jan 2026 23:38:24 +0530
Subject: [PATCH] Only fold `trunc X` to `(X & Mask)` for simple masks.

---
 llvm/lib/Analysis/CmpInstAnalysis.cpp | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/Analysis/CmpInstAnalysis.cpp b/llvm/lib/Analysis/CmpInstAnalysis.cpp
index 880006c0fcfac..5e434f3e711fe 100644
--- a/llvm/lib/Analysis/CmpInstAnalysis.cpp
+++ b/llvm/lib/Analysis/CmpInstAnalysis.cpp
@@ -12,6 +12,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "llvm/Analysis/CmpInstAnalysis.h"
+#include "llvm/ADT/APInt.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/Instructions.h"
 #include "llvm/IR/PatternMatch.h"
@@ -164,9 +165,16 @@ llvm::decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate Pred,
 
     // Try to convert (trunc X) eq/ne C into (X & Mask) eq/ne C
     if (LookThroughTrunc && isa<TruncInst>(LHS)) {
-      Result.Pred = Pred;
-      Result.Mask = APInt::getAllOnes(C.getBitWidth());
-      Result.C = C;
+      auto *TI = dyn_cast<TruncInst>(LHS);
+      unsigned SrcBW = TI->getSrcTy()->getScalarSizeInBits(),
+               DstBW = TI->getDestTy()->getScalarSizeInBits();
+      APInt DesiredMask = APInt::getLowBitsSet(SrcBW, DstBW);
+      APInt Mask = APInt::getAllOnes(C.getBitWidth()).zext(SrcBW);
+      if (Mask == DesiredMask) {
+        Result.Pred = Pred;
+        Result.Mask = Mask;
+        Result.C = C;
+      }
       break;
     }
 



More information about the llvm-commits mailing list