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