Skip to content

Fix 17 issues found in primitives - #3576

Open
martijnbastiaan wants to merge 18 commits into
masterfrom
martijn/evaluator-primitive-fixes
Open

martijnbastiaan wants to merge 18 commits into
masterfrom
martijn/evaluator-primitive-fixes

Conversation

@martijnbastiaan

Copy link
Copy Markdown
Member

Fix a whole bunch of issues with primitives, please see the individual commits and issue reports.

Context

I'm working on dehardcoding the evaluator as much as I can and, insofar it's possible, automatically identity check between Haskell, the Clash evaluator, and HDL implementations. This is the (first?) batch of issues that came out of that campaign.

Why catching errors is the way to go

In a follow-up PR (that I won't publish until this is merged to reduce the load..) I add a note on exceptions in primitives and add a warning flag to trace evaluations to X. For now:

Note [Exceptions in primitive rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Haskell function behind a primitive can throw: 'quot' on a zero divisor,
'shiftL' on a negative shift amount, and so on. A rule must not let that stop
the compiler. It gives an undefined result instead, and raises a warning that
is off by default: @-Wclash-evaluation-to-x@.

An exception does not mean the design is wrong. Haskell only evaluates what is
needed, but Clash rewrites a subterm without knowing whether the term around it
will keep that subterm. So the evaluator is also asked for results that a later
pass may remove, or else the synthesis tool may. Consider:

    isZero :: Unsigned 8 -> Bool
    isZero x = x == 0
    {-# OPAQUE isZero #-}

    quotient :: Unsigned 8 -> Unsigned 8 -> Unsigned 8
    quotient x y = x `quot` y
    {-# OPAQUE quotient #-}

    topEntity :: Unsigned 8
    topEntity = if isZero 0 then 0 else quotient 200 0

Haskell never calls @quotient@ here. Clash normalizes @isZero 0@ and
@quotient 200 0@ each on their own, and so asks the evaluator for
@quot# 200 0@. Only after that does 'caseCon' see that the condition is @True@
and drop the other alternative. The HDL is the constant 0.

If the condition is an input, Clash will not remove the undefined result:

    topEntity :: Bool -> Unsigned 8
    topEntity enable = if enable then quotient 200 0 else 0

becomes

    assign result = enable ? ({8 {1'bx}}) : 8'd0;

This is fine too. The rest of the design may never set @enable@, and the
synthesis tool is free to pick a value for the undefined bits that makes the
multiplexer go away.

https://github.com/clash-lang/clash-compiler/issues/2815 is a real design that
runs into this.

For a rule this means:

  * Wrap a term that can throw in 'catchDivByZero', 'catchErrorCall' or
    'catchArithException'. They force the term, and give the undefined result
    if that throws the exception they are named after, or an 'XException'.
    Other exceptions are bugs in the evaluator, and are not caught.

  * Some functions do not throw. E.g. @quotInt#@ kills the process on a zero
    divisor, and @indexWordArray#@ does not check its index. A rule for such a
    function calls one that does throw ('quot' at 'Int'), or checks the
    arguments itself and gives 'undefinedResult'.

These three and 'undefinedResult' are fields of 'PrimStepContext'.

Fixes #3559
Fixes #3560
Fixes #3561
Fixes #3562
Fixes #3563
Fixes #3564
Fixes #3565
Fixes #3566
Fixes #3567
Fixes #3568
Fixes #3569
Fixes #3570
Fixes #3571
Fixes #3572
Fixes #3573
Fixes #3574
Fixes #3575

@rowanG077
rowanG077 self-requested a review December 1, 2026 10:53
-- A string is a literal, or the empty list: that is how GHC writes
-- @""@.
string = \case
PrimVal _ _ [Lit (StringLiteral s)] -> Just s

@rowanG077 rowanG077 Dec 1, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is wrong I think. StringLiteral s it's not just important what the s contains but also how it's used. For example, consider é.

GHC.Exts.unpackCString# "\xE9"# == GHC.Exts.unpackCStringUtf8# "\xC3\xA9"# -- True

Perhaps a nice way is to have normalize this in the evaluator as well?

BA.unsafeFreezeByteArray (BA.MutableByteArray dst_mba1)
ba3 = Literal (ByteArrayLiteral ba2)
in Just . setTerm (Prim rwTy) $ primUpdate (fromInteger dst_mba) ba3 mach
in if len <= List.genericLength addr && hasBytesAt dst_ba off len then

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The length check is not right as it misses the NULL terminator, For example "abcdefg"# contains 8 bytes and we can copy that into the ByteArray but the check rejects it because List.genericLength addr reports 7.

ghci> :set -XMagicHash
ghci> import GHC.Exts (unpackCString#, unpackNBytes#)
ghci> length (unpackCString# "abcdefg"#)
7
ghci> unpackNBytes# "abcdefg"# 8#
"abcdefg\NUL"

undefinedResult = TyApp (Prim NP.undefined) (getResultTy tcm ty tys)

mkResultTuple fields =
let (_, tyView -> TyConApp tupTcNm tyArgs) = splitFunForallTy ty

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should use getResultTy tcm ty tys here too. I tried readWordArray# @RealWorld. Before evaluation its result type is (# State# RealWorld, Word# #), but afterwards I get (# State# d, Word# #).

type: 'integerToNatural
:: Integer -> Natural'
template: resize(unsigned(std_logic_vector(~ARG[0])),~SIZE[~TYPO])
template: resize(unsigned(std_logic_vector(abs(~ARG[0]))),~SIZE[~TYPO])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is no longer workInfo: never right?

type: 'integerToNatural
:: Integer -> Natural'
template: $unsigned(~VAR[n][0][(~SIZE[~TYPO]-1):0])
template: '$unsigned((~ARG[0] < ~SIZE[~TYP[0]]''sd0) ? -~ARG[0] : ~ARG[0])'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here with the work info.

type: 'integerToNaturalThrow
:: Integer -> Natural'
template: '(~ARG[0] < ~SIZE[~TYP[0]]''d0 ? ~ERRORO: $unsigned(~VAR[n][0][(~SIZE[~TYPO]-1):0]))'
template: '(~ARG[0] < ~SIZE[~TYP[0]]''sd0 ? ~ERRORO: $unsigned(~VAR[n][0][(~SIZE[~TYPO]-1):0]))'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here with the work info.

type: 'integerToNatural
:: Integer -> Natural'
template: '(~ARG[0] < ~SIZE[~TYP[0]]''d0 ? ~SIZE[~TYPO]''d0 : $unsigned(~VAR[n][0][(~SIZE[~TYPO]-1):0]))'
template: '(~ARG[0] < ~SIZE[~TYP[0]]''sd0 ? ~SIZE[~TYPO]''d0 : $unsigned(~VAR[n][0][(~SIZE[~TYPO]-1):0]))'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here with the work info.

[ testCase "writeWordArray#" $
apply 'GHC.Exts.writeWordArray#
[mutableWordArray [1, 2], int 1, word 7, realWorld] statePrimTy
==> State

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we also check what ended up in the array? For example, writeWordArray# actually should write into the array, so I’d expect the resulting array to contain [1, 7]. At the moment this test still passes if the write is dropped. Similar for other tests.

Add a `clash-ghc:unittests` suite that applies the evaluator's rule for a
primitive to literal arguments and checks the result, without compiling a
design.
…evaluator

The evaluator counted the trailing zeros on a native `Word`, so it gave the
wrong result when the lower 8, 16 or 32 bits were zero. Count on a `Word8`,
`Word16` or `Word32` instead.

Fixes #3559
The typing issue made other primitive rules not recognize the literal.

Fixes #3560
The evaluator kept the bits that the primitive shifts out, and a later right
shift brought them back.

Fixes #3561
The evaluator shifted an `Integer` by the amount as given. A negative amount
threw an exception and a very large one ran out of memory. GHC leaves shifts
by an amount outside 0..63 unspecified; Clash now gives what the primitive
gives on the machine that runs it.

Fixes #3562
The `ghcPrimUnwind` cases for `fromInteger#` and `fromInteger##` called `error`
when their arguments were not literals, for example an undefined `Integer`.
Let them fall through to the check for an undefined argument.

Fixes #3563
For a zero divisor the rules caught the exception in each field of the result
tuple, so each field became an `undefined` of the tuple's type. The functions
throw before they return a tuple: catch around the whole tuple.

Fixes #3564
`quotRemWord2#` kills the process with SIGFPE when the quotient does not fit
in a word, which includes a zero divisor. Return an undefined result for such
arguments.

Fixes #3566
`writeWordArray#`, `setByteArray#`, `copyByteArray#`, `copyAddrToByteArray#`
and `shrinkMutableByteArray#` do not check their arguments, so outside the
array the evaluator wrote into its own memory. Give an undefined result
instead.

Fixes #3570
The rules for `quotInt#`, `quotRemInt#`, `divInt#`, `GHC.Base.quotInt` and
`GHC.Base.divInt` divided `Integer`s, so `minBound` by -1 gave `minBound`, or
for the last two a literal outside the range of `Int`. The primitives kill the
process there: give an undefined result, like the sized rules do.

Fixes #3571
…turalThrow`

The templates tested for a negative number with `x < 64'd0`. The unsigned
literal makes Verilog compare unsigned, so the test was never true. Use a
signed literal.

Fixes #3572
GHC writes such a literal with `unpackCStringUtf8#`. The evaluator had no rule
for it and did not treat it as a value, so it got stuck on the literal and
never reached `eqString`. Treat it as a value, like `unpackCString#`.

Fixes #3575
@martijnbastiaan
martijnbastiaan force-pushed the martijn/evaluator-primitive-fixes branch from 56fdd04 to 87a5d18 Compare December 3, 2026 10:30
@martijnbastiaan

Copy link
Copy Markdown
Member Author

Thanks for the review @rowanG077. I've applied all your comments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment