lean4-htt/tests/lean/run/bv_popcount.lean
Paul Reichert 98e4b2882f
refactor: migrate to new ranges (#8841)
This PR migrates usages of `Std.Range` to the new polymorphic ranges.

This PR unfortunately increases the transitive imports for
frequently-used parts of `Init` because the ranges now rely on iterators
in order to provide their functionality for types other than `Nat`.
However, iteration over ranges in compiled code is as efficient as
before in the examples I checked. This is because of a special
`IteratorLoop` implementation provided in the PR for this purpose.

There were two issues that were uncovered during migration:

* In `IndPredBelow.lean`, migrating the last remaining range causes
`compilerTest1.lean` to break. I have minimized the issue and came to
the conclusion it's a compiler bug. Therefore, I have not replaced said
old range usage yet (see #9186).
* In `BRecOn.lean`, we are publicly importing the ranges. Making this
import private should theoretically work, but there seems to be a
problem with the module system, causing the build to panic later in
`Init.Data.Grind.Poly` (see #9185).
* In `FuzzyMatching.lean`, inlining fails with the new ranges, which
would have led to significant slowdown. Therefore, I have not migrated
this file either.
2025-07-07 12:41:53 +00:00

57 lines
1.4 KiB
Text

import Std.Tactic.BVDecide
/-
This is based on: https://saw.galois.com/intro/IntroToSAW.html#the-code
-/
namespace Popcount
/-
int pop_spec(uint32_t x) {
uint32_t pop = 0;
uint32_t mask = 1;
for (int i = 0; i < 32; i++) {
if (x & mask) { pop++; }
mask = mask << 1;
}
return pop;
}
-/
def pop_spec (x : BitVec 32) : BitVec 32 := Id.run do
let mut pop : BitVec 32 := 0
let mut mask : BitVec 32 := 1
for _ in *...(32 : Nat) do
if (x &&& mask != 0) then
pop := pop + 1
mask := mask <<< 1
return pop
/-
We do currently not have nice support for if statements in the bit blaster and arguing about
monadic for loops is not nicely done as well, instead we will use a recursive version:
-/
def pop_spec' (x : BitVec 32) : BitVec 32 :=
go x 0 32
where
go (x : BitVec 32) (pop : BitVec 32) (i : Nat) : BitVec 32 :=
match i with
| 0 => pop
| i + 1 =>
let pop := pop + (x &&& 1)
go (x >>> 1) pop i
def optimized (x : BitVec 32) : BitVec 32 :=
let x := x - ((x >>> 1) &&& 0x55555555);
let x := (x &&& 0x33333333) + ((x >>> 2) &&& 0x33333333);
let x := (x + (x >>> 4)) &&& 0x0F0F0F0F;
let x := x + (x >>> 8);
let x := x + (x >>> 16);
x &&& 0x0000003F
example (x : BitVec 32) : pop_spec' x = optimized x := by
dsimp [pop_spec', pop_spec'.go, optimized]
bv_decide
end Popcount