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