73ef49d5d9757b103a2569fa91ea5e37acf1ad3f
[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 DynFlags ( 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 UniqSupply       ( splitUniqSupply, uniqFromSupply )
44 import List             ( partition )
45 import Maybe            ( isJust )
46 import Outputable
47 import DATA_IOREF       ( IORef, readIORef, writeIORef )
48 import FastTypes  hiding ( fastOr )
49 \end{code}
50
51
52 %************************************************************************
53 %*                                                                      *
54 \subsection{What goes on}
55 %*                                                                      * 
56 %************************************************************************
57
58 [SLPJ: 19 Nov 00]
59
60 The plan is this.  
61
62 Step 1: Figure out external Ids
63 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
64 First we figure out which Ids are "external" Ids.  An
65 "external" Id is one that is visible from outside the compilation
66 unit.  These are
67         a) the user exported ones
68         b) ones mentioned in the unfoldings, workers, 
69            or rules of externally-visible ones 
70 This exercise takes a sweep of the bindings bottom to top.  Actually,
71 in Step 2 we're also going to need to know which Ids should be
72 exported with their unfoldings, so we produce not an IdSet but an
73 IdEnv Bool
74
75
76 Step 2: Tidy the program
77 ~~~~~~~~~~~~~~~~~~~~~~~~
78 Next we traverse the bindings top to bottom.  For each *top-level*
79 binder
80
81  1. Make it into a GlobalId
82
83  2. Give it a system-wide Unique.
84     [Even non-exported things need system-wide Uniques because the
85     byte-code generator builds a single Name->BCO symbol table.]
86
87     We use the NameCache kept in the HscEnv as the
88     source of such system-wide uniques.
89
90     For external Ids, use the original-name cache in the NameCache
91     to ensure that the unique assigned is the same as the Id had 
92     in any previous compilation run.
93   
94  3. If it's an external Id, make it have a global Name, otherwise
95     make it have a local Name.
96     This is used by the code generator to decide whether
97     to make the label externally visible
98
99  4. Give external Ids a "tidy" occurrence name.  This means
100     we can print them in interface files without confusing 
101     "x" (unique 5) with "x" (unique 10).
102   
103  5. Give it its UTTERLY FINAL IdInfo; in ptic, 
104         * Its IdDetails becomes VanillaGlobal, reflecting the fact that
105           from now on we regard it as a global, not local, Id
106
107         * its unfolding, if it should have one
108         
109         * its arity, computed from the number of visible lambdas
110
111         * its CAF info, computed from what is free in its RHS
112
113                 
114 Finally, substitute these new top-level binders consistently
115 throughout, including in unfoldings.  We also tidy binders in
116 RHSs, so that they print nicely in interfaces.
117
118 \begin{code}
119 tidyCorePgm :: HscEnv -> ModGuts -> IO ModGuts
120
121 tidyCorePgm hsc_env
122             mod_impl@(ModGuts { mg_module = mod, 
123                                 mg_types = env_tc, mg_insts = insts_tc, 
124                                 mg_binds = binds_in, mg_rules = orphans_in })
125   = do  { let { dflags = hsc_dflags hsc_env
126               ; nc_var = hsc_NC hsc_env }
127         ; showPass dflags "Tidy Core"
128
129         ; let omit_iface_prags = dopt Opt_OmitInterfacePragmas dflags
130         ; let ext_ids   = findExternalSet   omit_iface_prags binds_in
131         ; let ext_rules = findExternalRules omit_iface_prags binds_in orphans_in ext_ids
132                 -- findExternalRules filters ext_rules to avoid binders that 
133                 -- aren't externally visible; but the externally-visible binders 
134                 -- are computed (by findExternalSet) assuming that all orphan
135                 -- rules are exported (they get their Exported flag set in the desugarer)
136                 -- So in fact we may export more than we need. 
137                 -- (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 dflags 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 (not . internal_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     internal_rule (IdCoreRule id is_orphan rule)
283         =  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 is_orphan && internal_id id)
289                 -- Rule for an Id in this module; internal if the
290                 -- Id is not exported
291
292         || any internal_id (varSetElems (ruleLhsFreeIds rule))
293                 -- Don't export a rule whose LHS mentions an Id that
294                 -- is completely internal (i.e. not visible to an
295                 -- importing module)
296
297     internal_id id = not (id `elemVarEnv` ext_ids)
298 \end{code}
299
300 %************************************************************************
301 %*                                                                      *
302 \subsection{Step 1: finding externals}
303 %*                                                                      * 
304 %************************************************************************
305
306 \begin{code}
307 findExternalSet :: Bool         -- Omit interface pragmas
308                 -> [CoreBind]
309                 -> IdEnv Bool   -- In domain => external
310                                 -- Range = True <=> show unfolding
311         -- Step 1 from the notes above
312 findExternalSet omit_iface_prags binds
313   = foldr find emptyVarEnv binds
314   where
315     find (NonRec id rhs) needed
316         | need_id needed id = addExternal omit_iface_prags (id,rhs) needed
317         | otherwise         = needed
318     find (Rec prs) needed   = find_prs prs needed
319
320         -- For a recursive group we have to look for a fixed point
321     find_prs prs needed 
322         | null needed_prs = needed
323         | otherwise       = find_prs other_prs new_needed
324         where
325           (needed_prs, other_prs) = partition (need_pr needed) prs
326           new_needed = foldr (addExternal omit_iface_prags) needed needed_prs
327
328         -- The 'needed' set contains the Ids that are needed by earlier
329         -- interface file emissions.  If the Id isn't in this set, and isn't
330         -- exported, there's no need to emit anything
331     need_id needed_set id       = id `elemVarEnv` needed_set || isExportedId id 
332     need_pr needed_set (id,rhs) = need_id needed_set id
333
334 addExternal :: Bool -> (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
335 -- The Id is needed; extend the needed set
336 -- with it and its dependents (free vars etc)
337 addExternal omit_iface_prags (id,rhs) needed
338   = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
339                  id show_unfold
340   where
341     add_occ id needed = extendVarEnv needed id False
342         -- "False" because we don't know we need the Id's unfolding
343         -- We'll override it later when we find the binding site
344
345     new_needed_ids | omit_iface_prags = emptyVarSet
346                    | otherwise        = worker_ids      `unionVarSet`
347                                         unfold_ids      `unionVarSet`
348                                         spec_ids
349
350     idinfo         = idInfo id
351     dont_inline    = isNeverActive (inlinePragInfo idinfo)
352     loop_breaker   = isLoopBreaker (occInfo idinfo)
353     bottoming_fn   = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
354     spec_ids       = rulesRhsFreeVars (specInfo idinfo)
355     worker_info    = workerInfo idinfo
356
357         -- Stuff to do with the Id's unfolding
358         -- The simplifier has put an up-to-date unfolding
359         -- in the IdInfo, but the RHS will do just as well
360     unfolding    = unfoldingInfo idinfo
361     rhs_is_small = not (neverUnfold unfolding)
362
363         -- We leave the unfolding there even if there is a worker
364         -- In GHCI the unfolding is used by importers
365         -- When writing an interface file, we omit the unfolding 
366         -- if there is a worker
367     show_unfold = not bottoming_fn       &&     -- Not necessary
368                   not dont_inline        &&
369                   not loop_breaker       &&
370                   rhs_is_small                  -- Small enough
371
372     unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
373                | otherwise   = emptyVarSet
374
375     worker_ids = case worker_info of
376                    HasWorker work_id _ -> unitVarSet work_id
377                    otherwise           -> emptyVarSet
378 \end{code}
379
380
381 %************************************************************************
382 %*                                                                      *
383 \subsection{Step 2: top-level tidying}
384 %*                                                                      *
385 %************************************************************************
386
387
388 \begin{code}
389 -- TopTidyEnv: when tidying we need to know
390 --   * nc_var: The NameCache, containing a unique supply and any pre-ordained Names.  
391 --        These may have arisen because the
392 --        renamer read in an interface file mentioning M.$wf, say,
393 --        and assigned it unique r77.  If, on this compilation, we've
394 --        invented an Id whose name is $wf (but with a different unique)
395 --        we want to rename it to have unique r77, so that we can do easy
396 --        comparisons with stuff from the interface file
397 --
398 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
399 --     are 'used'
400 --
401 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
402
403 tidyTopBinds :: DynFlags
404              -> 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 dflags mod nc_var ext_ids tidy_env []
411   = return (tidy_env, [])
412
413 tidyTopBinds dflags mod nc_var ext_ids tidy_env (b:bs)
414   = do  { (tidy_env1, b')  <- tidyTopBind  dflags mod nc_var ext_ids tidy_env b
415         ; (tidy_env2, bs') <- tidyTopBinds dflags mod nc_var ext_ids tidy_env1 bs
416         ; return (tidy_env2, b':bs') }
417
418 ------------------------
419 tidyTopBind  :: DynFlags
420              -> Module
421              -> IORef NameCache -- For allocating new unique names
422              -> IdEnv Bool      -- Domain = Ids that should be external
423                                 -- True <=> their unfolding is external too
424              -> TidyEnv -> CoreBind
425              -> IO (TidyEnv, CoreBind)
426
427 tidyTopBind dflags mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (NonRec bndr rhs)
428   = do  { (occ_env2, name') <- tidyTopName mod nc_var ext_ids occ_env1 bndr
429         ; let   { (bndr', rhs') = tidyTopPair ext_ids tidy_env2 caf_info name' (bndr, rhs)
430                 ; subst2        = extendVarEnv subst1 bndr bndr'
431                 ; tidy_env2     = (occ_env2, subst2) }
432         ; return (tidy_env2, NonRec bndr' rhs') }
433   where
434     caf_info = hasCafRefs dflags subst1 (idArity bndr) rhs
435
436 tidyTopBind dflags mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (Rec prs)
437   = do  { (occ_env2, names') <- tidyTopNames mod nc_var ext_ids occ_env1 bndrs
438         ; let   { prs'      = zipWith (tidyTopPair ext_ids tidy_env2 caf_info)
439                                       names' prs
440                 ; subst2    = extendVarEnvList subst1 (bndrs `zip` map fst prs')
441                 ; tidy_env2 = (occ_env2, subst2) }
442         ; return (tidy_env2, Rec prs') }
443   where
444     bndrs = map fst prs
445
446         -- the CafInfo for a recursive group says whether *any* rhs in
447         -- the group may refer indirectly to a CAF (because then, they all do).
448     caf_info 
449         | or [ mayHaveCafRefs (hasCafRefs dflags subst1 (idArity bndr) rhs)
450              | (bndr,rhs) <- prs ] = MayHaveCafRefs
451         | otherwise                = NoCafRefs
452
453 --------------------------------------------------------------------
454 --              tidyTopName
455 -- This is where we set names to local/global based on whether they really are 
456 -- externally visible (see comment at the top of this module).  If the name
457 -- was previously local, we have to give it a unique occurrence name if
458 -- we intend to externalise it.
459 tidyTopNames mod nc_var ext_ids occ_env [] = return (occ_env, [])
460 tidyTopNames mod nc_var ext_ids occ_env (id:ids)
461   = do  { (occ_env1, name)  <- tidyTopName  mod nc_var ext_ids occ_env id
462         ; (occ_env2, names) <- tidyTopNames mod nc_var ext_ids occ_env1 ids
463         ; return (occ_env2, name:names) }
464
465 tidyTopName :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
466             -> Id -> IO (TidyOccEnv, Name)
467 tidyTopName mod nc_var ext_ids occ_env id
468   | global && internal = return (occ_env, localiseName name)
469
470   | global && external = return (occ_env, name)
471         -- Global names are assumed to have been allocated by the renamer,
472         -- so they already have the "right" unique
473         -- And it's a system-wide unique too
474
475   -- Now we get to the real reason that all this is in the IO Monad:
476   -- we have to update the name cache in a nice atomic fashion
477
478   | local  && internal = do { nc <- readIORef nc_var
479                             ; let (nc', new_local_name) = mk_new_local nc
480                             ; writeIORef nc_var nc'
481                             ; return (occ_env', new_local_name) }
482         -- Even local, internal names must get a unique occurrence, because
483         -- if we do -split-objs we externalise the name later, in the code generator
484         --
485         -- Similarly, we must make sure it has a system-wide Unique, because
486         -- the byte-code generator builds a system-wide Name->BCO symbol table
487
488   | local  && external = do { nc <- readIORef nc_var
489                             ; let (nc', new_external_name) = mk_new_external nc
490                             ; writeIORef nc_var nc'
491                             ; return (occ_env', new_external_name) }
492   where
493     name        = idName id
494     external    = id `elemVarEnv` ext_ids
495     global      = isExternalName name
496     local       = not global
497     internal    = not external
498     mb_parent   = nameParent_maybe name
499     loc         = nameSrcLoc name
500
501     (occ_env', occ') = tidyOccName occ_env (nameOccName name)
502
503     mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
504                     where
505                       (us1, us2) = splitUniqSupply (nsUniqs nc)
506                       uniq       = uniqFromSupply us1
507
508     mk_new_external nc = allocateGlobalBinder nc mod occ' mb_parent loc
509         -- If we want to externalise a currently-local name, check
510         -- whether we have already assigned a unique for it.
511         -- If so, use it; if not, extend the table.
512         -- All this is done by allcoateGlobalBinder.
513         -- This is needed when *re*-compiling a module in GHCi; we want to
514         -- use the same name for externally-visible things as we did before.
515
516
517 -----------------------------------------------------------
518 tidyTopPair :: VarEnv Bool
519             -> TidyEnv  -- The TidyEnv is used to tidy the IdInfo
520                         -- It is knot-tied: don't look at it!
521             -> CafInfo
522             -> Name             -- New name
523             -> (Id, CoreExpr)   -- Binder and RHS before tidying
524             -> (Id, CoreExpr)
525         -- This function is the heart of Step 2
526         -- The rec_tidy_env is the one to use for the IdInfo
527         -- It's necessary because when we are dealing with a recursive
528         -- group, a variable late in the group might be mentioned
529         -- in the IdInfo of one early in the group
530
531 tidyTopPair ext_ids rhs_tidy_env caf_info name' (bndr, rhs)
532   = ASSERT(isLocalId bndr)  -- "all Ids defined in this module are local
533                             -- until the CoreTidy phase"  --GHC comentary
534     (bndr', rhs')
535   where
536     bndr'   = mkVanillaGlobal name' ty' idinfo'
537     ty'     = tidyTopType (idType bndr)
538     rhs'    = tidyExpr rhs_tidy_env rhs
539     idinfo' = tidyTopIdInfo rhs_tidy_env (isJust maybe_external)
540                             (idInfo bndr) unfold_info arity
541                             caf_info
542
543     -- Expose an unfolding if ext_ids tells us to
544     -- Remember that ext_ids maps an Id to a Bool: 
545     --  True to show the unfolding, False to hide it
546     maybe_external = lookupVarEnv ext_ids bndr
547     show_unfold = maybe_external `orElse` False
548     unfold_info | show_unfold = mkTopUnfolding rhs'
549                 | otherwise   = noUnfolding
550
551     -- Usually the Id will have an accurate arity on it, because
552     -- the simplifier has just run, but not always. 
553     -- One case I found was when the last thing the simplifier
554     -- did was to let-bind a non-atomic argument and then float
555     -- it to the top level. So it seems more robust just to
556     -- fix it here.
557     arity = exprArity rhs
558
559
560 -- tidyTopIdInfo creates the final IdInfo for top-level
561 -- binders.  There are two delicate pieces:
562 --
563 --  * Arity.  After CoreTidy, this arity must not change any more.
564 --      Indeed, CorePrep must eta expand where necessary to make
565 --      the manifest arity equal to the claimed arity.
566 --
567 --  * CAF info.  This must also remain valid through to code generation.
568 --      We add the info here so that it propagates to all
569 --      occurrences of the binders in RHSs, and hence to occurrences in
570 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
571 --      CoreToStg makes use of this when constructing SRTs.
572
573 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity caf_info
574   | not is_external     -- For internal Ids (not externally visible)
575   = vanillaIdInfo       -- we only need enough info for code generation
576                         -- Arity and strictness info are enough;
577                         --      c.f. CoreTidy.tidyLetBndr
578         `setCafInfo`           caf_info
579         `setArityInfo`         arity
580         `setAllStrictnessInfo` newStrictnessInfo idinfo
581
582   | otherwise           -- Externally-visible Ids get the whole lot
583   = vanillaIdInfo
584         `setCafInfo`           caf_info
585         `setArityInfo`         arity
586         `setAllStrictnessInfo` newStrictnessInfo idinfo
587         `setInlinePragInfo`    inlinePragInfo idinfo
588         `setUnfoldingInfo`     unfold_info
589         `setWorkerInfo`        tidyWorker tidy_env (workerInfo idinfo)
590                 -- NB: we throw away the Rules
591                 -- They have already been extracted by findExternalRules
592
593
594
595 ------------  Worker  --------------
596 tidyWorker tidy_env (HasWorker work_id wrap_arity) 
597   = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
598 tidyWorker tidy_env other
599   = NoWorker
600 \end{code}
601
602 %************************************************************************
603 %*                                                                      *
604 \subsection{Figuring out CafInfo for an expression}
605 %*                                                                      *
606 %************************************************************************
607
608 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
609 We mark such things as `MayHaveCafRefs' because this information is
610 used to decide whether a particular closure needs to be referenced
611 in an SRT or not.
612
613 There are two reasons for setting MayHaveCafRefs:
614         a) The RHS is a CAF: a top-level updatable thunk.
615         b) The RHS refers to something that MayHaveCafRefs
616
617 Possible improvement: In an effort to keep the number of CAFs (and 
618 hence the size of the SRTs) down, we could also look at the expression and 
619 decide whether it requires a small bounded amount of heap, so we can ignore 
620 it as a CAF.  In these cases however, we would need to use an additional
621 CAF list to keep track of non-collectable CAFs.  
622
623 \begin{code}
624 hasCafRefs  :: DynFlags -> VarEnv Var -> Arity -> CoreExpr -> CafInfo
625 hasCafRefs dflags p arity expr 
626   | is_caf || mentions_cafs = MayHaveCafRefs
627   | otherwise               = NoCafRefs
628  where
629   mentions_cafs = isFastTrue (cafRefs p expr)
630   is_caf = not (arity > 0 || rhsIsStatic dflags expr)
631   -- NB. we pass in the arity of the expression, which is expected
632   -- to be calculated by exprArity.  This is because exprArity
633   -- knows how much eta expansion is going to be done by 
634   -- CorePrep later on, and we don't want to duplicate that
635   -- knowledge in rhsIsStatic below.
636
637 cafRefs p (Var id)
638         -- imported Ids first:
639   | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
640         -- now Ids local to this module:
641   | otherwise =
642      case lookupVarEnv p id of
643         Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
644         Nothing  -> fastBool False
645
646 cafRefs p (Lit l)              = fastBool False
647 cafRefs p (App f a)            = fastOr (cafRefs p f) (cafRefs p) a
648 cafRefs p (Lam x e)            = cafRefs p e
649 cafRefs p (Let b e)            = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
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}