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