Debian Codegraph @

src-ghc/Clash/GHC/Evaluator.hs

raw
1 {-|
2 Copyright : (C) 2017-2022, Google Inc.,
3 2021-2024, QBayLogic B.V.
4 License : BSD2 (see the file LICENSE)
5 Maintainer : QBayLogic B.V. <[email protected]>
6
7 Call-by-need evaluator based on the evaluator described in:
8
9 Maximilian Bolingbroke, Simon Peyton Jones, "Supercompilation by evaluation",
10 Haskell '10, Baltimore, Maryland, USA.
11
12 -}
13
14 {-# LANGUAGE CPP #-}
15 {-# LANGUAGE LambdaCase #-}
16 {-# LANGUAGE MagicHash #-}
17 {-# LANGUAGE NamedFieldPuns #-}
18 {-# LANGUAGE OverloadedStrings #-}
19 {-# LANGUAGE TemplateHaskell #-}
20
21 module Clash.GHC.Evaluator where
22
23 import Prelude hiding (lookup)
24
25 import Data.Either (lefts,rights)
26 import Data.List (mapAccumL)
27 #if !MIN_VERSION_base(4,20,0)
28 import Data.List (foldl')
29 #endif
30 import qualified Data.Primitive.ByteArray as BA
31 import qualified Data.Text as Text
32 #if MIN_VERSION_base(4,15,0)
33 import GHC.Num.Integer (Integer (..))
34 #else
35 import GHC.Integer.GMP.Internals
36 (Integer (..), BigNat (..))
37 #endif
38
39 import Clash.Core.DataCon
40 import Clash.Core.Evaluator.Types
41 import Clash.Core.HasFreeVars
42 import Clash.Core.HasType
43 import Clash.Core.Literal
44 import Clash.Core.Name
45 import Clash.Core.Pretty
46 import Clash.Core.Subst
47 import Clash.Core.Term
48 import Clash.Core.TyCon
49 import Clash.Core.Type
50 import Clash.Core.Util
51 import Clash.Core.Var
52 import Clash.Core.VarEnv
53 import Clash.Debug
54 import qualified Clash.Normalize.Primitives as NP (removedArg, undefined, undefinedX)
55 import Clash.Unique
56 import Clash.Util (curLoc)
57 import Clash.Util.Supply (Supply, freshId)
58
59 import Clash.GHC.Evaluator.Primitive
60
61 evaluator :: Evaluator
62 evaluator = Evaluator
63 { step = ghcStep
64 , unwind = ghcUnwind
65 , primStep = ghcPrimStep
66 , primUnwind = ghcPrimUnwind
67 }
68
69 {- [Note: forcing special primitives]
70 Clash uses the `whnf` function in two places (for now):
71
72 1. The case-of-known-constructor transformation
73 2. The reduceConstant transformation
74
75 The first transformation is needed to reach the required normal form. The
76 second transformation is more of cleanup transformation, so non-essential.
77
78 Normally, `whnf` would force the evaluation of all primitives, which is needed
79 in the `case-of-known-constructor` transformation. However, there are some
80 primitives which we want to leave unevaluated in the `reduceConstant`
81 transformation. Such primitives are:
82
83 - Primitives such as `Clash.Sized.Vector.transpose`, `Clash.Sized.Vector.map`,
84 etc. that do not reduce to an expression in normal form. Where the
85 `reduceConstant` transformation is supposed to be normal-form preserving.
86 - Primitives such as `GHC.Int.I8#`, `GHC.Word.W32#`, etc. which seem like
87 wrappers around a 64-bit literal, but actually perform truncation to the
88 desired bit-size.
89
90 This is why the Primitive Evaluator gets a flag telling whether it should
91 evaluate these special primitives.
92 -}
93
94 stepVar :: Id -> Step
95 stepVar i m _
96 | Just e <- heapLookup LocalId i m
97 = go LocalId e
98
99 | Just e <- heapLookup GlobalId i m
100 , isGlobalId i
101 = go GlobalId e
102
103 | otherwise
104 = Nothing
105 where
106 go s e =
107 let term = deShadowTerm (mScopeNames m) (tickExpr e)
108 in Just . setTerm term . stackPush (Update s i) $ heapDelete s i m
109
110 -- Removing the heap-bound value on a force ensures we do not get stuck on
111 -- expressions such as: "let x = x in x"
112 tickExpr = Tick (NameMod PrefixName (LitTy . SymTy $ toStr i))
113 unQualName = snd . Text.breakOnEnd "."
114 toStr = Text.unpack . unQualName . flip Text.snoc '_' . nameOcc . varName
115
116 stepData :: DataCon -> Step
117 stepData dc = ghcUnwind (DC dc [])
118
119 stepLiteral :: Literal -> Step
120 stepLiteral l = ghcUnwind (Lit l)
121
122 stepPrim :: PrimInfo -> Step
123 stepPrim pInfo m tcm
124 | primName pInfo == "GHC.Prim.realWorld#" =
125 ghcUnwind (PrimVal pInfo [] []) m tcm
126
127 | otherwise =
128 case fst $ splitFunForallTy (primType pInfo) of
129 [] -> ghcPrimStep tcm (forcePrims m) pInfo [] [] m
130 tys -> newBinder tys (Prim pInfo) m tcm
131
132 stepLam :: Id -> Term -> Step
133 stepLam x e = ghcUnwind (Lambda x e)
134
135 stepTyLam :: TyVar -> Term -> Step
136 stepTyLam x e = ghcUnwind (TyLambda x e)
137
138 stepApp :: Term -> Term -> Step
139 stepApp x y m tcm =
140 case term of
141 Data dc ->
142 let tys = fst $ splitFunForallTy (dcType dc)
143 in case compare (length args) (length tys) of
144 EQ -> ghcUnwind (DC dc args) m tcm
145 LT -> newBinder tys' (App x y) m tcm
146 GT -> error "Overapplied DC"
147
148 Prim p ->
149 let tys = fst $ splitFunForallTy (primType p)
150 in case compare (length args) (length tys) of
151 EQ -> case lefts args of
152 -- We make boolean conjunction and disjunction extra lazy by
153 -- deferring the evaluation of the arguments during the evaluation
154 -- of the primop rule.
155 --
156 -- This allows us to implement:
157 --
158 -- x && True --> x
159 -- x && False --> False
160 -- x || True --> True
161 -- x || False --> x
162 --
163 -- even when that 'x' is _|_. This makes the evaluation
164 -- rule lazier than the actual Haskel implementations which
165 -- are strict in the first argument and lazy in the second.
166 [a0, a1] | primName p `elem` ["GHC.Classes.&&","GHC.Classes.||"] ->
167 let (m0,i) = newLetBinding tcm m a0
168 (m1,j) = newLetBinding tcm m0 a1
169 in ghcPrimStep tcm (forcePrims m) p [] [Suspend (Var i), Suspend (Var j)] m1
170
171 (e':es)
172 | primName p `elem` (undefinedXPrims ++ undefinedPrims)
173 -- The above primitives are (bottoming) values, whose arguments
174 -- are never used anywhere in the rest of the compiler. So
175 -- instead of pushing a PrimApply frame on the stack to evaluate
176 -- those arguments, we instead just unwind the stack with the
177 -- primitive value and leave its arguments in an unevaluated
178 -- state (Suspend).
179 -> ghcUnwind (PrimVal p (rights args) (map Suspend (e':es))) m tcm
180 | otherwise
181 -> Just . setTerm e' $ stackPush (PrimApply p (rights args) [] es) m
182
183 _ -> error "internal error"
184
185 LT -> newBinder tys' (App x y) m tcm
186
187 GT -> let (m0, n) = newLetBinding tcm m y
188 in Just . setTerm x $ stackPush (Apply n) m0
189
190 _ -> let (m0, n) = newLetBinding tcm m y
191 in Just . setTerm x $ stackPush (Apply n) m0
192 where
193 (term, args, _) = collectArgsTicks (App x y)
194 tys' = fst . splitFunForallTy . inferCoreTypeOf tcm $ App x y
195
196 stepTyApp :: Term -> Type -> Step
197 stepTyApp x ty m tcm =
198 case term of
199 Data dc ->
200 let tys = fst $ splitFunForallTy (dcType dc)
201 in case compare (length args) (length tys) of
202 EQ -> ghcUnwind (DC dc args) m tcm
203 LT -> newBinder tys' (TyApp x ty) m tcm
204 GT -> error "Overapplied DC"
205
206 Prim p ->
207 let tys = fst $ splitFunForallTy (primType p)
208 in case compare (length args) (length tys) of
209 EQ -> case lefts args of
210 [] | primName p `elem` fmap primName [ NP.removedArg
211 , NP.undefined
212 , NP.undefinedX ] ->
213 ghcUnwind (PrimVal p (rights args) []) m tcm
214
215 | otherwise ->
216 ghcPrimStep tcm (forcePrims m) p (rights args) [] m
217
218 (e':es) ->
219 Just . setTerm e' $ stackPush (PrimApply p (rights args) [] es) m
220
221 LT -> newBinder tys' (TyApp x ty) m tcm
222 GT -> Just . setTerm x $ stackPush (Instantiate ty) m
223
224 _ -> Just . setTerm x $ stackPush (Instantiate ty) m
225 where
226 (term, args, _) = collectArgsTicks (TyApp x ty)
227 tys' = fst . splitFunForallTy . inferCoreTypeOf tcm $ TyApp x ty
228
229 stepLet :: Bind Term -> Term -> Step
230 stepLet (NonRec i b) x m _ = Just (allocate [(i,b)] x m)
231 stepLet (Rec bs) x m _ = Just (allocate bs x m)
232
233 stepCase :: Term -> Type -> [Alt] -> Step
234 stepCase scrut ty alts m _ =
235 Just . setTerm scrut $ stackPush (Scrutinise ty alts) m
236
237 -- TODO Support stepwise evaluation of casts.
238 --
239 stepCast :: Term -> Type -> Type -> Step
240 stepCast _ _ _ _ _ =
241 flip trace Nothing $ unlines
242 [ "WARNING: " <> $(curLoc) <> "Clash can't symbolically evaluate casts"
243 , "Please file an issue at https://github.com/clash-lang/clash-compiler/issues"
244 ]
245
246 stepTick :: TickInfo -> Term -> Step
247 stepTick tick x m _ =
248 Just . setTerm x $ stackPush (Tickish tick) m
249
250 -- | Small-step operational semantics.
251 --
252 ghcStep :: Step
253 ghcStep m = case mTerm m of
254 Var i -> stepVar i m
255 Data dc -> stepData dc m
256 Literal l -> stepLiteral l m
257 Prim p -> stepPrim p m
258 Lam v x -> stepLam v x m
259 TyLam v x -> stepTyLam v x m
260 App x y -> stepApp x y m
261 TyApp x ty -> stepTyApp x ty m
262 Let bs x -> stepLet bs x m
263 Case s ty as -> stepCase s ty as m
264 Cast x a b -> stepCast x a b m
265 Tick t x -> stepTick t x m
266
267 -- | Take a list of types or type variables and create a lambda / type lambda
268 -- for each one around the given term.
269 --
270 newBinder :: [Either TyVar Type] -> Term -> Step
271 newBinder tys e m tcm =
272 let ((supply1,_), e1) = etaExpand (mSupply m, mScopeNames m) tys
273 m1 = m { mSupply = supply1, mTerm = e1 }
274 in ghcStep m1 tcm
275 where
276 etaExpand env args =
277 let (env1,args1) = mapAccumL go env args
278 in (env1,mkAbstraction (foldl' go2 e args1) args1)
279
280 go env (Left tv) = (env, Right tv)
281 go env (Right ty) =
282 let (env1, n) = mkUniqSystemId env ("x", ty)
283 in (env1, Left n)
284
285 go2 u (Left i) = App u (Var i)
286 go2 u (Right tv) = TyApp u (VarTy tv)
287
288 newLetBinding
289 :: TyConMap
290 -> Machine
291 -> Term
292 -> (Machine, Id)
293 newLetBinding tcm m e
294 | Var v <- e
295 , heapContains LocalId v m
296 = (m, v)
297
298 | otherwise
299 = let m' = heapInsert LocalId id_ e m
300 in (m' { mSupply = ids', mScopeNames = is1 }, id_)
301 where
302 ty = inferCoreTypeOf tcm e
303 ((ids', is1), id_) = mkUniqSystemId (mSupply m, mScopeNames m) ("x", ty)
304
305 -- | Unwind the stack by 1
306 ghcUnwind :: Unwind
307 ghcUnwind v m tcm = do
308 (m', kf) <- stackPop m
309 go kf m'
310 where
311 go (Update s x) = return . update s x v
312 go (Apply x) = return . apply tcm v x
313 go (Instantiate ty) = return . instantiate tcm v ty
314 go (PrimApply p tys vs tms) = ghcPrimUnwind tcm p tys vs v tms
315 go (Scrutinise altTy as) = return . scrutinise v altTy as
316 go (Tickish _) = return . setTerm (valToTerm v)
317
318 -- | Update the Heap with the evaluated term
319 update :: IdScope -> Id -> Value -> Machine -> Machine
320 update s x (valToTerm -> term) =
321 setTerm term . heapInsert s x term
322
323 -- | Apply a value to a function
324 apply :: TyConMap -> Value -> Id -> Machine -> Machine
325 apply _tcm (Lambda x' e) x m =
326 setTerm (substTm "Evaluator.apply" subst e) m
327 where
328 subst = extendIdSubst subst0 x' (Var x)
329 subst0 = mkSubst $ extendInScopeSet (mScopeNames m) x
330 apply tcm pVal@(PrimVal (PrimInfo{primType}) tys vs) x m
331 | isUndefinedXPrimVal pVal
332 = setTerm (TyApp (Prim NP.undefinedX) ty) m
333 | isUndefinedPrimVal pVal
334 = setTerm (TyApp (Prim NP.undefined) ty) m
335 where
336 ty = piResultTys tcm primType (tys ++ map (inferCoreTypeOf tcm . valToTerm) vs ++ [varType x])
337
338 apply _ v _ m = error $ "Evaluator.apply: Not a lambda: " ++ show v ++ "\n" ++ show m
339
340 -- | Instantiate a type-abstraction
341 instantiate :: TyConMap -> Value -> Type -> Machine -> Machine
342 instantiate _tcm (TyLambda x e) ty m =
343 setTerm (substTm "Evaluator.instantiate1" subst e) m
344 where
345 subst = extendTvSubst subst0 x ty
346 subst0 = mkSubst iss0
347 iss0 = mkInScopeSet (freeVarsOf e <> freeVarsOf ty)
348 -- The evaluator is setup in such a way that under normal conditions anything
349 -- of type 'forall a . ty' must be a ty-lambda.
350 --
351 -- However, sometimes we evaluate to an error /value/. When this happens,
352 -- instead of doing a regural type substitition we:
353 --
354 -- 1. Calculate the 'forall a . ty' type of the error value
355 -- 2. Substitute the 'a' by the applied type.
356 -- 3. Create a new error value of the shape: 'undefined @substituted_type'
357 -- Where this particular 'undefined' has type 'forall a . a'. We destinquish
358 -- between error values throwing X exceptions and other error values, and
359 -- create appropriate error values that we return. We make this distinctions
360 -- in onder to enable conversion of X-exception throwing code to undefined
361 -- bitvectors.
362 instantiate tcm pVal@(PrimVal (PrimInfo{primType}) tys es) ty m
363 | isUndefinedXPrimVal pVal
364 = setTerm (TyApp (Prim NP.undefinedX) primType1) m
365 | isUndefinedPrimVal pVal
366 = setTerm (TyApp (Prim NP.undefined) primType1) m
367 where
368 esTys = map (inferCoreTypeOf tcm) es
369 -- Calculate the type of: prim @ty0 .. @tyN e0 .. eN @ty
370 --
371 -- This combines the above-mentioned step 1 and 2
372 primType1 = piResultTys tcm primType (tys ++ esTys ++ [ty])
373
374 instantiate _ p _ _ = error $ "Evaluator.instantiate: Not a tylambda: " ++ show p
375
376 -- | Evaluate a case-expression
377 scrutinise :: Value -> Type -> [Alt] -> Machine -> Machine
378 scrutinise v _altTy [] m = setTerm (valToTerm v) m
379 -- [Note: empty case expressions]
380 --
381 -- Clash does not have empty case-expressions; instead, empty case-expressions
382 -- are used to indicate that the `whnf` function was called the context of a
383 -- case-expression, which means certain special primitives must be forced.
384 -- See also [Note: forcing special primitives]
385 scrutinise (Lit l) _altTy alts m = case alts of
386 (DefaultPat, altE):alts1 -> setTerm (go altE alts1) m
387 _ -> let term = go (error $ "Evaluator.scrutinise: no match "
388 <> showPpr (Case (valToTerm (Lit l)) (ConstTy Arrow) alts)) alts
389 in setTerm term m
390 where
391 go def [] = def
392 go _ ((LitPat l1,altE):_) | l1 == l = altE
393 go _ ((DataPat dc [] [x],altE):_)
394 | IntegerLiteral l1 <- l
395 , Just patE <- case dcTag dc of
396 1 | l1 >= ((-2)^(63::Int)) && l1 < 2^(63::Int) ->
397 Just (IntLiteral l1)
398 2 | l1 >= (2^(63::Int)) ->
399 #if MIN_VERSION_base(4,15,0)
400 let !(IP ba0) = l1
401 #else
402 let !(Jp# !(BN# ba0)) = l1
403 #endif
404 ba1 = BA.ByteArray ba0
405 in Just (ByteArrayLiteral ba1)
406 3 | l1 < ((-2)^(63::Int)) ->
407 #if MIN_VERSION_base(4,15,0)
408 let !(IN ba0) = l1
409 #else
410 let !(Jn# !(BN# ba0)) = l1
411 #endif
412 ba1 = BA.ByteArray ba0
413 in Just (ByteArrayLiteral ba1)
414 _ -> Nothing
415 = let inScope = freeVarsOf altE
416 subst0 = mkSubst (mkInScopeSet inScope)
417 subst1 = extendIdSubst subst0 x (Literal patE)
418 in substTm "Evaluator.scrutinise" subst1 altE
419 | NaturalLiteral l1 <- l
420 , Just patE <- case dcTag dc of
421 1 | l1 >= 0 && l1 < 2^(64::Int) ->
422 Just (WordLiteral l1)
423 2 | l1 >= (2^(64::Int)) ->
424 #if MIN_VERSION_base(4,15,0)
425 let !(IP ba0) = l1
426 #else
427 let !(Jp# !(BN# ba0)) = l1
428 #endif
429 ba1 = BA.ByteArray ba0
430 in Just (ByteArrayLiteral ba1)
431 _ -> Nothing
432 = let inScope = freeVarsOf altE
433 subst0 = mkSubst (mkInScopeSet inScope)
434 subst1 = extendIdSubst subst0 x (Literal patE)
435 in substTm "Evaluator.scrutinise" subst1 altE
436 go def (_:alts1) = go def alts1
437
438 scrutinise (DC dc xs) _altTy alts m
439 | altE:_ <- [substInAlt altDc tvs pxs xs altE
440 | (DataPat altDc tvs pxs,altE) <- alts, altDc == dc ] ++
441 [altE | (DefaultPat,altE) <- alts ]
442 = setTerm altE m
443
444 scrutinise v@(PrimVal p _ vs) altTy alts m
445 | isUndefinedXPrimVal v
446 = setTerm (TyApp (Prim NP.undefinedX) altTy) m
447 | isUndefinedPrimVal v
448 = setTerm (TyApp (Prim NP.undefined) altTy) m
449
450 | any (\case {(LitPat {},_) -> True; _ -> False}) alts
451 = case alts of
452 ((DefaultPat,altE):alts1) -> setTerm (go altE alts1) m
453 _ -> let term = go (error $ "Evaluator.scrutinise: no match "
454 <> showPpr (Case (valToTerm v) (ConstTy Arrow) alts)) alts
455 in setTerm term m
456 where
457 go def [] = def
458 go _ ((LitPat l1,altE):_) | l1 == l = altE
459 go def (_:alts1) = go def alts1
460
461 l = case primName p of
462 "Clash.Sized.Internal.BitVector.fromInteger##"
463 | [Lit (WordLiteral 0), Lit l0] <- vs -> l0
464 "Clash.Sized.Internal.BitVector.fromInteger#"
465 | [_,Lit (NaturalLiteral 0),Lit l0] <- vs -> l0
466 "Clash.Sized.Internal.Index.fromInteger#"
467 | [_,Lit l0] <- vs -> l0
468 "Clash.Sized.Internal.Signed.fromInteger#"
469 | [_,Lit l0] <- vs -> l0
470 "Clash.Sized.Internal.Unsigned.fromInteger#"
471 | [_,Lit l0] <- vs -> l0
472 _ -> error ("scrutinise: " ++ showPpr (Case (valToTerm v) (ConstTy Arrow) alts))
473
474 scrutinise v _altTy alts _ =
475 error ("scrutinise: " ++ showPpr (Case (valToTerm v) (ConstTy Arrow) alts))
476
477 substInAlt :: DataCon -> [TyVar] -> [Id] -> [Either Term Type] -> Term -> Term
478 substInAlt dc tvs xs args e = substTm "Evaluator.substInAlt" subst e
479 where
480 tys = rights args
481 tms = lefts args
482 substTyMap = zip tvs (drop (length (dcUnivTyVars dc)) tys)
483 substTmMap = zip xs tms
484 inScope = freeVarsOf tys `unionVarSet` freeVarsOf (e:tms)
485 subst = extendTvSubstList (extendIdSubstList subst0 substTmMap) substTyMap
486 subst0 = mkSubst (mkInScopeSet inScope)
487
488 -- | Allocate let-bindings on the heap
489 allocate :: [LetBinding] -> Term -> Machine -> Machine
490 allocate xes e m =
491 m { mHeapLocal = extendVarEnvList (mHeapLocal m) xes'
492 , mSupply = ids'
493 , mScopeNames = isN
494 , mTerm = e'
495 }
496 where
497 xNms = fmap fst xes
498 is1 = extendInScopeSetList (mScopeNames m) xNms
499 (ids', s) = mapAccumL (letSubst (mHeapLocal m)) (mSupply m) xNms
500 (nms, s') = unzip s
501 isN = extendInScopeSetList is1 nms
502 subst = extendIdSubstList subst0 s'
503 subst0 = mkSubst (foldl' extendInScopeSet is1 nms)
504 xes' = zip nms (fmap (substTm "Evaluator.allocate0" subst . snd) xes)
505 e' = substTm "Evaluator.allocate1" subst e
506
507 -- | Create a unique name and substitution for a let-binder
508 letSubst
509 :: PureHeap
510 -> Supply
511 -> Id
512 -> (Supply, (Id, (Id, Term)))
513 letSubst h acc id0 =
514 let (acc',id1) = mkUniqueHeapId h acc id0
515 in (acc',(id1,(id0,Var id1)))
516 where
517 mkUniqueHeapId :: PureHeap -> Supply -> Id -> (Supply, Id)
518 mkUniqueHeapId h' ids x =
519 maybe (ids', x') (const $ mkUniqueHeapId h' ids' x) (lookupVarEnv x' h')
520 where
521 (i,ids') = freshId ids
522 x' = modifyVarName (`setUnique` i) x