[llvm] [SimplifyCFG] When only one case value is missing, replace default with that case (PR #76669)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Mon Jan 1 02:19:23 PST 2024


================
@@ -5609,10 +5612,30 @@ static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU,
       Known.getBitWidth() - (Known.Zero | Known.One).popcount();
   assert(NumUnknownBits <= Known.getBitWidth());
   if (HasDefault && DeadCases.empty() &&
-      NumUnknownBits < 64 /* avoid overflow */ &&
-      SI->getNumCases() == (1ULL << NumUnknownBits)) {
-    createUnreachableSwitchDefault(SI, DTU);
-    return true;
+      NumUnknownBits < 64 /* avoid overflow */) {
+    uint64_t AllNumCases = 1ULL << NumUnknownBits;
+    if (SI->getNumCases() == AllNumCases) {
+      createUnreachableSwitchDefault(SI, DTU);
+      return true;
+    }
+    // When only one case value is missing, replace default with that case.
+    if (SI->getNumCases() == AllNumCases - 1) {
+      uint64_t MissingCaseVal = 0;
+      for (const auto &Case : SI->cases())
+        MissingCaseVal ^= Case.getCaseValue()->getValue().getLimitedValue();
+      for (uint64_t I = 0; I < AllNumCases; I++)
+        MissingCaseVal ^= I;
+      auto *MissingCase =
+          cast<ConstantInt>(ConstantInt::get(Cond->getType(), MissingCaseVal));
+      SI->addCase(MissingCase, SI->getDefaultDest());
+      SwitchInstProfUpdateWrapper SIW(*SI);
----------------
dtcxzyw wrote:

Could you please add a test for updating the branch weight?


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


More information about the llvm-commits mailing list