summaryrefslogtreecommitdiff
path: root/compiler/utils/Util.hs
diff options
context:
space:
mode:
Diffstat (limited to 'compiler/utils/Util.hs')
-rw-r--r--compiler/utils/Util.hs24
1 files changed, 24 insertions, 0 deletions
diff --git a/compiler/utils/Util.hs b/compiler/utils/Util.hs
index 121fdbbf6f..0b16fba72d 100644
--- a/compiler/utils/Util.hs
+++ b/compiler/utils/Util.hs
@@ -78,6 +78,9 @@ module Util (
-- * Argument processing
getCmd, toCmdArgs, toArgs,
+ -- * Integers
+ exactLog2,
+
-- * Floating point
readRational,
@@ -985,6 +988,27 @@ toArgs str
Right (arg, rest)
_ ->
Left ("Couldn't read " ++ show s ++ " as String")
+-----------------------------------------------------------------------------
+-- Integers
+
+-- This algorithm for determining the $\log_2$ of exact powers of 2 comes
+-- from GCC. It requires bit manipulation primitives, and we use GHC
+-- extensions. Tough.
+
+exactLog2 :: Integer -> Maybe Integer
+exactLog2 x
+ = if (x <= 0 || x >= 2147483648) then
+ Nothing
+ else
+ if (x .&. (-x)) /= x then
+ Nothing
+ else
+ Just (pow2 x)
+ where
+ pow2 x | x == 1 = 0
+ | otherwise = 1 + pow2 (x `shiftR` 1)
+
+
{-
-- -----------------------------------------------------------------------------
-- Floats