optionally use shift operations on target numerals for efficient execution
authorhaftmann
Sat, 04 Jan 2025 14:41:30 +0100
changeset 81713 378b9d6c52b2
parent 81712 97987036f051
child 81714 5e3dd01a9eb2
optionally use shift operations on target numerals for efficient execution
NEWS
src/Doc/Codegen/Adaptation.thy
src/HOL/Code_Numeral.thy
src/HOL/Codegenerator_Test/Code_Test_GHC.thy
src/HOL/Codegenerator_Test/Code_Test_OCaml.thy
src/HOL/Codegenerator_Test/Code_Test_PolyML.thy
src/HOL/Codegenerator_Test/Code_Test_Scala.thy
src/HOL/Library/Code_Target_Bit_Shifts.thy
src/HOL/Library/Code_Target_Numeral.thy
--- a/NEWS	Sat Jan 04 14:25:56 2025 +0100
+++ b/NEWS	Sat Jan 04 14:41:30 2025 +0100
@@ -225,6 +225,10 @@
 * Code generator: command 'code_reserved' now uses parentheses for
 target languages, similar to 'code_printing'.
 
+* Theory HOL-Library.Code_Target_Bit_Shifts implemented bit shifts on numeric
+types by target-language operations; this is also used by
+HOL-Library.Code_Target_Numeral.
+
 * Sledgehammer:
   - Update of bundled provers:
       . E 3.1 -- with patch on Windows/Cygwin for proper interrupts
--- a/src/Doc/Codegen/Adaptation.thy	Sat Jan 04 14:25:56 2025 +0100
+++ b/src/Doc/Codegen/Adaptation.thy	Sat Jan 04 14:41:30 2025 +0100
@@ -204,13 +204,17 @@
        Pattern matching with \<^term>\<open>0::nat\<close> / \<^const>\<open>Suc\<close> is eliminated
        by a preprocessor.
 
+    \item[\<open>Code_Target_Bit_Shifts\<close>] implements bit shifts on \<^typ>\<open>integer\<close>
+       by target-language operations. Combined with \<open>Code_Target_Int\<close>
+       or \<open>Code_Target_Nat\<close>, bit shifts on \<^typ>\<open>int\<close> or \<^type>\<open>nat\<close> can
+       be implemented by target-language operations.
+
     \item[\<open>Code_Target_Numeral\<close>] is a convenience theory
-       containing both \<open>Code_Target_Nat\<close> and
-       \<open>Code_Target_Int\<close>.
+       containing \<open>Code_Target_Nat\<close>, \<open>Code_Target_Int\<close> and \<open>Code_Target_Bit_Shifts\<close>-
 
     \item[\<open>Code_Abstract_Char\<close>] implements type \<^typ>\<open>char\<close> by target language
        integers, sacrificing pattern patching in exchange for dramatically
-       increased performance for comparisions.
+       increased performance for comparisons.
 
     \item[\<^theory>\<open>HOL-Library.IArray\<close>] provides a type \<^typ>\<open>'a iarray\<close>
        isomorphic to lists but implemented by (effectively immutable)
--- a/src/HOL/Code_Numeral.thy	Sat Jan 04 14:25:56 2025 +0100
+++ b/src/HOL/Code_Numeral.thy	Sat Jan 04 14:41:30 2025 +0100
@@ -377,19 +377,6 @@
 begin
 
 lemma [code]:
-  \<open>bit k n \<longleftrightarrow> odd (drop_bit n k)\<close>
-  \<open>NOT k = - k - 1\<close>
-  \<open>mask n = 2 ^ n - (1 :: integer)\<close>
-  \<open>set_bit n k = k OR push_bit n 1\<close>
-  \<open>unset_bit n k = k AND NOT (push_bit n 1)\<close>
-  \<open>flip_bit n k = k XOR push_bit n 1\<close>
-  \<open>push_bit n k = k * 2 ^ n\<close>
-  \<open>drop_bit n k = k div 2 ^ n\<close>
-  \<open>take_bit n k = k mod 2 ^ n\<close> for k :: integer
-  by (fact bit_iff_odd_drop_bit not_eq_complement mask_eq_exp_minus_1
-    set_bit_eq_or unset_bit_eq_and_not flip_bit_eq_xor push_bit_eq_mult drop_bit_eq_div take_bit_eq_mod)+
-
-lemma [code]:
   \<open>k AND l = (if k = 0 \<or> l = 0 then 0 else if k = - 1 then l else if l = - 1 then k
     else (k mod 2) * (l mod 2) + 2 * ((k div 2) AND (l div 2)))\<close> for k l :: integer
   by transfer (fact and_int_unfold) 
