c925735c0473f4687b1dec1e78a044590a30a321
[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      ( 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 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 :: Module
405              -> IORef NameCache -- For allocating new unique names
406              -> IdEnv Bool      -- Domain = Ids that should be external
407                                 -- True <=> their unfolding is external too
408              -> TidyEnv -> [CoreBind]
409              -> IO (TidyEnv, [CoreBind])
410 tidyTopBinds mod nc_var ext_ids tidy_env []
411   = return (tidy_env, [])
412
413 tidyTopBinds mod nc_var ext_ids tidy_env (b:bs)
414   = do  { (tidy_env1, b')  <- tidyTopBind  mod nc_var ext_ids tidy_env b
415         ; (tidy_env2, bs') <- tidyTopBinds mod nc_var ext_ids tidy_env1 bs
416         ; return (tidy_env2, b':bs') }
417
418 ------------------------
419 tidyTopBind :: Module
420              -> IORef NameCache -- For allocating new unique names
421              -> IdEnv Bool      -- Domain = Ids that should be external
422                                 -- True <=> their unfolding is external too
423              -> TidyEnv -> CoreBind
424              -> IO (TidyEnv, CoreBind)
425
426 tidyTopBind mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (NonRec bndr rhs)
427   = do  { (occ_env2, name') <- tidyTopName mod nc_var ext_ids occ_env1 bndr
428         ; let   { (bndr', rhs') = tidyTopPair ext_ids tidy_env2 caf_info name' (bndr, rhs)
429                 ; subst2        = extendVarEnv subst1 bndr bndr'
430                 ; tidy_env2     = (occ_env2, subst2) }
431         ; return (tidy_env2, NonRec bndr' rhs') }
432   where
433     caf_info = hasCafRefs subst1 (idArity bndr) rhs
434
435 tidyTopBind mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (Rec prs)
436   = do  { (occ_env2, names') <- tidyTopNames mod nc_var ext_ids occ_env1 bndrs
437         ; let   { prs'      = zipWith (tidyTopPair ext_ids tidy_env2 caf_info)
438                                       names' prs
439                 ; subst2    = extendVarEnvList subst1 (bndrs `zip` map fst prs')
440                 ; tidy_env2 = (occ_env2, subst2) }
441         ; return (tidy_env2, Rec prs') }
442   where
443     bndrs = map fst prs
444
445         -- the CafInfo for a recursive group says whether *any* rhs in
446         -- the group may refer indirectly to a CAF (because then, they all do).
447     caf_info 
448         | or [ mayHaveCafRefs (hasCafRefs subst1 (idArity bndr) rhs)
449              | (bndr,rhs) <- prs ] = MayHaveCafRefs
450         | otherwise                = NoCafRefs
451
452 --------------------------------------------------------------------
453 --              tidyTopName
454 -- This is where we set names to local/global based on whether they really are 
455 -- externally visible (see comment at the top of this module).  If the name
456 -- was previously local, we have to give it a unique occurrence name if
457 -- we intend to externalise it.
458 tidyTopNames mod nc_var ext_ids occ_env [] = return (occ_env, [])
459 tidyTopNames mod nc_var ext_ids occ_env (id:ids)
460   = do  { (occ_env1, name)  <- tidyTopName  mod nc_var ext_ids occ_env id
461         ; (occ_env2, names) <- tidyTopNames mod nc_var ext_ids occ_env1 ids
462         ; return (occ_env2, name:names) }
463
464 tidyTopName :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
465             -> Id -> IO (TidyOccEnv, Name)
466 tidyTopName mod nc_var ext_ids occ_env id
467   | global && internal = return (occ_env, localiseName name)
468
469   | global && external = return (occ_env, name)
470         -- Global names are assumed to have been allocated by the renamer,
471         -- so they already have the "right" unique
472         -- And it's a system-wide unique too
473
474   -- Now we get to the real reason that all this is in the IO Monad:
475   -- we have to update the name cache in a nice atomic fashion
476
477   | local  && internal = do { nc <- readIORef nc_var
478                             ; let (nc', new_local_name) = mk_new_local nc
479                             ; writeIORef nc_var nc'
480                             ; return (occ_env', new_local_name) }
481         -- Even local, internal names must get a unique occurrence, because
482         -- if we do -split-objs we externalise the name later, in the code generator
483         --
484         -- Similarly, we must make sure it has a system-wide Unique, because
485         -- the byte-code generator builds a system-wide Name->BCO symbol table
486
487   | local  && external = do { nc <- readIORef nc_var
488                             ; let (nc', new_external_name) = mk_new_external nc
489                             ; writeIORef nc_var nc'
490                             ; return (occ_env', new_external_name) }
491   where
492     name        = idName id
493     external    = id `elemVarEnv` ext_ids
494     global      = isExternalName name
495     local       = not global
496     internal    = not external
497     mb_parent   = nameParent_maybe name
498     loc         = nameSrcLoc name
499
500     (occ_env', occ') = tidyOccName occ_env (nameOccName name)
501
502     mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
503                     where
504                       (us1, us2) = splitUniqSupply (nsUniqs nc)
505                       uniq       = uniqFromSupply us1
506
507     mk_new_external nc = allocateGlobalBinder nc mod occ' mb_parent loc
508         -- If we want to externalise a currently-local name, check
509         -- whether we have already assigned a unique for it.
510         -- If so, use it; if not, extend the table.
511         -- All this is done by allcoateGlobalBinder.
512         -- This is needed when *re*-compiling a module in GHCi; we want to
513         -- use the same name for externally-visible things as we did before.
514
515
516 -----------------------------------------------------------
517 tidyTopPair :: VarEnv Bool
518             -> TidyEnv  -- The TidyEnv is used to tidy the IdInfo
519                         -- It is knot-tied: don't look at it!
520             -> CafInfo
521             -> Name             -- New name
522             -> (Id, CoreExpr)   -- Binder and RHS before tidying
523             -> (Id, CoreExpr)
524         -- This function is the heart of Step 2
525         -- The rec_tidy_env is the one to use for the IdInfo
526         -- It's necessary because when we are dealing with a recursive
527         -- group, a variable late in the group might be mentioned
528         -- in the IdInfo of one early in the group
529
530 tidyTopPair ext_ids rhs_tidy_env caf_info name' (bndr, rhs)
531   = ASSERT(isLocalId bndr)  -- "all Ids defined in this module are local
532                             -- until the CoreTidy phase"  --GHC comentary
533     (bndr', rhs')
534   where
535     bndr'   = mkVanillaGlobal name' ty' idinfo'
536     ty'     = tidyTopType (idType bndr)
537     rhs'    = tidyExpr rhs_tidy_env rhs
538     idinfo' = tidyTopIdInfo rhs_tidy_env (isJust maybe_external)
539                             (idInfo bndr) unfold_info arity
540                             caf_info
541
542     -- Expose an unfolding if ext_ids tells us to
543     -- Remember that ext_ids maps an Id to a Bool: 
544     --  True to show the unfolding, False to hide it
545     maybe_external = lookupVarEnv ext_ids bndr
546     show_unfold = maybe_external `orElse` False
547     unfold_info | show_unfold = mkTopUnfolding rhs'
548                 | otherwise   = noUnfolding
549
550     -- Usually the Id will have an accurate arity on it, because
551     -- the simplifier has just run, but not always. 
552     -- One case I found was when the last thing the simplifier
553     -- did was to let-bind a non-atomic argument and then float
554     -- it to the top level. So it seems more robust just to
555     -- fix it here.
556     arity = exprArity rhs
557
558
559 -- tidyTopIdInfo creates the final IdInfo for top-level
560 -- binders.  There are two delicate pieces:
561 --
562 --  * Arity.  After CoreTidy, this arity must not change any more.
563 --      Indeed, CorePrep must eta expand where necessary to make
564 --      the manifest arity equal to the claimed arity.
565 --
566 --  * CAF info.  This must also remain valid through to code generation.
567 --      We add the info here so that it propagates to all
568 --      occurrences of the binders in RHSs, and hence to occurrences in
569 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
570 --      CoreToStg makes use of this when constructing SRTs.
571
572 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity caf_info
573   | not is_external     -- For internal Ids (not externally visible)
574   = vanillaIdInfo       -- we only need enough info for code generation
575                         -- Arity and strictness info are enough;
576                         --      c.f. CoreTidy.tidyLetBndr
577         `setCafInfo`           caf_info
578         `setArityInfo`         arity
579         `setAllStrictnessInfo` newStrictnessInfo idinfo
580
581   | otherwise           -- Externally-visible Ids get the whole lot
582   = vanillaIdInfo
583         `setCafInfo`           caf_info
584         `setArityInfo`         arity
585         `setAllStrictnessInfo` newStrictnessInfo idinfo
586         `setInlinePragInfo`    inlinePragInfo idinfo
587         `setUnfoldingInfo`     unfold_info
588         `setWorkerInfo`        tidyWorker tidy_env (workerInfo idinfo)
589                 -- NB: we throw away the Rules
590                 -- They have already been extracted by findExternalRules
591
592
593
594 ------------  Worker  --------------
595 tidyWorker tidy_env (HasWorker work_id wrap_arity) 
596   = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
597 tidyWorker tidy_env other
598   = NoWorker
599 \end{code}
600
601 %************************************************************************
602 %*                                                                      *
603 \subsection{Figuring out CafInfo for an expression}
604 %*                                                                      *
605 %************************************************************************
606
607 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
608 We mark such things as `MayHaveCafRefs' because this information is
609 used to decide whether a particular closure needs to be referenced
610 in an SRT or not.
611
612 There are two reasons for setting MayHaveCafRefs:
613         a) The RHS is a CAF: a top-level updatable thunk.
614         b) The RHS refers to something that MayHaveCafRefs
615
616 Possible improvement: In an effort to keep the number of CAFs (and 
617 hence the size of the SRTs) down, we could also look at the expression and 
618 decide whether it requires a small bounded amount of heap, so we can ignore 
619 it as a CAF.  In these cases however, we would need to use an additional
620 CAF list to keep track of non-collectable CAFs.  
621
622 \begin{code}
623 hasCafRefs  :: VarEnv Var -> Arity -> CoreExpr -> CafInfo
624 hasCafRefs p arity expr 
625   | is_caf || mentions_cafs = MayHaveCafRefs
626   | otherwise               = NoCafRefs
627  where
628   mentions_cafs = isFastTrue (cafRefs p expr)
629   is_caf = not (arity > 0 || rhsIsStatic expr)
630   -- NB. we pass in the arity of the expression, which is expected
631   -- to be calculated by exprArity.  This is because exprArity
632   -- knows how much eta expansion is going to be done by 
633   -- CorePrep later on, and we don't want to duplicate that
634   -- knowledge in rhsIsStatic below.
635
636 cafRefs p (Var id)
637         -- imported Ids first:
638   | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
639         -- now Ids local to this module:
640   | otherwise =
641      case lookupVarEnv p id of
642         Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
643         Nothing  -> fastBool False
644
645 cafRefs p (Lit l)            = fastBool False
646 cafRefs p (App f a)          = fastOr (cafRefs p f) (cafRefs p) a
647 cafRefs p (Lam x e)          = cafRefs p e
648 cafRefs p (Let b e)          = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
649 -- gaw 2004
650 cafRefs p (Case e bndr _ alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
651 cafRefs p (Note n e)         = cafRefs p e
652 cafRefs p (Type t)           = fastBool False
653
654 cafRefss p []     = fastBool False
655 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
656
657 -- hack for lazy-or over FastBool.
658 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))
659 \end{code}