[llvm] r179587 - simplifycfg: Fix integer overflow converting switch into icmp.

Hans Wennborg hans at hanshq.net
Tue Apr 16 01:35:37 PDT 2013


Author: hans
Date: Tue Apr 16 03:35:36 2013
New Revision: 179587

URL: http://llvm.org/viewvc/llvm-project?rev=179587&view=rev
Log:
simplifycfg: Fix integer overflow converting switch into icmp.

If a switch instruction has a case for every possible value of its type,
with the same successor, SimplifyCFG would replace it with an icmp ult,
but the computation of the bound overflows in that case, which inverts
the test.

Patch by Jed Davis!

Modified:
    llvm/trunk/lib/Transforms/Utils/SimplifyCFG.cpp
    llvm/trunk/test/Transforms/SimplifyCFG/switch-to-icmp.ll

Modified: llvm/trunk/lib/Transforms/Utils/SimplifyCFG.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Utils/SimplifyCFG.cpp?rev=179587&r1=179586&r2=179587&view=diff
==============================================================================
--- llvm/trunk/lib/Transforms/Utils/SimplifyCFG.cpp (original)
+++ llvm/trunk/lib/Transforms/Utils/SimplifyCFG.cpp Tue Apr 16 03:35:36 2013
@@ -3073,7 +3073,12 @@ static bool TurnSwitchRangeIntoICmp(Swit
   Value *Sub = SI->getCondition();
   if (!Offset->isNullValue())
     Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
-  Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
+  Value *Cmp;
+  // If NumCases overflowed, then all possible values jump to the successor.
+  if (NumCases->isNullValue() && SI->getNumCases() != 0)
+    Cmp = ConstantInt::getTrue(SI->getContext());
+  else
+    Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
   BranchInst *NewBI = Builder.CreateCondBr(
       Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
 

Modified: llvm/trunk/test/Transforms/SimplifyCFG/switch-to-icmp.ll
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/SimplifyCFG/switch-to-icmp.ll?rev=179587&r1=179586&r2=179587&view=diff
==============================================================================
--- llvm/trunk/test/Transforms/SimplifyCFG/switch-to-icmp.ll (original)
+++ llvm/trunk/test/Transforms/SimplifyCFG/switch-to-icmp.ll Tue Apr 16 03:35:36 2013
@@ -37,3 +37,21 @@ lor.end:
 ; CHECK: @test2
 ; CHECK: %switch = icmp ult i32 %x, 2
 }
+
+define i32 @test3(i1 %flag) {
+entry:
+ switch i1 %flag, label %bad [
+   i1 true, label %good
+   i1 false, label %good
+ ]
+
+good:
+ ret i32 0
+
+bad:
+ ret i32 1
+
+; CHECK: @test3
+; CHECK: entry:
+; CHECK-NEXT: ret i32 0
+}





More information about the llvm-commits mailing list