@@ -404,6 +391,42 @@
     else \<bar>k mod 2 - l mod 2\<bar> + 2 * ((k div 2) XOR (l div 2)))\<close> for k l :: integer
   by transfer (fact xor_int_unfold)
 
+lemma [code]:
+  \<open>NOT k = - k - 1\<close> for k :: integer
+  by (fact not_eq_complement)
+
+lemma [code]:
+  \<open>bit k n \<longleftrightarrow> k AND push_bit n 1 \<noteq> (0 :: integer)\<close>
+  by (simp add: and_exp_eq_0_iff_not_bit)
+
+lemma [code]:
+  \<open>mask n = push_bit n 1 - (1 :: integer)\<close>
+  by (simp add: mask_eq_exp_minus_1)
+
+lemma [code]:
+  \<open>set_bit n k = k OR push_bit n 1\<close> for k :: integer
+  by (fact set_bit_def)
+
+lemma [code]:
+  \<open>unset_bit n k = k AND NOT (push_bit n 1)\<close> for k :: integer
+  by (fact unset_bit_def)
+
+lemma [code]:
+  \<open>flip_bit n k = k XOR push_bit n 1\<close> for k :: integer
+  by (fact flip_bit_def)
+
+lemma [code]:
+  \<open>push_bit n k = k * 2 ^ n\<close> for k :: integer
+  by (fact push_bit_eq_mult)
+
+lemma [code]:
+  \<open>drop_bit n k = k div  2 ^ n\<close> for k :: integer
+  by (fact drop_bit_eq_div)
+
+lemma [code]:
+  \<open>take_bit n k = k AND mask n\<close> for k :: integer
+  by (fact take_bit_eq_mask)
+
 end
 
 instantiation integer :: linordered_euclidean_semiring_division
--- a/src/HOL/Codegenerator_Test/Code_Test_GHC.thy	Sat Jan 04 14:25:56 2025 +0100
+++ b/src/HOL/Codegenerator_Test/Code_Test_GHC.thy	Sat Jan 04 14:41:30 2025 +0100
@@ -5,6 +5,7 @@
 
 theory Code_Test_GHC
 imports
+  "HOL-Library.Code_Target_Bit_Shifts"
   "HOL-Library.Code_Test"
   Code_Lazy_Test
 begin
--- a/src/HOL/Codegenerator_Test/Code_Test_OCaml.thy	Sat Jan 04 14:25:56 2025 +0100
+++ b/src/HOL/Codegenerator_Test/Code_Test_OCaml.thy	Sat Jan 04 14:41:30 2025 +0100
@@ -5,6 +5,7 @@
 
 theory Code_Test_OCaml
 imports
+  "HOL-Library.Code_Target_Bit_Shifts"
   "HOL-Library.Code_Test"
   Code_Lazy_Test
 begin
--- a/src/HOL/Codegenerator_Test/Code_Test_PolyML.thy	Sat Jan 04 14:25:56 2025 +0100
+++ b/src/HOL/Codegenerator_Test/Code_Test_PolyML.thy	Sat Jan 04 14:41:30 2025 +0100
@@ -5,6 +5,7 @@
 
 theory Code_Test_PolyML
 imports 
+  "HOL-Library.Code_Target_Bit_Shifts"
   "HOL-Library.Code_Test"
   Code_Lazy_Test
 begin
--- a/src/HOL/Codegenerator_Test/Code_Test_Scala.thy	Sat Jan 04 14:25:56 2025 +0100
+++ b/src/HOL/Codegenerator_Test/Code_Test_Scala.thy	Sat Jan 04 14:41:30 2025 +0100
@@ -3,7 +3,9 @@
     Author:     Florian Haftmann, TU Muenchen
 *)
 
