88a30596010a36629ff58fbb9dad68e052c0a929
[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 CoreArity        ( exprArity )
23 import Class            ( classSelIds )
24 import VarEnv
25 import VarSet
26 import Var
27 import Id
28 import IdInfo
29 import InstEnv
30 import NewDemand
31 import BasicTypes
32 import Name hiding (varName)
33 import NameSet
34 import IfaceEnv
35 import NameEnv
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 import Util
47
48 import Data.List        ( sortBy )
49 import Data.IORef       ( IORef, readIORef, writeIORef )
50 \end{code}
51
52
53 Constructing the TypeEnv, Instances, Rules, VectInfo from which the
54 ModIface is constructed, and which goes on to subsequent modules in
55 --make mode.
56
57 Most of the interface file is obtained simply by serialising the
58 TypeEnv.  One important consequence is that if the *interface file*
59 has pragma info if and only if the final TypeEnv does. This is not so
60 important for *this* module, but it's essential for ghc --make:
61 subsequent compilations must not see (e.g.) the arity if the interface
62 file does not contain arity If they do, they'll exploit the arity;
63 then the arity might change, but the iface file doesn't change =>
64 recompilation does not happen => disaster. 
65
66 For data types, the final TypeEnv will have a TyThing for the TyCon,
67 plus one for each DataCon; the interface file will contain just one
68 data type declaration, but it is de-serialised back into a collection
69 of TyThings.
70
71 %************************************************************************
72 %*                                                                      *
73                 Plan A: simpleTidyPgm
74 %*                                                                      * 
75 %************************************************************************
76
77
78 Plan A: mkBootModDetails: omit pragmas, make interfaces small
79 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
80 * Ignore the bindings
81
82 * Drop all WiredIn things from the TypeEnv 
83         (we never want them in interface files)
84
85 * Retain all TyCons and Classes in the TypeEnv, to avoid
86         having to find which ones are mentioned in the
87         types of exported Ids
88
89 * Trim off the constructors of non-exported TyCons, both
90         from the TyCon and from the TypeEnv
91
92 * Drop non-exported Ids from the TypeEnv
93
94 * Tidy the types of the DFunIds of Instances, 
95   make them into GlobalIds, (they already have External Names)
96   and add them to the TypeEnv
97
98 * Tidy the types of the (exported) Ids in the TypeEnv,
99   make them into GlobalIds (they already have External Names)
100
101 * Drop rules altogether
102
103 * Tidy the bindings, to ensure that the Caf and Arity
104   information is correct for each top-level binder; the 
105   code generator needs it. And to ensure that local names have
106   distinct OccNames in case of object-file splitting
107
108 \begin{code}
109 -- This is Plan A: make a small type env when typechecking only,
110 -- or when compiling a hs-boot file, or simply when not using -O
111 --
112 -- We don't look at the bindings at all -- there aren't any
113 -- for hs-boot files
114
115 mkBootModDetailsTc :: HscEnv -> TcGblEnv -> IO ModDetails
116 mkBootModDetailsTc hsc_env 
117         TcGblEnv{ tcg_exports   = exports,
118                   tcg_type_env  = type_env,
119                   tcg_insts     = insts,
120                   tcg_fam_insts = fam_insts
121                 }
122   = mkBootModDetails hsc_env exports type_env insts fam_insts
123
124 mkBootModDetailsDs :: HscEnv -> ModGuts -> IO ModDetails
125 mkBootModDetailsDs hsc_env 
126         ModGuts{ mg_exports   = exports,
127                  mg_types     = type_env,
128                  mg_insts     = insts,
129                  mg_fam_insts = fam_insts
130                 }
131   = mkBootModDetails hsc_env exports type_env insts fam_insts
132   
133 mkBootModDetails :: HscEnv -> [AvailInfo] -> NameEnv TyThing
134                  -> [Instance] -> [FamInstEnv.FamInst] -> IO ModDetails
135 mkBootModDetails hsc_env exports type_env insts fam_insts
136   = do  { let dflags = hsc_dflags hsc_env 
137         ; showPass dflags "Tidy [hoot] type env"
138
139         ; let { insts'     = tidyInstances globaliseAndTidyId insts
140               ; dfun_ids   = map instanceDFunId insts'
141               ; type_env1  = tidyBootTypeEnv (availsToNameSet exports) type_env
142               ; type_env'  = extendTypeEnvWithIds type_env1 dfun_ids
143               }
144         ; return (ModDetails { md_types     = type_env'
145                              , md_insts     = insts'
146                              , md_fam_insts = fam_insts
147                              , md_rules     = []
148                              , md_anns      = []
149                              , md_exports   = exports
150                              , md_vect_info = noVectInfo
151                              })
152         }
153   where
154
155 tidyBootTypeEnv :: NameSet -> TypeEnv -> TypeEnv
156 tidyBootTypeEnv exports type_env 
157   = tidyTypeEnv True False exports type_env final_ids
158   where
159         -- Find the LocalIds in the type env that are exported
160         -- Make them into GlobalIds, and tidy their types
161         --
162         -- It's very important to remove the non-exported ones
163         -- because we don't tidy the OccNames, and if we don't remove
164         -- the non-exported ones we'll get many things with the
165         -- same name in the interface file, giving chaos.
166     final_ids = [ globaliseAndTidyId id
167                 | id <- typeEnvIds type_env
168                 , isLocalId id
169                 , keep_it id ]
170
171         -- default methods have their export flag set, but everything
172         -- else doesn't (yet), because this is pre-desugaring, so we
173         -- must test both.
174     keep_it id = isExportedId id || idName id `elemNameSet` exports
175
176
177
178 globaliseAndTidyId :: Id -> Id
179 -- Takes an LocalId with an External Name, 
180 -- makes it into a GlobalId 
181 --     * unchanged Name (might be Internal or External)
182 --     * unchanged details
183 --     * VanillaIdInfo (makes a conservative assumption about Caf-hood)
184 globaliseAndTidyId id   
185   = Id.setIdType (globaliseId id) tidy_type
186   where
187     tidy_type = tidyTopType (idType id)
188 \end{code}
189
190
191 %************************************************************************
192 %*                                                                      *
193         Plan B: tidy bindings, make TypeEnv full of IdInfo
194 %*                                                                      * 
195 %************************************************************************
196
197 Plan B: include pragmas, make interfaces 
198 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
199 * Figure out which Ids are externally visible
200
201 * Tidy the bindings, externalising appropriate Ids
202
203 * Drop all Ids from the TypeEnv, and add all the External Ids from 
204   the bindings.  (This adds their IdInfo to the TypeEnv; and adds
205   floated-out Ids that weren't even in the TypeEnv before.)
206
207 Step 1: Figure out external Ids
208 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
209 Note [choosing external names]
210
211 See also the section "Interface stability" in the
212 RecompilationAvoidance commentary:
213   http://hackage.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance
214
215 First we figure out which Ids are "external" Ids.  An
216 "external" Id is one that is visible from outside the compilation
217 unit.  These are
218         a) the user exported ones
219         b) ones mentioned in the unfoldings, workers, 
220            or rules of externally-visible ones 
221
222 While figuring out which Ids are external, we pick a "tidy" OccName
223 for each one.  That is, we make its OccName distinct from the other
224 external OccNames in this module, so that in interface files and
225 object code we can refer to it unambiguously by its OccName.  The
226 OccName for each binder is prefixed by the name of the exported Id
227 that references it; e.g. if "f" references "x" in its unfolding, then
228 "x" is renamed to "f_x".  This helps distinguish the different "x"s
229 from each other, and means that if "f" is later removed, things that
230 depend on the other "x"s will not need to be recompiled.  Of course,
231 if there are multiple "f_x"s, then we have to disambiguate somehow; we
232 use "f_x0", "f_x1" etc.
233
234 As far as possible we should assign names in a deterministic fashion.
235 Each time this module is compiled with the same options, we should end
236 up with the same set of external names with the same types.  That is,
237 the ABI hash in the interface should not change.  This turns out to be
238 quite tricky, since the order of the bindings going into the tidy
239 phase is already non-deterministic, as it is based on the ordering of
240 Uniques, which are assigned unpredictably.
241
242 To name things in a stable way, we do a depth-first-search of the
243 bindings, starting from the exports sorted by name.  This way, as long
244 as the bindings themselves are deterministic (they sometimes aren't!),
245 the order in which they are presented to the tidying phase does not
246 affect the names we assign.
247
248 Step 2: Tidy the program
249 ~~~~~~~~~~~~~~~~~~~~~~~~
250 Next we traverse the bindings top to bottom.  For each *top-level*
251 binder
252
253  1. Make it into a GlobalId; its IdDetails becomes VanillaGlobal, 
254     reflecting the fact that from now on we regard it as a global, 
255     not local, Id
256
257  2. Give it a system-wide Unique.
258     [Even non-exported things need system-wide Uniques because the
259     byte-code generator builds a single Name->BCO symbol table.]
260
261     We use the NameCache kept in the HscEnv as the
262     source of such system-wide uniques.
263
264     For external Ids, use the original-name cache in the NameCache
265     to ensure that the unique assigned is the same as the Id had 
266     in any previous compilation run.
267
268  3. Rename top-level Ids according to the names we chose in step 1.
269     If it's an external Id, make it have a External Name, otherwise
270     make it have an Internal Name.  This is used by the code generator
271     to decide whether to make the label externally visible
272
273  4. Give it its UTTERLY FINAL IdInfo; in ptic, 
274         * its unfolding, if it should have one
275         
276         * its arity, computed from the number of visible lambdas
277
278         * its CAF info, computed from what is free in its RHS
279
280                 
281 Finally, substitute these new top-level binders consistently
282 throughout, including in unfoldings.  We also tidy binders in
283 RHSs, so that they print nicely in interfaces.
284
285 \begin{code}
286 tidyProgram :: HscEnv -> ModGuts -> IO (CgGuts, ModDetails)
287 tidyProgram hsc_env  (ModGuts { mg_module = mod, mg_exports = exports, 
288                                 mg_types = type_env, 
289                                 mg_insts = insts, mg_fam_insts = fam_insts,
290                                 mg_binds = binds, 
291                                 mg_rules = imp_rules,
292                                 mg_vect_info = vect_info,
293                                 mg_dir_imps = dir_imps, 
294                                 mg_anns = anns,
295                                 mg_deps = deps, 
296                                 mg_foreign = foreign_stubs,
297                                 mg_hpc_info = hpc_info,
298                                 mg_modBreaks = modBreaks })
299
300   = do  { let dflags = hsc_dflags hsc_env
301         ; showPass dflags "Tidy Core"
302
303         ; let { omit_prags = dopt Opt_OmitInterfacePragmas dflags
304               ; th         = dopt Opt_TemplateHaskell      dflags
305               }
306
307         ; let { implicit_binds = getImplicitBinds type_env }
308
309         ; (unfold_env, tidy_occ_env)
310               <- chooseExternalIds hsc_env mod omit_prags binds implicit_binds
311
312         ; let { ext_rules 
313                    | omit_prags = []
314                    | otherwise  = findExternalRules binds imp_rules unfold_env
315                 -- findExternalRules filters imp_rules to avoid binders that 
316                 -- aren't externally visible; but the externally-visible binders 
317                 -- are computed (by findExternalIds) assuming that all orphan
318                 -- rules are exported (they get their Exported flag set in the desugarer)
319                 -- So in fact we may export more than we need. 
320                 -- (It's a sort of mutual recursion.)
321         }
322
323         ; let { (tidy_env, tidy_binds)
324                  = tidyTopBinds hsc_env unfold_env tidy_occ_env binds }
325
326         ; let { export_set = availsToNameSet exports
327               ; final_ids  = [ id | id <- bindersOfBinds tidy_binds, 
328                                     isExternalName (idName id)]
329               ; tidy_type_env = tidyTypeEnv omit_prags th export_set
330                                             type_env final_ids
331               ; tidy_insts    = tidyInstances (lookup_dfun tidy_type_env) insts
332                 -- A DFunId will have a binding in tidy_binds, and so
333                 -- will now be in final_env, replete with IdInfo
334                 -- Its name will be unchanged since it was born, but
335                 -- we want Global, IdInfo-rich (or not) DFunId in the
336                 -- tidy_insts
337
338               ; tidy_rules = tidyRules tidy_env ext_rules
339                 -- You might worry that the tidy_env contains IdInfo-rich stuff
340                 -- and indeed it does, but if omit_prags is on, ext_rules is
341                 -- empty
342
343               ; tidy_vect_info = tidyVectInfo tidy_env vect_info
344
345               -- See Note [Injecting implicit bindings]
346               ; all_tidy_binds = implicit_binds ++ tidy_binds
347
348               ; alg_tycons = filter isAlgTyCon (typeEnvTyCons type_env)
349               }
350
351         ; endPass dflags "Tidy Core" Opt_D_dump_simpl all_tidy_binds
352         ; dumpIfSet_core dflags Opt_D_dump_simpl
353                 "Tidy Core Rules"
354                 (pprRules tidy_rules)
355
356         ; let dir_imp_mods = moduleEnvKeys dir_imps
357
358         ; return (CgGuts { cg_module   = mod, 
359                            cg_tycons   = alg_tycons,
360                            cg_binds    = all_tidy_binds,
361                            cg_dir_imps = dir_imp_mods,
362                            cg_foreign  = foreign_stubs,
363                            cg_dep_pkgs = dep_pkgs deps,
364                            cg_hpc_info = hpc_info,
365                            cg_modBreaks = modBreaks }, 
366
367                    ModDetails { md_types     = tidy_type_env,
368                                 md_rules     = tidy_rules,
369                                 md_insts     = tidy_insts,
370                                 md_vect_info = tidy_vect_info,                                                   md_fam_insts = fam_insts,
371                                 md_exports   = exports,
372                                 md_anns      = anns      -- are already tidy
373                               })
374         }
375
376 lookup_dfun :: TypeEnv -> Var -> Id
377 lookup_dfun type_env dfun_id
378   = case lookupTypeEnv type_env (idName dfun_id) of
379         Just (AnId dfun_id') -> dfun_id'
380         _other -> pprPanic "lookup_dfun" (ppr dfun_id)
381
382 --------------------------
383 tidyTypeEnv :: Bool     -- Compiling without -O, so omit prags
384             -> Bool     -- Template Haskell is on
385             -> NameSet -> TypeEnv -> [Id] -> TypeEnv
386
387 -- The competed type environment is gotten from
388 --      Dropping any wired-in things, and then
389 --      a) keeping the types and classes
390 --      b) removing all Ids, 
391 --      c) adding Ids with correct IdInfo, including unfoldings,
392 --              gotten from the bindings
393 -- From (c) we keep only those Ids with External names;
394 --          the CoreTidy pass makes sure these are all and only
395 --          the externally-accessible ones
396 -- This truncates the type environment to include only the 
397 -- exported Ids and things needed from them, which saves space
398
399 tidyTypeEnv omit_prags th exports type_env final_ids
400  = let  type_env1 = filterNameEnv keep_it type_env
401         type_env2 = extendTypeEnvWithIds type_env1 final_ids
402         type_env3 | omit_prags = mapNameEnv (trimThing th exports) type_env2
403                   | otherwise  = type_env2
404     in 
405     type_env3
406   where
407         -- We keep GlobalIds, because they won't appear 
408         -- in the bindings from which final_ids are derived!
409         -- (The bindings bind LocalIds.)
410     keep_it thing | isWiredInThing thing = False
411     keep_it (AnId id) = isGlobalId id   -- Keep GlobalIds (e.g. class ops)
412     keep_it _other    = True            -- Keep all TyCons, DataCons, and Classes
413
414 --------------------------
415 isWiredInThing :: TyThing -> Bool
416 isWiredInThing thing = isWiredInName (getName thing)
417
418 --------------------------
419 trimThing :: Bool -> NameSet -> TyThing -> TyThing
420 -- Trim off inessentials, for boot files and no -O
421 trimThing th exports (ATyCon tc)
422    | not th && not (mustExposeTyCon exports tc)
423    = ATyCon (makeTyConAbstract tc)      -- Note [Trimming and Template Haskell]
424
425 trimThing _th _exports (AnId id)
426    | not (isImplicitId id) 
427    = AnId (id `setIdInfo` vanillaIdInfo)
428
429 trimThing _th _exports other_thing 
430   = other_thing
431
432
433 {- Note [Trimming and Template Haskell]
434    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
435 Consider (Trac #2386) this
436         module M(T, makeOne) where
437           data T = Yay String
438           makeOne = [| Yay "Yep" |]
439 Notice that T is exported abstractly, but makeOne effectively exports it too!
440 A module that splices in $(makeOne) will then look for a declartion of Yay,
441 so it'd better be there.  Hence, brutally but simply, we switch off type
442 constructor trimming if TH is enabled in this module. -}
443
444
445 mustExposeTyCon :: NameSet      -- Exports
446                 -> TyCon        -- The tycon
447                 -> Bool         -- Can its rep be hidden?
448 -- We are compiling without -O, and thus trying to write as little as 
449 -- possible into the interface file.  But we must expose the details of
450 -- any data types whose constructors or fields are exported
451 mustExposeTyCon exports tc
452   | not (isAlgTyCon tc)         -- Synonyms
453   = True
454   | isEnumerationTyCon tc       -- For an enumeration, exposing the constructors
455   = True                        -- won't lead to the need for further exposure
456                                 -- (This includes data types with no constructors.)
457   | isOpenTyCon tc              -- Open type family
458   = True
459
460   | otherwise                   -- Newtype, datatype
461   = any exported_con (tyConDataCons tc)
462         -- Expose rep if any datacon or field is exported
463
464   || (isNewTyCon tc && isFFITy (snd (newTyConRhs tc)))
465         -- Expose the rep for newtypes if the rep is an FFI type.  
466         -- For a very annoying reason.  'Foreign import' is meant to
467         -- be able to look through newtypes transparently, but it
468         -- can only do that if it can "see" the newtype representation
469   where
470     exported_con con = any (`elemNameSet` exports) 
471                            (dataConName con : dataConFieldLabels con)
472
473 tidyInstances :: (DFunId -> DFunId) -> [Instance] -> [Instance]
474 tidyInstances tidy_dfun ispecs
475   = map tidy ispecs
476   where
477     tidy ispec = setInstanceDFunId ispec $
478                  tidy_dfun (instanceDFunId ispec)
479 \end{code}
480
481 \begin{code}
482 tidyVectInfo :: TidyEnv -> VectInfo -> VectInfo
483 tidyVectInfo (_, var_env) info@(VectInfo { vectInfoVar     = vars
484                                          , vectInfoPADFun  = pas
485                                          , vectInfoIso     = isos })
486   = info { vectInfoVar    = tidy_vars
487          , vectInfoPADFun = tidy_pas
488          , vectInfoIso    = tidy_isos }
489   where
490     tidy_vars = mkVarEnv
491               $ map tidy_var_mapping
492               $ varEnvElts vars
493
494     tidy_pas = mapNameEnv tidy_snd_var pas
495     tidy_isos = mapNameEnv tidy_snd_var isos
496
497     tidy_var_mapping (from, to) = (from', (from', lookup_var to))
498       where from' = lookup_var from
499     tidy_snd_var (x, var) = (x, lookup_var var)
500       
501     lookup_var var = lookupWithDefaultVarEnv var_env var var
502 \end{code}
503
504
505 %************************************************************************
506 %*                                                                      *
507         Implicit bindings
508 %*                                                                      *
509 %************************************************************************
510
511 Note [Injecting implicit bindings]
512 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
513 We inject the implict bindings right at the end, in CoreTidy.
514 Some of these bindings, notably record selectors, are not
515 constructed in an optimised form.  E.g. record selector for
516         data T = MkT { x :: {-# UNPACK #-} !Int }
517 Then the unfolding looks like
518         x = \t. case t of MkT x1 -> let x = I# x1 in x
519 This generates bad code unless it's first simplified a bit.  That is
520 why CoreUnfold.mkImplicitUnfolding uses simleExprOpt to do a bit of
521 optimisation first.  (Only matters when the selector is used curried;
522 eg map x ys.)  See Trac #2070.
523
524 [Oct 09: in fact, record selectors are no longer implicit Ids at all,
525 because we really do want to optimise them properly. They are treated
526 much like any other Id.  But doing "light" optimisation on an implicit
527 Id still makes sense.]
528
529 At one time I tried injecting the implicit bindings *early*, at the
530 beginning of SimplCore.  But that gave rise to real difficulty,
531 becuase GlobalIds are supposed to have *fixed* IdInfo, but the
532 simplifier and other core-to-core passes mess with IdInfo all the
533 time.  The straw that broke the camels back was when a class selector
534 got the wrong arity -- ie the simplifier gave it arity 2, whereas
535 importing modules were expecting it to have arity 1 (Trac #2844).
536 It's much safer just to inject them right at the end, after tidying.
537
538 Oh: two other reasons for injecting them late:
539
540   - If implicit Ids are already in the bindings when we start TidyPgm,
541     we'd have to be careful not to treat them as external Ids (in
542     the sense of findExternalIds); else the Ids mentioned in *their*
543     RHSs will be treated as external and you get an interface file 
544     saying      a18 = <blah>
545     but nothing refererring to a18 (because the implicit Id is the 
546     one that does, and implicit Ids don't appear in interface files).
547
548   - More seriously, the tidied type-envt will include the implicit
549     Id replete with a18 in its unfolding; but we won't take account
550     of a18 when computing a fingerprint for the class; result chaos.
551     
552 There is one sort of implicit binding that is injected still later,
553 namely those for data constructor workers. Reason (I think): it's
554 really just a code generation trick.... binding itself makes no sense.
555 See CorePrep Note [Data constructor workers].
556
557 \begin{code}
558 getImplicitBinds :: TypeEnv -> [CoreBind]
559 getImplicitBinds type_env
560   = map get_defn (concatMap implicit_ids (typeEnvElts type_env))
561   where
562     implicit_ids (ATyCon tc)  = mapCatMaybes dataConWrapId_maybe (tyConDataCons tc)
563     implicit_ids (AClass cls) = classSelIds cls
564     implicit_ids _            = []
565     
566     get_defn :: Id -> CoreBind
567     get_defn id = NonRec id (unfoldingTemplate (idUnfolding id))
568 \end{code}
569
570
571 %************************************************************************
572 %*                                                                      *
573 \subsection{Step 1: finding externals}
574 %*                                                                      * 
575 %************************************************************************
576
577 Sete Note [choosing external names].
578
579 \begin{code}
580 type UnfoldEnv  = IdEnv (Name{-new name-}, Bool {-show unfolding-})
581   -- maps each top-level Id to its new Name (the Id is tidied in step 2)
582   -- The Unique is unchanged.  If the new Id is external, it will be
583   -- visible in the interface file.  
584   --
585   -- Bool => expose unfolding or not.
586
587 chooseExternalIds :: HscEnv
588                   -> Module
589                   -> Bool
590                   -> [CoreBind]
591                   -> [CoreBind]
592                   -> IO (UnfoldEnv, TidyOccEnv)
593         -- Step 1 from the notes above
594
595 chooseExternalIds hsc_env mod omit_prags binds implicit_binds
596   = do
597     (unfold_env1,occ_env1) 
598         <- search (zip sorted_exports sorted_exports) emptyVarEnv init_occ_env
599     let internal_ids = filter (not . (`elemVarEnv` unfold_env1)) binders
600     tidy_internal internal_ids unfold_env1 occ_env1
601  where
602   nc_var = hsc_NC hsc_env 
603
604   -- the exports, sorted by OccName.  This is a deterministic list of
605   -- Ids (i.e. it's the same list every time this module is compiled),
606   -- in contrast to the bindings, which are ordered
607   -- non-deterministically.
608   --
609   -- This list will serve as a starting point for finding a
610   -- deterministic, tidy, renaming for all external Ids in this
611   -- module.
612   sorted_exports = sortBy (compare `on` getOccName) $
613                      filter isExportedId binders
614
615   binders = bindersOfBinds binds
616   implicit_binders = bindersOfBinds implicit_binds
617
618   bind_env :: IdEnv (Id,CoreExpr)
619   bind_env = mkVarEnv (zip (map fst bs) bs) where bs = flattenBinds binds
620
621   avoids   = [getOccName name | bndr <- binders ++ implicit_binders,
622                                 let name = idName bndr,
623                                 isExternalName name ]
624                 -- In computing our "avoids" list, we must include
625                 --      all implicit Ids
626                 --      all things with global names (assigned once and for
627                 --                                      all by the renamer)
628                 -- since their names are "taken".
629                 -- The type environment is a convenient source of such things.
630                 -- In particular, the set of binders doesn't include
631                 -- implicit Ids at this stage.
632
633         -- We also make sure to avoid any exported binders.  Consider
634         --      f{-u1-} = 1     -- Local decl
635         --      ...
636         --      f{-u2-} = 2     -- Exported decl
637         --
638         -- The second exported decl must 'get' the name 'f', so we
639         -- have to put 'f' in the avoids list before we get to the first
640         -- decl.  tidyTopId then does a no-op on exported binders.
641   init_occ_env = initTidyOccEnv avoids
642
643
644   search :: [(Id,Id)]    -- (external id, referrring id)
645          -> UnfoldEnv    -- id -> (new Name, show_unfold)
646          -> TidyOccEnv   -- occ env for choosing new Names
647          -> IO (UnfoldEnv, TidyOccEnv)
648
649   search [] unfold_env occ_env = return (unfold_env, occ_env)
650
651   search ((idocc,referrer) : rest) unfold_env occ_env
652     | idocc `elemVarEnv` unfold_env = search rest unfold_env occ_env
653     | otherwise = do
654       (occ_env', name') <- tidyTopName mod nc_var (Just referrer) occ_env idocc
655       let 
656           (id, rhs) = expectJust (showSDoc (text "chooseExternalIds: " <>
657                                             ppr idocc)) $
658                                  lookupVarEnv bind_env idocc
659           -- NB. idocc might be an *occurrence* of an Id, whereas we want
660           -- the Id from the binding site, because only the latter is
661           -- guaranteed to have the unfolding attached.  This is why we
662           -- keep binding site Ids in the bind_env.
663           (new_ids, show_unfold)
664                 | omit_prags = ([], False)
665                 | otherwise  = addExternal id rhs
666           unfold_env' = extendVarEnv unfold_env id (name',show_unfold)
667           referrer' | isExportedId id = id
668                     | otherwise       = referrer
669       --
670       search (zip new_ids (repeat referrer') ++ rest) unfold_env' occ_env'
671
672   tidy_internal :: [Id] -> UnfoldEnv -> TidyOccEnv
673                 -> IO (UnfoldEnv, TidyOccEnv)
674   tidy_internal []       unfold_env occ_env = return (unfold_env,occ_env)
675   tidy_internal (id:ids) unfold_env occ_env = do
676       (occ_env', name') <- tidyTopName mod nc_var Nothing occ_env id
677       let unfold_env' = extendVarEnv unfold_env id (name',False)
678       tidy_internal ids unfold_env' occ_env'
679
680 addExternal :: Id -> CoreExpr -> ([Id],Bool)
681 addExternal id rhs = (new_needed_ids, show_unfold)
682   where
683     new_needed_ids = unfold_ids ++
684                      filter (\id -> isLocalId id &&
685                                     not (id `elemVarSet` unfold_set))
686                        (varSetElems worker_ids ++ 
687                         varSetElems spec_ids) -- XXX non-det ordering
688
689     idinfo         = idInfo id
690     dont_inline    = isNeverActive (inlinePragmaActivation (inlinePragInfo idinfo))
691     loop_breaker   = isNonRuleLoopBreaker (occInfo idinfo)
692     bottoming_fn   = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
693     spec_ids       = specInfoFreeVars (specInfo idinfo)
694     worker_info    = workerInfo idinfo
695
696         -- Stuff to do with the Id's unfolding
697         -- The simplifier has put an up-to-date unfolding
698         -- in the IdInfo, but the RHS will do just as well
699     unfolding    = unfoldingInfo idinfo
700     rhs_is_small = not (neverUnfold unfolding)
701
702         -- We leave the unfolding there even if there is a worker
703         -- In GHCI the unfolding is used by importers
704         -- When writing an interface file, we omit the unfolding 
705         -- if there is a worker
706     show_unfold = not bottoming_fn       &&     -- Not necessary
707                   not dont_inline        &&
708                   not loop_breaker       &&
709                   rhs_is_small                  -- Small enough
710
711     (unfold_set, unfold_ids)
712                | show_unfold = freeVarsInDepthFirstOrder rhs
713                | otherwise   = (emptyVarSet, [])
714
715     worker_ids = case worker_info of
716                    HasWorker work_id _ -> unitVarSet work_id
717                    _otherwise          -> emptyVarSet
718
719
720 -- We want a deterministic free-variable list.  exprFreeVars gives us
721 -- a VarSet, which is in a non-deterministic order when converted to a
722 -- list.  Hence, here we define a free-variable finder that returns
723 -- the free variables in the order that they are encountered.
724 --
725 -- Note [choosing external names]
726
727 freeVarsInDepthFirstOrder :: CoreExpr -> (VarSet, [Id])
728 freeVarsInDepthFirstOrder e = 
729   case dffvExpr e of
730     DFFV m -> case m emptyVarSet [] of
731                 (set,ids,_) -> (set,ids)
732
733 newtype DFFV a = DFFV (VarSet -> [Var] -> (VarSet,[Var],a))
734
735 instance Monad DFFV where
736   return a = DFFV $ \set ids -> (set, ids, a)
737   (DFFV m) >>= k = DFFV $ \set ids ->
738     case m set ids of
739        (set',ids',a) -> case k a of
740                           DFFV f -> f set' ids' 
741
742 insert :: Var -> DFFV ()
743 insert v = DFFV $ \ set ids  -> case () of 
744  _ | v `elemVarSet` set -> (set,ids,())
745    | otherwise          -> (extendVarSet set v, v:ids, ())
746
747 dffvExpr :: CoreExpr -> DFFV ()
748 dffvExpr e = go emptyVarSet e
749   where
750     go scope e = case e of
751       Var v | isLocalId v && not (v `elemVarSet` scope) -> insert v
752       App e1 e2          -> do go scope e1; go scope e2
753       Lam v e            -> go (extendVarSet scope v) e
754       Note _ e           -> go scope e
755       Cast e _           -> go scope e
756       Let (NonRec x r) e -> do go scope r; go (extendVarSet scope x) e
757       Let (Rec prs) e    -> do let scope' = extendVarSetList scope (map fst prs)
758                                mapM_ (go scope') (map snd prs)
759                                go scope' e
760       Case e b _ as      -> do go scope e
761                                mapM_ (go_alt (extendVarSet scope b)) as
762       _other             -> return ()
763
764     go_alt scope (_,xs,r) = go (extendVarSetList scope xs) r
765 \end{code}
766
767
768 --------------------------------------------------------------------
769 --              tidyTopName
770 -- This is where we set names to local/global based on whether they really are 
771 -- externally visible (see comment at the top of this module).  If the name
772 -- was previously local, we have to give it a unique occurrence name if
773 -- we intend to externalise it.
774
775 \begin{code}
776 tidyTopName :: Module -> IORef NameCache -> Maybe Id -> TidyOccEnv
777             -> Id -> IO (TidyOccEnv, Name)
778 tidyTopName mod nc_var maybe_ref occ_env id
779   | global && internal = return (occ_env, localiseName name)
780
781   | global && external = return (occ_env, name)
782         -- Global names are assumed to have been allocated by the renamer,
783         -- so they already have the "right" unique
784         -- And it's a system-wide unique too
785
786   -- Now we get to the real reason that all this is in the IO Monad:
787   -- we have to update the name cache in a nice atomic fashion
788
789   | local  && internal = do { nc <- readIORef nc_var
790                             ; let (nc', new_local_name) = mk_new_local nc
791                             ; writeIORef nc_var nc'
792                             ; return (occ_env', new_local_name) }
793         -- Even local, internal names must get a unique occurrence, because
794         -- if we do -split-objs we externalise the name later, in the code generator
795         --
796         -- Similarly, we must make sure it has a system-wide Unique, because
797         -- the byte-code generator builds a system-wide Name->BCO symbol table
798
799   | local  && external = do { nc <- readIORef nc_var
800                             ; let (nc', new_external_name) = mk_new_external nc
801                             ; writeIORef nc_var nc'
802                             ; return (occ_env', new_external_name) }
803
804   | otherwise = panic "tidyTopName"
805   where
806     name        = idName id
807     external    = isJust maybe_ref
808     global      = isExternalName name
809     local       = not global
810     internal    = not external
811     loc         = nameSrcSpan name
812
813     old_occ     = nameOccName name
814     new_occ
815       | Just ref <- maybe_ref, ref /= id = 
816           mkOccName (occNameSpace old_occ) $
817              let
818                  ref_str = occNameString (getOccName ref)
819                  occ_str = occNameString old_occ
820              in
821              case occ_str of
822                '$':'w':_ -> occ_str
823                   -- workers: the worker for a function already
824                   -- includes the occname for its parent, so there's
825                   -- no need to prepend the referrer.
826                _other | isSystemName name -> ref_str
827                       | otherwise         -> ref_str ++ '_' : occ_str
828                   -- If this name was system-generated, then don't bother
829                   -- to retain its OccName, just use the referrer.  These
830                   -- system-generated names will become "f1", "f2", etc. for
831                   -- a referrer "f".
832       | otherwise = old_occ
833
834     (occ_env', occ') = tidyOccName occ_env new_occ
835
836     mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
837                     where
838                       (us1, us2) = splitUniqSupply (nsUniqs nc)
839                       uniq       = uniqFromSupply us1
840
841     mk_new_external nc = allocateGlobalBinder nc mod occ' loc
842         -- If we want to externalise a currently-local name, check
843         -- whether we have already assigned a unique for it.
844         -- If so, use it; if not, extend the table.
845         -- All this is done by allcoateGlobalBinder.
846         -- This is needed when *re*-compiling a module in GHCi; we must
847         -- use the same name for externally-visible things as we did before.
848 \end{code}
849
850 \begin{code}
851 findExternalRules :: [CoreBind]
852                   -> [CoreRule] -- Non-local rules (i.e. ones for imported fns)
853                   -> UnfoldEnv  -- Ids that are exported, so we need their rules
854                   -> [CoreRule]
855   -- The complete rules are gotten by combining
856   --    a) the non-local rules
857   --    b) rules embedded in the top-level Ids
858 findExternalRules binds non_local_rules unfold_env
859   = filter (not . internal_rule) (non_local_rules ++ local_rules)
860   where
861     local_rules  = [ rule
862                    | id <- bindersOfBinds binds,
863                      external_id id,
864                      rule <- idCoreRules id
865                    ]
866
867     internal_rule rule
868         =  any (not . external_id) (varSetElems (ruleLhsFreeIds rule))
869                 -- Don't export a rule whose LHS mentions a locally-defined
870                 --  Id that is completely internal (i.e. not visible to an
871                 -- importing module)
872
873     external_id id
874       | Just (name,_) <- lookupVarEnv unfold_env id = isExternalName name
875       | otherwise = False
876 \end{code}
877
878
879
880 %************************************************************************
881 %*                                                                      *
882 \subsection{Step 2: top-level tidying}
883 %*                                                                      *
884 %************************************************************************
885
886
887 \begin{code}
888 -- TopTidyEnv: when tidying we need to know
889 --   * nc_var: The NameCache, containing a unique supply and any pre-ordained Names.  
890 --        These may have arisen because the
891 --        renamer read in an interface file mentioning M.$wf, say,
892 --        and assigned it unique r77.  If, on this compilation, we've
893 --        invented an Id whose name is $wf (but with a different unique)
894 --        we want to rename it to have unique r77, so that we can do easy
895 --        comparisons with stuff from the interface file
896 --
897 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
898 --     are 'used'
899 --
900 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
901
902 tidyTopBinds :: HscEnv
903              -> UnfoldEnv
904              -> TidyOccEnv
905              -> [CoreBind]
906              -> (TidyEnv, [CoreBind])
907
908 tidyTopBinds hsc_env unfold_env init_occ_env binds
909   = tidy init_env binds
910   where
911     init_env = (init_occ_env, emptyVarEnv)
912
913     this_pkg = thisPackage (hsc_dflags hsc_env)
914
915     tidy env []     = (env, [])
916     tidy env (b:bs) = let (env1, b')  = tidyTopBind this_pkg unfold_env env b
917                           (env2, bs') = tidy env1 bs
918                       in
919                           (env2, b':bs')
920
921 ------------------------
922 tidyTopBind  :: PackageId
923              -> UnfoldEnv
924              -> TidyEnv
925              -> CoreBind
926              -> (TidyEnv, CoreBind)
927
928 tidyTopBind this_pkg unfold_env (occ_env,subst1) (NonRec bndr rhs)
929   = (tidy_env2,  NonRec bndr' rhs')
930   where
931     Just (name',show_unfold) = lookupVarEnv unfold_env bndr
932     caf_info      = hasCafRefs this_pkg subst1 (idArity bndr) rhs
933     (bndr', rhs') = tidyTopPair show_unfold tidy_env2 caf_info name' (bndr, rhs)
934     subst2        = extendVarEnv subst1 bndr bndr'
935     tidy_env2     = (occ_env, subst2)
936
937 tidyTopBind this_pkg unfold_env (occ_env,subst1) (Rec prs)
938   = (tidy_env2, Rec prs')
939   where
940     prs' = [ tidyTopPair show_unfold tidy_env2 caf_info name' (id,rhs)
941            | (id,rhs) <- prs,
942              let (name',show_unfold) = 
943                     expectJust "tidyTopBind" $ lookupVarEnv unfold_env id
944            ]
945
946     subst2    = extendVarEnvList subst1 (bndrs `zip` map fst prs')
947     tidy_env2 = (occ_env, subst2)
948
949     bndrs = map fst prs
950
951         -- the CafInfo for a recursive group says whether *any* rhs in
952         -- the group may refer indirectly to a CAF (because then, they all do).
953     caf_info 
954         | or [ mayHaveCafRefs (hasCafRefs this_pkg subst1 (idArity bndr) rhs)
955              | (bndr,rhs) <- prs ] = MayHaveCafRefs
956         | otherwise                = NoCafRefs
957
958 -----------------------------------------------------------
959 tidyTopPair :: Bool  -- show unfolding
960             -> TidyEnv  -- The TidyEnv is used to tidy the IdInfo
961                         -- It is knot-tied: don't look at it!
962             -> CafInfo
963             -> Name             -- New name
964             -> (Id, CoreExpr)   -- Binder and RHS before tidying
965             -> (Id, CoreExpr)
966         -- This function is the heart of Step 2
967         -- The rec_tidy_env is the one to use for the IdInfo
968         -- It's necessary because when we are dealing with a recursive
969         -- group, a variable late in the group might be mentioned
970         -- in the IdInfo of one early in the group
971
972 tidyTopPair show_unfold rhs_tidy_env caf_info name' (bndr, rhs)
973   = (bndr', rhs')
974   where
975     bndr' = mkGlobalId details name' ty' idinfo'
976     details = idDetails bndr    -- Preserve the IdDetails
977     ty'     = tidyTopType (idType bndr)
978     rhs'    = tidyExpr rhs_tidy_env rhs
979     idinfo  = idInfo bndr
980     idinfo' = tidyTopIdInfo (isExternalName name')
981                             idinfo unfold_info worker_info
982                             arity caf_info
983
984     unfold_info | show_unfold = mkTopUnfolding rhs'
985                 | otherwise   = noUnfolding
986     worker_info = tidyWorker rhs_tidy_env show_unfold (workerInfo idinfo)
987
988     -- Usually the Id will have an accurate arity on it, because
989     -- the simplifier has just run, but not always. 
990     -- One case I found was when the last thing the simplifier
991     -- did was to let-bind a non-atomic argument and then float
992     -- it to the top level. So it seems more robust just to
993     -- fix it here.
994     arity = exprArity rhs
995
996
997 -- tidyTopIdInfo creates the final IdInfo for top-level
998 -- binders.  There are two delicate pieces:
999 --
1000 --  * Arity.  After CoreTidy, this arity must not change any more.
1001 --      Indeed, CorePrep must eta expand where necessary to make
1002 --      the manifest arity equal to the claimed arity.
1003 --
1004 --  * CAF info.  This must also remain valid through to code generation.
1005 --      We add the info here so that it propagates to all
1006 --      occurrences of the binders in RHSs, and hence to occurrences in
1007 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
1008 --      CoreToStg makes use of this when constructing SRTs.
1009 tidyTopIdInfo :: Bool -> IdInfo -> Unfolding
1010               -> WorkerInfo -> ArityInfo -> CafInfo
1011               -> IdInfo
1012 tidyTopIdInfo is_external idinfo unfold_info worker_info arity caf_info
1013   | not is_external     -- For internal Ids (not externally visible)
1014   = vanillaIdInfo       -- we only need enough info for code generation
1015                         -- Arity and strictness info are enough;
1016                         --      c.f. CoreTidy.tidyLetBndr
1017         `setCafInfo`           caf_info
1018         `setArityInfo`         arity
1019         `setAllStrictnessInfo` newStrictnessInfo idinfo
1020
1021   | otherwise           -- Externally-visible Ids get the whole lot
1022   = vanillaIdInfo
1023         `setCafInfo`           caf_info
1024         `setArityInfo`         arity
1025         `setAllStrictnessInfo` newStrictnessInfo idinfo
1026         `setInlinePragInfo`    inlinePragInfo idinfo
1027         `setUnfoldingInfo`     unfold_info
1028         `setWorkerInfo`        worker_info
1029                 -- NB: we throw away the Rules
1030                 -- They have already been extracted by findExternalRules
1031
1032
1033
1034 ------------  Worker  --------------
1035 tidyWorker :: TidyEnv -> Bool -> WorkerInfo -> WorkerInfo
1036 tidyWorker _tidy_env _show_unfold NoWorker
1037   = NoWorker
1038 tidyWorker tidy_env show_unfold (HasWorker work_id wrap_arity) 
1039   | show_unfold = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
1040   | otherwise   = NoWorker
1041     -- NB: do *not* expose the worker if show_unfold is off,
1042     --     because that means this thing is a loop breaker or
1043     --     marked NOINLINE or something like that
1044     -- This is important: if you expose the worker for a loop-breaker
1045     -- then you can make the simplifier go into an infinite loop, because
1046     -- in effect the unfolding is exposed.  See Trac #1709
1047     -- 
1048     -- You might think that if show_unfold is False, then the thing should
1049     -- not be w/w'd in the first place.  But a legitimate reason is this:
1050     --    the function returns bottom
1051     -- In this case, show_unfold will be false (we don't expose unfoldings
1052     -- for bottoming functions), but we might still have a worker/wrapper
1053     -- split (see Note [Worker-wrapper for bottoming functions] in WorkWrap.lhs
1054 \end{code}
1055
1056 %************************************************************************
1057 %*                                                                      *
1058 \subsection{Figuring out CafInfo for an expression}
1059 %*                                                                      *
1060 %************************************************************************
1061
1062 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
1063 We mark such things as `MayHaveCafRefs' because this information is
1064 used to decide whether a particular closure needs to be referenced
1065 in an SRT or not.
1066
1067 There are two reasons for setting MayHaveCafRefs:
1068         a) The RHS is a CAF: a top-level updatable thunk.
1069         b) The RHS refers to something that MayHaveCafRefs
1070
1071 Possible improvement: In an effort to keep the number of CAFs (and 
1072 hence the size of the SRTs) down, we could also look at the expression and 
1073 decide whether it requires a small bounded amount of heap, so we can ignore 
1074 it as a CAF.  In these cases however, we would need to use an additional
1075 CAF list to keep track of non-collectable CAFs.  
1076
1077 \begin{code}
1078 hasCafRefs  :: PackageId -> VarEnv Var -> Arity -> CoreExpr -> CafInfo
1079 hasCafRefs this_pkg p arity expr 
1080   | is_caf || mentions_cafs 
1081                             = MayHaveCafRefs
1082   | otherwise               = NoCafRefs
1083  where
1084   mentions_cafs = isFastTrue (cafRefs p expr)
1085   is_caf = not (arity > 0 || rhsIsStatic this_pkg expr)
1086
1087   -- NB. we pass in the arity of the expression, which is expected
1088   -- to be calculated by exprArity.  This is because exprArity
1089   -- knows how much eta expansion is going to be done by 
1090   -- CorePrep later on, and we don't want to duplicate that
1091   -- knowledge in rhsIsStatic below.
1092
1093 cafRefs :: VarEnv Id -> Expr a -> FastBool
1094 cafRefs p (Var id)
1095         -- imported Ids first:
1096   | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
1097         -- now Ids local to this module:
1098   | otherwise =
1099      case lookupVarEnv p id of
1100         Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
1101         Nothing  -> fastBool False
1102
1103 cafRefs _ (Lit _)              = fastBool False
1104 cafRefs p (App f a)            = fastOr (cafRefs p f) (cafRefs p) a
1105 cafRefs p (Lam _ e)            = cafRefs p e
1106 cafRefs p (Let b e)            = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
1107 cafRefs p (Case e _bndr _ alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
1108 cafRefs p (Note _n e)          = cafRefs p e
1109 cafRefs p (Cast e _co)         = cafRefs p e
1110 cafRefs _ (Type _)             = fastBool False
1111
1112 cafRefss :: VarEnv Id -> [Expr a] -> FastBool
1113 cafRefss _ []     = fastBool False
1114 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
1115
1116 fastOr :: FastBool -> (a -> FastBool) -> a -> FastBool
1117 -- hack for lazy-or over FastBool.
1118 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))
1119 \end{code}