[project @ 2001-03-08 18:03:34 by qrczak]
[ghc-hetmet.git] / ghc / compiler / compMan / CmLink.lhs
1 %
2 % (c) The University of Glasgow, 2000
3 %
4 \section[CmLink]{Linker for GHCI}
5
6 \begin{code}
7 module CmLink ( Linkable(..),  Unlinked(..),
8                 filterModuleLinkables, 
9                 findModuleLinkable_maybe,
10                 LinkResult(..),
11                 link, 
12                 unload,
13                 PersistentLinkerState{-abstractly!-}, emptyPLS,
14 #ifdef GHCI
15                 updateClosureEnv,
16                 linkExpr
17 #endif
18   ) where
19
20
21 #ifdef GHCI
22 import ByteCodeLink     ( linkIModules, linkIExpr )
23 #endif
24
25 import Interpreter
26 import DriverPipeline
27 import CmTypes
28 import CmStaticInfo     ( GhciMode(..) )
29 import Outputable       ( SDoc )
30 import Digraph          ( SCC(..), flattenSCC )
31 import Name             ( Name )
32 import Module           ( ModuleName )
33 import FiniteMap
34 import Outputable
35 import ErrUtils         ( showPass )
36 import CmdLineOpts      ( DynFlags(..) )
37 import Panic            ( panic, GhcException(..) )
38
39 import Exception
40 import List
41 import Monad
42 import IO
43
44 #include "HsVersions.h"
45 \end{code}
46
47 \begin{code}
48 data PersistentLinkerState 
49    = PersistentLinkerState {
50
51
52 #ifdef GHCI
53         -- Current global mapping from RdrNames to closure addresses
54         closure_env :: ClosureEnv,
55
56         -- the current global mapping from RdrNames of DataCons to 
57         -- info table addresses.
58         -- When a new Unlinked is linked into the running image, or an existing
59         -- module in the image is replaced, the itbl_env must be updated
60         -- appropriately.
61         itbl_env    :: ItblEnv,
62
63         -- list of objects we've loaded (we'll need to unload them again
64         -- before re-loading the same module), together with the ClockTime
65         -- of the linkable they were loaded from.
66         objects_loaded :: [Linkable]
67
68         -- notionally here, but really lives in the C part of the linker:
69         --            object_symtab :: FiniteMap String Addr
70 #else
71         dummy :: ()     --  sigh, can't have an empty record
72 #endif
73
74      }
75
76 data LinkResult 
77    = LinkOK   PersistentLinkerState
78    | LinkErrs PersistentLinkerState [SDoc]
79
80 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
81 findModuleLinkable_maybe lis mod 
82    = case [LM time nm us | LM time nm us <- lis, nm == mod] of
83         []   -> Nothing
84         [li] -> Just li
85         many -> pprPanic "findModuleLinkable" (ppr mod)
86
87
88 emptyPLS :: IO PersistentLinkerState
89 #ifdef GHCI
90 emptyPLS = return (PersistentLinkerState { closure_env = emptyFM, 
91                                            itbl_env    = emptyFM,
92                                            objects_loaded = [] })
93 #else
94 emptyPLS = return (PersistentLinkerState {})
95 #endif
96
97 #ifdef GHCI
98 updateClosureEnv :: PersistentLinkerState -> [(Name,HValue)] 
99         -> IO PersistentLinkerState
100 updateClosureEnv pls new_bindings
101   = return pls{ closure_env = addListToFM (closure_env pls) new_bindings }
102 #endif
103
104 -----------------------------------------------------------------------------
105 -- Unloading old objects ready for a new compilation sweep.
106 --
107 -- The compilation manager provides us with a list of linkables that it
108 -- considers "stable", i.e. won't be recompiled this time around.  For
109 -- each of the modules current linked in memory,
110 --
111 --      * if the linkable is stable (and it's the same one - the
112 --        user may have recompiled the module on the side), we keep it,
113 --
114 --      * otherwise, we unload it.
115 --
116 --      * we also implicitly unload all temporary bindings at this point.
117
118 unload :: GhciMode
119        -> DynFlags
120        -> [Linkable]            -- stable linkables
121        -> PersistentLinkerState
122        -> IO PersistentLinkerState 
123
124 unload Batch dflags linkables pls = return pls
125
126 #ifdef GHCI
127 unload Interactive dflags linkables pls
128   = do new_loaded <- filterM maybeUnload (objects_loaded pls)
129        let mods_retained = map linkableModName new_loaded
130            itbl_env'     = filterNameMap mods_retained (itbl_env pls)
131            closure_env'  = filterNameMap mods_retained (closure_env pls)
132
133        let verb = verbosity dflags
134        when (verb >= 3) $ do
135             hPutStrLn stderr (showSDoc 
136                 (text "CmLink.unload: retaining" <+> ppr mods_retained))
137
138        return pls{ objects_loaded = new_loaded,
139                    itbl_env = itbl_env',
140                    closure_env = closure_env' }
141   where
142         maybeUnload :: Linkable -> IO Bool
143         maybeUnload (LM time mod objs) = do
144           case findModuleLinkable_maybe linkables mod of
145                 Nothing -> do unloadObjs; return False
146                 Just l | linkableTime l /= time -> do unloadObjs; return False
147                        | otherwise              -> return True
148           where
149              unloadObjs = mapM unloadObj [ f | DotO f <- objs ]
150 #else
151 unload Interactive dflags linkables pls = panic "CmLink.unload: no interpreter"
152 #endif
153 -----------------------------------------------------------------------------
154 -- Linking
155
156 link :: GhciMode                -- interactive or batch
157      -> DynFlags                -- dynamic flags
158      -> Bool                    -- attempt linking in batch mode?
159      -> [Linkable]
160      -> PersistentLinkerState 
161      -> IO LinkResult
162
163 -- For the moment, in the batch linker, we don't bother to tell doLink
164 -- which packages to link -- it just tries all that are available.
165 -- batch_attempt_linking should only be *looked at* in batch mode.  It
166 -- should only be True if the upsweep was successful and someone
167 -- exports main, i.e., we have good reason to believe that linking
168 -- will succeed.
169
170 -- There will be (ToDo: are) two lists passed to link.  These
171 -- correspond to
172 --
173 --      1. The list of all linkables in the current home package.  This is
174 --         used by the batch linker to link the program, and by the interactive
175 --         linker to decide which modules from the previous link it can 
176 --         throw away.
177 --      2. The list of modules on which we just called "compile".  This list
178 --         is used by the interactive linker to decide which modules need
179 --         to be actually linked this time around (or unlinked and re-linked 
180 --         if the module was recompiled).
181
182 link mode dflags batch_attempt_linking linkables pls1
183    = do let verb = verbosity dflags
184         when (verb >= 3) $ do
185              hPutStrLn stderr "CmLink.link: linkables are ..."
186              hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
187         res <- link' mode dflags batch_attempt_linking linkables pls1
188         when (verb >= 3) $ 
189              hPutStrLn stderr "CmLink.link: done"
190         return res
191
192 link' Batch dflags batch_attempt_linking linkables pls1
193    | batch_attempt_linking
194    = do let o_files = concatMap getOfiles linkables
195         when (verb >= 1) $
196              hPutStrLn stderr "ghc: linking ..."
197         -- don't showPass in Batch mode; doLink will do that for us.
198         doLink o_files
199         -- doLink only returns if it succeeds
200         return (LinkOK pls1)
201    | otherwise
202    = do when (verb >= 3) $ do
203             hPutStrLn stderr "CmLink.link(batch): upsweep (partially) failed OR"
204             hPutStrLn stderr "   Main.main not exported; not linking."
205         return (LinkOK pls1)
206    where
207       verb = verbosity dflags
208       getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
209
210 link' Interactive dflags batch_attempt_linking linkables pls
211     = do showPass dflags "Linking"
212          let (objs, bcos) = partition (isObject.head.linkableUnlinked) linkables
213          linkObjs (objs ++ bcos) pls
214            -- get the objects first
215
216 ppLinkableSCC :: SCC Linkable -> SDoc
217 ppLinkableSCC = ppr . flattenSCC
218
219 filterModuleLinkables :: (ModuleName -> Bool) -> [Linkable] -> [Linkable]
220 filterModuleLinkables p [] = []
221 filterModuleLinkables p (li:lis)
222    = case li of
223         LM _ modnm _ -> if p modnm then retain else dump
224      where
225         dump   = filterModuleLinkables p lis
226         retain = li : dump
227
228 -----------------------------------------------------------------------------
229 -- Linker for interactive mode
230
231 #ifndef GHCI
232 linkObjs      = panic "CmLink.linkObjs: no interpreter"
233 #else
234 linkObjs [] pls = linkFinish pls []
235 linkObjs (l@(LM _ m uls) : ls) pls
236    | all isObject uls = do
237         if isLoaded l pls then linkObjs ls pls else do
238         let objs = [ file | DotO file <- uls ] 
239         mapM_ loadObj objs
240         linkObjs ls pls{objects_loaded = l : objects_loaded pls}
241    | all isInterpretable uls  = linkInterpretedCode (l:ls) [] pls
242    | otherwise                = invalidLinkable
243
244 isLoaded :: Linkable -> PersistentLinkerState -> Bool
245 isLoaded l pls = 
246   case findModuleLinkable_maybe (objects_loaded pls) (linkableModName l) of
247         Nothing -> False
248         Just m  -> linkableTime l == linkableTime m
249  
250 linkInterpretedCode [] ul_trees pls = linkFinish pls ul_trees
251 linkInterpretedCode (l@(LM _ m uls) : ls) ul_trees pls
252    | all isInterpretable uls = 
253         if isLoaded l pls then linkInterpretedCode ls ul_trees pls else
254         linkInterpretedCode ls (uls++ul_trees) 
255                 pls{objects_loaded = l : objects_loaded pls}
256    | any isObject uls
257         = throwDyn (OtherError 
258              "can't link object code that depends on interpreted code")
259    | otherwise = invalidLinkable
260
261 invalidLinkable = panic "CmLink: linkable doesn't contain entirely objects or interpreted code"
262
263
264 -- link all the interpreted code in one go.
265 linkFinish pls ul_bcos = do
266    resolveObjs
267
268    let stuff = [ (bcos,itbls) | BCOs bcos itbls <- ul_bcos ]
269
270    (ibinds, new_itbl_env, new_closure_env) <-
271         linkIModules (itbl_env pls) (closure_env pls) stuff
272
273    let new_pls = pls { closure_env = new_closure_env,
274                        itbl_env    = new_itbl_env
275                      }
276    return (LinkOK new_pls)
277
278 linkExpr :: PersistentLinkerState -> UnlinkedBCOExpr -> IO HValue
279 linkExpr PersistentLinkerState{ itbl_env = ie, closure_env = ce } bcos
280   = linkIExpr ie ce bcos
281 #endif
282 \end{code}