-theory Code_Test_Scala imports
+theory Code_Test_Scala
+imports
+  "HOL-Library.Code_Target_Bit_Shifts"
   "HOL-Library.Code_Test"
   Code_Lazy_Test
 begin
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Library/Code_Target_Bit_Shifts.thy	Sat Jan 04 14:41:30 2025 +0100
@@ -0,0 +1,186 @@
+(*  Title:      HOL/Library/Code_Target_Bit_Shifts.thy
+    Author:     Florian Haftmann, TU Muenchen
+*)
+
+section \<open>Implementation of bit-shifts on target-language integers by built-in operations\<close>
+
+theory Code_Target_Bit_Shifts
+imports Main
+begin
+
+context
+begin
+
+qualified definition push_bit :: \<open>integer \<Rightarrow> integer \<Rightarrow> integer\<close>
+  where \<open>push_bit i k = Bit_Operations.push_bit (nat_of_integer \<bar>i\<bar>) k\<close>
+
+qualified lemma push_bit_code [code]:
+  \<open>push_bit i k = k * 2 ^ nat_of_integer \<bar>i\<bar>\<close>
+  by (simp add: push_bit_def push_bit_eq_mult)
+
+lemma push_bit_integer_code [code]:
+  \<open>Bit_Operations.push_bit n k = push_bit (of_nat n) k\<close>
+  by (simp add: push_bit_def)
+
+qualified definition drop_bit :: \<open>integer \<Rightarrow> integer \<Rightarrow> integer\<close>
+  where \<open>drop_bit i k = Bit_Operations.drop_bit (nat_of_integer \<bar>i\<bar>) k\<close>
+
+qualified lemma drop_bit_code [code]:
+  \<open>drop_bit i k = k div 2 ^ nat_of_integer \<bar>i\<bar>\<close>
+  by (simp add: drop_bit_def drop_bit_eq_div)
+
+lemma drop_bit_integer_code [code]:
+  \<open>Bit_Operations.drop_bit n k = drop_bit (of_nat n) k\<close>
+  by (simp add: drop_bit_def)
+
+end
+
+code_printing code_module Bit_Shifts \<rightharpoonup>
+    (SML) \<open>
+structure Bit_Shifts : sig
+  type int = IntInf.int
+  val push : int -> int -> int
+  val drop : int -> int -> int
+end = struct
+
+type int = IntInf.int;
+
+fun curry f x y = f (x, y);
+
+fun fold _ [] y = y
+  | fold f (x :: xs) y = fold f xs (f x y);
+
+fun replicate n x = (if n <= 0 then [] else x :: replicate (n - 1) x);
+
+val exp = curry IntInf.pow 2;
+
+val div_mod = curry IntInf.divMod;
+
+val max_index = exp (Word.wordSize - 3) - 1; (*experimentally determined*)
+
+val word_of_int = Word.fromLargeInt o IntInf.toLarge;
+
+val word_max_index = word_of_int max_index;
+
+fun words_of_int k = case div_mod k max_index
+  of (b, s) => word_of_int s :: (replicate b word_max_index);
+
+fun push' i k = IntInf.<< (k, i);
+
+fun drop' i k = IntInf.~>> (k, i);
+
+(* The implementations are formally total, though indices >~ max_index will produce heavy computation load *)
+
+fun push i = fold push' (words_of_int (IntInf.abs i));
+
+fun drop i = fold drop' (words_of_int (IntInf.abs i));
+
+end;\<close> for constant Code_Target_Bit_Shifts.push_bit Code_Target_Bit_Shifts.drop_bit
+    and (OCaml) \<open>
+module Bit_Shifts : sig
+  val push : Z.t -> Z.t -> Z.t
+  val drop : Z.t -> Z.t -> Z.t
+end = struct
+
+let curry f x y = f (x, y);;
+
+let rec fold f xs y = match xs with
+  [] -> y
+  | (x :: xs) -> fold f xs (f x y);;
+
+let rec replicate n x = (if Z.leq n Z.zero then [] else x :: replicate (Z.pred n) x);;
+
+let max_index = Z.of_int max_int;;
+
+let splitIndex i = let (b, s) = Z.div_rem i max_index
+  in Z.to_int s :: (replicate b max_int);;
+
+let push' i k = Z.shift_left k i;;
+
+let drop' i k = Z.shift_right k i;;
+
+(* The implementations are formally total, though indices >~ max_index will produce heavy computation load *)
+
+let push i = fold push' (splitIndex (Z.abs i));;
+
+let drop i = fold drop' (splitIndex (Z.abs i));;
+
+end;;
+\<close> for constant Code_Target_Bit_Shifts.push_bit Code_Target_Bit_Shifts.drop_bit
+    and (Haskell) \<open>
+module Bit_Shifts where
+
+import Prelude (Int, Integer, toInteger, fromInteger, maxBound, divMod, (-), (<=), abs, flip)
+import GHC.Bits (Bits)
+import Data.Bits (shiftL, shiftR)
+
+fold :: (a -> b -> b) -> [a] -> b -> b
+fold _ [] y = y
+fold f (x : xs) y = fold f xs (f x y)
+
+replicate :: Integer -> a -> [a]
+replicate k x = if k <= 0 then [] else x : replicate (k - 1) x
+
+maxIndex :: Integer
+maxIndex = toInteger (maxBound :: Int)
+
+splitIndex :: Integer -> [Int]
+splitIndex i = fromInteger s : replicate (fromInteger b) maxBound
+  where (b, s) = i `divMod` maxIndex
+
+{- The implementations are formally total, though indices >~ maxIndex will produce heavy computation load -}
+
+push' :: Int -> Int -> Int
+push' i = flip shiftL (abs i)
+
+push :: Integer -> Integer -> Integer
+push i = fold (flip shiftL) (splitIndex (abs i))
+
+drop' :: Int -> Int -> Int
+drop' i = flip shiftR (abs i)
+
+drop :: Integer -> Integer -> Integer
+drop i = fold (flip shiftR) (splitIndex (abs i))
+\<close> for constant Code_Target_Bit_Shifts.push_bit Code_Target_Bit_Shifts.drop_bit
+    and (Scala) \<open>
+object Bit_Shifts {
+
+private val maxIndex : BigInt = BigInt(Int.MaxValue);
+
+private def replicate[A](i : BigInt, x : A) : List[A] =
+  if (i <= 0) Nil else x :: replicate[A](i - 1, x)
+
+private def splitIndex(i : BigInt) : List[Int] = {
+  val (b, s) = i /% maxIndex
+  return s.intValue :: replicate(b, Int.MaxValue)
+}
+
+/* The implementations are formally total, though indices >~ maxIndex will produce heavy computation load */
+
+def push(i: BigInt, k: BigInt) : BigInt =
+  splitIndex(i).foldLeft(k) { (l, j) => l << j }
+
+def drop(i: BigInt, k: BigInt) : BigInt =
+  splitIndex(i).foldLeft(k) { (l, j) => l >> j }
+
+}
+\<close> for constant Code_Target_Bit_Shifts.push_bit Code_Target_Bit_Shifts.drop_bit
+| constant Code_Target_Bit_Shifts.push_bit \<rightharpoonup>
+    (SML) "Bit'_Shifts.push"
+    and (OCaml) "Bit'_Shifts.push"
+    and (Haskell) "Bit'_Shifts.push"
+    and (Haskell_Quickcheck) "Bit'_Shifts.push'"
+    and (Scala) "Bit'_Shifts.push"
+| constant Code_Target_Bit_Shifts.drop_bit \<rightharpoonup>
+    (SML) "Bit'_Shifts.drop"
+    and (OCaml) "Bit'_Shifts.drop"
+    and (Haskell) "Bit'_Shifts.drop"
+    and (Haskell_Quickcheck) "Bit'_Shifts.drop'"
+    and (Scala) "Bit'_Shifts.drop"
+
+code_reserved
+  (SML) Bit_Shifts
+  and (Haskell) Bit_Shifts
+  and (Scala) Bit_Shifts
+
+end
--- a/src/HOL/Library/Code_Target_Numeral.thy	Sat Jan 04 14:25:56 2025 +0100
+++ b/src/HOL/Library/Code_Target_Numeral.thy	Sat Jan 04 14:41:30 2025 +0100
@@ -5,7 +5,7 @@
 section \<open>Implementation of natural and integer numbers by target-language integers\<close>
 
 theory Code_Target_Numeral
-imports Code_Target_Int Code_Target_Nat
+imports Code_Target_Nat Code_Target_Int Code_Target_Bit_Shifts
 begin
 
 end