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