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