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