From: David Majnemer Date: Tue, 14 Oct 2014 20:28:40 +0000 (+0000) Subject: InstCombine: Don't miscompile X % ((Pow2 << A) >>u B) X-Git-Url: http://plrg.eecs.uci.edu/git/?p=oota-llvm.git;a=commitdiff_plain;h=505187a9bd6beb779d3ae76b44efa69a72f68173 InstCombine: Don't miscompile X % ((Pow2 << A) >>u B) We assumed that A must be greater than B because the right hand side of a remainder operator must be nonzero. However, it is possible for A to be less than B if Pow2 is a power of two greater than 1. Take for example: i32 %A = 0 i32 %B = 31 i32 Pow2 = 2147483648 ((Pow2 << 0) >>u 31) is non-zero but A is less than B. This fixes PR21274. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@219713 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp b/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp index 530a66dab9c..8c48dce81de 100644 --- a/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp +++ b/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp @@ -36,14 +36,11 @@ static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC, // ((1 << A) >>u B) --> (1 << (A-B)) // Because V cannot be zero, we know that B is less than A. - Value *A = nullptr, *B = nullptr, *PowerOf2 = nullptr; - if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))), - m_Value(B))) && - // The "1" can be any value known to be a power of 2. - isKnownToBeAPowerOfTwo(PowerOf2, false, 0, IC.getAssumptionTracker(), - CxtI, IC.getDominatorTree())) { + Value *A = nullptr, *B = nullptr, *One = nullptr; + if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) && + match(One, m_One())) { A = IC.Builder->CreateSub(A, B); - return IC.Builder->CreateShl(PowerOf2, A); + return IC.Builder->CreateShl(One, A); } // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it diff --git a/test/Transforms/InstCombine/div.ll b/test/Transforms/InstCombine/div.ll index f2a70fd0f0d..284104317d4 100644 --- a/test/Transforms/InstCombine/div.ll +++ b/test/Transforms/InstCombine/div.ll @@ -265,7 +265,7 @@ define i32 @test30(i32 %a) { ; CHECK-NEXT: ret i32 %a } -define <2 x i32> @test31(<2 x i32> %x) nounwind { +define <2 x i32> @test31(<2 x i32> %x) { %shr = lshr <2 x i32> %x, %div = udiv <2 x i32> %shr, ret <2 x i32> %div @@ -274,3 +274,15 @@ define <2 x i32> @test31(<2 x i32> %x) nounwind { ; CHECK-NEXT: udiv <2 x i32> %[[shr]], ; CHECK-NEXT: ret <2 x i32> } + +define i32 @test32(i32 %a, i32 %b) { + %shl = shl i32 2, %b + %div = lshr i32 %shl, 2 + %div2 = udiv i32 %a, %div + ret i32 %div2 +; CHECK-LABEL: @test32( +; CHECK-NEXT: %[[shl:.*]] = shl i32 2, %b +; CHECK-NEXT: %[[shr:.*]] = lshr i32 %[[shl]], 2 +; CHECK-NEXT: %[[div:.*]] = udiv i32 %a, %[[shr]] +; CHECK-NEXT: ret i32 +}