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