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