[project @ 2005-06-21 10:44:37 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( mkBootModDetails, tidyProgram ) 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, tidyRules )
16 import PprCore          ( pprRules )
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, isGlobalId,
23                           isExportedId, mkVanillaGlobal, isLocalId, 
24                           idArity, idCafInfo, idUnfolding, isImplicitId, setIdInfo
25                         ) 
26 import IdInfo           {- loads of stuff -}
27 import InstEnv          ( Instance, DFunId, instanceDFunId, setInstanceDFunId )
28 import NewDemand        ( isBottomingSig, topSig )
29 import BasicTypes       ( Arity, isNeverActive )
30 import Name             ( Name, getOccName, nameOccName, mkInternalName,
31                           localiseName, isExternalName, nameSrcLoc, nameParent_maybe,
32                           isWiredInName, getName
33                         )
34 import NameSet          ( NameSet, elemNameSet )
35 import IfaceEnv         ( allocateGlobalBinder )
36 import NameEnv          ( filterNameEnv, mapNameEnv )
37 import OccName          ( TidyOccEnv, initTidyOccEnv, tidyOccName )
38 import Type             ( tidyTopType )
39 import TcType           ( isFFITy )
40 import DataCon          ( dataConName, dataConFieldLabels, dataConWrapId_maybe )
41 import TyCon            ( TyCon, makeTyConAbstract, tyConDataCons, isNewTyCon, 
42                           newTyConRep, tyConSelIds, isAlgTyCon )
43 import Class            ( classSelIds )
44 import Module           ( Module )
45 import HscTypes         ( HscEnv(..), NameCache( nsUniqs ), CgGuts(..),
46                           TypeEnv, typeEnvIds, typeEnvElts, typeEnvTyCons, 
47                           extendTypeEnvWithIds, lookupTypeEnv,
48                           ModGuts(..), TyThing(..), ModDetails(..), Dependencies(..)
49                         )
50 import Maybes           ( orElse, mapCatMaybes )
51 import ErrUtils         ( showPass, dumpIfSet_core )
52 import UniqSupply       ( splitUniqSupply, uniqFromSupply )
53 import List             ( partition )
54 import Maybe            ( isJust )
55 import Outputable
56 import DATA_IOREF       ( IORef, readIORef, writeIORef )
57 import FastTypes  hiding ( fastOr )
58 \end{code}
59
60
61 Constructing the TypeEnv, Instances, Rules from which the ModIface is
62 constructed, and which goes on to subsequent modules in --make mode.
63
64 Most of the interface file is obtained simply by serialising the
65 TypeEnv.  One important consequence is that if the *interface file*
66 has pragma info if and only if the final TypeEnv does. This is not so
67 important for *this* module, but it's essential for ghc --make:
68 subsequent compilations must not see (e.g.) the arity if the interface
69 file does not contain arity If they do, they'll exploit the arity;
70 then the arity might change, but the iface file doesn't change =>
71 recompilation does not happen => disaster. 
72
73 For data types, the final TypeEnv will have a TyThing for the TyCon,
74 plus one for each DataCon; the interface file will contain just one
75 data type declaration, but it is de-serialised back into a collection
76 of TyThings.
77
78 %************************************************************************
79 %*                                                                      *
80                 Plan A: simpleTidyPgm
81 %*                                                                      * 
82 %************************************************************************
83
84
85 Plan A: mkBootModDetails: omit pragmas, make interfaces small
86 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
87 * Ignore the bindings
88
89 * Drop all WiredIn things from the TypeEnv 
90         (we never want them in interface files)
91
92 * Retain all TyCons and Classes in the TypeEnv, to avoid
93         having to find which ones are mentioned in the
94         types of exported Ids
95
96 * Trim off the constructors of non-exported TyCons, both
97         from the TyCon and from the TypeEnv
98
99 * Drop non-exported Ids from the TypeEnv
100
101 * Tidy the types of the DFunIds of Instances, 
102   make them into GlobalIds, (they already have External Names)
103   and add them to the TypeEnv
104
105 * Tidy the types of the (exported) Ids in the TypeEnv,
106   make them into GlobalIds (they already have External Names)
107
108 * Drop rules altogether
109
110 * Tidy the bindings, to ensure that the Caf and Arity
111   information is correct for each top-level binder; the 
112   code generator needs it. And to ensure that local names have
113   distinct OccNames in case of object-file splitting
114
115 \begin{code}
116 mkBootModDetails :: HscEnv -> ModGuts -> IO ModDetails
117 -- This is Plan A: make a small type env when typechecking only,
118 -- or when compiling a hs-boot file, or simply when not using -O
119 --
120 -- We don't look at the bindings at all -- there aren't any
121 -- for hs-boot files
122
123 mkBootModDetails hsc_env (ModGuts { mg_module = mod, 
124                                     mg_exports = exports,
125                                     mg_types = type_env,        
126                                     mg_insts = ispecs })
127   = do  { let dflags = hsc_dflags hsc_env 
128         ; showPass dflags "Tidy [hoot] type env"
129
130         ; let { ispecs'   = tidyInstances tidyExternalId ispecs
131               ; type_env1 = filterNameEnv (not . isWiredInThing) type_env
132               ; type_env2 = mapNameEnv tidyBootThing type_env1
133               ; type_env' = extendTypeEnvWithIds type_env2
134                                 (map instanceDFunId ispecs')
135               }
136         ; return (ModDetails { md_types = type_env',
137                                md_insts = ispecs',
138                                md_rules = [],
139                                md_exports = exports })
140         }
141   where
142
143 isWiredInThing :: TyThing -> Bool
144 isWiredInThing thing = isWiredInName (getName thing)
145
146 tidyBootThing :: TyThing -> TyThing
147 -- Just externalise the Ids; keep everything
148 tidyBootThing (AnId id) | isLocalId id = AnId (tidyExternalId id)
149 tidyBootThing thing                    = thing
150
151 tidyExternalId :: Id -> Id
152 -- Takes an LocalId with an External Name, 
153 -- makes it into a GlobalId with VanillaIdInfo, and tidies its type
154 -- (NB: vanillaIdInfo makes a conservative assumption about Caf-hood.)
155 tidyExternalId id 
156   = ASSERT2( isLocalId id && isExternalName (idName id), ppr id )
157     mkVanillaGlobal (idName id) (tidyTopType (idType id)) vanillaIdInfo
158 \end{code}
159
160
161 %************************************************************************
162 %*                                                                      *
163         Plan B: tidy bindings, make TypeEnv full of IdInfo
164 %*                                                                      * 
165 %************************************************************************
166
167 Plan B: include pragmas, make interfaces 
168 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
169 * Figure out which Ids are externally visible
170
171 * Tidy the bindings, externalising appropriate Ids
172
173 * Drop all Ids from the TypeEnv, and add all the External Ids from 
174   the bindings.  (This adds their IdInfo to the TypeEnv; and adds
175   floated-out Ids that weren't even in the TypeEnv before.)
176
177 Step 1: Figure out external Ids
178 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
179 First we figure out which Ids are "external" Ids.  An
180 "external" Id is one that is visible from outside the compilation
181 unit.  These are
182         a) the user exported ones
183         b) ones mentioned in the unfoldings, workers, 
184            or rules of externally-visible ones 
185 This exercise takes a sweep of the bindings bottom to top.  Actually,
186 in Step 2 we're also going to need to know which Ids should be
187 exported with their unfoldings, so we produce not an IdSet but an
188 IdEnv Bool
189
190
191 Step 2: Tidy the program
192 ~~~~~~~~~~~~~~~~~~~~~~~~
193 Next we traverse the bindings top to bottom.  For each *top-level*
194 binder
195
196  1. Make it into a GlobalId; its IdDetails becomes VanillaGlobal, 
197     reflecting the fact that from now on we regard it as a global, 
198     not local, Id
199
200  2. Give it a system-wide Unique.
201     [Even non-exported things need system-wide Uniques because the
202     byte-code generator builds a single Name->BCO symbol table.]
203
204     We use the NameCache kept in the HscEnv as the
205     source of such system-wide uniques.
206
207     For external Ids, use the original-name cache in the NameCache
208     to ensure that the unique assigned is the same as the Id had 
209     in any previous compilation run.
210   
211  3. If it's an external Id, make it have a External Name, otherwise
212     make it have an Internal Name.
213     This is used by the code generator to decide whether
214     to make the label externally visible
215
216  4. Give external Ids a "tidy" OccName.  This means
217     we can print them in interface files without confusing 
218     "x" (unique 5) with "x" (unique 10).
219   
220  5. Give it its UTTERLY FINAL IdInfo; in ptic, 
221         * its unfolding, if it should have one
222         
223         * its arity, computed from the number of visible lambdas
224
225         * its CAF info, computed from what is free in its RHS
226
227                 
228 Finally, substitute these new top-level binders consistently
229 throughout, including in unfoldings.  We also tidy binders in
230 RHSs, so that they print nicely in interfaces.
231
232 \begin{code}
233 tidyProgram :: HscEnv -> ModGuts -> IO (CgGuts, ModDetails)
234 tidyProgram hsc_env
235             mod_impl@(ModGuts { mg_module = mod, mg_exports = exports, 
236                                 mg_types = type_env, mg_insts = insts_tc, 
237                                 mg_binds = binds, 
238                                 mg_rules = imp_rules,
239                                 mg_dir_imps = dir_imps, mg_deps = deps, 
240                                 mg_home_mods = home_mods,
241                                 mg_foreign = foreign_stubs })
242
243   = do  { let dflags = hsc_dflags hsc_env
244         ; showPass dflags "Tidy Core"
245
246         ; let { omit_prags = dopt Opt_OmitInterfacePragmas dflags
247               ; ext_ids = findExternalIds omit_prags binds
248               ; ext_rules 
249                    | omit_prags = []
250                    | otherwise  = findExternalRules binds imp_rules ext_ids
251                 -- findExternalRules filters imp_rules to avoid binders that 
252                 -- aren't externally visible; but the externally-visible binders 
253                 -- are computed (by findExternalIds) assuming that all orphan
254                 -- rules are exported (they get their Exported flag set in the desugarer)
255                 -- So in fact we may export more than we need. 
256                 -- (It's a sort of mutual recursion.)
257         }
258
259         ; (tidy_env, tidy_binds) <- tidyTopBinds hsc_env mod type_env ext_ids binds
260
261         ; let { tidy_type_env = tidyTypeEnv omit_prags exports type_env tidy_binds
262               ; tidy_ispecs   = tidyInstances (lookup_dfun tidy_type_env) insts_tc
263                 -- A DFunId will have a binding in tidy_binds, and so
264                 -- will now be in final_env, replete with IdInfo
265                 -- Its name will be unchanged since it was born, but
266                 -- we want Global, IdInfo-rich (or not) DFunId in the tidy_ispecs
267
268               ; tidy_rules = tidyRules tidy_env ext_rules
269                 -- You might worry that the tidy_env contains IdInfo-rich stuff
270                 -- and indeed it does, but if omit_prags is on, ext_rules is empty
271
272               ; implicit_binds = getImplicitBinds type_env
273               ; alg_tycons = filter isAlgTyCon (typeEnvTyCons type_env)
274               }
275
276         ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
277         ; dumpIfSet_core dflags Opt_D_dump_simpl
278                 "Tidy Core Rules"
279                 (pprRules tidy_rules)
280
281         ; return (CgGuts { cg_module   = mod, 
282                            cg_tycons   = alg_tycons,
283                            cg_binds    = implicit_binds ++ tidy_binds,
284                            cg_dir_imps = dir_imps,
285                            cg_foreign  = foreign_stubs,
286                            cg_home_mods = home_mods,
287                            cg_dep_pkgs = dep_pkgs deps }, 
288
289                    ModDetails { md_types = tidy_type_env,
290                                 md_rules = tidy_rules,
291                                 md_insts = tidy_ispecs,
292                                 md_exports = exports })
293         }
294
295 lookup_dfun type_env dfun_id
296   = case lookupTypeEnv type_env (idName dfun_id) of
297         Just (AnId dfun_id') -> dfun_id'
298         other -> pprPanic "lookup_dfun" (ppr dfun_id)
299
300 tidyTypeEnv :: Bool -> NameSet -> TypeEnv -> [CoreBind] -> TypeEnv
301
302 -- The competed type environment is gotten from
303 --      Dropping any wired-in things, and then
304 --      a) keeping the types and classes
305 --      b) removing all Ids, 
306 --      c) adding Ids with correct IdInfo, including unfoldings,
307 --              gotten from the bindings
308 -- From (c) we keep only those Ids with External names;
309 --          the CoreTidy pass makes sure these are all and only
310 --          the externally-accessible ones
311 -- This truncates the type environment to include only the 
312 -- exported Ids and things needed from them, which saves space
313
314 tidyTypeEnv omit_prags exports type_env tidy_binds
315   = let type_env1 = filterNameEnv keep_it type_env
316         type_env2 = extendTypeEnvWithIds type_env1 final_ids
317         type_env3 | omit_prags = mapNameEnv trim_thing type_env2
318                   | otherwise  = type_env2
319     in 
320     type_env3
321   where
322     final_ids  = [ id | id <- bindersOfBinds tidy_binds, 
323                         isExternalName (idName id)]
324
325         -- We keep GlobalIds, because they won't appear 
326         -- in the bindings from which final_ids are derived!
327         -- (The bindings bind LocalIds.)
328     keep_it thing | isWiredInThing thing = False
329     keep_it (AnId id) = isGlobalId id   -- Keep GlobalIds (e.g. class ops)
330     keep_it other     = True            -- Keep all TyCons, DataCons, and Classes
331
332     trim_thing thing
333         = case thing of
334             ATyCon tc | mustExposeTyCon exports tc -> thing
335                       | otherwise -> ATyCon (makeTyConAbstract tc)
336
337             AnId id | isImplicitId id -> thing
338                     | otherwise       -> AnId (id `setIdInfo` vanillaIdInfo)
339
340             other -> thing
341
342 mustExposeTyCon :: NameSet      -- Exports
343                 -> TyCon        -- The tycon
344                 -> Bool         -- Can its rep be hidden?
345 -- We are compiling without -O, and thus trying to write as little as 
346 -- possible into the interface file.  But we must expose the details of
347 -- any data types whose constructors or fields are exported
348 mustExposeTyCon exports tc
349   | not (isAlgTyCon tc)         -- Synonyms
350   = True
351   | otherwise                   -- Newtype, datatype
352   = any exported_con (tyConDataCons tc)
353         -- Expose rep if any datacon or field is exported
354
355   || (isNewTyCon tc && isFFITy (snd (newTyConRep tc)))
356         -- Expose the rep for newtypes if the rep is an FFI type.  
357         -- For a very annoying reason.  'Foreign import' is meant to
358         -- be able to look through newtypes transparently, but it
359         -- can only do that if it can "see" the newtype representation
360   where
361     exported_con con = any (`elemNameSet` exports) 
362                            (dataConName con : dataConFieldLabels con)
363
364 tidyInstances :: (DFunId -> DFunId) -> [Instance] -> [Instance]
365 tidyInstances tidy_dfun ispecs
366   = map tidy ispecs
367   where
368     tidy ispec = setInstanceDFunId ispec $
369                  tidy_dfun (instanceDFunId ispec)
370
371 getImplicitBinds :: TypeEnv -> [CoreBind]
372 getImplicitBinds type_env
373   = map get_defn (concatMap implicit_con_ids (typeEnvTyCons type_env)
374                   ++ concatMap other_implicit_ids (typeEnvElts type_env))
375         -- Put the constructor wrappers first, because
376         -- other implicit bindings (notably the fromT functions arising 
377         -- from generics) use the constructor wrappers.  At least that's
378         -- what External Core likes
379   where
380     implicit_con_ids tc = mapCatMaybes dataConWrapId_maybe (tyConDataCons tc)
381     
382     other_implicit_ids (ATyCon tc) = tyConSelIds tc
383     other_implicit_ids (AClass cl) = classSelIds cl
384     other_implicit_ids other       = []
385     
386     get_defn :: Id -> CoreBind
387     get_defn id = NonRec id (tidyExpr emptyTidyEnv rhs)
388         where
389           rhs = unfoldingTemplate (idUnfolding id)
390         -- Don't forget to tidy the body !  Otherwise you get silly things like
391         --      \ tpl -> case tpl of tpl -> (tpl,tpl) -> tpl
392 \end{code}
393
394
395 %************************************************************************
396 %*                                                                      *
397 \subsection{Step 1: finding externals}
398 %*                                                                      * 
399 %************************************************************************
400
401 \begin{code}
402 findExternalIds :: Bool
403                 -> [CoreBind]
404                 -> IdEnv Bool   -- In domain => external
405                                 -- Range = True <=> show unfolding
406         -- Step 1 from the notes above
407 findExternalIds omit_prags binds
408   | omit_prags
409   = mkVarEnv [ (id,False) | id <- bindersOfBinds binds, isExportedId id ]
410
411   | otherwise
412   = foldr find emptyVarEnv binds
413   where
414     find (NonRec id rhs) needed
415         | need_id needed id = addExternal (id,rhs) needed
416         | otherwise         = needed
417     find (Rec prs) needed   = find_prs prs needed
418
419         -- For a recursive group we have to look for a fixed point
420     find_prs prs needed 
421         | null needed_prs = needed
422         | otherwise       = find_prs other_prs new_needed
423         where
424           (needed_prs, other_prs) = partition (need_pr needed) prs
425           new_needed = foldr addExternal needed needed_prs
426
427         -- The 'needed' set contains the Ids that are needed by earlier
428         -- interface file emissions.  If the Id isn't in this set, and isn't
429         -- exported, there's no need to emit anything
430     need_id needed_set id       = id `elemVarEnv` needed_set || isExportedId id 
431     need_pr needed_set (id,rhs) = need_id needed_set id
432
433 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
434 -- The Id is needed; extend the needed set
435 -- with it and its dependents (free vars etc)
436 addExternal (id,rhs) needed
437   = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
438                  id show_unfold
439   where
440     add_occ id needed = extendVarEnv needed id False
441         -- "False" because we don't know we need the Id's unfolding
442         -- We'll override it later when we find the binding site
443
444     new_needed_ids = worker_ids `unionVarSet`
445                      unfold_ids `unionVarSet`
446                      spec_ids
447
448     idinfo         = idInfo id
449     dont_inline    = isNeverActive (inlinePragInfo idinfo)
450     loop_breaker   = isLoopBreaker (occInfo idinfo)
451     bottoming_fn   = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
452     spec_ids       = specInfoFreeVars (specInfo idinfo)
453     worker_info    = workerInfo idinfo
454
455         -- Stuff to do with the Id's unfolding
456         -- The simplifier has put an up-to-date unfolding
457         -- in the IdInfo, but the RHS will do just as well
458     unfolding    = unfoldingInfo idinfo
459     rhs_is_small = not (neverUnfold unfolding)
460
461         -- We leave the unfolding there even if there is a worker
462         -- In GHCI the unfolding is used by importers
463         -- When writing an interface file, we omit the unfolding 
464         -- if there is a worker
465     show_unfold = not bottoming_fn       &&     -- Not necessary
466                   not dont_inline        &&
467                   not loop_breaker       &&
468                   rhs_is_small                  -- Small enough
469
470     unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
471                | otherwise   = emptyVarSet
472
473     worker_ids = case worker_info of
474                    HasWorker work_id _ -> unitVarSet work_id
475                    otherwise           -> emptyVarSet
476 \end{code}
477
478
479 \begin{code}
480 findExternalRules :: [CoreBind]
481                   -> [CoreRule] -- Non-local rules (i.e. ones for imported fns)
482                   -> IdEnv a    -- Ids that are exported, so we need their rules
483                   -> [CoreRule]
484   -- The complete rules are gotten by combining
485   --    a) the non-local rules
486   --    b) rules embedded in the top-level Ids
487 findExternalRules binds non_local_rules ext_ids
488   = filter (not . internal_rule) (non_local_rules ++ local_rules)
489   where
490     local_rules  = [ rule
491                    | id <- bindersOfBinds binds,
492                      id `elemVarEnv` ext_ids,
493                      rule <- idCoreRules id
494                    ]
495
496     internal_rule rule
497         =  any internal_id (varSetElems (ruleLhsFreeIds rule))
498                 -- Don't export a rule whose LHS mentions a locally-defined
499                 --  Id that is completely internal (i.e. not visible to an
500                 -- importing module)
501
502     internal_id id = not (id `elemVarEnv` ext_ids)
503 \end{code}
504
505
506
507 %************************************************************************
508 %*                                                                      *
509 \subsection{Step 2: top-level tidying}
510 %*                                                                      *
511 %************************************************************************
512
513
514 \begin{code}
515 -- TopTidyEnv: when tidying we need to know
516 --   * nc_var: The NameCache, containing a unique supply and any pre-ordained Names.  
517 --        These may have arisen because the
518 --        renamer read in an interface file mentioning M.$wf, say,
519 --        and assigned it unique r77.  If, on this compilation, we've
520 --        invented an Id whose name is $wf (but with a different unique)
521 --        we want to rename it to have unique r77, so that we can do easy
522 --        comparisons with stuff from the interface file
523 --
524 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
525 --     are 'used'
526 --
527 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
528
529 tidyTopBinds :: HscEnv
530              -> Module
531              -> TypeEnv
532              -> IdEnv Bool      -- Domain = Ids that should be external
533                                 -- True <=> their unfolding is external too
534              -> [CoreBind]
535              -> IO (TidyEnv, [CoreBind])
536
537 tidyTopBinds hsc_env mod type_env ext_ids binds
538   = tidy init_env binds
539   where
540     dflags = hsc_dflags hsc_env
541     nc_var = hsc_NC hsc_env 
542
543         -- We also make sure to avoid any exported binders.  Consider
544         --      f{-u1-} = 1     -- Local decl
545         --      ...
546         --      f{-u2-} = 2     -- Exported decl
547         --
548         -- The second exported decl must 'get' the name 'f', so we
549         -- have to put 'f' in the avoids list before we get to the first
550         -- decl.  tidyTopId then does a no-op on exported binders.
551     init_env = (initTidyOccEnv avoids, emptyVarEnv)
552     avoids   = [getOccName name | bndr <- typeEnvIds type_env,
553                                   let name = idName bndr,
554                                   isExternalName name]
555                 -- In computing our "avoids" list, we must include
556                 --      all implicit Ids
557                 --      all things with global names (assigned once and for
558                 --                                      all by the renamer)
559                 -- since their names are "taken".
560                 -- The type environment is a convenient source of such things.
561
562     tidy env []     = return (env, [])
563     tidy env (b:bs) = do { (env1, b')  <- tidyTopBind dflags mod nc_var ext_ids env b
564                          ; (env2, bs') <- tidy env1 bs
565                          ; return (env2, b':bs') }
566
567 ------------------------
568 tidyTopBind  :: DynFlags
569              -> Module
570              -> IORef NameCache -- For allocating new unique names
571              -> IdEnv Bool      -- Domain = Ids that should be external
572                                 -- True <=> their unfolding is external too
573              -> TidyEnv -> CoreBind
574              -> IO (TidyEnv, CoreBind)
575
576 tidyTopBind dflags mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (NonRec bndr rhs)
577   = do  { (occ_env2, name') <- tidyTopName mod nc_var ext_ids occ_env1 bndr
578         ; let   { (bndr', rhs') = tidyTopPair ext_ids tidy_env2 caf_info name' (bndr, rhs)
579                 ; subst2        = extendVarEnv subst1 bndr bndr'
580                 ; tidy_env2     = (occ_env2, subst2) }
581         ; return (tidy_env2, NonRec bndr' rhs') }
582   where
583     caf_info = hasCafRefs dflags subst1 (idArity bndr) rhs
584
585 tidyTopBind dflags mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (Rec prs)
586   = do  { (occ_env2, names') <- tidyTopNames mod nc_var ext_ids occ_env1 bndrs
587         ; let   { prs'      = zipWith (tidyTopPair ext_ids tidy_env2 caf_info)
588                                       names' prs
589                 ; subst2    = extendVarEnvList subst1 (bndrs `zip` map fst prs')
590                 ; tidy_env2 = (occ_env2, subst2) }
591         ; return (tidy_env2, Rec prs') }
592   where
593     bndrs = map fst prs
594
595         -- the CafInfo for a recursive group says whether *any* rhs in
596         -- the group may refer indirectly to a CAF (because then, they all do).
597     caf_info 
598         | or [ mayHaveCafRefs (hasCafRefs dflags subst1 (idArity bndr) rhs)
599              | (bndr,rhs) <- prs ] = MayHaveCafRefs
600         | otherwise                = NoCafRefs
601
602 --------------------------------------------------------------------
603 --              tidyTopName
604 -- This is where we set names to local/global based on whether they really are 
605 -- externally visible (see comment at the top of this module).  If the name
606 -- was previously local, we have to give it a unique occurrence name if
607 -- we intend to externalise it.
608 tidyTopNames mod nc_var ext_ids occ_env [] = return (occ_env, [])
609 tidyTopNames mod nc_var ext_ids occ_env (id:ids)
610   = do  { (occ_env1, name)  <- tidyTopName  mod nc_var ext_ids occ_env id
611         ; (occ_env2, names) <- tidyTopNames mod nc_var ext_ids occ_env1 ids
612         ; return (occ_env2, name:names) }
613
614 tidyTopName :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
615             -> Id -> IO (TidyOccEnv, Name)
616 tidyTopName mod nc_var ext_ids occ_env id
617   | global && internal = return (occ_env, localiseName name)
618
619   | global && external = return (occ_env, name)
620         -- Global names are assumed to have been allocated by the renamer,
621         -- so they already have the "right" unique
622         -- And it's a system-wide unique too
623
624   -- Now we get to the real reason that all this is in the IO Monad:
625   -- we have to update the name cache in a nice atomic fashion
626
627   | local  && internal = do { nc <- readIORef nc_var
628                             ; let (nc', new_local_name) = mk_new_local nc
629                             ; writeIORef nc_var nc'
630                             ; return (occ_env', new_local_name) }
631         -- Even local, internal names must get a unique occurrence, because
632         -- if we do -split-objs we externalise the name later, in the code generator
633         --
634         -- Similarly, we must make sure it has a system-wide Unique, because
635         -- the byte-code generator builds a system-wide Name->BCO symbol table
636
637   | local  && external = do { nc <- readIORef nc_var
638                             ; let (nc', new_external_name) = mk_new_external nc
639                             ; writeIORef nc_var nc'
640                             ; return (occ_env', new_external_name) }
641   where
642     name        = idName id
643     external    = id `elemVarEnv` ext_ids
644     global      = isExternalName name
645     local       = not global
646     internal    = not external
647     mb_parent   = nameParent_maybe name
648     loc         = nameSrcLoc name
649
650     (occ_env', occ') = tidyOccName occ_env (nameOccName name)
651
652     mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
653                     where
654                       (us1, us2) = splitUniqSupply (nsUniqs nc)
655                       uniq       = uniqFromSupply us1
656
657     mk_new_external nc = allocateGlobalBinder nc mod occ' mb_parent loc
658         -- If we want to externalise a currently-local name, check
659         -- whether we have already assigned a unique for it.
660         -- If so, use it; if not, extend the table.
661         -- All this is done by allcoateGlobalBinder.
662         -- This is needed when *re*-compiling a module in GHCi; we must
663         -- use the same name for externally-visible things as we did before.
664
665
666 -----------------------------------------------------------
667 tidyTopPair :: VarEnv Bool
668             -> TidyEnv  -- The TidyEnv is used to tidy the IdInfo
669                         -- It is knot-tied: don't look at it!
670             -> CafInfo
671             -> Name             -- New name
672             -> (Id, CoreExpr)   -- Binder and RHS before tidying
673             -> (Id, CoreExpr)
674         -- This function is the heart of Step 2
675         -- The rec_tidy_env is the one to use for the IdInfo
676         -- It's necessary because when we are dealing with a recursive
677         -- group, a variable late in the group might be mentioned
678         -- in the IdInfo of one early in the group
679
680 tidyTopPair ext_ids rhs_tidy_env caf_info name' (bndr, rhs)
681   | isGlobalId bndr             -- Injected binding for record selector, etc
682   = (bndr, tidyExpr rhs_tidy_env rhs)
683   | otherwise
684   = (bndr', rhs')
685   where
686     bndr'   = mkVanillaGlobal name' ty' idinfo'
687     ty'     = tidyTopType (idType bndr)
688     rhs'    = tidyExpr rhs_tidy_env rhs
689     idinfo' = tidyTopIdInfo rhs_tidy_env (isJust maybe_external)
690                             (idInfo bndr) unfold_info arity
691                             caf_info
692
693     -- Expose an unfolding if ext_ids tells us to
694     -- Remember that ext_ids maps an Id to a Bool: 
695     --  True to show the unfolding, False to hide it
696     maybe_external = lookupVarEnv ext_ids bndr
697     show_unfold = maybe_external `orElse` False
698     unfold_info | show_unfold = mkTopUnfolding rhs'
699                 | otherwise   = noUnfolding
700
701     -- Usually the Id will have an accurate arity on it, because
702     -- the simplifier has just run, but not always. 
703     -- One case I found was when the last thing the simplifier
704     -- did was to let-bind a non-atomic argument and then float
705     -- it to the top level. So it seems more robust just to
706     -- fix it here.
707     arity = exprArity rhs
708
709
710 -- tidyTopIdInfo creates the final IdInfo for top-level
711 -- binders.  There are two delicate pieces:
712 --
713 --  * Arity.  After CoreTidy, this arity must not change any more.
714 --      Indeed, CorePrep must eta expand where necessary to make
715 --      the manifest arity equal to the claimed arity.
716 --
717 --  * CAF info.  This must also remain valid through to code generation.
718 --      We add the info here so that it propagates to all
719 --      occurrences of the binders in RHSs, and hence to occurrences in
720 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
721 --      CoreToStg makes use of this when constructing SRTs.
722
723 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity caf_info
724   | not is_external     -- For internal Ids (not externally visible)
725   = vanillaIdInfo       -- we only need enough info for code generation
726                         -- Arity and strictness info are enough;
727                         --      c.f. CoreTidy.tidyLetBndr
728         `setCafInfo`           caf_info
729         `setArityInfo`         arity
730         `setAllStrictnessInfo` newStrictnessInfo idinfo
731
732   | otherwise           -- Externally-visible Ids get the whole lot
733   = vanillaIdInfo
734         `setCafInfo`           caf_info
735         `setArityInfo`         arity
736         `setAllStrictnessInfo` newStrictnessInfo idinfo
737         `setInlinePragInfo`    inlinePragInfo idinfo
738         `setUnfoldingInfo`     unfold_info
739         `setWorkerInfo`        tidyWorker tidy_env (workerInfo idinfo)
740                 -- NB: we throw away the Rules
741                 -- They have already been extracted by findExternalRules
742
743
744
745 ------------  Worker  --------------
746 tidyWorker tidy_env (HasWorker work_id wrap_arity) 
747   = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
748 tidyWorker tidy_env other
749   = NoWorker
750 \end{code}
751
752 %************************************************************************
753 %*                                                                      *
754 \subsection{Figuring out CafInfo for an expression}
755 %*                                                                      *
756 %************************************************************************
757
758 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
759 We mark such things as `MayHaveCafRefs' because this information is
760 used to decide whether a particular closure needs to be referenced
761 in an SRT or not.
762
763 There are two reasons for setting MayHaveCafRefs:
764         a) The RHS is a CAF: a top-level updatable thunk.
765         b) The RHS refers to something that MayHaveCafRefs
766
767 Possible improvement: In an effort to keep the number of CAFs (and 
768 hence the size of the SRTs) down, we could also look at the expression and 
769 decide whether it requires a small bounded amount of heap, so we can ignore 
770 it as a CAF.  In these cases however, we would need to use an additional
771 CAF list to keep track of non-collectable CAFs.  
772
773 \begin{code}
774 hasCafRefs  :: DynFlags -> VarEnv Var -> Arity -> CoreExpr -> CafInfo
775 hasCafRefs dflags p arity expr 
776   | is_caf || mentions_cafs = MayHaveCafRefs
777   | otherwise               = NoCafRefs
778  where
779   mentions_cafs = isFastTrue (cafRefs p expr)
780   is_caf = not (arity > 0 || rhsIsStatic dflags expr)
781   -- NB. we pass in the arity of the expression, which is expected
782   -- to be calculated by exprArity.  This is because exprArity
783   -- knows how much eta expansion is going to be done by 
784   -- CorePrep later on, and we don't want to duplicate that
785   -- knowledge in rhsIsStatic below.
786
787 cafRefs p (Var id)
788         -- imported Ids first:
789   | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
790         -- now Ids local to this module:
791   | otherwise =
792      case lookupVarEnv p id of
793         Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
794         Nothing  -> fastBool False
795
796 cafRefs p (Lit l)              = fastBool False
797 cafRefs p (App f a)            = fastOr (cafRefs p f) (cafRefs p) a
798 cafRefs p (Lam x e)            = cafRefs p e
799 cafRefs p (Let b e)            = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
800 cafRefs p (Case e bndr _ alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
801 cafRefs p (Note n e)           = cafRefs p e
802 cafRefs p (Type t)             = fastBool False
803
804 cafRefss p []     = fastBool False
805 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
806
807 -- hack for lazy-or over FastBool.
808 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))
809 \end{code}