[llvm] [llvm][CodeGen] Added a check in CodeGenPrepare::optimizeSwitchType (PR #83322)

Panagiotis K via llvm-commits llvm-commits at lists.llvm.org
Tue Apr 23 05:29:46 PDT 2024


================
@@ -7387,17 +7387,38 @@ bool CodeGenPrepare::optimizeSwitchType(SwitchInst *SI) {
   // attribute. In that case, we can avoid an unnecessary mask/extension by
   // matching the argument extension instead.
   Instruction::CastOps ExtType = Instruction::ZExt;
-  // Some targets prefer SExt over ZExt.
-  if (TLI->isSExtCheaperThanZExt(OldVT, RegType))
-    ExtType = Instruction::SExt;
 
+  unsigned SExtUsers = 0;
+  unsigned ZExtUsers = 0;
   if (auto *Arg = dyn_cast<Argument>(Cond)) {
     if (Arg->hasSExtAttr())
-      ExtType = Instruction::SExt;
+      SExtUsers++;
     if (Arg->hasZExtAttr())
-      ExtType = Instruction::ZExt;
+      ZExtUsers++;
+  }
+  for (auto U : Cond->users()) {
+    if (isa<SExtInst>(U)) {
+      SExtUsers++;
+    } else if (isa<ZExtInst>(U)) {
+      ZExtUsers++;
+    } else if (auto *IC = dyn_cast<ICmpInst>(U)) {
+      if (IC->isSigned()) {
+        SExtUsers++;
+      } else if (IC->isUnsigned()) {
+        ZExtUsers++;
+      }
+    }
+  }
+  if (SExtUsers > ZExtUsers) {
+    ExtType = Instruction::SExt;
+  } else {
+    ExtType = Instruction::ZExt;
   }
 
+  // Some targets prefer SExt over ZExt.
+  if (TLI->isSExtCheaperThanZExt(OldVT, RegType))
----------------
karouzakisp wrote:

Yes isSExtCheaperThanZExt needs to take precedence if it doesn't agree with the computation that I perform otherwise the code size increases as I showed above.
Maybe the gain is very small compared to the cost because we need a User Scan. 

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


More information about the llvm-commits mailing list