Debian Codegraph @

src-ghc/Clash/GHC/LoadInterfaceFiles.hs

raw
1 {-|
2 Copyright : (C) 2013-2016, University of Twente,
3 2016-2017, Myrtle Software Ltd
4 2022-2024, 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 QuasiQuotes #-}
13 {-# LANGUAGE RecordWildCards #-}
14 {-# LANGUAGE TemplateHaskell #-}
15 {-# LANGUAGE TupleSections #-}
16
17 module Clash.GHC.LoadInterfaceFiles
18 ( loadExternalExprs
19 , loadExternalBinders
20 , getUnresolvedPrimitives
21 , LoadedBinders(..)
22 )
23 where
24
25 -- External Modules
26 import Control.Monad.IO.Class (MonadIO (..))
27 import Control.Monad (forM_, join)
28 import Control.Monad.State.Strict
29 (StateT, gets, MonadState (get), MonadTrans (lift), execStateT)
30 import Control.Monad.Trans.State.Strict (modify)
31 import Control.Monad.Extra (unlessM)
32 import qualified Data.ByteString.Lazy.UTF8 as BLU
33 import qualified Data.ByteString.Lazy as BL
34 import qualified Data.Sequence as Seq
35 import Data.Sequence (Seq)
36 import Data.Either (partitionEithers)
37 #if !MIN_VERSION_base(4,20,0)
38 import Data.Foldable (foldl')
39 #endif
40 import Data.List (elemIndex)
41 import qualified Data.Text as Text
42 import Data.Maybe (isNothing, mapMaybe, catMaybes)
43 import Data.Map.Strict (Map)
44 import qualified Data.Map.Strict as Map
45 import Data.Set (Set)
46 import qualified Data.Set as Set
47 import Data.Word (Word8)
48
49 -- GHC
50 #if MIN_VERSION_ghc(9,8,0)
51 import GHC.Types.Error (defaultOpts)
52 import GHC.Iface.Errors.Ppr (missingInterfaceErrorDiagnostic)
53 #endif
54 #if MIN_VERSION_ghc(9,4,0)
55 import GHC.Driver.Env.KnotVars (emptyKnotVars)
56 #endif
57 #if MIN_VERSION_ghc(9,0,0)
58 import GHC.Types.Annotations (Annotation(..))
59 import qualified GHC.Types.Annotations as Annotations
60 import qualified GHC.Core.Class as Class
61 import qualified GHC.Core.FVs as CoreFVs
62 import qualified GHC.Core as CoreSyn
63 import qualified GHC.Types.Demand as Demand
64 import qualified GHC
65 import qualified GHC.Types.Id as Id
66 import qualified GHC.Types.Id.Info as IdInfo
67 import qualified GHC.Iface.Syntax as IfaceSyn
68 import qualified GHC.Iface.Load as LoadIface
69 import qualified GHC.Data.Maybe as Maybes
70 import qualified GHC.Core.Make as MkCore
71 import qualified GHC.Unit.Module as Module
72 import qualified GHC.Unit.Module.Env as ModuleEnv
73 import qualified GHC.Utils.Monad as MonadUtils
74 import qualified GHC.Types.Name as Name
75 import qualified GHC.Types.Name.Env as NameEnv
76 import GHC.Utils.Outputable as Outputable (text)
77 import qualified GHC.Plugins as GhcPlugins (deserializeWithData, fromSerialized)
78 import qualified GHC.IfaceToCore as TcIface
79 import qualified GHC.Tc.Utils.Monad as TcRnMonad
80 import qualified GHC.Tc.Types as TcRnTypes
81 import qualified GHC.Types.Unique.FM as UniqFM
82 import qualified GHC.Types.Var as Var
83 import qualified GHC.Unit.Types as UnitTypes
84 #else
85 import Annotations (Annotation(..), getAnnTargetName_maybe)
86 import qualified Annotations
87 import qualified Class
88 import qualified CoreFVs
89 import qualified CoreSyn
90 import qualified Demand
91 import qualified GHC
92 import qualified Id
93 import qualified IdInfo
94 import qualified IfaceSyn
95 import qualified LoadIface
96 import qualified Maybes
97 import qualified MkCore
98 import qualified Module
99 import qualified MonadUtils
100 import qualified Name
101 import Outputable (text)
102 import qualified GhcPlugins (deserializeWithData, fromSerialized)
103 import qualified TcIface
104 import qualified TcRnMonad
105 import qualified TcRnTypes
106 import qualified UniqFM
107 import qualified Var
108 #endif
109
110 -- Internal Modules
111 import Clash.Annotations.BitRepresentation.Internal
112 (DataRepr', dataReprAnnToDataRepr')
113 import Clash.Annotations.Primitive
114 import Clash.Annotations.BitRepresentation (DataReprAnn)
115 import Clash.Debug (traceIf)
116 import Clash.Primitives.Types (UnresolvedPrimitive, name)
117 import Clash.Primitives.Util (decodeOrErrJson, decodeOrErrYaml)
118 import Clash.GHC.GHC2Core (qualifiedNameString')
119 import Clash.Util (curLoc)
120 import qualified Clash.Util.Interpolate as I
121 import Clash.GHC.Util
122
123 -- | Data structure tracking loaded binders (and their related data)
124 data LoadedBinders = LoadedBinders
125 { lbBinders :: !(Map CoreSyn.CoreBndr CoreSyn.CoreExpr)
126 -- ^ Binder + expression it's binding
127 , lbClassOps :: !(Map CoreSyn.CoreBndr Int)
128 -- ^ Type class dict projection functions
129 , lbUnlocatable :: !(Set CoreSyn.CoreBndr)
130 -- ^ Binders with missing unfoldings
131 , lbPrims :: !(Seq (Either UnresolvedPrimitive FilePath))
132 -- ^ Primitives; either an primitive data structure or a path to a directory
133 -- containing json files
134 , lbReprs :: !(Seq DataRepr')
135 -- ^ Custom data representations
136 , lbCache :: !DeclCache
137 -- ^ Loaded module cache
138 }
139
140 type LoadedBinderT m a = StateT LoadedBinders m a
141
142 -- | Stores modules with easy binder lookup
143 type DeclCache = Map GHC.Module (Maybe (Map GHC.Name IfaceSyn.IfaceDecl))
144
145
146 -- | Collects free variables in an expression, and splits them into "normal"
147 -- free variables and class ops.
148 bndrsInExpr :: CoreSyn.CoreExpr -> ([CoreSyn.CoreBndr], [(CoreSyn.CoreBndr, Int)])
149 bndrsInExpr e = partitionEithers (map go freeVars)
150 where
151 freeVars = CoreFVs.exprSomeFreeVarsList isInteresting e
152 isInteresting v = Var.isId v && isNothing (Id.isDataConId_maybe v)
153
154 go :: Var.Var -> Either Var.Id (CoreSyn.CoreBndr, Int)
155 go v = case Id.isClassOpId_maybe v of
156 Just cls -> Right (v, goClsOp v cls)
157 Nothing -> Left v
158
159 goClsOp :: Var.Var -> GHC.Class -> Int
160 goClsOp v c =
161 case elemIndex v (Class.classAllSelIds c) of
162 Nothing -> error [I.i|
163 Internal error: couldn't find class method
164
165 #{showPprUnsafe v}
166
167 in class
168
169 #{showPprUnsafe c}
170 |]
171 Just n -> n
172
173 -- | Add a binder to the appropriate fields of 'LoadedBinders', and recursively
174 -- load binders found in the optionally supplied expression.
175 addBndrM ::
176 GHC.GhcMonad m =>
177 HDL ->
178 CoreSyn.CoreBndr ->
179 Maybe CoreSyn.CoreExpr ->
180 LoadedBinderT m ()
181 addBndrM hdl bndr exprM =
182 case exprM of
183 Nothing ->
184 modify $ \lb@LoadedBinders{..} ->
185 lb{lbUnlocatable=Set.insert bndr lbUnlocatable}
186 Just expr -> do
187 -- Add current expression and its class ops
188 let (fvs, clsOps) = bndrsInExpr expr
189 modify $ \lb@LoadedBinders{..} ->
190 lb { lbBinders=Map.insert bndr expr lbBinders
191 , lbClassOps=mapInsertAll lbClassOps clsOps }
192
193 -- Load all free variables - if not yet loaded
194 forM_ fvs $ \v ->
195 unlessM (isLoadedBinderM v) (loadExprFromIface hdl v)
196 where
197 -- Insert a list of keys and values into a 'Map'
198 mapInsertAll :: Ord k => Map k a -> [(k, a)] -> Map k a
199 mapInsertAll = foldl' (\m (k, v) -> Map.insert k v m)
200
201
202 isLoadedBinderM :: Monad m => CoreSyn.CoreBndr -> LoadedBinderT m Bool
203 isLoadedBinderM bndr = gets $ \LoadedBinders{..} ->
204 Map.member bndr lbBinders
205 || Map.member bndr lbClassOps
206 || Set.member bndr lbUnlocatable
207
208 emptyLb :: LoadedBinders
209 emptyLb = LoadedBinders
210 { lbBinders = mempty
211 , lbClassOps = mempty
212 , lbUnlocatable = mempty
213 , lbPrims = mempty
214 , lbReprs = mempty
215 , lbCache = mempty
216 }
217
218 #if MIN_VERSION_ghc(9,0,0)
219 notBoot :: UnitTypes.IsBootInterface
220 notBoot = UnitTypes.NotBoot
221 #else
222 notBoot :: Bool
223 notBoot = False
224 #endif
225
226 runIfl :: GHC.GhcMonad m => GHC.Module -> TcRnTypes.IfL a -> m a
227 runIfl modName action = do
228 let
229 localEnv = TcRnTypes.IfLclEnv
230 { TcRnTypes.if_mod = modName
231 , TcRnTypes.if_boot = notBoot
232 , TcRnTypes.if_loc = text "runIfl"
233 , TcRnTypes.if_nsubst = Nothing
234 , TcRnTypes.if_implicits_env = Nothing
235 , TcRnTypes.if_tv_env = UniqFM.emptyUFM
236 , TcRnTypes.if_id_env = UniqFM.emptyUFM
237 }
238
239 globalEnv = TcRnTypes.IfGblEnv
240 { TcRnTypes.if_doc = text "Clash.runIfl"
241 #if MIN_VERSION_ghc(9,4,0)
242 , TcRnTypes.if_rec_types = emptyKnotVars
243 #else
244 , TcRnTypes.if_rec_types = Nothing
245 #endif
246 }
247
248 hscEnv <- GHC.getSession
249 MonadUtils.liftIO $
250 TcRnMonad.initTcRnIf 'r' hscEnv globalEnv localEnv action
251
252 loadDecl :: IfaceSyn.IfaceDecl -> TcRnTypes.IfL GHC.TyThing
253 loadDecl = TcIface.tcIfaceDecl False
254
255 #if MIN_VERSION_ghc(9,4,0)
256 loadIface :: GHC.HscEnv -> GHC.Module -> IO (Maybe GHC.ModIface)
257 loadIface env foundMod = do
258 #else
259 loadIface :: GHC.Module -> TcRnTypes.IfL (Maybe GHC.ModIface)
260 loadIface foundMod = do
261 #endif
262 #if MIN_VERSION_ghc(9,4,0)
263 ifaceFailM <- LoadIface.findAndReadIface env (Outputable.text "loadIface")
264 (fst (Module.getModuleInstantiation foundMod)) foundMod UnitTypes.NotBoot
265 #elif MIN_VERSION_ghc(9,0,0)
266 ifaceFailM <- LoadIface.findAndReadIface (Outputable.text "loadIface")
267 (fst (Module.getModuleInstantiation foundMod)) foundMod UnitTypes.NotBoot
268 #else
269 ifaceFailM <- LoadIface.findAndReadIface (Outputable.text "loadIface")
270 (fst (Module.splitModuleInsts foundMod)) foundMod False
271 #endif
272 case ifaceFailM of
273 Maybes.Succeeded (modInfo,_) -> return (Just modInfo)
274 Maybes.Failed msg -> let msg' = concat [ $(curLoc)
275 , "Failed to load interface for module: "
276 , showPprUnsafe foundMod
277 , "\nReason: "
278 #if MIN_VERSION_ghc(9,8,0)
279 , showSDocUnsafe (missingInterfaceErrorDiagnostic defaultOpts msg)
280 #else
281 , showSDocUnsafe msg
282 #endif
283 ]
284 in traceIf True msg' (return Nothing)
285
286 -- | Given a list of top-level binders, recursively load all the binders,
287 -- primitives, and type classes it is using. (Exported function.)
288 loadExternalBinders :: GHC.GhcMonad m => HDL -> [CoreSyn.CoreBndr] -> m LoadedBinders
289 loadExternalBinders hdl bndrs =
290 flip execStateT emptyLb $
291 mapM_ (loadExprFromIface hdl) bndrs
292
293 -- Given a list of binds, recursively load all its binders, primitives, and
294 -- type classes it is using. (Exported function.)
295 loadExternalExprs :: GHC.GhcMonad m => HDL -> [CoreSyn.CoreBind] -> m LoadedBinders
296 loadExternalExprs hdl binds0 =
297 flip execStateT initLb $
298 mapM_ (\(b, e) -> addBndrM hdl b (Just e)) binds1
299 where
300 -- 'lbBinders' is preinitialized with all binders in given binds, as the given
301 -- binders can't be loaded from precompiled modules
302 initLb = emptyLb{lbBinders=Map.fromList binds1}
303 binds1 = CoreSyn.flattenBinds binds0
304
305 -- | Try to fetch a IfaceDecl from a 'DeclCache'. If a module has not been loaded
306 -- before, load it using GHC. Additionally, add annotations mentioned in the
307 -- module to 'LoadedBinders'.
308 getIfaceDeclM ::
309 forall m.
310 GHC.GhcMonad m =>
311 HDL ->
312 -- | Binder to load
313 CoreSyn.CoreBndr ->
314 -- | Declaration, if found
315 LoadedBinderT m (Maybe (GHC.Module, IfaceSyn.IfaceDecl))
316 getIfaceDeclM hdl bndr = do
317 let modM = Name.nameModule_maybe bndrName
318 join <$> mapM go modM
319 where
320 bndrName = Var.varName bndr
321
322 go :: GHC.Module -> LoadedBinderT m (Maybe (GHC.Module, IfaceSyn.IfaceDecl))
323 go nameMod = do
324 LoadedBinders{lbCache} <- get
325 case Map.lookup nameMod lbCache of
326 Nothing -> do
327 -- Not loaded before
328 #if MIN_VERSION_ghc(9,4,0)
329 env <- lift GHC.getSession
330 ifaceM <- lift (liftIO (loadIface env nameMod))
331 #else
332 ifaceM <- lift (runIfl nameMod (loadIface nameMod))
333 #endif
334 case ifaceM of
335 Just iface -> do
336 -- Add binder : decl map to cache
337 let
338 decls = map snd (GHC.mi_decls iface)
339 names = map IfaceSyn.ifName decls
340 let declMap = Just (Map.fromList (zip names decls))
341 modify (\lb -> lb{lbCache=Map.insert nameMod declMap lbCache})
342
343 -- Load annotations and add them to state
344 loadAnnotationsM hdl nameMod iface
345 Nothing ->
346 -- XXX: 'runIfl' should probably error hard if this happens?
347 modify (\lb -> lb{lbCache=Map.insert nameMod Nothing lbCache})
348
349 -- Update cache and try again
350 go nameMod
351
352 Just Nothing ->
353 -- Loaded before, but couldn't find decl
354 pure Nothing
355 Just (Just declMap) ->
356 -- Loaded before, decl found
357 pure ((nameMod,) <$> Map.lookup bndrName declMap)
358
359 loadAnnotationsM ::
360 GHC.GhcMonad m =>
361 HDL ->
362 GHC.Module ->
363 GHC.ModIface ->
364 StateT LoadedBinders m ()
365 loadAnnotationsM hdl modName iface = do
366 anns <- lift (runIfl modName (TcIface.tcIfaceAnnotations (GHC.mi_anns iface)))
367 primFPs <- loadPrimitiveAnnotations hdl anns
368 let reprs = loadCustomReprAnnotations anns
369 modify $ \lb@LoadedBinders{..} -> lb
370 { lbPrims = lbPrims <> Seq.fromList primFPs
371 , lbReprs = lbReprs <> Seq.fromList reprs
372 }
373
374 loadExprFromIface ::
375 GHC.GhcMonad m =>
376 HDL ->
377 CoreSyn.CoreBndr ->
378 LoadedBinderT m ()
379 loadExprFromIface hdl bndr = do
380 namedDeclM <- getIfaceDeclM hdl bndr
381 case namedDeclM of
382 Nothing -> addBndrM hdl bndr Nothing
383 Just (nameMod, namedDecl) -> do
384 tyThing <- lift (runIfl nameMod (loadDecl namedDecl))
385 addBndrM hdl bndr (loadExprFromTyThing bndr tyThing)
386
387
388 loadCustomReprAnnotations :: [Annotations.Annotation] -> [DataRepr']
389 loadCustomReprAnnotations anns =
390 mapMaybe go $ catMaybes $ zipWith filterNameless anns reprs
391 where
392 env = Annotations.mkAnnEnv anns
393 deserialize = GhcPlugins.deserializeWithData :: [Word8] -> DataReprAnn
394
395 #if MIN_VERSION_ghc(9,4,0)
396 (mEnv, nEnv) = Annotations.deserializeAnns deserialize env
397 reprs = ModuleEnv.moduleEnvElts mEnv <> NameEnv.nonDetNameEnvElts nEnv
398 #elif MIN_VERSION_ghc(9,0,0)
399 (mEnv, nEnv) = Annotations.deserializeAnns deserialize env
400 reprs = ModuleEnv.moduleEnvElts mEnv <> NameEnv.nameEnvElts nEnv
401 #else
402 reprs = UniqFM.eltsUFM (Annotations.deserializeAnns deserialize env)
403 #endif
404
405 filterNameless :: Annotation -> [DataReprAnn] -> Maybe (Name.Name, [DataReprAnn])
406 filterNameless (Annotation ann_target _) reprs' =
407 (,reprs') <$> getAnnTargetName_maybe ann_target
408
409 go :: (Name.Name, [DataReprAnn]) -> Maybe DataRepr'
410 go (_name, []) = Nothing
411 go (_name, [repr]) = Just $ dataReprAnnToDataRepr' repr
412 go (name, reprs') =
413 error [I.i|
414 Multiple DataReprAnn annotations for same type:
415
416 #{showPprUnsafe name}
417
418 Reprs:
419
420 #{reprs'}
421 |]
422
423 loadPrimitiveAnnotations ::
424 MonadIO m
425 => HDL
426 -> [Annotations.Annotation]
427 -> m [Either UnresolvedPrimitive FilePath]
428 loadPrimitiveAnnotations hdl anns =
429 concat <$> mapM (getUnresolvedPrimitives hdl) prims
430 where
431 prims = mapMaybe filterPrim anns
432 filterPrim (Annotations.Annotation target value) =
433 (target,) <$> deserialize value
434 deserialize =
435 GhcPlugins.fromSerialized
436 (GhcPlugins.deserializeWithData :: [Word8] -> Primitive)
437
438 getUnresolvedPrimitives
439 :: MonadIO m
440 => HDL
441 -> (Annotations.CoreAnnTarget, Primitive)
442 -> m [Either UnresolvedPrimitive FilePath]
443 getUnresolvedPrimitives hdl (target, prim) | hdl `elem` primHdls prim =
444 case prim of
445 Primitive _ fp -> pure [Right fp]
446
447 InlineYamlPrimitive _ contentOrFp ->
448 case target of
449 -- Module annotation, can house many primitives
450 Annotations.ModuleTarget _ ->
451 liftIO (decodeOrErrYaml contentOrFp <$> BL.readFile contentOrFp)
452 Annotations.NamedTarget targetName0 ->
453 let targetName1 = Text.unpack (qualifiedNameString' targetName0)
454 primOrErr = decodeOrErrYaml targetName1 (BLU.fromString contentOrFp)
455 primName = Text.unpack (name primOrErr) in
456
457 if primName /= targetName1
458 then inlineNameError targetName1 primName
459 else pure [Left primOrErr]
460
461 InlinePrimitive _ contentOrFp ->
462 case target of
463 -- Module annotation, can house many primitives
464 Annotations.ModuleTarget _ ->
465 liftIO (decodeOrErrJson contentOrFp <$> BL.readFile contentOrFp)
466 Annotations.NamedTarget targetName0 ->
467 let targetName1 = Text.unpack (qualifiedNameString' targetName0)
468 primOrErr =
469 case decodeOrErrJson targetName1 (BLU.fromString contentOrFp) of
470 [] -> error $ "No annotations found for " ++ targetName1
471 ++ " even though it had an InlinePrimitive annotation."
472 [p] -> p
473 _ -> error $ "Multiple primitive definitions found in "
474 ++ "InlinePrimitive annotation for " ++ targetName1 ++ ". "
475 ++ "Expected a single one."
476
477 primName = Text.unpack (name primOrErr) in
478
479 if primName /= targetName1
480 then inlineNameError targetName1 primName
481 else pure [Left primOrErr]
482 where
483 inlineNameError targetName primName =
484 error $ concat
485 [ "Function " ++ targetName ++ " was annotated with an inline "
486 , "primitive for " ++ primName ++ ". These names "
487 , "should be the same." ]
488
489 primHdls = \case
490 Primitive hdls _ -> hdls
491 InlinePrimitive hdls _ -> hdls
492 InlineYamlPrimitive hdls _ -> hdls
493
494 getUnresolvedPrimitives _ _ = return []
495
496 loadExprFromTyThing :: CoreSyn.CoreBndr -> GHC.TyThing -> Maybe CoreSyn.CoreExpr
497 loadExprFromTyThing bndr tyThing = case tyThing of
498 GHC.AnId _id | Var.isId _id ->
499 let _idInfo = Var.idInfo _id
500 #if MIN_VERSION_ghc(9,4,0)
501 unfolding = IdInfo.realUnfoldingInfo _idInfo
502 #else
503 unfolding = IdInfo.unfoldingInfo _idInfo
504 #endif
505 in case unfolding of
506 CoreSyn.CoreUnfolding {} ->
507 Just (CoreSyn.unfoldingTemplate unfolding)
508 CoreSyn.DFunUnfolding dfbndrs dc es ->
509 Just (MkCore.mkCoreLams dfbndrs (MkCore.mkCoreConApps dc es))
510 CoreSyn.NoUnfolding
511 #if MIN_VERSION_ghc(9,4,0)
512 | Demand.isDeadEndSig $ IdInfo.dmdSigInfo _idInfo
513 #elif MIN_VERSION_ghc(9,0,0)
514 | Demand.isDeadEndSig $ IdInfo.strictnessInfo _idInfo
515 #else
516 | Demand.isBottomingSig $ IdInfo.strictnessInfo _idInfo
517 #endif
518 -> do
519 let noUnfoldingErr = "no_unfolding " ++ showPprUnsafe bndr
520 Just (MkCore.mkAbsentErrorApp (Var.varType _id) noUnfoldingErr)
521 _ -> Nothing
522 _ -> Nothing
523
524 #if MIN_VERSION_ghc(9,0,0)
525 -- | Get the 'name' of an annotation target if it exists.
526 getAnnTargetName_maybe :: Annotations.AnnTarget name -> Maybe name
527 getAnnTargetName_maybe (Annotations.NamedTarget nm) = Just nm
528 getAnnTargetName_maybe _ = Nothing
529 #endif