]> granicus.if.org Git - clang/commitdiff
[analyzer] Left shifting a negative value is undefined
authorGabor Horvath <xazax.hun@gmail.com>
Mon, 30 Oct 2017 17:06:42 +0000 (17:06 +0000)
committerGabor Horvath <xazax.hun@gmail.com>
Mon, 30 Oct 2017 17:06:42 +0000 (17:06 +0000)
The analyzer did not return an UndefVal in case a negative value was left
shifted. I also altered the UndefResultChecker to emit a clear warning in this
case.

Differential Revision: https://reviews.llvm.org/D39423

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@316924 91177308-0d34-0410-b5e6-96231b3b80d8

lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
lib/StaticAnalyzer/Core/BasicValueFactory.cpp
test/Analysis/bitwise-ops.c

index 21e8b107c9ec715651ef896a86ba5b887ad0f09d..172ce346f1ba7a6d53b6aee83a976e0ee2054278 100644 (file)
@@ -137,6 +137,10 @@ void UndefResultChecker::checkPostStmt(const BinaryOperator *B,
 
         OS << " greater or equal to the width of type '"
            << B->getLHS()->getType().getAsString() << "'.";
+      } else if (B->getOpcode() == BinaryOperatorKind::BO_Shl &&
+                 C.isNegative(B->getLHS())) {
+        OS << "The result of the left shift is undefined because the left "
+              "operand is negative";
       } else {
         OS << "The result of the '"
            << BinaryOperator::getOpcodeStr(B->getOpcode())
index ebbace4e33b38ec1f3b6d4ba4064fc8c9e8d1825..ec7a7e9e4b1c8ec4a8936e406e1b2e476b09fdea 100644 (file)
@@ -225,6 +225,8 @@ BasicValueFactory::evalAPSInt(BinaryOperator::Opcode Op,
       // test these conditions symbolically.
 
       // FIXME: Expand these checks to include all undefined behavior.
+      if (V1.isSigned() && V1.isNegative())
+        return nullptr;
 
       if (V2.isSigned() && V2.isNegative())
         return nullptr;
index acef6681d893982ca6e23d7c9142c35a7e0faa71..fe546580be3d8bd4c567b042eb6b80bd75bf36be 100644 (file)
@@ -44,3 +44,10 @@ int testNegativeShift(int a) {
   }
   return 0;
 }
+
+int testNegativeLeftShift(int a) {
+  if (a == -3) {
+    return a << 1; // expected-warning{{The result of the left shift is undefined because the left operand is negative}}
+  }
+  return 0;
+}