[project @ 2004-11-26 16:19:45 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / TidyPgm.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Tidying up Core}
5
6 \begin{code}
7 module TidyPgm( tidyCorePgm, tidyCoreExpr ) where
8
9 #include "HsVersions.h"
10
11 import CmdLineOpts      ( DynFlags, DynFlag(..), dopt )
12 import CoreSyn
13 import CoreUnfold       ( noUnfolding, mkTopUnfolding )
14 import CoreFVs          ( ruleLhsFreeIds, exprSomeFreeVars )
15 import CoreTidy         ( tidyExpr, tidyVarOcc, tidyIdRules )
16 import PprCore          ( pprIdRules )
17 import CoreLint         ( showPass, endPass )
18 import CoreUtils        ( exprArity, rhsIsStatic )
19 import VarEnv
20 import VarSet
21 import Var              ( Id, Var )
22 import Id               ( idType, idInfo, idName, idCoreRules, 
23                           isExportedId, mkVanillaGlobal, isLocalId, 
24                           isImplicitId, idArity, setIdInfo, idCafInfo
25                         ) 
26 import IdInfo           {- loads of stuff -}
27 import NewDemand        ( isBottomingSig, topSig )
28 import BasicTypes       ( Arity, isNeverActive )
29 import Name             ( Name, getOccName, nameOccName, mkInternalName,
30                           localiseName, isExternalName, nameSrcLoc, nameParent_maybe
31                         )
32 import IfaceEnv         ( allocateGlobalBinder )
33 import NameEnv          ( lookupNameEnv, filterNameEnv )
34 import OccName          ( TidyOccEnv, initTidyOccEnv, tidyOccName )
35 import Type             ( tidyTopType )
36 import Module           ( Module )
37 import HscTypes         ( HscEnv(..), NameCache( nsUniqs ),
38                           TypeEnv, extendTypeEnvList, typeEnvIds,
39                           ModGuts(..), ModGuts, TyThing(..)
40                         )
41 import Maybes           ( orElse )
42 import ErrUtils         ( showPass, dumpIfSet_core )
43 import UniqFM           ( mapUFM )
44 import UniqSupply       ( splitUniqSupply, uniqFromSupply )
45 import List             ( partition )
46 import Maybe            ( isJust )
47 import Outputable
48 import DATA_IOREF       ( IORef, readIORef, writeIORef )
49 import FastTypes  hiding ( fastOr )
50 \end{code}
51
52
53 %************************************************************************
54 %*                                                                      *
55 \subsection{What goes on}
56 %*                                                                      * 
57 %************************************************************************
58
59 [SLPJ: 19 Nov 00]
60
61 The plan is this.  
62
63 Step 1: Figure out external Ids
64 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
65 First we figure out which Ids are "external" Ids.  An
66 "external" Id is one that is visible from outside the compilation
67 unit.  These are
68         a) the user exported ones
69         b) ones mentioned in the unfoldings, workers, 
70            or rules of externally-visible ones 
71 This exercise takes a sweep of the bindings bottom to top.  Actually,
72 in Step 2 we're also going to need to know which Ids should be
73 exported with their unfoldings, so we produce not an IdSet but an
74 IdEnv Bool
75
76
77 Step 2: Tidy the program
78 ~~~~~~~~~~~~~~~~~~~~~~~~
79 Next we traverse the bindings top to bottom.  For each *top-level*
80 binder
81
82  1. Make it into a GlobalId
83
84  2. Give it a system-wide Unique.
85     [Even non-exported things need system-wide Uniques because the
86     byte-code generator builds a single Name->BCO symbol table.]
87
88     We use the NameCache kept in the HscEnv as the
89     source of such system-wide uniques.
90
91     For external Ids, use the original-name cache in the NameCache
92     to ensure that the unique assigned is the same as the Id had 
93     in any previous compilation run.
94   
95  3. If it's an external Id, make it have a global Name, otherwise
96     make it have a local Name.
97     This is used by the code generator to decide whether
98     to make the label externally visible
99
100  4. Give external Ids a "tidy" occurrence name.  This means
101     we can print them in interface files without confusing 
102     "x" (unique 5) with "x" (unique 10).
103   
104  5. Give it its UTTERLY FINAL IdInfo; in ptic, 
105         * Its IdDetails becomes VanillaGlobal, reflecting the fact that
106           from now on we regard it as a global, not local, Id
107
108         * its unfolding, if it should have one
109         
110         * its arity, computed from the number of visible lambdas
111
112         * its CAF info, computed from what is free in its RHS
113
114                 
115 Finally, substitute these new top-level binders consistently
116 throughout, including in unfoldings.  We also tidy binders in
117 RHSs, so that they print nicely in interfaces.
118
119 \begin{code}
120 tidyCorePgm :: HscEnv -> ModGuts -> IO ModGuts
121
122 tidyCorePgm hsc_env
123             mod_impl@(ModGuts { mg_module = mod, 
124                                 mg_types = env_tc, mg_insts = insts_tc, 
125                                 mg_binds = binds_in, mg_rules = orphans_in })
126   = do  { let { dflags = hsc_dflags hsc_env
127               ; nc_var = hsc_NC hsc_env }
128         ; showPass dflags "Tidy Core"
129
130         ; let omit_iface_prags = dopt Opt_OmitInterfacePragmas dflags
131         ; let ext_ids   = findExternalSet   omit_iface_prags binds_in
132         ; let ext_rules = findExternalRules omit_iface_prags binds_in orphans_in ext_ids
133                 -- findExternalRules filters ext_rules to avoid binders that 
134                 -- aren't externally visible; but the externally-visible binders 
135                 -- are computed (by findExternalSet) assuming that all orphan
136                 -- rules are exported (they get their Exported flag set in the desugarer)
137                 -- So in fact we may export more than we need. 
138                 -- (It's a sort of mutual recursion.)
139
140         -- We also make sure to avoid any exported binders.  Consider
141         --      f{-u1-} = 1     -- Local decl
142         --      ...
143         --      f{-u2-} = 2     -- Exported decl
144         --
145         -- The second exported decl must 'get' the name 'f', so we
146         -- have to put 'f' in the avoids list before we get to the first
147         -- decl.  tidyTopId then does a no-op on exported binders.
148         ; let   init_env = (initTidyOccEnv avoids, emptyVarEnv)
149                 avoids   = [getOccName name | bndr <- typeEnvIds env_tc,
150                                                    let name = idName bndr,
151                                                    isExternalName name]
152                 -- In computing our "avoids" list, we must include
153                 --      all implicit Ids
154                 --      all things with global names (assigned once and for
155                 --                                      all by the renamer)
156                 -- since their names are "taken".
157                 -- The type environment is a convenient source of such things.
158
159         ; (final_env, tidy_binds)
160                 <- tidyTopBinds dflags mod nc_var ext_ids init_env binds_in
161
162         ; let tidy_rules = tidyIdRules final_env ext_rules
163
164         ; let tidy_type_env = mkFinalTypeEnv omit_iface_prags env_tc tidy_binds
165
166                 -- Dfuns are local Ids that might have
167                 -- changed their unique during tidying.  Remember
168                 -- to lookup the id in the TypeEnv too, because
169                 -- those Ids have had their IdInfo stripped if
170                 -- necessary.
171         ; let (_, subst_env ) = final_env
172               lookup_dfun_id id = 
173                  case lookupVarEnv subst_env id of
174                    Nothing -> dfun_panic
175                    Just id -> 
176                       case lookupNameEnv tidy_type_env (idName id) of
177                         Just (AnId id) -> id
178                         _other -> dfun_panic
179                 where 
180                    dfun_panic = pprPanic "lookup_dfun_id" (ppr id)
181
182               tidy_dfun_ids = map lookup_dfun_id insts_tc
183
184         ; let tidy_result = mod_impl { mg_types = tidy_type_env,
185                                        mg_rules = tidy_rules,
186                                        mg_insts = tidy_dfun_ids,
187                                        mg_binds = tidy_binds }
188
189         ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
190         ; dumpIfSet_core dflags Opt_D_dump_simpl
191                 "Tidy Core Rules"
192                 (pprIdRules tidy_rules)
193
194         ; return tidy_result
195         }
196
197 tidyCoreExpr :: CoreExpr -> IO CoreExpr
198 tidyCoreExpr expr = return (tidyExpr emptyTidyEnv expr)
199 \end{code}
200
201
202 %************************************************************************
203 %*                                                                      *
204 \subsection{Write a new interface file}
205 %*                                                                      *
206 %************************************************************************
207
208 \begin{code}
209 mkFinalTypeEnv :: Bool          -- Omit interface pragmas
210                -> TypeEnv       -- From typechecker
211                -> [CoreBind]    -- Final Ids
212                -> TypeEnv
213
214 -- The competed type environment is gotten from
215 --      a) keeping the types and classes
216 --      b) removing all Ids, 
217 --      c) adding Ids with correct IdInfo, including unfoldings,
218 --              gotten from the bindings
219 -- From (c) we keep only those Ids with External names;
220 --          the CoreTidy pass makes sure these are all and only
221 --          the externally-accessible ones
222 -- This truncates the type environment to include only the 
223 -- exported Ids and things needed from them, which saves space
224 --
225 -- However, we do keep things like constructors, which should not appear 
226 -- in interface files, because they are needed by importing modules when
227 -- using the compilation manager
228
229 mkFinalTypeEnv omit_iface_prags type_env tidy_binds
230   = extendTypeEnvList (filterNameEnv keep_it type_env) final_ids
231   where
232     final_ids  = [ AnId (strip_id_info id)
233                  | bind <- tidy_binds,
234                    id <- bindersOf bind,
235                    isExternalName (idName id)]
236
237     strip_id_info id
238           | omit_iface_prags = id `setIdInfo` vanillaIdInfo
239           | otherwise        = id
240         -- If the interface file has no pragma info then discard all
241         -- info right here.
242         --
243         -- This is not so important for *this* module, but it's
244         -- vital for ghc --make:
245         --   subsequent compilations must not see (e.g.) the arity if
246         --   the interface file does not contain arity
247         -- If they do, they'll exploit the arity; then the arity might
248         -- change, but the iface file doesn't change => recompilation
249         -- does not happen => disaster
250         --
251         -- This IdInfo will live long-term in the Id => vanillaIdInfo makes
252         -- a conservative assumption about Caf-hood
253         -- 
254         -- We're not worried about occurrences of these Ids in unfoldings,
255         -- because in OmitInterfacePragmas mode we're stripping all the
256         -- unfoldings anyway.
257
258         -- We keep implicit Ids, because they won't appear 
259         -- in the bindings from which final_ids are derived!
260     keep_it (AnId id) = isImplicitId id -- Remove all Ids except implicit ones
261     keep_it other     = True            -- Keep all TyCons and Classes
262 \end{code}
263
264 \begin{code}
265 findExternalRules :: Bool         -- Omit interface pragmas 
266                   -> [CoreBind]
267                   -> [IdCoreRule] -- Orphan rules
268                   -> IdEnv a      -- Ids that are exported, so we need their rules
269                   -> [IdCoreRule]
270   -- The complete rules are gotten by combining
271   --    a) the orphan rules
272   --    b) rules embedded in the top-level Ids
273 findExternalRules omit_iface_prags binds orphan_rules ext_ids
274   | omit_iface_prags = []
275   | otherwise
276   = filter (not . internal_rule) (orphan_rules ++ local_rules)
277   where
278     local_rules  = [ rule
279                    | id <- bindersOfBinds binds,
280                      id `elemVarEnv` ext_ids,
281                      rule <- idCoreRules id
282                    ]
283     internal_rule (IdCoreRule id is_orphan rule)
284         =  isBuiltinRule rule
285                 -- We can't print builtin rules in interface files
286                 -- Since they are built in, an importing module
287                 -- will have access to them anyway
288
289         || (not is_orphan && internal_id id)
290                 -- Rule for an Id in this module; internal if the
291                 -- Id is not exported
292
293         || any internal_id (varSetElems (ruleLhsFreeIds rule))
294                 -- Don't export a rule whose LHS mentions an Id that
295                 -- is completely internal (i.e. not visible to an
296                 -- importing module)
297
298     internal_id id = not (id `elemVarEnv` ext_ids)
299 \end{code}
300
301 %************************************************************************
302 %*                                                                      *
303 \subsection{Step 1: finding externals}
304 %*                                                                      * 
305 %************************************************************************
306
307 \begin{code}
308 findExternalSet :: Bool         -- Omit interface pragmas
309                 -> [CoreBind]
310                 -> IdEnv Bool   -- In domain => external
311                                 -- Range = True <=> show unfolding
312         -- Step 1 from the notes above
313 findExternalSet omit_iface_prags binds
314   = foldr find emptyVarEnv binds
315   where
316     find (NonRec id rhs) needed
317         | need_id needed id = addExternal omit_iface_prags (id,rhs) needed
318         | otherwise         = needed
319     find (Rec prs) needed   = find_prs prs needed
320
321         -- For a recursive group we have to look for a fixed point
322     find_prs prs needed 
323         | null needed_prs = needed
324         | otherwise       = find_prs other_prs new_needed
325         where
326           (needed_prs, other_prs) = partition (need_pr needed) prs
327           new_needed = foldr (addExternal omit_iface_prags) needed needed_prs
328
329         -- The 'needed' set contains the Ids that are needed by earlier
330         -- interface file emissions.  If the Id isn't in this set, and isn't
331         -- exported, there's no need to emit anything
332     need_id needed_set id       = id `elemVarEnv` needed_set || isExportedId id 
333     need_pr needed_set (id,rhs) = need_id needed_set id
334
335 addExternal :: Bool -> (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
336 -- The Id is needed; extend the needed set
337 -- with it and its dependents (free vars etc)
338 addExternal omit_iface_prags (id,rhs) needed
339   = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
340                  id show_unfold
341   where
342     add_occ id needed = extendVarEnv needed id False
343         -- "False" because we don't know we need the Id's unfolding
344         -- We'll override it later when we find the binding site
345
346     new_needed_ids | omit_iface_prags = emptyVarSet
347                    | otherwise        = worker_ids      `unionVarSet`
348                                         unfold_ids      `unionVarSet`
349                                         spec_ids
350
351     idinfo         = idInfo id
352     dont_inline    = isNeverActive (inlinePragInfo idinfo)
353     loop_breaker   = isLoopBreaker (occInfo idinfo)
354     bottoming_fn   = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
355     spec_ids       = rulesRhsFreeVars (specInfo idinfo)
356     worker_info    = workerInfo idinfo
357
358         -- Stuff to do with the Id's unfolding
359         -- The simplifier has put an up-to-date unfolding
360         -- in the IdInfo, but the RHS will do just as well
361     unfolding    = unfoldingInfo idinfo
362     rhs_is_small = not (neverUnfold unfolding)
363
364         -- We leave the unfolding there even if there is a worker
365         -- In GHCI the unfolding is used by importers
366         -- When writing an interface file, we omit the unfolding 
367         -- if there is a worker
368     show_unfold = not bottoming_fn       &&     -- Not necessary
369                   not dont_inline        &&
370                   not loop_breaker       &&
371                   rhs_is_small                  -- Small enough
372
373     unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
374                | otherwise   = emptyVarSet
375
376     worker_ids = case worker_info of
377                    HasWorker work_id _ -> unitVarSet work_id
378                    otherwise           -> emptyVarSet
379 \end{code}
380
381
382 %************************************************************************
383 %*                                                                      *
384 \subsection{Step 2: top-level tidying}
385 %*                                                                      *
386 %************************************************************************
387
388
389 \begin{code}
390 -- TopTidyEnv: when tidying we need to know
391 --   * nc_var: The NameCache, containing a unique supply and any pre-ordained Names.  
392 --        These may have arisen because the
393 --        renamer read in an interface file mentioning M.$wf, say,
394 --        and assigned it unique r77.  If, on this compilation, we've
395 --        invented an Id whose name is $wf (but with a different unique)
396 --        we want to rename it to have unique r77, so that we can do easy
397 --        comparisons with stuff from the interface file
398 --
399 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
400 --     are 'used'
401 --
402 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
403
404 tidyTopBinds :: DynFlags
405              -> Module
406              -> IORef NameCache -- For allocating new unique names
407              -> IdEnv Bool      -- Domain = Ids that should be external
408                                 -- True <=> their unfolding is external too
409              -> TidyEnv -> [CoreBind]
410              -> IO (TidyEnv, [CoreBind])
411 tidyTopBinds dflags mod nc_var ext_ids tidy_env []
412   = return (tidy_env, [])
413
414 tidyTopBinds dflags mod nc_var ext_ids tidy_env (b:bs)
415   = do  { (tidy_env1, b')  <- tidyTopBind  dflags mod nc_var ext_ids tidy_env b
416         ; (tidy_env2, bs') <- tidyTopBinds dflags mod nc_var ext_ids tidy_env1 bs
417         ; return (tidy_env2, b':bs') }
418
419 ------------------------
420 tidyTopBind  :: DynFlags
421              -> Module
422              -> IORef NameCache -- For allocating new unique names
423              -> IdEnv Bool      -- Domain = Ids that should be external
424                                 -- True <=> their unfolding is external too
425              -> TidyEnv -> CoreBind
426              -> IO (TidyEnv, CoreBind)
427
428 tidyTopBind dflags mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (NonRec bndr rhs)
429   = do  { (occ_env2, name') <- tidyTopName mod nc_var ext_ids occ_env1 bndr
430         ; let   { (bndr', rhs') = tidyTopPair ext_ids tidy_env2 caf_info name' (bndr, rhs)
431                 ; subst2        = extendVarEnv subst1 bndr bndr'
432                 ; tidy_env2     = (occ_env2, subst2) }
433         ; return (tidy_env2, NonRec bndr' rhs') }
434   where
435     caf_info = hasCafRefs dflags subst1 (idArity bndr) rhs
436
437 tidyTopBind dflags mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (Rec prs)
438   = do  { (occ_env2, names') <- tidyTopNames mod nc_var ext_ids occ_env1 bndrs
439         ; let   { prs'      = zipWith (tidyTopPair ext_ids tidy_env2 caf_info)
440                                       names' prs
441                 ; subst2    = extendVarEnvList subst1 (bndrs `zip` map fst prs')
442                 ; tidy_env2 = (occ_env2, subst2) }
443         ; return (tidy_env2, Rec prs') }
444   where
445     bndrs = map fst prs
446
447         -- the CafInfo for a recursive group says whether *any* rhs in
448         -- the group may refer indirectly to a CAF (because then, they all do).
449     caf_info 
450         | or [ mayHaveCafRefs (hasCafRefs dflags subst1 (idArity bndr) rhs)
451              | (bndr,rhs) <- prs ] = MayHaveCafRefs
452         | otherwise                = NoCafRefs
453
454 --------------------------------------------------------------------
455 --              tidyTopName
456 -- This is where we set names to local/global based on whether they really are 
457 -- externally visible (see comment at the top of this module).  If the name
458 -- was previously local, we have to give it a unique occurrence name if
459 -- we intend to externalise it.
460 tidyTopNames mod nc_var ext_ids occ_env [] = return (occ_env, [])
461 tidyTopNames mod nc_var ext_ids occ_env (id:ids)
462   = do  { (occ_env1, name)  <- tidyTopName  mod nc_var ext_ids occ_env id
463         ; (occ_env2, names) <- tidyTopNames mod nc_var ext_ids occ_env1 ids
464         ; return (occ_env2, name:names) }
465
466 tidyTopName :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
467             -> Id -> IO (TidyOccEnv, Name)
468 tidyTopName mod nc_var ext_ids occ_env id
469   | global && internal = return (occ_env, localiseName name)
470
471   | global && external = return (occ_env, name)
472         -- Global names are assumed to have been allocated by the renamer,
473         -- so they already have the "right" unique
474         -- And it's a system-wide unique too
475
476   -- Now we get to the real reason that all this is in the IO Monad:
477   -- we have to update the name cache in a nice atomic fashion
478
479   | local  && internal = do { nc <- readIORef nc_var
480                             ; let (nc', new_local_name) = mk_new_local nc
481                             ; writeIORef nc_var nc'
482                             ; return (occ_env', new_local_name) }
483         -- Even local, internal names must get a unique occurrence, because
484         -- if we do -split-objs we externalise the name later, in the code generator
485         --
486         -- Similarly, we must make sure it has a system-wide Unique, because
487         -- the byte-code generator builds a system-wide Name->BCO symbol table
488
489   | local  && external = do { nc <- readIORef nc_var
490                             ; let (nc', new_external_name) = mk_new_external nc
491                             ; writeIORef nc_var nc'
492                             ; return (occ_env', new_external_name) }
493   where
494     name        = idName id
495     external    = id `elemVarEnv` ext_ids
496     global      = isExternalName name
497     local       = not global
498     internal    = not external
499     mb_parent   = nameParent_maybe name
500     loc         = nameSrcLoc name
501
502     (occ_env', occ') = tidyOccName occ_env (nameOccName name)
503
504     mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
505                     where
506                       (us1, us2) = splitUniqSupply (nsUniqs nc)
507                       uniq       = uniqFromSupply us1
508
509     mk_new_external nc = allocateGlobalBinder nc mod occ' mb_parent loc
510         -- If we want to externalise a currently-local name, check
511         -- whether we have already assigned a unique for it.
512         -- If so, use it; if not, extend the table.
513         -- All this is done by allcoateGlobalBinder.
514         -- This is needed when *re*-compiling a module in GHCi; we want to
515         -- use the same name for externally-visible things as we did before.
516
517
518 -----------------------------------------------------------
519 tidyTopPair :: VarEnv Bool
520             -> TidyEnv  -- The TidyEnv is used to tidy the IdInfo
521                         -- It is knot-tied: don't look at it!
522             -> CafInfo
523             -> Name             -- New name
524             -> (Id, CoreExpr)   -- Binder and RHS before tidying
525             -> (Id, CoreExpr)
526         -- This function is the heart of Step 2
527         -- The rec_tidy_env is the one to use for the IdInfo
528         -- It's necessary because when we are dealing with a recursive
529         -- group, a variable late in the group might be mentioned
530         -- in the IdInfo of one early in the group
531
532 tidyTopPair ext_ids rhs_tidy_env caf_info name' (bndr, rhs)
533   = ASSERT(isLocalId bndr)  -- "all Ids defined in this module are local
534                             -- until the CoreTidy phase"  --GHC comentary
535     (bndr', rhs')
536   where
537     bndr'   = mkVanillaGlobal name' ty' idinfo'
538     ty'     = tidyTopType (idType bndr)
539     rhs'    = tidyExpr rhs_tidy_env rhs
540     idinfo' = tidyTopIdInfo rhs_tidy_env (isJust maybe_external)
541                             (idInfo bndr) unfold_info arity
542                             caf_info
543
544     -- Expose an unfolding if ext_ids tells us to
545     -- Remember that ext_ids maps an Id to a Bool: 
546     --  True to show the unfolding, False to hide it
547     maybe_external = lookupVarEnv ext_ids bndr
548     show_unfold = maybe_external `orElse` False
549     unfold_info | show_unfold = mkTopUnfolding rhs'
550                 | otherwise   = noUnfolding
551
552     -- Usually the Id will have an accurate arity on it, because
553     -- the simplifier has just run, but not always. 
554     -- One case I found was when the last thing the simplifier
555     -- did was to let-bind a non-atomic argument and then float
556     -- it to the top level. So it seems more robust just to
557     -- fix it here.
558     arity = exprArity rhs
559
560
561 -- tidyTopIdInfo creates the final IdInfo for top-level
562 -- binders.  There are two delicate pieces:
563 --
564 --  * Arity.  After CoreTidy, this arity must not change any more.
565 --      Indeed, CorePrep must eta expand where necessary to make
566 --      the manifest arity equal to the claimed arity.
567 --
568 --  * CAF info.  This must also remain valid through to code generation.
569 --      We add the info here so that it propagates to all
570 --      occurrences of the binders in RHSs, and hence to occurrences in
571 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
572 --      CoreToStg makes use of this when constructing SRTs.
573
574 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity caf_info
575   | not is_external     -- For internal Ids (not externally visible)
576   = vanillaIdInfo       -- we only need enough info for code generation
577                         -- Arity and strictness info are enough;
578                         --      c.f. CoreTidy.tidyLetBndr
579         `setCafInfo`           caf_info
580         `setArityInfo`         arity
581         `setAllStrictnessInfo` newStrictnessInfo idinfo
582
583   | otherwise           -- Externally-visible Ids get the whole lot
584   = vanillaIdInfo
585         `setCafInfo`           caf_info
586         `setArityInfo`         arity
587         `setAllStrictnessInfo` newStrictnessInfo idinfo
588         `setInlinePragInfo`    inlinePragInfo idinfo
589         `setUnfoldingInfo`     unfold_info
590         `setWorkerInfo`        tidyWorker tidy_env (workerInfo idinfo)
591                 -- NB: we throw away the Rules
592                 -- They have already been extracted by findExternalRules
593
594
595
596 ------------  Worker  --------------
597 tidyWorker tidy_env (HasWorker work_id wrap_arity) 
598   = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
599 tidyWorker tidy_env other
600   = NoWorker
601 \end{code}
602
603 %************************************************************************
604 %*                                                                      *
605 \subsection{Figuring out CafInfo for an expression}
606 %*                                                                      *
607 %************************************************************************
608
609 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
610 We mark such things as `MayHaveCafRefs' because this information is
611 used to decide whether a particular closure needs to be referenced
612 in an SRT or not.
613
614 There are two reasons for setting MayHaveCafRefs:
615         a) The RHS is a CAF: a top-level updatable thunk.
616         b) The RHS refers to something that MayHaveCafRefs
617
618 Possible improvement: In an effort to keep the number of CAFs (and 
619 hence the size of the SRTs) down, we could also look at the expression and 
620 decide whether it requires a small bounded amount of heap, so we can ignore 
621 it as a CAF.  In these cases however, we would need to use an additional
622 CAF list to keep track of non-collectable CAFs.  
623
624 \begin{code}
625 hasCafRefs  :: DynFlags -> VarEnv Var -> Arity -> CoreExpr -> CafInfo
626 hasCafRefs dflags p arity expr 
627   | is_caf || mentions_cafs = MayHaveCafRefs
628   | otherwise               = NoCafRefs
629  where
630   mentions_cafs = isFastTrue (cafRefs p expr)
631   is_caf = not (arity > 0 || rhsIsStatic dflags expr)
632   -- NB. we pass in the arity of the expression, which is expected
633   -- to be calculated by exprArity.  This is because exprArity
634   -- knows how much eta expansion is going to be done by 
635   -- CorePrep later on, and we don't want to duplicate that
636   -- knowledge in rhsIsStatic below.
637
638 cafRefs p (Var id)
639         -- imported Ids first:
640   | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
641         -- now Ids local to this module:
642   | otherwise =
643      case lookupVarEnv p id of
644         Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
645         Nothing  -> fastBool False
646
647 cafRefs p (Lit l)            = fastBool False
648 cafRefs p (App f a)          = fastOr (cafRefs p f) (cafRefs p) a
649 cafRefs p (Lam x e)          = cafRefs p e
650 cafRefs p (Let b e)          = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
651 -- gaw 2004
652 cafRefs p (Case e bndr _ alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
653 cafRefs p (Note n e)         = cafRefs p e
654 cafRefs p (Type t)           = fastBool False
655
656 cafRefss p []     = fastBool False
657 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
658
659 -- hack for lazy-or over FastBool.
660 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))
661 \end{code}