Avoid some unnecessary unsigned -> signed casts (#70884)
authorJakob Botsch Nielsen <Jakob.botsch.nielsen@gmail.com>
Mon, 27 Jun 2022 11:07:31 +0000 (13:07 +0200)
committerGitHub <noreply@github.com>
Mon, 27 Jun 2022 11:07:31 +0000 (13:07 +0200)
We do not need a signed cast if we know the sign bit from a previous unsigned cast.

src/coreclr/jit/flowgraph.cpp

index 33d6fab..87b2d2e 100644 (file)
@@ -1277,11 +1277,16 @@ bool Compiler::fgCastNeeded(GenTree* tree, var_types toType)
         return false;
     }
     //
-    // If the sign-ness of the two types are different then a cast is necessary
+    // If the sign-ness of the two types are different then a cast is necessary, except for
+    // an unsigned -> signed cast where we already know the sign bit is zero.
     //
     if (varTypeIsUnsigned(toType) != varTypeIsUnsigned(fromType))
     {
-        return true;
+        bool isZeroExtension = varTypeIsUnsigned(fromType) && (genTypeSize(fromType) < genTypeSize(toType));
+        if (!isZeroExtension)
+        {
+            return true;
+        }
     }
     //
     // If the from type is the same size or smaller then an additional cast is not necessary