Debian Codegraph @

src-ghc/Clash/GHC/GenerateBindings.hs

raw
1 {-|
2 Copyright : (C) 2013-2016, University of Twente,
3 2017, QBayLogic, Google Inc.,
4 2021-2022, QBayLogic B.V.
5 License : BSD2 (see the file LICENSE)
6 Maintainer : QBayLogic B.V. <[email protected]>
7 -}
8
9 {-# LANGUAGE CPP #-}
10 {-# LANGUAGE LambdaCase #-}
11 {-# LANGUAGE NamedFieldPuns #-}
12 {-# LANGUAGE OverloadedStrings #-}
13 {-# LANGUAGE QuasiQuotes #-}
14
15 module Clash.GHC.GenerateBindings
16 (generateBindings)
17 where
18
19 import Control.Arrow ((***))
20 import Control.DeepSeq (deepseq)
21 import Control.Lens ((%~),(&),(.~))
22 import Control.Monad (unless)
23 import qualified Control.Monad.State as State
24 import qualified Control.Monad.RWS.Strict as RWS
25 import Data.Coerce (coerce)
26 import Data.Either (partitionEithers, lefts ,rights)
27 import Data.IntMap.Strict (IntMap)
28 import qualified Data.IntMap.Strict as IMS
29 import qualified Data.HashMap.Strict as HashMap
30 import Data.List (isPrefixOf)
31 import Data.Maybe (listToMaybe)
32 import qualified Data.Text as Text
33 import qualified Data.Time.Clock as Clock
34
35 import qualified GHC as GHC (Ghc)
36 #if MIN_VERSION_ghc(9,0,0)
37 #if MIN_VERSION_ghc(9,4,0)
38 import qualified GHC.Types.SourceText as GHC
39 #endif
40 #if MIN_VERSION_ghc(9,2,0)
41 import qualified GHC.Utils.Panic as GHC
42 #endif
43 import qualified GHC.Types.Basic as GHC
44 import qualified GHC.Core as GHC
45 import qualified GHC.Types.Demand as GHC
46 import qualified GHC.Driver.Session as GHC
47 import qualified GHC.Types.Id.Info as GHC
48 import qualified GHC.Utils.Outputable as GHC
49 import qualified GHC.Types.Name as GHC hiding (varName)
50 import qualified GHC.Core.FamInstEnv as GHC
51 import qualified GHC.Core.TyCon as GHC
52 import qualified GHC.Core.Type as GHC
53 import qualified GHC.Builtin.Types as GHC
54 import qualified GHC.Settings.Constants as GHC
55 import qualified GHC.Types.Var as GHC
56 import qualified GHC.Types.SrcLoc as GHC
57 #else
58 import qualified BasicTypes as GHC
59 import qualified Constants as GHC
60 import qualified CoreSyn as GHC
61 import qualified Demand as GHC
62 import qualified DynFlags as GHC
63 import qualified FamInstEnv as GHC
64 import qualified IdInfo as GHC
65 import qualified Outputable as GHC
66 import qualified Name as GHC hiding (varName)
67 import qualified TyCon as GHC
68 import qualified Type as GHC
69 import qualified TysWiredIn as GHC
70 import qualified Var as GHC
71 import qualified SrcLoc as GHC
72 #endif
73 import GHC.BasicTypes.Extra (isOpaque)
74
75 import Clash.Annotations.BitRepresentation.Internal (buildCustomReprs)
76 import Clash.Annotations.Primitive (HDL, extractPrim)
77
78 import Clash.Core.Subst (extendGblSubstList, mkSubst, substTm)
79 import Clash.Core.Term (Term (..), mkLams, mkTyLams)
80 import Clash.Core.Type (Type (..), TypeView (..), mkFunTy, splitFunForallTy, tyView)
81 import Clash.Core.TyCon (TyConMap, TyConName, isNewTypeTc)
82 import Clash.Core.TysPrim (tysPrimMap)
83 import Clash.Core.Util (mkInternalVar, mkSelectorCase)
84 import Clash.Core.Var (Var (..), Id, IdScope (..), setIdScope)
85 import Clash.Core.VarEnv
86 (InScopeSet, VarEnv, emptyInScopeSet, extendInScopeSet, mkInScopeSet
87 ,mkVarEnv, unionVarEnv, elemVarSet, mkVarSet)
88 import qualified Clash.Data.UniqMap as UniqMap
89 import Clash.Debug (traceIf)
90 import Clash.Driver (compilePrimitive)
91 import Clash.Driver.Bool (toGhcOverridingBool)
92 import Clash.Driver.Types (BindingMap, Binding(..), IsPrim(..), ClashEnv(..), ClashDesign(..), ClashOpts(..))
93 import Clash.GHC.GHC2Core
94 (C2C, GHC2CoreState, GHC2CoreEnv (..), tyConMap, coreToId, coreToName, coreToTerm,
95 makeAllTyCons, qualifiedNameString, emptyGHC2CoreState, srcSpan)
96 import Clash.GHC.LoadModules (ghcLibDir, loadModules)
97 import Clash.Netlist.BlackBox.Util (getUsedArguments)
98 import Clash.Netlist.Types (TopEntityT(..))
99 import Clash.Primitives.Types
100 (Primitive (..), CompiledPrimMap)
101 import Clash.Primitives.Util (generatePrimMap)
102 import Clash.Unique (Unique)
103 import Clash.Util (reportTimeDiff)
104 import qualified Clash.Util.Interpolate as I
105
106 -- | Safe indexing, returns a 'Nothing' if the index does not exist
107 indexMaybe :: [a] -> Int -> Maybe a
108 indexMaybe [] _ = Nothing
109 indexMaybe (x:_) 0 = Just x
110 indexMaybe (_:xs) n = indexMaybe xs (n-1)
111
112 generateBindings
113 :: ClashOpts
114 -> GHC.Ghc ()
115 -- ^ Allows us to have some initial action, such as sharing a linker state
116 -- See https://github.com/clash-lang/clash-compiler/issues/1686 and
117 -- https://mail.haskell.org/pipermail/ghc-devs/2021-March/019605.html
118 -> [FilePath]
119 -- ^ primitives (blackbox) directories
120 -> [FilePath]
121 -- ^ import directories (-i flag)
122 -> [FilePath]
123 -- ^ Package database
124 -> HDL
125 -- ^ HDL target
126 -> String
127 -> Maybe GHC.DynFlags
128 -> IO (ClashEnv, ClashDesign)
129 generateBindings opts startAction primDirs importDirs dbs hdl modName dflagsM = do
130 ( bindings
131 , clsOps
132 , unlocatable
133 , fiEnvs
134 , topEntities
135 , partitionEithers -> (unresolvedPrims, pFP)
136 , customBitRepresentations
137 , primGuards
138 , domainConfs ) <- loadModules startAction (toGhcOverridingBool (opt_color opts)) hdl modName dflagsM importDirs
139 startTime <- Clock.getCurrentTime
140 primMapR <- generatePrimMap unresolvedPrims primGuards (concat [pFP, primDirs, importDirs])
141 tdir <- maybe ghcLibDir (pure . GHC.topDir) dflagsM
142 primMapC <-
143 sequence $ HashMap.map
144 (sequence . fmap (compilePrimitive importDirs dbs tdir))
145 primMapR
146 let ((bindingsMap,clsVMap),tcMap,_) =
147 RWS.runRWS (mkBindings primMapC bindings clsOps unlocatable)
148 (GHC2CoreEnv GHC.noSrcSpan fiEnvs)
149 emptyGHC2CoreState
150 (tcMap',tupTcCache) = mkTupTyCons tcMap
151 tcCache = makeAllTyCons tcMap' fiEnvs
152 allTcCache = tysPrimMap <> tcCache
153 inScope0 = mkInScopeSet (
154 (fmap (coerce . bindingId) bindingsMap) <>
155 (fmap (coerce . bindingId) clsMap))
156 -- Recursion info is always False for class
157 -- selectors, no need to check free vars.
158 clsMap =
159 fmap (\(v,i) ->
160 #if MIN_VERSION_ghc(9,4,0)
161 (Binding v GHC.noSrcSpan (GHC.Inline GHC.NoSourceText) IsFun
162 #else
163 (Binding v GHC.noSrcSpan GHC.Inline IsFun
164 #endif
165 (mkClassSelector inScope0 allTcCache (varType v) i) False))
166 clsVMap
167 allBindings = bindingsMap `unionVarEnv` clsMap
168 topEntities' =
169 (\m -> fst (RWS.evalRWS m (GHC2CoreEnv GHC.noSrcSpan fiEnvs) tcMap')) $
170 mapM (\(topEnt,annM,isTb) -> do
171 topEnt' <- coreToName GHC.varName GHC.varUnique qualifiedNameString topEnt
172 return (topEnt', annM, isTb)) topEntities
173 topEntities'' =
174 map (\(topEnt, annM, isTb) ->
175 case UniqMap.lookup topEnt allBindings of
176 Just b -> TopEntityT (bindingId b) annM isTb
177 Nothing -> GHC.pgmError [I.i|
178 No top entity called '#{topEnt}' found. Make sure you are
179 compiling with the '-fexpose-all-unfoldings' flag.
180 |]
181 ) topEntities'
182 -- Parsing / compiling primitives:
183 prepTime <- startTime `deepseq` primMapC `seq` Clock.getCurrentTime
184 let prepStartDiff = reportTimeDiff prepTime startTime
185 putStrLn $ "Clash: Parsing and compiling primitives took " ++ prepStartDiff
186
187 let allBindings' = setNoInlineTopEntities allBindings topEntities''
188
189 return
190 ( ClashEnv
191 { envOpts = opts
192 , envTyConMap = allTcCache
193 , envTupleTyCons = tupTcCache
194 , envPrimitives = primMapC
195 , envCustomReprs = buildCustomReprs customBitRepresentations
196 , envDomains = domainConfs
197 }
198 , ClashDesign
199 { designEntities = topEntities''
200 , designBindings = allBindings'
201 }
202 )
203
204 setNoInlineTopEntities
205 :: BindingMap
206 -> [TopEntityT]
207 -> BindingMap
208 setNoInlineTopEntities bm tes =
209 fmap go bm
210 where
211 ids = mkVarSet (fmap topId tes)
212
213 go b@Binding{bindingId}
214 | bindingId `elemVarSet` ids
215 #if MIN_VERSION_ghc(9,4,0)
216 = b { bindingSpec = GHC.Opaque GHC.NoSourceText }
217 #else
218 = b { bindingSpec = GHC.NoInline }
219 #endif
220 | otherwise = b
221
222 -- TODO This function should be changed to provide the information that
223 -- Clash.Core.Termination.mkRecInfo provides. To achieve this, it should also
224 -- be changed to no longer flatten recursive groups (see the documentation for
225 -- mkRecInfo for an explanation of these).
226 --
227 mkBindings
228 :: CompiledPrimMap
229 -> [GHC.CoreBind]
230 -- Binders
231 -> [(GHC.CoreBndr,Int)]
232 -- Class operations
233 -> [GHC.CoreBndr]
234 -- Unlocatable Expressions
235 -> C2C ( BindingMap
236 , VarEnv (Id,Int)
237 )
238 mkBindings primMap bindings clsOps unlocatable = do
239 bindingsList <- mapM (\case
240 GHC.NonRec v e -> do
241 let sp = GHC.getSrcSpan v
242 inl = GHC.inlinePragmaSpec . GHC.inlinePragInfo $ GHC.idInfo v
243 tm <- RWS.local (srcSpan .~ sp) (coreToTerm primMap unlocatable e)
244 v' <- coreToId v
245 nm <- qualifiedNameString (GHC.varName v)
246 let pr = if HashMap.member nm primMap then IsPrim else IsFun
247 checkPrimitive primMap v
248 return [(v', (Binding v' sp inl pr tm False))]
249 GHC.Rec bs -> do
250 tms <- mapM (\(v,e) -> do
251 let sp = GHC.getSrcSpan v
252 inl = GHC.inlinePragmaSpec . GHC.inlinePragInfo $ GHC.idInfo v
253 tm <- RWS.local (srcSpan .~ sp) (coreToTerm primMap unlocatable e)
254 v' <- coreToId v
255 nm <- qualifiedNameString (GHC.varName v)
256 let pr = if HashMap.member nm primMap then IsPrim else IsFun
257 checkPrimitive primMap v
258 return (Binding v' sp inl pr tm True)
259 ) bs
260 case tms of
261 [Binding v sp inl pr tm r] -> return [(v, Binding v sp inl pr tm r)]
262
263 -- Rewrite the bindings to avoid triggering the recursion check.
264 -- See NOTE [bindings in recursive groups]
265 _ -> let vsL = map (setIdScope LocalId . bindingId) tms
266 vsV = map Var vsL
267 subst = extendGblSubstList (mkSubst emptyInScopeSet) (zip vsL vsV)
268 lbs = zipWith (\b vL -> (vL,substTm "mkBindings" subst (bindingTerm b))) tms vsL
269 tms1 = zipWith (\b (i, _) -> (bindingId b, b { bindingTerm = Letrec lbs (Var i), bindingRecursive = False })) tms lbs
270 in return tms1
271 ) bindings
272 clsOpList <- mapM (\(v,i) -> do
273 v' <- coreToId v
274 return (v', (v',i))
275 ) clsOps
276
277 return (mkVarEnv (concat bindingsList), mkVarEnv clsOpList)
278
279 {-
280 NOTE [bindings in recursive groups]
281 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
282 After normalization, Clash currently checks that all normalized entities are
283 not recursive and errors if any are. However, this check only applies to
284 recursion on global identifiers. Since GHC may present recursive groups of
285 global binders, these are rewritten to only be locally recursive, i.e.
286
287 f[GlobalId] = g[GlobalId] ...
288 g[GlobalId] = f[GlobalId] ...
289
290 will be rewritten (and inserted into the map of global bindings) as
291
292 f[GlobalId] = let f[LocalId] = g[LocalId] ...
293 g[LocalId] = f[LocalId] ...
294 in f[LocalId]
295
296 g[GlobalId] = let f[LocalId] = g[LocalId] ...
297 g[LocalId] = f[LocalId] ...
298 in g[LocalId]
299
300 Recursive groups with only a single binding (i.e. global self-recursive
301 definitions do not need this rewriting. This is because normalization can
302 trivially spot these self-recursive bindings and where necessary lift them to
303 global bindings when they appear in a term.
304 -}
305
306 -- | If this CoreBndr is a primitive, check it's Haskell definition
307 -- for potential problems.
308 --
309 -- Warns when a primitive:
310 -- * isn't marked NOINLINE
311 -- * produces an error when evaluating its result to WHNF
312 -- * isn't using all its arguments
313 checkPrimitive :: CompiledPrimMap -> GHC.CoreBndr -> C2C ()
314 checkPrimitive primMap v = do
315 nm <- qualifiedNameString (GHC.varName v)
316 case HashMap.lookup nm primMap >>= extractPrim of
317 Just (BlackBox{resultNames, resultInits, template, includes}) -> do
318 let
319 info = GHC.idInfo v
320 inline = GHC.inlinePragmaSpec $ GHC.inlinePragInfo info
321 #if MIN_VERSION_ghc(9,4,0)
322 strictness = GHC.dmdSigInfo info
323 #else
324 strictness = GHC.strictnessInfo info
325 #endif
326 ty = GHC.varType v
327 #if MIN_VERSION_ghc(9,2,0)
328 (argTys,_resTy) = GHC.splitFunTys (snd (GHC.splitForAllTyCoVars ty))
329 #else
330 (argTys,_resTy) = GHC.splitFunTys . snd . GHC.splitForAllTys $ ty
331 #endif
332 #if MIN_VERSION_ghc(9,4,0)
333 (dmdArgs,_dmdRes) = GHC.splitDmdSig strictness
334 #else
335 (dmdArgs,_dmdRes) = GHC.splitStrictSig strictness
336 #endif
337 nrOfArgs = length argTys
338 loc = case GHC.getSrcLoc v of
339 GHC.UnhelpfulLoc _ -> ""
340 #if MIN_VERSION_ghc(9,0,0)
341 GHC.RealSrcLoc l _ -> showPpr l ++ ": "
342 #else
343 GHC.RealSrcLoc l -> showPpr l ++ ": "
344 #endif
345 warnIf cond msg = traceIf cond ("\n"++loc++"Warning: "++msg) return ()
346 qName <- Text.unpack <$> qualifiedNameString (GHC.varName v)
347 let primStr = "primitive " ++ qName ++ " "
348 let usedArgs = concat [ concatMap getUsedArguments resultNames
349 , concatMap getUsedArguments resultInits
350 , getUsedArguments template
351 , concatMap (getUsedArguments . snd) includes
352 ]
353
354 let warnArgs [] = return ()
355 warnArgs (x:xs) = do
356 warnIf (maybe False GHC.isAbsDmd (indexMaybe dmdArgs x))
357 ("The Haskell implementation of " ++ primStr ++ "isn't using argument #" ++
358 show x ++ ", but the corresponding primitive blackbox does.\n" ++
359 "This can lead to incorrect HDL output because GHC can replace these " ++
360 "arguments by an undefined value.")
361 warnArgs xs
362
363 unless (qName == "Clash.XException.errorX" || "GHC." `isPrefixOf` qName) $ do
364 warnIf (not (isOpaque inline))
365 #if MIN_VERSION_ghc(9,4,0)
366 (primStr ++ "isn't marked OPAQUE."
367 #else
368 (primStr ++ "isn't marked NOINLINE."
369 #endif
370 ++ "\nThis might make Clash ignore this primitive.")
371 #if MIN_VERSION_ghc(9,2,0)
372 warnIf (GHC.isDeadEndAppSig strictness nrOfArgs)
373 #elif MIN_VERSION_ghc(9,0,0)
374 warnIf (GHC.appIsDeadEnd strictness nrOfArgs)
375 #else
376 warnIf (GHC.appIsBottom strictness nrOfArgs)
377 #endif
378 ("The Haskell implementation of " ++ primStr
379 ++ "produces a result that always results in an error.\n"
380 ++ "This can lead to compile failures because GHC can replace entire "
381 ++ "calls to this primitive by an undefined value.")
382 warnArgs usedArgs
383 _ -> return ()
384 where
385 showPpr :: GHC.Outputable a => a -> String
386 showPpr = GHC.showSDocUnsafe . GHC.ppr
387
388 mkClassSelector
389 :: InScopeSet
390 -> TyConMap
391 -> Type
392 -> Int
393 -> Term
394 mkClassSelector inScope0 tcm ty sel = newExpr
395 where
396 -- TODO: why can't we just use partitionEithers here?
397 (tvs,dicts) = (lefts *** rights)
398 . span (\l -> case l of {Left _ -> True; _ -> False})
399 $ fst (splitFunForallTy ty)
400 newExpr = case listToMaybe dicts of
401 Just dictTy@(tyView -> TyConApp tcNm _)
402 | Just tc <- UniqMap.lookup tcNm tcm
403 , not (isNewTypeTc tc)
404 -> flip State.evalState (0 :: Unique) $ do
405 dcId <- mkInternalVar inScope0 "dict" dictTy
406 let inScope1 = extendInScopeSet inScope0 dcId
407 selE <- mkSelectorCase "mkClassSelector" inScope1 tcm (Var dcId) 1 sel
408 return (mkTyLams (mkLams selE [dcId]) tvs)
409 Just (tyView -> FunTy arg res) -> flip State.evalState (0 :: Unique) $ do
410 dcId <- mkInternalVar inScope0 "dict" (mkFunTy arg res)
411 return (mkTyLams (mkLams (Var dcId) [dcId]) tvs)
412 Just dictTy -> flip State.evalState (0 :: Unique) $ do
413 dcId <- mkInternalVar inScope0 "dict" dictTy
414 return (mkTyLams (mkLams (Var dcId) [dcId]) tvs)
415 Nothing -> error "mkClassSelector: expected at least one dictionary argument"
416
417 mkTupTyCons :: GHC2CoreState -> (GHC2CoreState,IntMap TyConName)
418 mkTupTyCons tcMap = (tcMap'',tupTcCache)
419 where
420 tupTyCons = GHC.boolTyCon : GHC.promotedTrueDataCon : GHC.promotedFalseDataCon
421 : map (GHC.tupleTyCon GHC.Boxed) [2..GHC.mAX_TUPLE_SIZE]
422 (tcNames,tcMap',_) =
423 RWS.runRWS (mapM (\tc -> coreToName GHC.tyConName GHC.tyConUnique
424 qualifiedNameString tc) tupTyCons)
425 (GHC2CoreEnv GHC.noSrcSpan GHC.emptyFamInstEnvs)
426 tcMap
427 tupTcCache = IMS.fromList (zip [2..GHC.mAX_TUPLE_SIZE] (drop 3 tcNames))
428 tupHM = UniqMap.fromList (zip tcNames tupTyCons)
429 tcMap'' = tcMap' & tyConMap %~ (<> tupHM)