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