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