Debian Codegraph @

src-ghc/Clash/GHC/LoadModules.hs

raw
1 {-|
2 Copyright : (C) 2013-2016, University of Twente,
3 2016-2017, Myrtle Software Ltd,
4 2017-2024, Google Inc.
5 2021-2024, QBayLogic B.V.
6 License : BSD2 (see the file LICENSE)
7 Maintainer : QBayLogic B.V. <[email protected]>
8 -}
9
10 {-# LANGUAGE CPP #-}
11 {-# LANGUAGE DeriveAnyClass #-}
12 {-# LANGUAGE FlexibleContexts #-}
13 {-# LANGUAGE LambdaCase #-}
14 {-# LANGUAGE NamedFieldPuns #-}
15 {-# LANGUAGE QuasiQuotes #-}
16 {-# LANGUAGE RecordWildCards #-}
17 {-# LANGUAGE TemplateHaskell #-}
18
19 module Clash.GHC.LoadModules
20 ( loadModules
21 , ghcLibDir
22 , setWantedLanguageExtensions
23 )
24 where
25
26 #ifndef USE_GHC_PATHS
27 #ifndef TOOL_VERSION_ghc
28 #error TOOL_VERSION_ghc undefined
29 #endif
30 #endif
31
32 -- External Modules
33 import Clash.Annotations.Primitive (HDL, PrimitiveGuard(..))
34 import Clash.Annotations.TopEntity (TopEntity (..))
35 import Clash.Primitives.Types (UnresolvedPrimitive)
36 import Clash.Util (ClashException(..), pkgIdFromTypeable)
37 import qualified Clash.Util.Interpolate as I
38 import Control.Arrow (first)
39 import Control.Exception (SomeException, throw)
40 import Control.Monad (forM, join, when)
41 import Data.List.Extra (nubSort)
42 import Control.Exception (Exception, throwIO)
43 import Control.Monad (foldM)
44 #if MIN_VERSION_ghc(9,0,0)
45 import Control.Monad.Catch (catch, throwM)
46 import Control.Monad.Catch as MC (try)
47 #endif
48 import Control.Monad.IO.Class (liftIO)
49 import Data.Char (isDigit)
50 import Data.Generics.Uniplate.DataOnly (transform)
51 import Data.Data (Data)
52 import Data.Functor ((<&>))
53 import Data.Foldable (toList)
54 import Data.HashMap.Strict (HashMap)
55 import qualified Data.HashMap.Strict as HashMap
56 import Data.Typeable (Typeable)
57 import Data.List (nub, find)
58 #if !MIN_VERSION_base(4,20,0)
59 import Data.List (foldl')
60 #endif
61 import qualified Data.Map as Map
62 import Data.Maybe
63 (catMaybes, fromMaybe, listToMaybe, mapMaybe)
64 import qualified Data.Text as Text
65 import qualified Data.Text.Encoding as Text
66 import qualified Data.Time.Clock as Clock
67 import qualified Data.Set as Set
68 import qualified Data.Sequence as Seq
69 import Debug.Trace
70 import Language.Haskell.TH.Syntax (lift)
71 import GHC.Natural (naturalFromInteger)
72 import GHC.Stack (HasCallStack)
73 #if MIN_VERSION_ghc(9,4,0)
74 import System.FilePath.Posix (dropExtension, takeDirectory)
75 #endif
76 import Text.Read (readMaybe)
77
78 #ifdef USE_GHC_PATHS
79 import GHC.Paths (libdir)
80 #else
81 import System.Exit (ExitCode (..))
82 import System.IO (hGetLine)
83 import System.IO.Error (tryIOError)
84 import System.Process (runInteractiveCommand,
85 waitForProcess)
86 #endif
87
88 -- GHC API
89 #if MIN_VERSION_ghc(9,0,0)
90 #if MIN_VERSION_ghc(9,4,0)
91 import GHC.Driver.Phases (StopPhase(NoStop))
92 import GHC.Driver.Pipeline (mkPipeEnv, runPipeline, hscBackendPipeline)
93 #if MIN_VERSION_ghc(9,6,0)
94 import GHC.SysTools.Cpp (offsetIncludePaths)
95 import GHC.Unit.Home.ModInfo (homeMod_bytecode)
96 #else
97 import GHC.Driver.Pipeline.Execute (offsetIncludePaths)
98 import GHC.Driver.Pipeline.Monad (PipelineOutput(NoOutputFile, Persistent))
99 #endif
100 import GHC.Driver.Pipeline.Monad ( MonadUse(use) )
101 import GHC.Driver.Pipeline.Phases (TPhase(T_HscPostTc))
102 import GHC.Data.Bool (OverridingBool)
103 import GHC.Driver.Config.Tidy (initTidyOpts)
104 import GHC.Driver.Errors.Types (GhcMessage(GhcTcRnMessage))
105 import GHC.Driver.Monad (modifySession)
106 import GHC.Unit.Env (addHomeModInfoToHug)
107 import GHC.Unit.Home.ModInfo (HomeModInfo(HomeModInfo))
108 import GHC.Unit.Module.ModSummary (findTarget)
109 #else
110 import GHC.Utils.Misc (OverridingBool)
111 #endif
112 #if MIN_VERSION_ghc(9,2,0)
113 import qualified GHC.Driver.Env as HscTypes
114 import qualified GHC.Unit.Module.ModGuts as HscTypes
115 import qualified GHC.Types.SourceError as HscTypes
116 import qualified GHC.Unit.Module.Deps as HscTypes
117 import qualified GHC.Driver.Backend as Backend
118 import qualified GHC.Unit.Module.Graph as Graph
119 import qualified GHC.Platform.Ways as Ways
120 #if !MIN_VERSION_ghc(9,4,0)
121 import qualified GHC.Types.Error as Error
122 #endif
123 #else
124 import qualified GHC.Driver.Types as HscTypes
125 import qualified GHC.Driver.Ways as Ways
126 #endif
127 import qualified GHC.Types.Annotations as Annotations
128 import qualified GHC.Core.FVs as CoreFVs
129 import qualified GHC.Core as CoreSyn
130 import qualified GHC.Core.DataCon as DataCon
131 import qualified GHC.Data.Graph.Directed as Digraph
132 import qualified GHC.Runtime.Loader as DynamicLoading
133 import GHC.Driver.Session (GeneralFlag (..))
134 import qualified GHC.Driver.Session as DynFlags
135 import qualified GHC.Data.FastString as FastString
136 import qualified GHC
137 import qualified GHC.Driver.Main as HscMain
138 import qualified GHC.Utils.Monad as MonadUtils
139 import qualified GHC.Utils.Panic as Panic
140 import qualified GHC.Serialized as Serialized (deserializeWithData)
141 import qualified GHC.Unit.Types as UnitTypes (unitIdString)
142 import qualified GHC.Tc.Utils.Monad as TcRnMonad
143 import qualified GHC.Tc.Types as TcRnTypes
144 import qualified GHC.Iface.Tidy as TidyPgm
145 import qualified GHC.Core.TyCon as TyCon
146 import qualified GHC.Core.Type as Type
147 import qualified GHC.Types.Unique as Unique
148 import qualified GHC.Tc.Instance.Family as FamInst
149 import qualified GHC.Core.FamInstEnv as FamInstEnv
150 import qualified GHC.LanguageExtensions as LangExt
151 import qualified GHC.Types.Name as Name
152 import qualified GHC.Types.Name.Occurrence as OccName
153 import GHC.Utils.Outputable (ppr)
154 import qualified GHC.Utils.Outputable as Outputable
155 import qualified GHC.Types.Unique.Set as UniqSet
156 import qualified GHC.Types.Var as Var
157 import qualified GHC.Unit.Module.Env as ModuleEnv
158 import qualified GHC.Types.Name.Env as NameEnv
159 #else
160 import qualified Annotations
161 import qualified CoreFVs
162 import qualified CoreSyn
163 import qualified DataCon
164 import qualified Digraph
165 import qualified DynamicLoading
166 import DynFlags (GeneralFlag (..))
167 import qualified DynFlags
168 import qualified Exception
169 import qualified FastString
170 import qualified GHC
171 import qualified HscMain
172 import qualified HscTypes
173 import qualified MonadUtils
174 import qualified Panic
175 import qualified GhcPlugins (deserializeWithData, installedUnitIdString)
176 import qualified TcRnMonad
177 import qualified TcRnTypes
178 import qualified TidyPgm
179 import qualified TyCon
180 import qualified Type
181 import qualified Unique
182 import qualified UniqFM
183 import qualified FamInst
184 import qualified FamInstEnv
185 import qualified GHC.LanguageExtensions as LangExt
186 import qualified Name
187 import qualified OccName
188 import Outputable (ppr)
189 import qualified Outputable
190 import qualified UniqSet
191 import Util (OverridingBool)
192 import qualified Var
193 #endif
194
195 -- Internal Modules
196 import Clash.GHC.GHC2Core (modNameM, qualifiedNameString')
197 import Clash.GHC.LoadInterfaceFiles
198 (loadExternalExprs, getUnresolvedPrimitives, loadExternalBinders,
199 LoadedBinders(..))
200 import Clash.GHCi.Common (checkMonoLocalBindsMod)
201 import Clash.Util (curLoc, noSrcSpan, reportTimeDiff
202 ,wantedLanguageExtensions, unwantedLanguageExtensions)
203 import Clash.Annotations.BitRepresentation.Internal
204 (DataRepr', dataReprAnnToDataRepr')
205
206 import Clash.Signal.Internal
207
208 ghcLibDir :: IO FilePath
209 #ifdef USE_GHC_PATHS
210 ghcLibDir = return libdir
211 #else
212 ghcLibDir = do
213 (libDirM,exitCode) <- getProcessOutput $ "ghc-" ++ TOOL_VERSION_ghc ++ " --print-libdir"
214 case exitCode of
215 ExitSuccess -> case libDirM of
216 Just libDir -> return libDir
217 Nothing -> Panic.pgmError noGHC
218 ExitFailure i -> case i of
219 127 -> Panic.pgmError noGHC
220 i' -> Panic.pgmError $ "Calling GHC failed with error code: " ++ show i'
221 where
222 noGHC = "Clash needs the GHC compiler it was built with, ghc-" ++ TOOL_VERSION_ghc ++
223 ", but it was not found. Make sure its location is in your PATH variable."
224
225 getProcessOutput :: String -> IO (Maybe String, ExitCode)
226 getProcessOutput command =
227 -- Create the process
228 do (_, pOut, _, handle) <- runInteractiveCommand command
229 -- Wait for the process to finish and store its exit code
230 exitCode <- waitForProcess handle
231 -- Get the standard output.
232 output <- either (const Nothing) Just <$> tryIOError (hGetLine pOut)
233 -- return both the output and the exit code.
234 return (output, exitCode)
235 #endif
236
237 -- | Search databases for given module
238 loadExternalModule
239 :: (HasCallStack, GHC.GhcMonad m)
240 => HDL
241 -> String
242 -- ^ Module name. Can either be a filepath pointing to a .hs file, or a
243 -- qualified module name (example: "Data.List").
244 -> m (Either
245 SomeException
246 ( [CoreSyn.CoreBndr] -- Root binders
247 , FamInstEnv.FamInstEnv -- Local type family instances
248 , GHC.ModuleName -- Module name
249 , LoadedBinders
250 , [CoreSyn.CoreBind] -- All bindings
251 ) )
252 #if MIN_VERSION_ghc(9,0,0)
253 loadExternalModule hdl modName0 = MC.try $ do
254 #else
255 loadExternalModule hdl modName0 = Exception.gtry $ do
256 #endif
257 let modName1 = GHC.mkModuleName modName0
258 foundMod <- GHC.findModule modName1 Nothing
259 let errMsg = "Internal error: found module, but could not load it"
260 modInfo <- fromMaybe (error errMsg) <$> (GHC.getModuleInfo foundMod)
261 tyThings <- catMaybes <$> mapM GHC.lookupGlobalName (GHC.modInfoExports modInfo)
262 let rootIds = [id_ | GHC.AnId id_ <- tyThings]
263 loaded <- loadExternalBinders hdl rootIds
264 let allBinders = makeRecursiveGroups (Map.assocs (lbBinders loaded))
265 return (rootIds, FamInstEnv.emptyFamInstEnv, modName1, loaded, allBinders)
266
267 setupGhc
268 :: GHC.GhcMonad m
269 => OverridingBool
270 -> Maybe GHC.DynFlags
271 -> [FilePath]
272 -> m ()
273 setupGhc useColor dflagsM idirs = do
274 dflags <-
275 case dflagsM of
276 Just df -> return df
277 Nothing -> do
278 -- Make sure we read the .ghc environment files
279 df <- do
280 df <- GHC.getSessionDynFlags
281 #if MIN_VERSION_ghc(9,0,0)
282 #if MIN_VERSION_ghc(9,2,0)
283 logger <- GHC.getLogger
284 df1 <- liftIO (GHC.interpretPackageEnv logger df)
285 #else
286 df1 <- liftIO (GHC.interpretPackageEnv df)
287 #endif
288 _ <- GHC.setSessionDynFlags df1
289
290 #else
291 _ <- GHC.setSessionDynFlags df {DynFlags.pkgDatabase = Nothing}
292 #endif
293 GHC.getSessionDynFlags
294
295 let df1 = setWantedLanguageExtensions df
296 ghcTyLitNormPlugin = GHC.mkModuleName "GHC.TypeLits.Normalise"
297 ghcTyLitExtrPlugin = GHC.mkModuleName "GHC.TypeLits.Extra.Solver"
298 ghcTyLitKNPlugin = GHC.mkModuleName "GHC.TypeLits.KnownNat.Solver"
299 dfPlug = df1 { DynFlags.pluginModNames = nub $
300 ghcTyLitNormPlugin : ghcTyLitExtrPlugin :
301 ghcTyLitKNPlugin : DynFlags.pluginModNames df1
302 , DynFlags.useColor = useColor
303 , DynFlags.importPaths = idirs
304 }
305 return dfPlug
306
307 let dflags1 = dflags
308 { DynFlags.ghcMode = GHC.CompManager
309 , DynFlags.ghcLink = GHC.LinkInMemory
310 #if !MIN_VERSION_ghc(9,4,0)
311 , DynFlags.optLevel = 2
312 #endif
313 #if MIN_VERSION_ghc(9,2,0)
314 , DynFlags.backend =
315 if Ways.hostIsProfiled
316 #if MIN_VERSION_ghc(9,6,0)
317 then Backend.noBackend
318 #else
319 then Backend.NoBackend
320 #endif
321 else Backend.platformDefaultBackend (DynFlags.targetPlatform dflags)
322 #else
323 , DynFlags.hscTarget
324 #if MIN_VERSION_ghc(9,0,0)
325 = if Ways.hostIsProfiled
326 #else
327 = if DynFlags.rtsIsProfiled
328 #endif
329 then DynFlags.HscNothing
330 else DynFlags.defaultObjectTarget $
331 #if !MIN_VERSION_ghc(8,10,0)
332 DynFlags.targetPlatform
333 #endif
334 dflags
335 #endif
336 , DynFlags.reductionDepth = 1000
337 }
338 let dflags2 = unwantedOptimizationFlags dflags1
339 ghcDynamic = case lookup "GHC Dynamic" (DynFlags.compilerInfo dflags) of
340 Just "YES" -> True
341 _ -> False
342 dflags3 = if ghcDynamic then DynFlags.gopt_set dflags2 DynFlags.Opt_BuildDynamicToo
343 else dflags2
344
345 when (DynFlags.gopt DynFlags.Opt_WorkerWrapper dflags3) $
346 trace
347 (unlines ["WARNING:"
348 ,"`-fworker-wrapper` option is globally enabled, this can result in incorrect code."
349 ,"Are you compiling with `-O` or `-O2`? Consider adding `-fno-worker-wrapper`."
350 ,"`-fworker-wrapper` can be use in a diligent manner on a file-by-file basis"
351 ,"by using a `{-# OPTIONS_GHC -fworker-wrapper` #-} pragma."
352 ])
353 (return ())
354
355 #if MIN_VERSION_ghc(9,2,0)
356 _ <- GHC.setSessionDynFlags dflags3
357 hscenv <- GHC.getSession
358 hscenv1 <- MonadUtils.liftIO (DynamicLoading.initializePlugins hscenv)
359 GHC.setSession hscenv1
360 #elif MIN_VERSION_ghc(9,0,0)
361 _ <- GHC.setSessionDynFlags dflags3
362 hscenv <- GHC.getSession
363 dflags4 <- MonadUtils.liftIO (DynamicLoading.initializePlugins hscenv dflags3)
364 _ <- GHC.setSessionDynFlags dflags4
365 #else
366 hscenv <- GHC.getSession
367 dflags4 <- MonadUtils.liftIO (DynamicLoading.initializePlugins hscenv dflags3)
368 _ <- GHC.setSessionDynFlags dflags4
369 #endif
370
371 return ()
372
373 -- | Load a module from a Haskell file. Function does NOT look in currently
374 -- loaded modules.
375 loadLocalModule
376 :: GHC.GhcMonad m
377 => HDL
378 -> String
379 -- ^ Module name. Can either be a filepath pointing to a .hs file, or a
380 -- qualified module name (example: "Data.List").
381 -> m ( [CoreSyn.CoreBndr] -- Root binders
382 , FamInstEnv.FamInstEnv -- Local type family instances
383 , GHC.ModuleName -- Module name
384 , LoadedBinders
385 , [CoreSyn.CoreBind] -- All bindings
386 )
387 loadLocalModule hdl modName = do
388 #if MIN_VERSION_ghc(9,4,0)
389 target <- GHC.guessTarget modName Nothing Nothing
390 #else
391 target <- GHC.guessTarget modName Nothing
392 #endif
393 GHC.setTargets [target]
394 modGraph <- GHC.depanal [] False
395 let modGraph' = GHC.mapMG disableOptimizationsFlags modGraph
396 -- 'topSortModuleGraph' ensures that modGraph2, and hence tidiedMods
397 -- are in topological order, i.e. the root module is last.
398 modGraph2 = Digraph.flattenSCCs $
399 #if MIN_VERSION_ghc(9,2,0)
400 -- TODO: this might break backpack
401 Graph.filterToposortToModules $
402 #endif
403 GHC.topSortModuleGraph True modGraph' Nothing
404
405 liftIO $ mapM_ checkMonoLocalBindsMod modGraph2
406
407 tidiedMods <- forM modGraph2 $ \m -> do
408 oldDFlags <- GHC.getSessionDynFlags
409 pMod <- parseModule m
410 _ <- GHC.setSessionDynFlags (GHC.ms_hspp_opts (GHC.pm_mod_summary pMod))
411 tcMod <- GHC.typecheckModule (removeStrictnessAnnotations pMod)
412
413 -- The purpose of the home package table (HPT) is to track
414 -- the already compiled modules, so subsequent modules can
415 -- rely/use those compilation results
416 --
417 -- We need to update the home package table (HPT) ourselves
418 -- as we can no longer depend on 'GHC.load' to create a
419 -- proper HPT.
420 --
421 -- The reason we have to cannot rely on 'GHC.load' is that
422 -- it runs the rename/type-checker, which we also run in
423 -- the code above. This would mean that the renamer/type-checker
424 -- is run twice, which in turn means that template haskell
425 -- splices are run twice.
426 --
427 -- Given that TH splices can do non-trivial computation and I/O,
428 -- running TH twice must be avoid.
429 #if MIN_VERSION_ghc(9,4,0)
430 let (tc_result,_) = GHC.tm_internals_ tcMod
431 let tcMod' = tcMod
432 #else
433 tcMod' <- GHC.loadModule tcMod
434 #endif
435 dsMod <- fmap GHC.coreModule $ GHC.desugarModule tcMod'
436 hsc_env <- GHC.getSession
437 simpl_guts <- MonadUtils.liftIO $ HscMain.hscSimplify hsc_env [] dsMod
438 checkForInvalidPrelude simpl_guts
439 #if MIN_VERSION_ghc(9,4,0)
440 opts <- liftIO (initTidyOpts hsc_env)
441 (tidy_guts,_) <- MonadUtils.liftIO $ TidyPgm.tidyProgram opts simpl_guts
442 #else
443 (tidy_guts,_) <- MonadUtils.liftIO $ TidyPgm.tidyProgram hsc_env simpl_guts
444 #endif
445 #if MIN_VERSION_ghc(9,4,0)
446 let
447 loadAsByteCode
448 | Just GHC.Target { targetAllowObjCode = obj }
449 <- findTarget m (HscTypes.hsc_targets hsc_env)
450 , not obj
451 = True
452 | otherwise = False
453 lcl_dflags = GHC.ms_hspp_opts m
454 old_paths = GHC.includePaths lcl_dflags
455 location = GHC.ms_location m
456 input_fn = fromMaybe (error "loadLocalModule") (GHC.ml_hs_file location)
457 basename = dropExtension input_fn
458 current_dir = takeDirectory basename
459 #if MIN_VERSION_ghc(9,6,0)
460 interpreterBackend = Backend.interpreterBackend
461 #else
462 interpreterBackend = Backend.Interpreter
463 #endif
464 (bcknd, dflags3)
465 | loadAsByteCode
466 = ( interpreterBackend
467 , DynFlags.gopt_set
468 (lcl_dflags { GHC.backend = interpreterBackend })
469 Opt_ForceRecomp
470 )
471 | otherwise
472 = (GHC.backend dflags, lcl_dflags)
473 dflags = dflags3
474 { GHC.includePaths = offsetIncludePaths dflags3 $
475 DynFlags.addImplicitQuoteInclude
476 old_paths
477 [current_dir] }
478 #if MIN_VERSION_ghc(9,6,0)
479 pipelineOutput = Backend.backendPipelineOutput bcknd
480 #else
481 pipelineOutput = case bcknd of
482 GHC.Interpreter -> NoOutputFile
483 GHC.NoBackend -> NoOutputFile
484 _ -> Persistent
485 #endif
486 upd_summary = m { GHC.ms_hspp_opts = dflags }
487 hsc_env1 = HscTypes.hscSetFlags dflags hsc_env
488 pipe_env = mkPipeEnv NoStop input_fn Nothing pipelineOutput
489 pipeline = do
490 ac <- use (T_HscPostTc hsc_env1 upd_summary
491 (TcRnTypes.FrontendTypecheck tc_result) mempty Nothing )
492 hscBackendPipeline pipe_env hsc_env1 upd_summary ac
493 (iface, linkable) <- liftIO (runPipeline (HscTypes.hsc_hooks hsc_env1) pipeline)
494 #if MIN_VERSION_ghc(9,6,0)
495 details <- liftIO (HscMain.initModDetails hsc_env1 iface)
496 linkable1 <- liftIO (traverse (HscMain.initWholeCoreBindings hsc_env1 iface details)
497 (homeMod_bytecode linkable))
498 let linkable2 = linkable {homeMod_bytecode = linkable1}
499 #else
500 details <- liftIO (HscMain.initModDetails hsc_env1 upd_summary iface)
501 let linkable2 = linkable
502 #endif
503 let mod_info = HomeModInfo iface details linkable2
504 modifySession $ HscTypes.hscUpdateHUG (addHomeModInfoToHug mod_info)
505 #endif
506 let pgm = HscTypes.cg_binds tidy_guts
507 let modFamInstEnv = TcRnTypes.tcg_fam_inst_env $ fst $ GHC.tm_internals_ tcMod
508 _ <- GHC.setSessionDynFlags oldDFlags
509 return (pgm,modFamInstEnv)
510
511 let (binders,modFamInstEnvs) = unzip tidiedMods
512 binderIds = map fst (CoreSyn.flattenBinds (concat binders))
513 plusFamInst f1 f2 = FamInstEnv.extendFamInstEnvList f1 (FamInstEnv.famInstEnvElts f2)
514 modFamInstEnvs' = foldl' plusFamInst FamInstEnv.emptyFamInstEnv modFamInstEnvs
515 rootModule = GHC.ms_mod_name . last $ modGraph2
516
517 -- Because tidiedMods is in topological order, binders is also, and hence
518 -- the binders belonging to the "root" module are the last binders
519 let rootIds = map fst . CoreSyn.flattenBinds $ last binders
520 loaded0 <- loadExternalExprs hdl (concat binders)
521
522 -- Find local primitive annotations
523 localPrims <- findPrimitiveAnnotations hdl binderIds
524 let loaded1 = loaded0{lbPrims=lbPrims loaded0 <> Seq.fromList localPrims}
525
526 let allBinders = makeRecursiveGroups (Map.assocs (lbBinders loaded0))
527 pure (rootIds, modFamInstEnvs', rootModule, loaded1, allBinders)
528
529 nameString :: Name.Name -> String
530 nameString = OccName.occNameString . Name.nameOccName
531
532 varNameString :: Var.Var -> String
533 varNameString = nameString . Var.varName
534
535 data LoadModulesException = LoadModulesException
536 { moduleName :: String
537 , externalError :: String
538 , localError :: String
539 } deriving (Exception)
540
541 instance Show LoadModulesException where
542 showsPrec :: Int -> LoadModulesException -> ShowS
543 showsPrec _ LoadModulesException{moduleName, externalError, localError} = showString [I.i|
544 Failed to load module '#{moduleName}'.
545
546 Tried to load it from precompiled sources, error was:
547
548 #{externalError}
549
550 Tried to load it from local sources, error was:
551
552 #{localError}
553 |]
554
555 loadModules
556 :: GHC.Ghc ()
557 -- ^ Allows us to have some initial action, such as sharing a linker state
558 -- See https://github.com/clash-lang/clash-compiler/issues/1686 and
559 -- https://mail.haskell.org/pipermail/ghc-devs/2021-March/019605.html
560 -> OverridingBool
561 -- ^ Use color
562 -> HDL
563 -- ^ HDL target
564 -> String
565 -- ^ Module name
566 -> Maybe (DynFlags.DynFlags)
567 -- ^ Flags to run GHC with
568 -> [FilePath]
569 -- ^ Import dirs to use when no DynFlags are provided
570 -> IO ( [CoreSyn.CoreBind] -- Binders
571 , [(CoreSyn.CoreBndr,Int)] -- Class operations
572 , [CoreSyn.CoreBndr] -- Unlocatable Expressions
573 , FamInstEnv.FamInstEnvs
574 , [(CoreSyn.CoreBndr, Maybe TopEntity, Bool)] -- binder + synthesize annotation + is testbench?
575 , [Either UnresolvedPrimitive FilePath]
576 , [DataRepr']
577 , [(Text.Text, PrimitiveGuard ())]
578 , HashMap Text.Text VDomainConfiguration -- domain names to configuration
579 )
580 loadModules startAction useColor hdl modName dflagsM idirs = do
581 libDir <- MonadUtils.liftIO ghcLibDir
582 startTime <- Clock.getCurrentTime
583 GHC.runGhc (Just libDir) $ do
584 startAction
585 -- 'mainFunIs' is set to Nothing due to issue #1304:
586 -- https://github.com/clash-lang/clash-compiler/issues/1304
587 setupGhc useColor ((\d -> d{GHC.mainFunIs=Nothing}) <$> dflagsM) idirs
588 setupTime <- MonadUtils.liftIO Clock.getCurrentTime
589 let setupStartDiff = reportTimeDiff setupTime startTime
590 MonadUtils.liftIO $ putStrLn $ "GHC: Setting up GHC took: " ++ setupStartDiff
591
592 -- TODO: We currently load the transitive closure of _all_ bindings found
593 -- TODO: in the top module. This is wasteful if one or more binders don't
594 -- TODO: contribute to any top entities. This effect is worsened when using
595 -- TODO: -main-is, which only synthesizes a single top entity (and all its
596 -- TODO: dependencies).
597 (rootIds, modFamInstEnvs, _rootModule, LoadedBinders{..}, allBinders) <-
598 -- We need to try and load external modules first, because we can't
599 -- recover from errors in 'loadLocalModule'.
600 loadExternalModule hdl modName >>= \case
601 #if MIN_VERSION_ghc(9,0,0)
602 Left loadExternalErr -> do
603 catch @_ @SomeException
604 (loadLocalModule hdl modName)
605 (\localError ->
606 throwM
607 (LoadModulesException
608 { moduleName = modName
609 , externalError = show loadExternalErr
610 , localError = show localError
611 }))
612 #else
613 Left _loadExternalErr -> do
614 loadLocalModule hdl modName
615 #endif
616 Right res -> pure res
617
618 let allBinderIds = map fst (CoreSyn.flattenBinds allBinders)
619
620 modTime <- length allBinderIds `seq` MonadUtils.liftIO Clock.getCurrentTime
621 let modStartDiff = reportTimeDiff modTime setupTime
622 MonadUtils.liftIO $ putStrLn $ "GHC: Compiling and loading modules took: " ++ modStartDiff
623
624 -- Get type family instances: accumulated by GhcMonad during
625 -- 'loadExternalBinders' / 'loadExternalExprs'
626 hscEnv <- GHC.getSession
627 famInstEnvs <- do
628 (msgs, m) <- TcRnMonad.liftIO $ TcRnMonad.initTcInteractive hscEnv FamInst.tcGetFamInstEnvs
629 case m of
630 Nothing -> TcRnMonad.liftIO $ throwIO
631 $ HscTypes.mkSrcErr
632 #if MIN_VERSION_ghc(9,4,0)
633 $ fmap GhcTcRnMessage msgs
634 #elif MIN_VERSION_ghc(9,2,0)
635 $ Error.getErrorMessages msgs
636 #else
637 $ snd msgs
638 #endif
639 Just x -> return x
640
641 allSyn <- Map.fromList <$> findSynthesizeAnnotations allBinderIds
642 topSyn <- map fst <$> findSynthesizeAnnotations rootIds
643 benchAnn <- findTestBenches rootIds
644 reprs' <- findCustomReprAnnotations
645 primGuards <- findPrimitiveGuardAnnotations allBinderIds
646 let
647 -- All binders synthesized with Synthesize, all binders annotated with
648 -- TestBench and the binders they're pointing to, plus magically named
649 -- functions called "topEntity" or "testBench". Synthesized in case user
650 -- didn't specify a particular target.
651 isMagicName = (`elem` ["topEntity", "testBench"])
652 allImplicit = nubSort $
653 Map.keys benchAnn
654 <> Map.keys allSyn
655 <> concat (Map.elems benchAnn)
656 <> filter (isMagicName . varNameString) rootIds
657 <> topSyn
658
659 -- Top entities we wish to synthesize. Users can filter these with -main-is.
660 topEntities1 =
661 case GHC.mainFunIs =<< dflagsM of
662 Just mainIsNm ->
663 -- Use requested top entity.
664 --
665 -- TODO: Look up associated test benches in 'benchAnn'. This would
666 -- be wasted effort if implemented right now, as 'getMainTopEntity'
667 -- would later remove them again. Functionality of that function
668 -- should be moved here.
669 --
670 -- TODO: Handle fully qualified names to -main-is
671 case find ((==mainIsNm) . varNameString) rootIds of
672 Nothing ->
673 Panic.pgmError [I.i|
674 No top-level function called '#{mainIsNm}' found. Did you
675 forget to export it?
676 |]
677 Just top ->
678 -- Note that we return /all/ top entities here, even the ones
679 -- we don't which to synthesize. 'getMainTopEntity' will later
680 -- restrict this to just this top entity (and its dependencies,
681 -- which is why we return everything in the first place).
682 --
683 -- This is quite wasteful though; als Clash will load all
684 -- definitions even though it will end up using just a few. TODO
685 nubSort (top:allImplicit)
686 Nothing ->
687 -- User didn't specify anything.
688 case allImplicit of
689 [] ->
690 Panic.pgmError [I.i|
691 No top-level function called 'topEntity' or 'testBench' found,
692 nor any function annotated with a 'Synthesize' or 'TestBench'
693 annotation. If you want to synthesize a specific binder in
694 #{show modName}, use '-main-is myTopEntity'.
695 |]
696 _ ->
697 allImplicit
698
699 -- Include whether found top entity is a test bench
700 allBenchIds = Set.fromList (concat (Map.elems benchAnn))
701 topEntities2 = topEntities1 <&> \tid ->
702 ( tid
703 , tid `Map.lookup` allSyn -- include top entity annotation (if any)
704 , tid `Set.member` allBenchIds -- indicate whether top entity is test bench
705 )
706
707 let reprs1 = lbReprs <> Seq.fromList reprs'
708
709 let famInstEnvs' = (fst famInstEnvs, modFamInstEnvs)
710 allTCInsts = FamInstEnv.famInstEnvElts (fst famInstEnvs')
711 ++ FamInstEnv.famInstEnvElts (snd famInstEnvs')
712
713 knownConfs = filter (\x -> "KnownConf" == nameString (FamInstEnv.fi_fam x)) allTCInsts
714
715 #if MIN_VERSION_ghc(8,10,0)
716 fsToText = Text.decodeUtf8 . FastString.bytesFS
717 #else
718 fsToText = Text.decodeUtf8 . FastString.fastStringToByteString
719 #endif
720
721 famToDomain = fromMaybe (error "KnownConf: Expected Symbol at LHS of type family")
722 . join . fmap (fmap fsToText) . fmap Type.isStrLitTy
723 . listToMaybe . FamInstEnv.fi_tys
724 famToConf = unpackKnownConf . FamInstEnv.fi_rhs
725
726 knownConfNms = fmap famToDomain knownConfs
727 knownConfDs = fmap famToConf knownConfs
728
729 knownConfMap = HashMap.fromList (zip knownConfNms knownConfDs)
730
731 return ( allBinders
732 , Map.assocs lbClassOps
733 , Set.toList lbUnlocatable
734 , famInstEnvs'
735 , topEntities2
736 , toList lbPrims
737 , toList reprs1
738 , primGuards
739 , knownConfMap
740 )
741
742 -- | Given a type that represents the RHS of a KnownConf type family instance,
743 -- unpack the fields of the DomainConfiguration and make a VDomainConfiguration.
744 --
745 unpackKnownConf :: Type.Type -> VDomainConfiguration
746 unpackKnownConf ty
747 | [d,p,ae,rk,ib,rp] <- Type.tyConAppArgs ty
748 -- Domain name
749 , Just dom <- fmap FastString.unpackFS (Type.isStrLitTy d)
750 -- Period
751 , Just period <- fmap naturalFromInteger (Type.isNumLitTy p)
752 -- Active Edge
753 , aeTc <- Type.tyConAppTyCon ae
754 , Just aeDc <- TyCon.isPromotedDataCon_maybe aeTc
755 , aeNm <- OccName.occNameString $ Name.nameOccName (DataCon.dataConName aeDc)
756 -- Reset Kind
757 , rkTc <- Type.tyConAppTyCon rk
758 , Just rkDc <- TyCon.isPromotedDataCon_maybe rkTc
759 , rkNm <- OccName.occNameString $ Name.nameOccName (DataCon.dataConName rkDc)
760 -- Init Behavior
761 , ibTc <- Type.tyConAppTyCon ib
762 , Just ibDc <- TyCon.isPromotedDataCon_maybe ibTc
763 , ibNm <- OccName.occNameString $ Name.nameOccName (DataCon.dataConName ibDc)
764 -- Reset Polarity
765 , rpTc <- Type.tyConAppTyCon rp
766 , Just rpDc <- TyCon.isPromotedDataCon_maybe rpTc
767 , rpNm <- OccName.occNameString $ Name.nameOccName (DataCon.dataConName rpDc)
768 = VDomainConfiguration dom period
769 (asActiveEdge aeNm)
770 (asResetKind rkNm)
771 (asInitBehavior ibNm)
772 (asResetPolarity rpNm)
773
774 | otherwise
775 = error $ $(curLoc) ++ "Could not unpack domain configuration."
776 where
777 asActiveEdge :: HasCallStack => String -> ActiveEdge
778 asActiveEdge x = fromMaybe (error $ $(curLoc) ++ "Unknown active edge: " ++ show x) (readMaybe x)
779
780 asResetKind :: HasCallStack => String -> ResetKind
781 asResetKind x = fromMaybe (error $ $(curLoc) ++ "Unknown reset kind: " ++ show x) (readMaybe x)
782
783 asInitBehavior :: HasCallStack => String -> InitBehavior
784 asInitBehavior x = fromMaybe (error $ $(curLoc) ++ "Unknown init behavior: " ++ show x) (readMaybe x)
785
786 asResetPolarity :: HasCallStack => String -> ResetPolarity
787 asResetPolarity x = fromMaybe (error $ $(curLoc) ++ "Unknown reset polarity: " ++ show x) (readMaybe x)
788
789 -- | Given a set of bindings, make explicit non-recursive bindings and
790 -- recursive binding groups.
791 --
792 -- Needed because:
793 -- 1. GHC does not preserve this information in interface files,
794 -- 2. Binders in Clash's BindingsMap are not allowed to be mutually recursive,
795 -- only self-recursive.
796 -- 3. Clash.GHC.GenerateBindings.mkBindings turns groups of mutually recursive
797 -- bindings into self-recursive bindings which can go into the BindingsMap.
798 makeRecursiveGroups
799 :: [(CoreSyn.CoreBndr,CoreSyn.CoreExpr)]
800 -> [CoreSyn.CoreBind]
801 makeRecursiveGroups
802 = map makeBind
803 . Digraph.stronglyConnCompFromEdgedVerticesUniq
804 . map makeNode
805 where
806 makeNode
807 :: (CoreSyn.CoreBndr,CoreSyn.CoreExpr)
808 -> Digraph.Node Unique.Unique (CoreSyn.CoreBndr,CoreSyn.CoreExpr)
809 makeNode (b,e) =
810 Digraph.DigraphNode
811 (b,e)
812 (Var.varUnique b)
813 (UniqSet.nonDetKeysUniqSet (CoreFVs.exprSomeFreeVars Var.isId e))
814
815 makeBind
816 :: Digraph.SCC (CoreSyn.CoreBndr,CoreSyn.CoreExpr)
817 -> CoreSyn.CoreBind
818 makeBind (Digraph.AcyclicSCC (b,e)) = CoreSyn.NonRec b e
819 makeBind (Digraph.CyclicSCC bs) = CoreSyn.Rec bs
820
821 errOnDuplicateAnnotations
822 :: String
823 -- ^ Name of annotation
824 -> [CoreSyn.CoreBndr]
825 -- ^ Binders searched for
826 -> [[a]]
827 -- ^ Parsed annotations
828 -> [(CoreSyn.CoreBndr, a)]
829 errOnDuplicateAnnotations nm =
830 combineAnnotationsWith err nm
831 where
832 err _ _ = Left $ "A binder can't have more than one '" ++ nm ++ "' annotation."
833
834 combineAnnotationsWith
835 :: forall a. (a -> a -> Either String a)
836 -- ^ function to (attempts to) combine different annotations
837 -> String
838 -- ^ Name of annotation
839 -> [CoreSyn.CoreBndr]
840 -- ^ Binders searched for
841 -> [[a]]
842 -- ^ Parsed annotations
843 -> [(CoreSyn.CoreBndr, a)]
844 combineAnnotationsWith f nm bndrs anns =
845 go (zip bndrs anns)
846 where
847 go :: [(CoreSyn.CoreBndr, [a])] -> [(CoreSyn.CoreBndr, a)]
848 go [] = []
849 go ((_, []):ps) = go ps
850 go ((b, (a:as)):ps) = case foldM f a as of
851 Left err ->
852 Panic.pgmError $ "Error processing '" ++ nm ++ "' annotations on "
853 ++ Outputable.showSDocUnsafe (pprQualified $ Var.varName b)
854 ++ ":\n" ++ err
855 Right x -> (b, x) : go ps
856 pprQualified :: Name.Name -> Outputable.SDoc
857 pprQualified x = case Name.nameModule_maybe x of
858 Just m -> Outputable.hcat [ppr m, Outputable.dot, ppr x]
859 Nothing -> ppr x
860
861
862 -- | Find annotations by given targets
863 findAnnotationsByTargets
864 :: (GHC.GhcMonad m, Data a, Typeable a)
865 => [Annotations.AnnTarget Name.Name]
866 -> m [[a]]
867 findAnnotationsByTargets targets =
868 #if MIN_VERSION_ghc(9,0,0)
869 mapM (GHC.findGlobalAnns Serialized.deserializeWithData) targets
870 #else
871 mapM (GHC.findGlobalAnns GhcPlugins.deserializeWithData) targets
872 #endif
873
874 -- | Find all annotations of a certain type in all modules seen so far.
875 findAllModuleAnnotations
876 :: (GHC.GhcMonad m, Data a, Typeable a)
877 => m [a]
878 findAllModuleAnnotations = do
879 hsc_env <- GHC.getSession
880 ann_env <- liftIO $ HscTypes.prepareAnnotations hsc_env Nothing
881 return $ concat
882 #if MIN_VERSION_ghc(9,4,0)
883 $ (\(mEnv,nEnv) -> ModuleEnv.moduleEnvElts mEnv <> NameEnv.nonDetNameEnvElts nEnv)
884 #elif MIN_VERSION_ghc(9,0,0)
885 $ (\(mEnv,nEnv) -> ModuleEnv.moduleEnvElts mEnv <> NameEnv.nameEnvElts nEnv)
886 #else
887 $ UniqFM.nonDetEltsUFM
888 #endif
889 $ Annotations.deserializeAnns
890 #if MIN_VERSION_ghc(9,0,0)
891 Serialized.deserializeWithData
892 #else
893 GhcPlugins.deserializeWithData
894 #endif
895 ann_env
896
897 -- | Find all annotations belonging to all binders seen so far.
898 findNamedAnnotations
899 :: (GHC.GhcMonad m, Data a, Typeable a)
900 => [CoreSyn.CoreBndr]
901 -> m [[a]]
902 findNamedAnnotations bndrs =
903 findAnnotationsByTargets (map (Annotations.NamedTarget . Var.varName) bndrs)
904
905 findPrimitiveGuardAnnotations
906 :: GHC.GhcMonad m
907 => [CoreSyn.CoreBndr]
908 -> m [(Text.Text, (PrimitiveGuard ()))]
909 findPrimitiveGuardAnnotations bndrs = do
910 anns0 <- findNamedAnnotations bndrs
911 let anns1 = combineAnnotationsWith combinePrimGuards "PrimitiveGuard" bndrs anns0
912 pure (map (first (qualifiedNameString' . Var.varName)) anns1)
913 where
914 combinePrimGuards a b = case (a,b) of
915 (HasBlackBox x _, HasBlackBox y _) -> Right (HasBlackBox (x++y) ())
916 (DontTranslate , DontTranslate) -> Right DontTranslate
917 (_,_) -> Left "One binder can't have both HasBlackBox and DontTranslate annotations."
918
919
920 -- | Find annotations of type @DataReprAnn@ and convert them to @DataRepr'@
921 findCustomReprAnnotations
922 :: GHC.GhcMonad m
923 => m [DataRepr']
924 findCustomReprAnnotations =
925 map dataReprAnnToDataRepr' <$> findAllModuleAnnotations
926
927 -- | Find synthesize annotations and make sure each binder has no more than
928 -- a single annotation.
929 findSynthesizeAnnotations
930 :: GHC.GhcMonad m
931 => [CoreSyn.CoreBndr]
932 -> m [(CoreSyn.CoreBndr, TopEntity)]
933 findSynthesizeAnnotations bndrs = do
934 anns <- findNamedAnnotations bndrs
935 pure (errOnDuplicateAnnotations "Synthesize" bndrs (map (filter isSyn) anns))
936 where
937 isSyn (Synthesize {}) = True
938 isSyn _ = False
939
940 -- | Find test bench annotations and return a map tying top entities to their
941 -- test benches. If there is a binder called @testBench@ _without_ an annotation
942 -- it assumed to belong to a binder called @topEntity@. If the latter does not
943 -- exist, the function @testBench@ is left alone.
944 findTestBenches ::
945 GHC.GhcMonad m =>
946 -- | Root binders
947 [CoreSyn.CoreBndr] ->
948 -- | (design under test, associated test benches)
949 m (Map.Map CoreSyn.CoreBndr [CoreSyn.CoreBndr])
950 findTestBenches bndrs0 = do
951 anns <- findNamedAnnotations bndrs0
952 let
953 duts0 = foldl' insertTb Map.empty (concat (zipWith go0 bndrs0 anns))
954 duts1 = specialCaseMagicName duts0
955 pure duts1
956 where
957 insertTb m (dut, tb) = Map.insertWith (<>) dut [tb] m
958 bndrsMap = HashMap.fromList (map (\x -> (toQualNm x, x)) bndrs0)
959
960 -- Special case magic name 'testBench'. See function documentation.
961 specialCaseMagicName m =
962 let
963 topEntM = find ((=="topEntity") . varNameString) bndrs0
964 tbM = find ((=="testBench") . varNameString) bndrs0
965 in
966 case (topEntM, tbM) of
967 (Just dut, Just tb) -> insertTb m (dut, tb)
968 _ -> m
969
970 -- go0 + go1: map over all annotations; look for test bench annotations and
971 -- tie them to top entities indicated in the annotation.
972 go0 bndr anns = mapMaybe (go1 bndr) anns
973 go1 tbBndr (TestBench dutNm) =
974 case HashMap.lookup (Text.pack (show dutNm)) bndrsMap of
975 Nothing ->
976 Panic.pgmError [I.i|
977 Could not find design under test #{show (show dutNm)}, associated with
978 test bench #{show (toQualNm tbBndr)}. Note that testbenches should be
979 exported from the same module as the design under test.
980 |]
981 Just dutBndr ->
982 Just (dutBndr, tbBndr)
983 go1 _ _ = Nothing
984
985 -- | Create a fully qualified name from a var, excluding package. Example
986 -- output: @Clash.Sized.Internal.BitVector.low@.
987 toQualNm :: Var.Var -> Text.Text
988 toQualNm bndr =
989 let
990 bndrNm = Var.varName bndr
991 occName = Text.pack (OccName.occNameString (Name.nameOccName bndrNm))
992 in
993 maybe
994 occName
995 (\modName -> modName `Text.append` ('.' `Text.cons` occName))
996 (modNameM bndrNm)
997
998 -- | Find primitive annotations bound to given binders, or annotations made
999 -- in modules of those binders.
1000 findPrimitiveAnnotations
1001 :: GHC.GhcMonad m
1002 => HDL
1003 -> [CoreSyn.CoreBndr]
1004 -> m [Either UnresolvedPrimitive FilePath]
1005 findPrimitiveAnnotations hdl bndrs = do
1006 let
1007 annTargets =
1008 map
1009 (fmap Annotations.ModuleTarget . Name.nameModule_maybe)
1010 (map Var.varName bndrs)
1011
1012 let
1013 targets =
1014 (catMaybes annTargets) ++
1015 (map (Annotations.NamedTarget . Var.varName) bndrs)
1016
1017 anns <- findAnnotationsByTargets targets
1018
1019 concat <$>
1020 mapM (getUnresolvedPrimitives hdl)
1021 (concat $ zipWith (\t -> map ((,) t)) targets anns)
1022
1023 parseModule :: GHC.GhcMonad m => GHC.ModSummary -> m GHC.ParsedModule
1024 parseModule modSum = do
1025 #if MIN_VERSION_ghc(9,2,0)
1026 (GHC.ParsedModule pmModSum pmParsedSource extraSrc) <-
1027 GHC.parseModule modSum
1028 return (GHC.ParsedModule
1029 (disableOptimizationsFlags pmModSum)
1030 pmParsedSource extraSrc)
1031 #else
1032 (GHC.ParsedModule pmModSum pmParsedSource extraSrc anns) <-
1033 GHC.parseModule modSum
1034 return (GHC.ParsedModule
1035 (disableOptimizationsFlags pmModSum)
1036 pmParsedSource extraSrc anns)
1037 #endif
1038
1039 disableOptimizationsFlags :: GHC.ModSummary -> GHC.ModSummary
1040 disableOptimizationsFlags ms@(GHC.ModSummary {..})
1041 = ms {GHC.ms_hspp_opts = dflags}
1042 where
1043 dflags = unwantedOptimizationFlags (ms_hspp_opts
1044 { DynFlags.reductionDepth = 1000
1045 #if !MIN_VERSION_ghc(9,4,0)
1046 , DynFlags.optLevel = 2
1047 #endif
1048 })
1049
1050 unwantedOptimizationFlags :: GHC.DynFlags -> GHC.DynFlags
1051 unwantedOptimizationFlags df =
1052 foldl' DynFlags.xopt_unset
1053 (foldl' DynFlags.gopt_unset df unwanted) unwantedLang
1054 where
1055 unwanted = [ Opt_LiberateCase -- Perform unrolling of recursive RHS: avoid
1056 , Opt_SpecConstr -- Creates local-functions: avoid
1057 , Opt_IgnoreAsserts -- We don't care about assertions
1058 , Opt_DoEtaReduction -- We want eta-expansion
1059 , Opt_UnboxStrictFields -- Unboxed types are not handled properly: avoid
1060 , Opt_UnboxSmallStrictFields -- Unboxed types are not handled properly: avoid
1061 , Opt_RegsGraph -- Don't care
1062 , Opt_RegsGraph -- Don't care
1063 , Opt_PedanticBottoms -- Stops eta-expansion through case: avoid
1064 #if !MIN_VERSION_ghc(9,10,0)
1065 , Opt_LlvmTBAA -- Don't care
1066 #endif
1067 , Opt_CmmSink -- Don't care
1068 , Opt_CmmElimCommonBlocks -- Don't care
1069 , Opt_OmitYields -- Don't care
1070 , Opt_IgnoreInterfacePragmas -- We need all the unfoldings we can get
1071 , Opt_OmitInterfacePragmas -- We need all the unfoldings we can get
1072 , Opt_IrrefutableTuples -- Introduce irrefutPatError: avoid
1073 , Opt_Loopification -- STG pass, don't care
1074 , Opt_CprAnal -- The worker/wrapper introduced by CPR breaks Clash, see [NOTE: CPR breaks Clash]
1075 , Opt_FullLaziness -- increases sharing, but seems to result in worse circuits (in both area and propagation delay)
1076 ]
1077
1078 -- Coercions between Integer and Clash' numeric primitives cause Clash to
1079 -- fail. As strictness only affects simulation behavior, removing them
1080 -- is perfectly safe.
1081 unwantedLang = [ LangExt.Strict
1082 , LangExt.StrictData
1083 ]
1084
1085 -- [NOTE: CPR breaks Clash]
1086 -- We used to completely disable strictness analysis because it causes GHC to
1087 -- do the so-called "Constructed Product Result" (CPR) analysis, which in turn
1088 -- creates an annoying worker/wrapper which does the following:
1089 --
1090 -- * Scrutinise a Signal, and pack the head and tail of the
1091 -- Signal in an unboxed tuple.
1092 -- * Scrutinise on the unboxed tuple, and recreate the Signal.
1093 --
1094 -- This is problematic because the 'Signal' type is essentially treated as a "transparent"
1095 -- type by the Clash compiler, so observing its constructor leads to all kinds
1096 -- of problems.
1097 --
1098 -- The current solution is to disable strictness analysis in "Clash.Signal.Internal"
1099 -- so that functions manipulating 'Signal' constructor do not get a strictness/
1100 -- demand/CPR annotation, which in turn ensures GHC doesn't create worker/wrappers
1101 -- for when these functions are called in user code.
1102 --
1103 -- Ultimately we should stop treating Signal as a "transparent" type and deal
1104 -- handling of the Signal type, and the involved co-recursive functions,
1105 -- properly. At the moment, Clash cannot deal with this recursive type and the
1106 -- recursive functions involved, and hence we need to disable this useful transformation. After
1107 -- everything is done properly, we should enable it again.
1108
1109
1110 setWantedLanguageExtensions :: GHC.DynFlags -> GHC.DynFlags
1111 setWantedLanguageExtensions df =
1112 foldl' DynFlags.gopt_set
1113 (foldl' DynFlags.xopt_unset
1114 (foldl' DynFlags.xopt_set df wantedLanguageExtensions)
1115 unwantedLanguageExtensions)
1116 wantedOptimizations
1117 where
1118 wantedOptimizations =
1119 [ Opt_CSE -- CSE
1120 , Opt_Specialise -- Specialise on types, specialise type-class-overloaded function defined in this module for the types
1121 , Opt_DoLambdaEtaExpansion -- transform nested series of lambdas into one with multiple arguments, helps us achieve only top-level lambdas
1122 , Opt_CaseMerge -- We want fewer case-statements
1123 , Opt_DictsCheap -- Makes dictionaries seem cheap to optimizer: hopefully inline
1124 , Opt_ExposeAllUnfoldings -- We need all the unfoldings we can get
1125 , Opt_ForceRecomp -- Force recompilation: never bad
1126 , Opt_EnableRewriteRules -- Reduce number of functions
1127 , Opt_SimplPreInlining -- Inlines simple functions, we only care about the major first-order structure
1128 , Opt_StaticArgumentTransformation -- Turn on the static argument transformation, which turns a recursive function into a non-recursive one with a local recursive loop.
1129 , Opt_FloatIn -- Moves let-bindings inwards, although it defeats the normal-form with a single top-level let-binding, it helps with other transformations
1130 , Opt_DictsStrict -- Hopefully helps remove class method selectors
1131 , Opt_DmdTxDictSel -- I think demand and strictness are related, strictness helps with dead-code, enable
1132 , Opt_Strictness -- Strictness analysis helps with dead-code analysis. However, see [NOTE: CPR breaks Clash]
1133 , Opt_SpecialiseAggressively -- Needed to compile Fixed point number functions quickly
1134 , Opt_CrossModuleSpecialise -- Needed to compile Fixed point number functions quickly
1135 ]
1136
1137 -- | Remove all strictness annotations:
1138 --
1139 -- * Remove strictness annotations from data type declarations
1140 -- (only works for data types that are currently being compiled, i.e.,
1141 -- that are not part of a pre-compiled imported library)
1142 --
1143 -- We need to remove strictness annotations because GHC will introduce casts
1144 -- between Integer and Clash' numeric primitives otherwise, where Clash will
1145 -- error when it sees such casts. The reason it does this is because
1146 -- Integer is a completely unconstrained integer type and is currently
1147 -- (erroneously) translated to a 64-bit integer in the HDL; this means that
1148 -- we could lose bits when the original numeric type had more bits than 64.
1149 --
1150 -- Removing these strictness annotations is perfectly safe, as they only
1151 -- affect simulation behavior.
1152 removeStrictnessAnnotations ::
1153 GHC.ParsedModule
1154 -> GHC.ParsedModule
1155 removeStrictnessAnnotations pm =
1156 pm {GHC.pm_parsed_source = fmap rmPS (GHC.pm_parsed_source pm)}
1157 where
1158 -- rmPS :: GHC.DataId name => GHC.HsModule name -> GHC.HsModule name
1159 rmPS hsm = hsm {GHC.hsmodDecls = (fmap . fmap) rmHSD (GHC.hsmodDecls hsm)}
1160
1161 -- rmHSD :: GHC.DataId name => GHC.HsDecl name -> GHC.HsDecl name
1162 rmHSD (GHC.TyClD x tyClDecl) = GHC.TyClD x (rmTyClD tyClDecl)
1163 rmHSD hsd = hsd
1164
1165 -- rmTyClD :: GHC.DataId name => GHC.TyClDecl name -> GHC.TyClDecl name
1166 rmTyClD dc@(GHC.DataDecl {}) = dc {GHC.tcdDataDefn = rmDataDefn (GHC.tcdDataDefn dc)}
1167 rmTyClD tyClD = tyClD
1168
1169 -- rmDataDefn :: GHC.DataId name => GHC.HsDataDefn name -> GHC.HsDataDefn name
1170 #if MIN_VERSION_ghc(9,2,0)
1171 rmDataDefn :: GHC.HsDataDefn GHC.GhcPs -> GHC.HsDataDefn GHC.GhcPs
1172 #endif
1173 rmDataDefn hdf = hdf {GHC.dd_cons = (fmap . fmap) rmCD (GHC.dd_cons hdf)}
1174
1175 -- rmCD :: GHC.DataId name => GHC.ConDecl name -> GHC.ConDecl name
1176 rmCD gadt@(GHC.ConDeclGADT {}) = gadt {GHC.con_res_ty = rmHsType (GHC.con_res_ty gadt)
1177 #if MIN_VERSION_ghc(9,2,0)
1178 ,GHC.con_g_args = rmGConDetails (GHC.con_g_args gadt)
1179 #else
1180 ,GHC.con_args = rmConDetails (GHC.con_args gadt)
1181 #endif
1182 }
1183 rmCD h98@(GHC.ConDeclH98 {}) = h98 {GHC.con_args = rmConDetails (GHC.con_args h98)}
1184 #if !MIN_VERSION_ghc(9,0,0)
1185 rmCD xcon = xcon
1186 #endif
1187
1188 #if MIN_VERSION_ghc(9,10,0)
1189 rmGConDetails :: GHC.HsConDeclGADTDetails GHC.GhcPs -> GHC.HsConDeclGADTDetails GHC.GhcPs
1190 rmGConDetails (GHC.PrefixConGADT tkn args) = GHC.PrefixConGADT tkn (fmap rmHsScaledType args)
1191 rmGConDetails (GHC.RecConGADT tkn rec) = GHC.RecConGADT tkn ((fmap . fmap . fmap) rmConDeclF rec)
1192 #elif MIN_VERSION_ghc(9,4,0)
1193 rmGConDetails :: GHC.HsConDeclGADTDetails GHC.GhcPs -> GHC.HsConDeclGADTDetails GHC.GhcPs
1194 rmGConDetails (GHC.PrefixConGADT args) = GHC.PrefixConGADT (fmap rmHsScaledType args)
1195 rmGConDetails (GHC.RecConGADT rec tkn) = GHC.RecConGADT ((fmap . fmap . fmap) rmConDeclF rec) tkn
1196 #elif MIN_VERSION_ghc(9,2,0)
1197 rmGConDetails :: GHC.HsConDeclGADTDetails GHC.GhcPs -> GHC.HsConDeclGADTDetails GHC.GhcPs
1198 rmGConDetails (GHC.PrefixConGADT args) = GHC.PrefixConGADT (fmap rmHsScaledType args)
1199 rmGConDetails (GHC.RecConGADT rec) = GHC.RecConGADT ((fmap . fmap . fmap) rmConDeclF rec)
1200 #endif
1201
1202 -- type HsConDeclDetails name = HsConDetails (LBangType name) (Located [LConDeclField name])
1203 -- rmConDetails :: _ => GHC.HsConDeclDetails name -> GHC.HsConDeclDetails name
1204 #if MIN_VERSION_ghc(9,2,0)
1205 rmConDetails (GHC.PrefixCon tys args) = GHC.PrefixCon tys (fmap rmHsScaledType args)
1206 rmConDetails (GHC.InfixCon l r) = GHC.InfixCon (rmHsScaledType l) (rmHsScaledType r)
1207 #elif MIN_VERSION_ghc(9,0,0)
1208 rmConDetails (GHC.PrefixCon args) = GHC.PrefixCon (fmap rmHsScaledType args)
1209 rmConDetails (GHC.InfixCon l r) = GHC.InfixCon (rmHsScaledType l) (rmHsScaledType r)
1210 #else
1211 rmConDetails (GHC.PrefixCon args) = GHC.PrefixCon (fmap rmHsType args)
1212 rmConDetails (GHC.InfixCon l r) = GHC.InfixCon (rmHsType l) (rmHsType r)
1213 #endif
1214 rmConDetails (GHC.RecCon rec) = GHC.RecCon ((fmap . fmap . fmap) rmConDeclF rec)
1215
1216
1217 -- rmHsType :: GHC.DataId name => GHC.Located (GHC.HsType name) -> GHC.Located (GHC.HsType name)
1218 rmHsType = transform go
1219 where
1220 #if MIN_VERSION_ghc(9,2,0)
1221 go ::
1222 GHC.LBangType GHC.GhcPs ->
1223 GHC.LBangType GHC.GhcPs
1224 #endif
1225 go (GHC.unLoc -> GHC.HsBangTy _ _ ty) = ty
1226 go ty = ty
1227
1228 #if MIN_VERSION_ghc(9,0,0)
1229 rmHsScaledType = transform go
1230 where
1231 #if MIN_VERSION_ghc(9,2,0)
1232 go ::
1233 GHC.HsScaled GHC.GhcPs (GHC.LBangType GHC.GhcPs) ->
1234 GHC.HsScaled GHC.GhcPs (GHC.LBangType GHC.GhcPs)
1235 #endif
1236 go (GHC.HsScaled m (GHC.unLoc -> GHC.HsBangTy _ _ ty)) = GHC.HsScaled m ty
1237 go ty = ty
1238 #endif
1239
1240 -- rmConDeclF :: GHC.DataId name => GHC.ConDeclField name -> GHC.ConDeclField name
1241 rmConDeclF cdf = cdf {GHC.cd_fld_type = rmHsType (GHC.cd_fld_type cdf)}
1242
1243 -- | The package id of the clash-prelude we were built with
1244 preludePkgId :: String
1245 preludePkgId = $(lift $ pkgIdFromTypeable (undefined :: TopEntity))
1246
1247 -- | Check that we're using the same clash-prelude as we were built with
1248 --
1249 -- Because if they differ clash won't be able to recognize any ANNotations.
1250 checkForInvalidPrelude :: Monad m => HscTypes.ModGuts -> m ()
1251 checkForInvalidPrelude guts =
1252 case filter isWrongPrelude pkgIds of
1253 [] -> return ()
1254 (x:_) -> throw (ClashException noSrcSpan (msgWrongPrelude x) Nothing)
1255 where
1256 #if MIN_VERSION_ghc(9,4,0)
1257 pkgs = HscTypes.dep_direct_pkgs . HscTypes.mg_deps $ guts
1258 #else
1259 pkgs = HscTypes.dep_pkgs . HscTypes.mg_deps $ guts
1260 #endif
1261 #if MIN_VERSION_ghc(9,4,0)
1262 pkgIds = map (UnitTypes.unitIdString) (toList pkgs)
1263 #elif MIN_VERSION_ghc(9,0,0)
1264 pkgIds = map (UnitTypes.unitIdString . fst) pkgs
1265 #else
1266 pkgIds = map (GhcPlugins.installedUnitIdString . fst) pkgs
1267 #endif
1268 prelude = "clash-prelude-"
1269 isPrelude pkg = case splitAt (length prelude) pkg of
1270 (x,y:_) | x == prelude && isDigit y -> True -- check for a digit so we don't match clash-prelude-extras
1271 _ -> False
1272 isWrongPrelude pkg = isPrelude pkg && pkg /= preludePkgId
1273 msgWrongPrelude pkg = unlines ["Clash only works with the exact clash-prelude it was built with."
1274 ,"Clash was built with: " ++ preludePkgId
1275 ,"So can't run with: " ++ pkg
1276 ]