hsmt-0.1.0.0: src/HSMT/Theory/BitBlast.hs
-- | Bit-blasting: Boolean circuits for the bit-vector operators.
--
-- A bit-vector is a list of SAT literals, least significant bit first.
-- Gates are encoded with Tseitin clauses, simplified when an input is a
-- constant, and shared through a structural hash table, so building the
-- same gate twice yields the same literal.
--
-- Clauses go to a replaceable sink: while assertions are encoded they are
-- added to the SAT solver directly, and during search they are queued and
-- handed to the solver as theory lemmas.
--
-- The semantics follows SMT-LIB, including division by zero:
-- @bvudiv x 0 = ~0@ and @bvurem x 0 = x@.
module HSMT.Theory.BitBlast
( Circuit
, Bits
, newCircuit
, setSink
, emitClause
-- * Gates
, cTrue
, cFalse
, isConstLit
, andG
, orG
, xorG
, iteG
, andN
, orN
-- * Bit-vectors
, constBits
, freshBits
, bvNot
, bvAnd
, bvOr
, bvXor
, bvNeg
, bvAdd
, bvSub
, bvMul
, bvUDiv
, bvURem
, bvSDiv
, bvSRem
, bvSMod
, bvShl
, bvLShr
, bvAShr
, bvIte
, bvEq
, bvULt
, bvULe
, bvSLt
, bvSLe
, bitsValue
) where
import Control.Monad (forM, forM_, replicateM)
import Data.Bits (shiftL, testBit)
import Data.IORef
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import HSMT.SAT.Types
-- | A bit-vector: one literal per bit, least significant bit first.
type Bits = [Lit]
-- | A circuit builder: allocates gate outputs, emits their Tseitin clauses
-- to the current sink and shares structurally equal gates.
data Circuit = Circuit
{ cNewVar :: IO Var
, cSink :: IORef ([Lit] -> IO ())
, cTrueLit :: Lit
, cGates :: IORef (Map (Int, Lit, Lit, Lit) Lit)
-- ^ Gate kind (0: and, 1: xor, 2: ite) and inputs to output.
, cDivRem :: IORef (Map (Bits, Bits) (Bits, Bits))
-- ^ Quotient and remainder of each unsigned division.
}
-- | A circuit builder from a variable allocator, an initial clause sink and
-- the literal that is always true.
newCircuit :: IO Var -> ([Lit] -> IO ()) -> Lit -> IO Circuit
newCircuit nv sink t = Circuit nv <$> newIORef sink <*> pure t <*> newIORef Map.empty <*> newIORef Map.empty
-- | Replace the clause sink; later clauses go to the new sink.
setSink :: Circuit -> ([Lit] -> IO ()) -> IO ()
setSink c = writeIORef (cSink c)
-- | Send a clause to the current sink.
emitClause :: Circuit -> [Lit] -> IO ()
emitClause = emit
emit :: Circuit -> [Lit] -> IO ()
emit c cl = readIORef (cSink c) >>= \f -> f cl
fresh :: Circuit -> IO Lit
fresh c = posLit <$> cNewVar c
-- | The constant true and false literals of the circuit.
cTrue, cFalse :: Circuit -> Lit
cTrue = cTrueLit
cFalse = litNeg . cTrueLit
-- | @Just b@ when the literal is the constant @b@.
isConstLit :: Circuit -> Lit -> Maybe Bool
isConstLit c l
| l == cTrue c = Just True
| l == cFalse c = Just False
| otherwise = Nothing
-------------------------------------------------------------------------------
-- Gates
cached :: Circuit -> (Int, Lit, Lit, Lit) -> (Lit -> [[Lit]]) -> IO Lit
cached c key clauses =
Map.lookup key <$> readIORef (cGates c) >>= \case
Just x -> pure x
Nothing -> do
x <- fresh c
mapM_ (emit c) (clauses x)
modifyIORef' (cGates c) (Map.insert key x)
pure x
-- | Conjunction of two literals.
andG :: Circuit -> Lit -> Lit -> IO Lit
andG c a b
| a == cFalse c || b == cFalse c = pure (cFalse c)
| a == cTrue c = pure b
| b == cTrue c = pure a
| a == b = pure a
| a == litNeg b = pure (cFalse c)
| otherwise =
let (x, y) = (min a b, max a b)
in cached c (0, x, y, x) $ \o -> [[litNeg o, x], [litNeg o, y], [o, litNeg x, litNeg y]]
-- | Disjunction of two literals.
orG :: Circuit -> Lit -> Lit -> IO Lit
orG c a b = litNeg <$> andG c (litNeg a) (litNeg b)
-- | Exclusive or of two literals.
xorG :: Circuit -> Lit -> Lit -> IO Lit
xorG c a b
| Just va <- isConstLit c a = pure (if va then litNeg b else b)
| Just vb <- isConstLit c b = pure (if vb then litNeg a else a)
| a == b = pure (cFalse c)
| a == litNeg b = pure (cTrue c)
| otherwise = do
-- Normalize to positive inputs; each negation flips the output.
let flips = litSign a /= litSign b
pa = if litSign a then litNeg a else a
pb = if litSign b then litNeg b else b
(x, y) = (min pa pb, max pa pb)
o <-
cached c (1, x, y, x) $ \o ->
[ [litNeg o, x, y]
, [litNeg o, litNeg x, litNeg y]
, [o, litNeg x, y]
, [o, x, litNeg y]
]
pure (if flips then litNeg o else o)
-- | @iteG c s a b@ is @a@ when @s@ holds and @b@ otherwise.
iteG :: Circuit -> Lit -> Lit -> Lit -> IO Lit
iteG c s a b
| Just vs <- isConstLit c s = pure (if vs then a else b)
| a == b = pure a
| a == cTrue c = orG c s b
| a == cFalse c = andG c (litNeg s) b
| b == cTrue c = orG c (litNeg s) a
| b == cFalse c = andG c s a
| otherwise =
cached c (2, s, a, b) $ \o ->
[ [litNeg o, litNeg s, a]
, [litNeg o, s, b]
, [o, litNeg s, litNeg a]
, [o, s, litNeg b]
]
-- | Conjunction of a list of literals ('cTrue' when empty).
andN :: Circuit -> [Lit] -> IO Lit
andN c = foldlM' (andG c) (cTrue c)
-- | Disjunction of a list of literals ('cFalse' when empty).
orN :: Circuit -> [Lit] -> IO Lit
orN c = foldlM' (orG c) (cFalse c)
foldlM' :: (b -> a -> IO b) -> b -> [a] -> IO b
foldlM' f = go
where
go acc [] = pure acc
go acc (x : xs) = f acc x >>= \acc' -> go acc' xs
-------------------------------------------------------------------------------
-- Bit-vectors
-- | @constBits c w v@ is the constant vector of width @w@ holding the low
-- @w@ bits of @v@ (two's complement for negative @v@).
constBits :: Circuit -> Int -> Integer -> Bits
constBits c w v = [if testBit v i then cTrue c else cFalse c | i <- [0 .. w - 1]]
-- | A vector of @w@ fresh, unconstrained bits.
freshBits :: Circuit -> Int -> IO Bits
freshBits c w = replicateM w (fresh c)
-- | Bitwise negation; needs no gates.
bvNot :: Bits -> Bits
bvNot = map litNeg
-- | Bitwise and, or and xor of two vectors of the same width.
bvAnd, bvOr, bvXor :: Circuit -> Bits -> Bits -> IO Bits
bvAnd c = zipWithM' (andG c)
bvOr c = zipWithM' (orG c)
bvXor c = zipWithM' (xorG c)
zipWithM' :: (a -> b -> IO d) -> [a] -> [b] -> IO [d]
zipWithM' f xs ys = sequence (zipWith f xs ys)
-- | Sum with a carry-in, truncated to the width of the inputs.
addWithCarry :: Circuit -> Lit -> Bits -> Bits -> IO Bits
addWithCarry c = go
where
go _ [] _ = pure []
go _ _ [] = pure []
go carry (a : as) (b : bs) = do
ab <- xorG c a b
s <- xorG c ab carry
g <- andG c a b
p <- andG c ab carry
carry' <- orG c g p
(s :) <$> go carry' as bs
-- | Ripple-carry sum, truncated to the width of the inputs (modulo @2^w@).
bvAdd :: Circuit -> Bits -> Bits -> IO Bits
bvAdd c = addWithCarry c (cFalse c)
-- | @a - b = a + ~b + 1@.
bvSub :: Circuit -> Bits -> Bits -> IO Bits
bvSub c a b = addWithCarry c (cTrue c) a (bvNot b)
-- | Two's complement negation, @0 - a@.
bvNeg :: Circuit -> Bits -> IO Bits
bvNeg c a = bvSub c (map (const (cFalse c)) a) a
-- | Shift-and-add multiplier, truncated to the width of the inputs.
bvMul :: Circuit -> Bits -> Bits -> IO Bits
bvMul c a b = foldlM' step (map (const (cFalse c)) a) (zip [0 ..] b)
where
w = length a
step acc (i, bi) = do
partial <- mapM (andG c bi) (take (w - i) a)
bvAdd c acc (replicate i (cFalse c) <> partial)
-- | Unsigned quotient and remainder. They are fresh vectors constrained by
-- @a = q * b + r@ and @r < b@ when @b /= 0@, computed in double width so
-- that the product cannot overflow, and by @q = ~0@, @r = a@ when @b = 0@.
udivRem :: Circuit -> Bits -> Bits -> IO (Bits, Bits)
udivRem c a b =
Map.lookup (a, b) <$> readIORef (cDivRem c) >>= \case
Just qr -> pure qr
Nothing -> do
let w = length a
zeros = replicate w (cFalse c)
q <- freshBits c w
r <- freshBits c w
bz <- litNeg <$> orN c b
-- b = 0
forM_ q $ \qi -> emit c [litNeg bz, qi]
forM_ (zip r a) $ \(ri, ai) -> do
emit c [litNeg bz, litNeg ri, ai]
emit c [litNeg bz, ri, litNeg ai]
-- b /= 0
prod <- bvMul c (q <> zeros) (b <> zeros)
total <- bvAdd c prod (r <> zeros)
exact <- bvEq c total (a <> zeros)
smaller <- bvULt c r b
emit c [bz, exact]
emit c [bz, smaller]
modifyIORef' (cDivRem c) (Map.insert (a, b) (q, r))
pure (q, r)
-- | Unsigned quotient and remainder; both share one division circuit.
-- Division by zero gives @~0@ (quotient) and the dividend (remainder).
bvUDiv, bvURem :: Circuit -> Bits -> Bits -> IO Bits
bvUDiv c a b = fst <$> udivRem c a b
bvURem c a b = snd <$> udivRem c a b
msb :: Bits -> Lit
msb = last
-- | Absolute value in two's complement.
absBits :: Circuit -> Bits -> IO Bits
absBits c a = do
n <- bvNeg c a
bvIte c (msb a) n a
-- | Signed division, defined by SMT-LIB through unsigned division of the
-- absolute values.
bvSDiv :: Circuit -> Bits -> Bits -> IO Bits
bvSDiv c a b = do
ua <- absBits c a
ub <- absBits c b
u <- bvUDiv c ua ub
negative <- xorG c (msb a) (msb b)
nu <- bvNeg c u
bvIte c negative nu u
-- | Signed remainder; its sign follows the dividend.
bvSRem :: Circuit -> Bits -> Bits -> IO Bits
bvSRem c a b = do
ua <- absBits c a
ub <- absBits c b
u <- bvURem c ua ub
nu <- bvNeg c u
bvIte c (msb a) nu u
-- | Signed modulo; its sign follows the divisor.
bvSMod :: Circuit -> Bits -> Bits -> IO Bits
bvSMod c a b = do
ua <- absBits c a
ub <- absBits c b
u <- bvURem c ua ub
nu <- bvNeg c u
zero <- litNeg <$> orN c u
negPlusB <- bvAdd c nu b
uPlusB <- bvAdd c u b
let (sa, sb) = (msb a, msb b)
-- (sa, sb) = (0,0): u; (1,0): -u + b; (0,1): u + b; (1,1): -u
whenNegA <- bvIte c sb nu negPlusB
whenPosA <- bvIte c sb uPlusB u
r <- bvIte c sa whenNegA whenPosA
bvIte c zero u r
-- | Barrel shifter. @fill@ is the bit shifted in; shift amounts of at least
-- the width produce a vector of fill bits.
shiftBy :: Circuit -> (Int -> Bits -> Bits) -> Lit -> Bits -> Bits -> IO Bits
shiftBy c shiftConst fill a b = do
let w = length a
stages = [(k, bk) | (k, bk) <- zip [0 :: Int ..] b, (1 `shiftL` k) < w]
overflowBits = [bk | (k, bk) <- zip [0 :: Int ..] b, (1 `shiftL` k) >= w]
shifted <-
foldlM'
(\cur (k, bk) -> bvIte c bk (shiftConst (1 `shiftL` k) cur) cur)
a
stages
overflow <- orN c overflowBits
bvIte c overflow (replicate w fill) shifted
-- | Shift left by the unsigned amount in the second vector, filling with
-- zeros.
bvShl :: Circuit -> Bits -> Bits -> IO Bits
bvShl c a = shiftBy c (\k xs -> take (length xs) (replicate k (cFalse c) <> xs)) (cFalse c) a
-- | Logical shift right by the unsigned amount in the second vector,
-- filling with zeros.
bvLShr :: Circuit -> Bits -> Bits -> IO Bits
bvLShr c a = shiftBy c (\k xs -> drop k xs <> replicate (min k (length xs)) (cFalse c)) (cFalse c) a
-- | Arithmetic shift right by the unsigned amount in the second vector,
-- filling with copies of the sign bit.
bvAShr :: Circuit -> Bits -> Bits -> IO Bits
bvAShr c a = shiftBy c (\k xs -> drop k xs <> replicate (min k (length xs)) (msb xs)) (msb a) a
-- | @bvIte c s a b@ is @a@ when @s@ holds and @b@ otherwise, bit by bit.
bvIte :: Circuit -> Lit -> Bits -> Bits -> IO Bits
bvIte c s = zipWithM' (iteG c s)
-- | The literal of @a = b@, for vectors of the same width.
bvEq :: Circuit -> Bits -> Bits -> IO Lit
bvEq c a b = do
diffs <- zipWithM' (xorG c) a b
litNeg <$> orN c diffs
-- | Unsigned @a < b@, scanning from the least significant bit: the most
-- significant differing bit decides.
bvULt :: Circuit -> Bits -> Bits -> IO Lit
bvULt c a b = foldlM' step (cFalse c) (zip a b)
where
step lt (ai, bi) = do
differ <- xorG c ai bi
iteG c differ bi lt
-- | Unsigned @a <= b@.
bvULe :: Circuit -> Bits -> Bits -> IO Lit
bvULe c a b = litNeg <$> bvULt c b a
-- | Signed comparisons flip the sign bits and compare unsigned.
bvSLt :: Circuit -> Bits -> Bits -> IO Lit
bvSLt c a b = bvULt c (flipMsb a) (flipMsb b)
where
flipMsb xs = init xs <> [litNeg (last xs)]
-- | Signed (two's complement) @a <= b@.
bvSLe :: Circuit -> Bits -> Bits -> IO Lit
bvSLe c a b = litNeg <$> bvSLt c b a
-- | The unsigned value of a vector under an assignment.
bitsValue :: (Lit -> IO Bool) -> Bits -> IO Integer
bitsValue val bs = do
vs <- forM bs val
pure (sum [if v then 1 `shiftL` i else 0 | (i, v) <- zip [0 ..] vs])