[project @ 2005-04-29 08:19:49 by simonpj]
[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_foreign = foreign_stubs })
241
242   = do  { let dflags = hsc_dflags hsc_env
243         ; showPass dflags "Tidy Core"
244
245         ; let { omit_prags = dopt Opt_OmitInterfacePragmas dflags
246               ; ext_ids = findExternalIds omit_prags binds
247               ; ext_rules 
248                    | omit_prags = []
249                    | otherwise  = findExternalRules binds imp_rules ext_ids
250                 -- findExternalRules filters imp_rules to avoid binders that 
251                 -- aren't externally visible; but the externally-visible binders 
252                 -- are computed (by findExternalIds) assuming that all orphan
253                 -- rules are exported (they get their Exported flag set in the desugarer)
254                 -- So in fact we may export more than we need. 
255                 -- (It's a sort of mutual recursion.)
256         }
257
258         ; (tidy_env, tidy_binds) <- tidyTopBinds hsc_env mod type_env ext_ids binds
259
260         ; let { tidy_type_env = tidyTypeEnv omit_prags exports type_env tidy_binds
261               ; tidy_ispecs   = tidyInstances (lookup_dfun tidy_type_env) insts_tc
262                 -- A DFunId will have a binding in tidy_binds, and so
263                 -- will now be in final_env, replete with IdInfo
264                 -- Its name will be unchanged since it was born, but
265                 -- we want Global, IdInfo-rich (or not) DFunId in the tidy_ispecs
266
267               ; tidy_rules = tidyRules tidy_env ext_rules
268                 -- You might worry that the tidy_env contains IdInfo-rich stuff
269                 -- and indeed it does, but if omit_prags is on, ext_rules is empty
270
271               ; implicit_binds = getImplicitBinds type_env
272               ; alg_tycons = filter isAlgTyCon (typeEnvTyCons type_env)
273               }
274
275         ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
276         ; dumpIfSet_core dflags Opt_D_dump_simpl
277                 "Tidy Core Rules"
278                 (pprRules tidy_rules)
279
280         ; return (CgGuts { cg_module   = mod, 
281                            cg_tycons   = alg_tycons,
282                            cg_binds    = implicit_binds ++ tidy_binds,
283                            cg_dir_imps = dir_imps,
284                            cg_foreign  = foreign_stubs,
285                            cg_dep_pkgs = dep_pkgs deps }, 
286
287                    ModDetails { md_types = tidy_type_env,
288                                 md_rules = tidy_rules,
289                                 md_insts = tidy_ispecs,
290                                 md_exports = exports })
291         }
292
293 lookup_dfun type_env dfun_id
294   = case lookupTypeEnv type_env (idName dfun_id) of
295         Just (AnId dfun_id') -> dfun_id'
296         other -> pprPanic "lookup_dfun" (ppr dfun_id)
297
298 tidyTypeEnv :: Bool -> NameSet -> TypeEnv -> [CoreBind] -> TypeEnv
299
300 -- The competed type environment is gotten from
301 --      Dropping any wired-in things, and then
302 --      a) keeping the types and classes
303 --      b) removing all Ids, 
304 --      c) adding Ids with correct IdInfo, including unfoldings,
305 --              gotten from the bindings
306 -- From (c) we keep only those Ids with External names;
307 --          the CoreTidy pass makes sure these are all and only
308 --          the externally-accessible ones
309 -- This truncates the type environment to include only the 
310 -- exported Ids and things needed from them, which saves space
311
312 tidyTypeEnv omit_prags exports type_env tidy_binds
313   = let type_env1 = filterNameEnv keep_it type_env
314         type_env2 = extendTypeEnvWithIds type_env1 final_ids
315         type_env3 | omit_prags = mapNameEnv trim_thing type_env2
316                   | otherwise  = type_env2
317     in 
318     type_env3
319   where
320     final_ids  = [ id | id <- bindersOfBinds tidy_binds, 
321                         isExternalName (idName id)]
322
323         -- We keep GlobalIds, because they won't appear 
324         -- in the bindings from which final_ids are derived!
325         -- (The bindings bind LocalIds.)
326     keep_it thing | isWiredInThing thing = False
327     keep_it (AnId id) = isGlobalId id   -- Keep GlobalIds (e.g. class ops)
328     keep_it other     = True            -- Keep all TyCons, DataCons, and Classes
329
330     trim_thing thing
331         = case thing of
332             ATyCon tc | mustExposeTyCon exports tc -> thing
333                       | otherwise -> ATyCon (makeTyConAbstract tc)
334
335             AnId id | isImplicitId id -> thing
336                     | otherwise       -> AnId (id `setIdInfo` vanillaIdInfo)
337
338             other -> thing
339
340 mustExposeTyCon :: NameSet      -- Exports
341                 -> TyCon        -- The tycon
342                 -> Bool         -- Can its rep be hidden?
343 -- We are compiling without -O, and thus trying to write as little as 
344 -- possible into the interface file.  But we must expose the details of
345 -- any data types whose constructors or fields are exported
346 mustExposeTyCon exports tc
347   | not (isAlgTyCon tc)         -- Synonyms
348   = True
349   | otherwise                   -- Newtype, datatype
350   = any exported_con (tyConDataCons tc)
351         -- Expose rep if any datacon or field is exported
352
353   || (isNewTyCon tc && isFFITy (snd (newTyConRep tc)))
354         -- Expose the rep for newtypes if the rep is an FFI type.  
355         -- For a very annoying reason.  'Foreign import' is meant to
356         -- be able to look through newtypes transparently, but it
357         -- can only do that if it can "see" the newtype representation
358   where
359     exported_con con = any (`elemNameSet` exports) 
360                            (dataConName con : dataConFieldLabels con)
361
362 tidyInstances :: (DFunId -> DFunId) -> [Instance] -> [Instance]
363 tidyInstances tidy_dfun ispecs
364   = map tidy ispecs
365   where
366     tidy ispec = setInstanceDFunId ispec $
367                  tidy_dfun (instanceDFunId ispec)
368
369 getImplicitBinds :: TypeEnv -> [CoreBind]
370 getImplicitBinds type_env
371   = map get_defn (concatMap implicit_con_ids (typeEnvTyCons type_env)
372                   ++ concatMap other_implicit_ids (typeEnvElts type_env))
373         -- Put the constructor wrappers first, because
374         -- other implicit bindings (notably the fromT functions arising 
375         -- from generics) use the constructor wrappers.  At least that's
376         -- what External Core likes
377   where
378     implicit_con_ids tc = mapCatMaybes dataConWrapId_maybe (tyConDataCons tc)
379     
380     other_implicit_ids (ATyCon tc) = tyConSelIds tc
381     other_implicit_ids (AClass cl) = classSelIds cl
382     other_implicit_ids other       = []
383     
384     get_defn :: Id -> CoreBind
385     get_defn id = NonRec id (tidyExpr emptyTidyEnv rhs)
386         where
387           rhs = unfoldingTemplate (idUnfolding id)
388         -- Don't forget to tidy the body !  Otherwise you get silly things like
389         --      \ tpl -> case tpl of tpl -> (tpl,tpl) -> tpl
390 \end{code}
391
392
393 %************************************************************************
394 %*                                                                      *
395 \subsection{Step 1: finding externals}
396 %*                                                                      * 
397 %************************************************************************
398
399 \begin{code}
400 findExternalIds :: Bool
401                 -> [CoreBind]
402                 -> IdEnv Bool   -- In domain => external
403                                 -- Range = True <=> show unfolding
404         -- Step 1 from the notes above
405 findExternalIds omit_prags binds
406   | omit_prags
407   = mkVarEnv [ (id,False) | id <- bindersOfBinds binds, isExportedId id ]
408
409   | otherwise
410   = foldr find emptyVarEnv binds
411   where
412     find (NonRec id rhs) needed
413         | need_id needed id = addExternal (id,rhs) needed
414         | otherwise         = needed
415     find (Rec prs) needed   = find_prs prs needed
416
417         -- For a recursive group we have to look for a fixed point
418     find_prs prs needed 
419         | null needed_prs = needed
420         | otherwise       = find_prs other_prs new_needed
421         where
422           (needed_prs, other_prs) = partition (need_pr needed) prs
423           new_needed = foldr addExternal needed needed_prs
424
425         -- The 'needed' set contains the Ids that are needed by earlier
426         -- interface file emissions.  If the Id isn't in this set, and isn't
427         -- exported, there's no need to emit anything
428     need_id needed_set id       = id `elemVarEnv` needed_set || isExportedId id 
429     need_pr needed_set (id,rhs) = need_id needed_set id
430
431 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
432 -- The Id is needed; extend the needed set
433 -- with it and its dependents (free vars etc)
434 addExternal (id,rhs) needed
435   = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
436                  id show_unfold
437   where
438     add_occ id needed = extendVarEnv needed id False
439         -- "False" because we don't know we need the Id's unfolding
440         -- We'll override it later when we find the binding site
441
442     new_needed_ids = worker_ids `unionVarSet`
443                      unfold_ids `unionVarSet`
444                      spec_ids
445
446     idinfo         = idInfo id
447     dont_inline    = isNeverActive (inlinePragInfo idinfo)
448     loop_breaker   = isLoopBreaker (occInfo idinfo)
449     bottoming_fn   = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
450     spec_ids       = specInfoFreeVars (specInfo idinfo)
451     worker_info    = workerInfo idinfo
452
453         -- Stuff to do with the Id's unfolding
454         -- The simplifier has put an up-to-date unfolding
455         -- in the IdInfo, but the RHS will do just as well
456     unfolding    = unfoldingInfo idinfo
457     rhs_is_small = not (neverUnfold unfolding)
458
459         -- We leave the unfolding there even if there is a worker
460         -- In GHCI the unfolding is used by importers
461         -- When writing an interface file, we omit the unfolding 
462         -- if there is a worker
463     show_unfold = not bottoming_fn       &&     -- Not necessary
464                   not dont_inline        &&
465                   not loop_breaker       &&
466                   rhs_is_small                  -- Small enough
467
468     unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
469                | otherwise   = emptyVarSet
470
471     worker_ids = case worker_info of
472                    HasWorker work_id _ -> unitVarSet work_id
473                    otherwise           -> emptyVarSet
474 \end{code}
475
476
477 \begin{code}
478 findExternalRules :: [CoreBind]
479                   -> [CoreRule] -- Non-local rules (i.e. ones for imported fns)
480                   -> IdEnv a    -- Ids that are exported, so we need their rules
481                   -> [CoreRule]
482   -- The complete rules are gotten by combining
483   --    a) the non-local rules
484   --    b) rules embedded in the top-level Ids
485 findExternalRules binds non_local_rules ext_ids
486   = filter (not . internal_rule) (non_local_rules ++ local_rules)
487   where
488     local_rules  = [ rule
489                    | id <- bindersOfBinds binds,
490                      id `elemVarEnv` ext_ids,
491                      rule <- idCoreRules id
492                    ]
493
494     internal_rule rule
495         =  any internal_id (varSetElems (ruleLhsFreeIds rule))
496                 -- Don't export a rule whose LHS mentions a locally-defined
497                 --  Id that is completely internal (i.e. not visible to an
498                 -- importing module)
499
500     internal_id id = not (id `elemVarEnv` ext_ids)
501 \end{code}
502
503
504
505 %************************************************************************
506 %*                                                                      *
507 \subsection{Step 2: top-level tidying}
508 %*                                                                      *
509 %************************************************************************
510
511
512 \begin{code}
513 -- TopTidyEnv: when tidying we need to know
514 --   * nc_var: The NameCache, containing a unique supply and any pre-ordained Names.  
515 --        These may have arisen because the
516 --        renamer read in an interface file mentioning M.$wf, say,
517 --        and assigned it unique r77.  If, on this compilation, we've
518 --        invented an Id whose name is $wf (but with a different unique)
519 --        we want to rename it to have unique r77, so that we can do easy
520 --        comparisons with stuff from the interface file
521 --
522 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
523 --     are 'used'
524 --
525 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
526
527 tidyTopBinds :: HscEnv
528              -> Module
529              -> TypeEnv
530              -> IdEnv Bool      -- Domain = Ids that should be external
531                                 -- True <=> their unfolding is external too
532              -> [CoreBind]
533              -> IO (TidyEnv, [CoreBind])
534
535 tidyTopBinds hsc_env mod type_env ext_ids binds
536   = tidy init_env binds
537   where
538     dflags = hsc_dflags hsc_env
539     nc_var = hsc_NC hsc_env 
540
541         -- We also make sure to avoid any exported binders.  Consider
542         --      f{-u1-} = 1     -- Local decl
543         --      ...
544         --      f{-u2-} = 2     -- Exported decl
545         --
546         -- The second exported decl must 'get' the name 'f', so we
547         -- have to put 'f' in the avoids list before we get to the first
548         -- decl.  tidyTopId then does a no-op on exported binders.
549     init_env = (initTidyOccEnv avoids, emptyVarEnv)
550     avoids   = [getOccName name | bndr <- typeEnvIds type_env,
551                                   let name = idName bndr,
552                                   isExternalName name]
553                 -- In computing our "avoids" list, we must include
554                 --      all implicit Ids
555                 --      all things with global names (assigned once and for
556                 --                                      all by the renamer)
557                 -- since their names are "taken".
558                 -- The type environment is a convenient source of such things.
559
560     tidy env []     = return (env, [])
561     tidy env (b:bs) = do { (env1, b')  <- tidyTopBind dflags mod nc_var ext_ids env b
562                          ; (env2, bs') <- tidy env1 bs
563                          ; return (env2, b':bs') }
564
565 ------------------------
566 tidyTopBind  :: DynFlags
567              -> Module
568              -> IORef NameCache -- For allocating new unique names
569              -> IdEnv Bool      -- Domain = Ids that should be external
570                                 -- True <=> their unfolding is external too
571              -> TidyEnv -> CoreBind
572              -> IO (TidyEnv, CoreBind)
573
574 tidyTopBind dflags mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (NonRec bndr rhs)
575   = do  { (occ_env2, name') <- tidyTopName mod nc_var ext_ids occ_env1 bndr
576         ; let   { (bndr', rhs') = tidyTopPair ext_ids tidy_env2 caf_info name' (bndr, rhs)
577                 ; subst2        = extendVarEnv subst1 bndr bndr'
578                 ; tidy_env2     = (occ_env2, subst2) }
579         ; return (tidy_env2, NonRec bndr' rhs') }
580   where
581     caf_info = hasCafRefs dflags subst1 (idArity bndr) rhs
582
583 tidyTopBind dflags mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (Rec prs)
584   = do  { (occ_env2, names') <- tidyTopNames mod nc_var ext_ids occ_env1 bndrs
585         ; let   { prs'      = zipWith (tidyTopPair ext_ids tidy_env2 caf_info)
586                                       names' prs
587                 ; subst2    = extendVarEnvList subst1 (bndrs `zip` map fst prs')
588                 ; tidy_env2 = (occ_env2, subst2) }
589         ; return (tidy_env2, Rec prs') }
590   where
591     bndrs = map fst prs
592
593         -- the CafInfo for a recursive group says whether *any* rhs in
594         -- the group may refer indirectly to a CAF (because then, they all do).
595     caf_info 
596         | or [ mayHaveCafRefs (hasCafRefs dflags subst1 (idArity bndr) rhs)
597              | (bndr,rhs) <- prs ] = MayHaveCafRefs
598         | otherwise                = NoCafRefs
599
600 --------------------------------------------------------------------
601 --              tidyTopName
602 -- This is where we set names to local/global based on whether they really are 
603 -- externally visible (see comment at the top of this module).  If the name
604 -- was previously local, we have to give it a unique occurrence name if
605 -- we intend to externalise it.
606 tidyTopNames mod nc_var ext_ids occ_env [] = return (occ_env, [])
607 tidyTopNames mod nc_var ext_ids occ_env (id:ids)
608   = do  { (occ_env1, name)  <- tidyTopName  mod nc_var ext_ids occ_env id
609         ; (occ_env2, names) <- tidyTopNames mod nc_var ext_ids occ_env1 ids
610         ; return (occ_env2, name:names) }
611
612 tidyTopName :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
613             -> Id -> IO (TidyOccEnv, Name)
614 tidyTopName mod nc_var ext_ids occ_env id
615   | global && internal = return (occ_env, localiseName name)
616
617   | global && external = return (occ_env, name)
618         -- Global names are assumed to have been allocated by the renamer,
619         -- so they already have the "right" unique
620         -- And it's a system-wide unique too
621
622   -- Now we get to the real reason that all this is in the IO Monad:
623   -- we have to update the name cache in a nice atomic fashion
624
625   | local  && internal = do { nc <- readIORef nc_var
626                             ; let (nc', new_local_name) = mk_new_local nc
627                             ; writeIORef nc_var nc'
628                             ; return (occ_env', new_local_name) }
629         -- Even local, internal names must get a unique occurrence, because
630         -- if we do -split-objs we externalise the name later, in the code generator
631         --
632         -- Similarly, we must make sure it has a system-wide Unique, because
633         -- the byte-code generator builds a system-wide Name->BCO symbol table
634
635   | local  && external = do { nc <- readIORef nc_var
636                             ; let (nc', new_external_name) = mk_new_external nc
637                             ; writeIORef nc_var nc'
638                             ; return (occ_env', new_external_name) }
639   where
640     name        = idName id
641     external    = id `elemVarEnv` ext_ids
642     global      = isExternalName name
643     local       = not global
644     internal    = not external
645     mb_parent   = nameParent_maybe name
646     loc         = nameSrcLoc name
647
648     (occ_env', occ') = tidyOccName occ_env (nameOccName name)
649
650     mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
651                     where
652                       (us1, us2) = splitUniqSupply (nsUniqs nc)
653                       uniq       = uniqFromSupply us1
654
655     mk_new_external nc = allocateGlobalBinder nc mod occ' mb_parent loc
656         -- If we want to externalise a currently-local name, check
657         -- whether we have already assigned a unique for it.
658         -- If so, use it; if not, extend the table.
659         -- All this is done by allcoateGlobalBinder.
660         -- This is needed when *re*-compiling a module in GHCi; we must
661         -- use the same name for externally-visible things as we did before.
662
663
664 -----------------------------------------------------------
665 tidyTopPair :: VarEnv Bool
666             -> TidyEnv  -- The TidyEnv is used to tidy the IdInfo
667                         -- It is knot-tied: don't look at it!
668             -> CafInfo
669             -> Name             -- New name
670             -> (Id, CoreExpr)   -- Binder and RHS before tidying
671             -> (Id, CoreExpr)
672         -- This function is the heart of Step 2
673         -- The rec_tidy_env is the one to use for the IdInfo
674         -- It's necessary because when we are dealing with a recursive
675         -- group, a variable late in the group might be mentioned
676         -- in the IdInfo of one early in the group
677
678 tidyTopPair ext_ids rhs_tidy_env caf_info name' (bndr, rhs)
679   | isGlobalId bndr             -- Injected binding for record selector, etc
680   = (bndr, tidyExpr rhs_tidy_env rhs)
681   | otherwise
682   = (bndr', rhs')
683   where
684     bndr'   = mkVanillaGlobal name' ty' idinfo'
685     ty'     = tidyTopType (idType bndr)
686     rhs'    = tidyExpr rhs_tidy_env rhs
687     idinfo' = tidyTopIdInfo rhs_tidy_env (isJust maybe_external)
688                             (idInfo bndr) unfold_info arity
689                             caf_info
690
691     -- Expose an unfolding if ext_ids tells us to
692     -- Remember that ext_ids maps an Id to a Bool: 
693     --  True to show the unfolding, False to hide it
694     maybe_external = lookupVarEnv ext_ids bndr
695     show_unfold = maybe_external `orElse` False
696     unfold_info | show_unfold = mkTopUnfolding rhs'
697                 | otherwise   = noUnfolding
698
699     -- Usually the Id will have an accurate arity on it, because
700     -- the simplifier has just run, but not always. 
701     -- One case I found was when the last thing the simplifier
702     -- did was to let-bind a non-atomic argument and then float
703     -- it to the top level. So it seems more robust just to
704     -- fix it here.
705     arity = exprArity rhs
706
707
708 -- tidyTopIdInfo creates the final IdInfo for top-level
709 -- binders.  There are two delicate pieces:
710 --
711 --  * Arity.  After CoreTidy, this arity must not change any more.
712 --      Indeed, CorePrep must eta expand where necessary to make
713 --      the manifest arity equal to the claimed arity.
714 --
715 --  * CAF info.  This must also remain valid through to code generation.
716 --      We add the info here so that it propagates to all
717 --      occurrences of the binders in RHSs, and hence to occurrences in
718 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
719 --      CoreToStg makes use of this when constructing SRTs.
720
721 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity caf_info
722   | not is_external     -- For internal Ids (not externally visible)
723   = vanillaIdInfo       -- we only need enough info for code generation
724                         -- Arity and strictness info are enough;
725                         --      c.f. CoreTidy.tidyLetBndr
726         `setCafInfo`           caf_info
727         `setArityInfo`         arity
728         `setAllStrictnessInfo` newStrictnessInfo idinfo
729
730   | otherwise           -- Externally-visible Ids get the whole lot
731   = vanillaIdInfo
732         `setCafInfo`           caf_info
733         `setArityInfo`         arity
734         `setAllStrictnessInfo` newStrictnessInfo idinfo
735         `setInlinePragInfo`    inlinePragInfo idinfo
736         `setUnfoldingInfo`     unfold_info
737         `setWorkerInfo`        tidyWorker tidy_env (workerInfo idinfo)
738                 -- NB: we throw away the Rules
739                 -- They have already been extracted by findExternalRules
740
741
742
743 ------------  Worker  --------------
744 tidyWorker tidy_env (HasWorker work_id wrap_arity) 
745   = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
746 tidyWorker tidy_env other
747   = NoWorker
748 \end{code}
749
750 %************************************************************************
751 %*                                                                      *
752 \subsection{Figuring out CafInfo for an expression}
753 %*                                                                      *
754 %************************************************************************
755
756 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
757 We mark such things as `MayHaveCafRefs' because this information is
758 used to decide whether a particular closure needs to be referenced
759 in an SRT or not.
760
761 There are two reasons for setting MayHaveCafRefs:
762         a) The RHS is a CAF: a top-level updatable thunk.
763         b) The RHS refers to something that MayHaveCafRefs
764
765 Possible improvement: In an effort to keep the number of CAFs (and 
766 hence the size of the SRTs) down, we could also look at the expression and 
767 decide whether it requires a small bounded amount of heap, so we can ignore 
768 it as a CAF.  In these cases however, we would need to use an additional
769 CAF list to keep track of non-collectable CAFs.  
770
771 \begin{code}
772 hasCafRefs  :: DynFlags -> VarEnv Var -> Arity -> CoreExpr -> CafInfo
773 hasCafRefs dflags p arity expr 
774   | is_caf || mentions_cafs = MayHaveCafRefs
775   | otherwise               = NoCafRefs
776  where
777   mentions_cafs = isFastTrue (cafRefs p expr)
778   is_caf = not (arity > 0 || rhsIsStatic dflags expr)
779   -- NB. we pass in the arity of the expression, which is expected
780   -- to be calculated by exprArity.  This is because exprArity
781   -- knows how much eta expansion is going to be done by 
782   -- CorePrep later on, and we don't want to duplicate that
783   -- knowledge in rhsIsStatic below.
784
785 cafRefs p (Var id)
786         -- imported Ids first:
787   | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
788         -- now Ids local to this module:
789   | otherwise =
790      case lookupVarEnv p id of
791         Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
792         Nothing  -> fastBool False
793
794 cafRefs p (Lit l)              = fastBool False
795 cafRefs p (App f a)            = fastOr (cafRefs p f) (cafRefs p) a
796 cafRefs p (Lam x e)            = cafRefs p e
797 cafRefs p (Let b e)            = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
798 cafRefs p (Case e bndr _ alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
799 cafRefs p (Note n e)           = cafRefs p e
800 cafRefs p (Type t)             = fastBool False
801
802 cafRefss p []     = fastBool False
803 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
804
805 -- hack for lazy-or over FastBool.
806 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))
807 \end{code}