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