[clang] [llvm] [InstCombine] Infer nsw/nuw for trunc (PR #87910)

Yingwei Zheng via cfe-commits cfe-commits at lists.llvm.org
Tue Apr 9 00:26:19 PDT 2024


================
@@ -897,7 +897,20 @@ Instruction *InstCombinerImpl::visitTrunc(TruncInst &Trunc) {
     }
   }
 
-  return nullptr;
+  bool Changed = false;
+  if (!Trunc.hasNoSignedWrap() &&
+      ComputeMaxSignificantBits(Src, /*Depth=*/0, &Trunc) <= DestWidth) {
+    Trunc.setHasNoSignedWrap(true);
+    Changed = true;
+  }
+  if (!Trunc.hasNoUnsignedWrap() &&
+      MaskedValueIsZero(Src, APInt::getBitsSetFrom(SrcWidth, DestWidth),
+                        /*Depth=*/0, &Trunc)) {
+    Trunc.setHasNoUnsignedWrap(true);
+    Changed = true;
----------------
dtcxzyw wrote:

> We can't infer nsw, but we can infer nuw.

I prefer to infer both flags here, then we may reuse KnownBits in further patches.

> Do you see any reason why doing this in SimplifyDemanded would be problematic?

`SimplifyDemanded` is context-sensitive. IMO it is not the right place to infer flags.


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


More information about the cfe-commits mailing list