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