[project @ 2002-03-20 11:24:42 by simonpj]
[ghc-hetmet.git] / ghc / 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( tidyCorePgm, tidyCoreExpr ) where
8
9 #include "HsVersions.h"
10
11 import CmdLineOpts      ( DynFlags, DynFlag(..), opt_OmitInterfacePragmas )
12 import CoreSyn
13 import CoreUnfold       ( noUnfolding, mkTopUnfolding, okToUnfoldInHiFile )
14 import CoreFVs          ( ruleLhsFreeIds, ruleRhsFreeVars, exprSomeFreeVars )
15 import CoreTidy         ( tidyExpr, tidyVarOcc, tidyIdRules )
16 import PprCore          ( pprIdRules )
17 import CoreLint         ( showPass, endPass )
18 import CoreUtils        ( exprArity )
19 import VarEnv
20 import VarSet
21 import Var              ( Id, Var )
22 import Id               ( idType, idInfo, idName, idCoreRules, 
23                           isExportedId, idUnique, mkVanillaGlobal, isLocalId, 
24                           isImplicitId, mkUserLocal, setIdInfo
25                         ) 
26 import IdInfo           {- loads of stuff -}
27 import NewDemand        ( isBottomingSig, topSig )
28 import BasicTypes       ( isNeverActive )
29 import Name             ( getOccName, nameOccName, mkInternalName, mkExternalName, 
30                           localiseName, isExternalName, nameSrcLoc
31                         )
32 import NameEnv          ( filterNameEnv )
33 import OccName          ( TidyOccEnv, initTidyOccEnv, tidyOccName )
34 import Type             ( tidyTopType )
35 import Module           ( Module, moduleName )
36 import HscTypes         ( PersistentCompilerState( pcs_PRS ), 
37                           PersistentRenamerState( prsOrig ),
38                           NameSupply( nsNames, nsUniqs ),
39                           TypeEnv, extendTypeEnvList, typeEnvIds,
40                           ModDetails(..), TyThing(..)
41                         )
42 import FiniteMap        ( lookupFM, addToFM )
43 import Maybes           ( orElse )
44 import ErrUtils         ( showPass, dumpIfSet_core )
45 import SrcLoc           ( noSrcLoc )
46 import UniqFM           ( mapUFM )
47 import UniqSupply       ( splitUniqSupply, uniqFromSupply )
48 import List             ( partition )
49 import Util             ( mapAccumL )
50 import Maybe            ( isJust )
51 import Outputable
52 \end{code}
53
54
55
56 %************************************************************************
57 %*                                                                      *
58 \subsection{What goes on}
59 %*                                                                      * 
60 %************************************************************************
61
62 [SLPJ: 19 Nov 00]
63
64 The plan is this.  
65
66 Step 1: Figure out external Ids
67 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
68 First we figure out which Ids are "external" Ids.  An
69 "external" Id is one that is visible from outside the compilation
70 unit.  These are
71         a) the user exported ones
72         b) ones mentioned in the unfoldings, workers, 
73            or rules of externally-visible ones 
74 This exercise takes a sweep of the bindings bottom to top.  Actually,
75 in Step 2 we're also going to need to know which Ids should be
76 exported with their unfoldings, so we produce not an IdSet but an
77 IdEnv Bool
78
79
80 Step 2: Tidy the program
81 ~~~~~~~~~~~~~~~~~~~~~~~~
82 Next we traverse the bindings top to bottom.  For each *top-level*
83 binder
84
85  1. Make it into a GlobalId
86
87  2. Give it a system-wide Unique.
88     [Even non-exported things need system-wide Uniques because the
89     byte-code generator builds a single Name->BCO symbol table.]
90
91     We use the NameSupply kept in the PersistentRenamerState as the
92     source of such system-wide uniques.
93
94     For external Ids, use the original-name cache in the NameSupply 
95     to ensure that the unique assigned is the same as the Id had 
96     in any previous compilation run.
97   
98  3. If it's an external Id, make it have a global Name, otherwise
99     make it have a local Name.
100     This is used by the code generator to decide whether
101     to make the label externally visible
102
103  4. Give external Ids a "tidy" occurrence name.  This means
104     we can print them in interface files without confusing 
105     "x" (unique 5) with "x" (unique 10).
106   
107  5. Give it its UTTERLY FINAL IdInfo; in ptic, 
108         * Its IdDetails becomes VanillaGlobal, reflecting the fact that
109           from now on we regard it as a global, not local, Id
110
111         * its unfolding, if it should have one
112         
113         * its arity, computed from the number of visible lambdas
114
115         * its CAF info, computed from what is free in its RHS
116
117                 
118 Finally, substitute these new top-level binders consistently
119 throughout, including in unfoldings.  We also tidy binders in
120 RHSs, so that they print nicely in interfaces.
121
122 \begin{code}
123 tidyCorePgm :: DynFlags -> Module
124             -> PersistentCompilerState
125             -> CgInfoEnv                -- Information from the back end,
126                                         -- to be splatted into the IdInfo
127             -> ModDetails
128             -> IO (PersistentCompilerState, ModDetails)
129
130 tidyCorePgm dflags mod pcs cg_info_env
131             (ModDetails { md_types = env_tc, md_insts = insts_tc, 
132                           md_binds = binds_in, md_rules = orphans_in })
133   = do  { showPass dflags "Tidy Core"
134
135         ; let ext_ids   = findExternalSet   binds_in orphans_in
136         ; let ext_rules = findExternalRules binds_in orphans_in ext_ids
137                 -- findExternalRules filters ext_rules to avoid binders that 
138                 -- aren't externally visible; but the externally-visible binders 
139                 -- are computed (by findExternalSet) assuming that all orphan
140                 -- rules are exported.  So in fact we may export more than we
141                 -- need.  (It's a sort of mutual recursion.)
142
143         -- We also make sure to avoid any exported binders.  Consider
144         --      f{-u1-} = 1     -- Local decl
145         --      ...
146         --      f{-u2-} = 2     -- Exported decl
147         --
148         -- The second exported decl must 'get' the name 'f', so we
149         -- have to put 'f' in the avoids list before we get to the first
150         -- decl.  tidyTopId then does a no-op on exported binders.
151         ; let   prs           = pcs_PRS pcs
152                 orig_ns       = prsOrig prs
153
154                 init_tidy_env = (orig_ns, initTidyOccEnv avoids, emptyVarEnv)
155                 avoids        = [getOccName name | bndr <- typeEnvIds env_tc,
156                                                    let name = idName bndr,
157                                                    isExternalName name]
158                 -- In computing our "avoids" list, we must include
159                 --      all implicit Ids
160                 --      all things with global names (assigned once and for
161                 --                                      all by the renamer)
162                 -- since their names are "taken".
163                 -- The type environment is a convenient source of such things.
164
165         ; let ((orig_ns', occ_env, subst_env), tidy_binds) 
166                         = mapAccumL (tidyTopBind mod ext_ids cg_info_env) 
167                                     init_tidy_env binds_in
168
169         ; let tidy_rules = tidyIdRules (occ_env,subst_env) ext_rules
170
171         ; let prs' = prs { prsOrig = orig_ns' }
172               pcs' = pcs { pcs_PRS = prs' }
173
174         ; let final_ids  = [ id 
175                            | bind <- tidy_binds
176                            , id <- bindersOf bind
177                            , isExternalName (idName id)]
178
179                 -- Dfuns are local Ids that might have
180                 -- changed their unique during tidying
181         ; let lookup_dfun_id id = lookupVarEnv subst_env id `orElse` 
182                                   pprPanic "lookup_dfun_id" (ppr id)
183
184
185         ; let tidy_type_env = mkFinalTypeEnv env_tc final_ids
186               tidy_dfun_ids = map lookup_dfun_id insts_tc
187
188         ; let tidy_details = ModDetails { md_types = tidy_type_env,
189                                           md_rules = tidy_rules,
190                                           md_insts = tidy_dfun_ids,
191                                           md_binds = tidy_binds }
192
193         ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
194         ; dumpIfSet_core dflags Opt_D_dump_simpl
195                 "Tidy Core Rules"
196                 (pprIdRules tidy_rules)
197
198         ; return (pcs', tidy_details)
199         }
200
201 tidyCoreExpr :: CoreExpr -> IO CoreExpr
202 tidyCoreExpr expr = return (tidyExpr emptyTidyEnv expr)
203 \end{code}
204
205
206 %************************************************************************
207 %*                                                                      *
208 \subsection{Write a new interface file}
209 %*                                                                      *
210 %************************************************************************
211
212 \begin{code}
213 mkFinalTypeEnv :: TypeEnv       -- From typechecker
214                -> [Id]          -- Final Ids
215                -> TypeEnv
216
217 mkFinalTypeEnv type_env final_ids
218   = extendTypeEnvList (filterNameEnv keep_it type_env)
219                       (map AnId final_ids)
220   where
221         -- The competed type environment is gotten from
222         --      a) keeping the types and classes
223         --      b) removing all Ids, 
224         --      c) adding Ids with correct IdInfo, including unfoldings,
225         --              gotten from the bindings
226         -- From (c) we keep only those Ids with Global names;
227         --          the CoreTidy pass makes sure these are all and only
228         --          the externally-accessible ones
229         -- This truncates the type environment to include only the 
230         -- exported Ids and things needed from them, which saves space
231         --
232         -- However, we do keep things like constructors, which should not appear 
233         -- in interface files, because they are needed by importing modules when
234         -- using the compilation manager
235
236         -- We keep implicit Ids, because they won't appear 
237         -- in the bindings from which final_ids are derived!
238     keep_it (AnId id) = isImplicitId id -- Remove all Ids except implicit ones
239     keep_it other     = True            -- Keep all TyCons and Classes
240 \end{code}
241
242 \begin{code}
243 findExternalRules :: [CoreBind]
244                   -> [IdCoreRule] -- Orphan rules
245                   -> IdEnv a      -- Ids that are exported, so we need their rules
246                   -> [IdCoreRule]
247   -- The complete rules are gotten by combining
248   --    a) the orphan rules
249   --    b) rules embedded in the top-level Ids
250 findExternalRules binds orphan_rules ext_ids
251   | opt_OmitInterfacePragmas = []
252   | otherwise
253   = filter needed_rule (orphan_rules ++ local_rules)
254   where
255     local_rules  = [ rule
256                    | id <- bindersOfBinds binds,
257                      id `elemVarEnv` ext_ids,
258                      rule <- idCoreRules id
259                    ]
260     needed_rule (id, rule)
261         =  not (isBuiltinRule rule)
262                 -- We can't print builtin rules in interface files
263                 -- Since they are built in, an importing module
264                 -- will have access to them anyway
265
266         && not (any internal_id (varSetElems (ruleLhsFreeIds rule)))
267                 -- Don't export a rule whose LHS mentions an Id that
268                 -- is completely internal (i.e. not visible to an
269                 -- importing module)
270
271     internal_id id = isLocalId id && not (id `elemVarEnv` ext_ids)
272 \end{code}
273
274 %************************************************************************
275 %*                                                                      *
276 \subsection{Step 1: finding externals}
277 %*                                                                      * 
278 %************************************************************************
279
280 \begin{code}
281 findExternalSet :: [CoreBind] -> [IdCoreRule]
282                 -> IdEnv Bool   -- In domain => external
283                                 -- Range = True <=> show unfolding
284         -- Step 1 from the notes above
285 findExternalSet binds orphan_rules
286   = foldr find init_needed binds
287   where
288     orphan_rule_ids :: IdSet
289     orphan_rule_ids = unionVarSets [ ruleRhsFreeVars rule 
290                                    | (_, rule) <- orphan_rules]
291     init_needed :: IdEnv Bool
292     init_needed = mapUFM (\_ -> False) orphan_rule_ids
293         -- The mapUFM is a bit cheesy.  It is a cheap way
294         -- to turn the set of orphan_rule_ids, which we use to initialise
295         -- the sweep, into a mapping saying 'don't expose unfolding'    
296         -- (When we come to the binding site we may change our mind, of course.)
297
298     find (NonRec id rhs) needed
299         | need_id needed id = addExternal (id,rhs) needed
300         | otherwise         = needed
301     find (Rec prs) needed   = find_prs prs needed
302
303         -- For a recursive group we have to look for a fixed point
304     find_prs prs needed 
305         | null needed_prs = needed
306         | otherwise       = find_prs other_prs new_needed
307         where
308           (needed_prs, other_prs) = partition (need_pr needed) prs
309           new_needed = foldr addExternal needed needed_prs
310
311         -- The 'needed' set contains the Ids that are needed by earlier
312         -- interface file emissions.  If the Id isn't in this set, and isn't
313         -- exported, there's no need to emit anything
314     need_id needed_set id       = id `elemVarEnv` needed_set || isExportedId id 
315     need_pr needed_set (id,rhs) = need_id needed_set id
316
317 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
318 -- The Id is needed; extend the needed set
319 -- with it and its dependents (free vars etc)
320 addExternal (id,rhs) needed
321   = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
322                  id show_unfold
323   where
324     add_occ id needed = extendVarEnv needed id False
325         -- "False" because we don't know we need the Id's unfolding
326         -- We'll override it later when we find the binding site
327
328     new_needed_ids | opt_OmitInterfacePragmas = emptyVarSet
329                    | otherwise                = worker_ids      `unionVarSet`
330                                                 unfold_ids      `unionVarSet`
331                                                 spec_ids
332
333     idinfo         = idInfo id
334     dont_inline    = isNeverActive (inlinePragInfo idinfo)
335     loop_breaker   = isLoopBreaker (occInfo idinfo)
336     bottoming_fn   = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
337     spec_ids       = rulesRhsFreeVars (specInfo idinfo)
338     worker_info    = workerInfo idinfo
339
340         -- Stuff to do with the Id's unfolding
341         -- The simplifier has put an up-to-date unfolding
342         -- in the IdInfo, but the RHS will do just as well
343     unfolding    = unfoldingInfo idinfo
344     rhs_is_small = not (neverUnfold unfolding)
345
346         -- We leave the unfolding there even if there is a worker
347         -- In GHCI the unfolding is used by importers
348         -- When writing an interface file, we omit the unfolding 
349         -- if there is a worker
350     show_unfold = not bottoming_fn       &&     -- Not necessary
351                   not dont_inline        &&
352                   not loop_breaker       &&
353                   rhs_is_small           &&     -- Small enough
354                   okToUnfoldInHiFile rhs        -- No casms etc
355
356     unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
357                | otherwise   = emptyVarSet
358
359     worker_ids = case worker_info of
360                    HasWorker work_id _ -> unitVarSet work_id
361                    otherwise           -> emptyVarSet
362 \end{code}
363
364
365 %************************************************************************
366 %*                                                                      *
367 \subsection{Step 2: top-level tidying}
368 %*                                                                      *
369 %************************************************************************
370
371
372 \begin{code}
373 type TopTidyEnv = (NameSupply, TidyOccEnv, VarEnv Var)
374
375 -- TopTidyEnv: when tidying we need to know
376 --   * ns: The NameSupply, containing a unique supply and any pre-ordained Names.  
377 --        These may have arisen because the
378 --        renamer read in an interface file mentioning M.$wf, say,
379 --        and assigned it unique r77.  If, on this compilation, we've
380 --        invented an Id whose name is $wf (but with a different unique)
381 --        we want to rename it to have unique r77, so that we can do easy
382 --        comparisons with stuff from the interface file
383 --
384 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
385 --     are 'used'
386 --
387 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
388 \end{code}
389
390
391 \begin{code}
392 tidyTopBind :: Module
393             -> IdEnv Bool       -- Domain = Ids that should be external
394                                 -- True <=> their unfolding is external too
395             -> CgInfoEnv
396             -> TopTidyEnv -> CoreBind
397             -> (TopTidyEnv, CoreBind)
398
399 tidyTopBind mod ext_ids cg_info_env top_tidy_env (NonRec bndr rhs)
400   = ((orig,occ,subst) , NonRec bndr' rhs')
401   where
402     ((orig,occ,subst), bndr')
403          = tidyTopBinder mod ext_ids cg_info_env 
404                          rec_tidy_env rhs rhs' top_tidy_env bndr
405     rec_tidy_env = (occ,subst)
406     rhs' = tidyExpr rec_tidy_env rhs
407
408 tidyTopBind mod ext_ids cg_info_env top_tidy_env (Rec prs)
409   = (final_env, Rec prs')
410   where
411     (final_env@(_,occ,subst), prs') = mapAccumL do_one top_tidy_env prs
412     rec_tidy_env = (occ,subst)
413
414     do_one top_tidy_env (bndr,rhs) 
415         = ((orig,occ,subst), (bndr',rhs'))
416         where
417         ((orig,occ,subst), bndr')
418            = tidyTopBinder mod ext_ids cg_info_env
419                 rec_tidy_env rhs rhs' top_tidy_env bndr
420
421         rhs' = tidyExpr rec_tidy_env rhs
422
423 tidyTopBinder :: Module -> IdEnv Bool -> CgInfoEnv
424               -> TidyEnv        -- The TidyEnv is used to tidy the IdInfo
425               -> CoreExpr       -- RHS *before* tidying
426               -> CoreExpr       -- RHS *after* tidying
427                         -- The TidyEnv and the after-tidying RHS are
428                         -- both are knot-tied: don't look at them!
429               -> TopTidyEnv -> Id -> (TopTidyEnv, Id)
430   -- NB: tidyTopBinder doesn't affect the unique supply
431
432 tidyTopBinder mod ext_ids cg_info_env rec_tidy_env rhs tidy_rhs
433               env@(ns2, occ_env2, subst_env2) id
434         -- This function is the heart of Step 2
435         -- The rec_tidy_env is the one to use for the IdInfo
436         -- It's necessary because when we are dealing with a recursive
437         -- group, a variable late in the group might be mentioned
438         -- in the IdInfo of one early in the group
439
440         -- The rhs is already tidied
441         
442   = ((orig_env', occ_env', subst_env'), id')
443   where
444     (orig_env', occ_env', name') = tidyTopName mod ns2 occ_env2
445                                                is_external
446                                                (idName id)
447     ty'    = tidyTopType (idType id)
448     idinfo = tidyTopIdInfo rec_tidy_env is_external 
449                            (idInfo id) unfold_info arity
450                            (lookupCgInfo cg_info_env name')
451
452     id' = mkVanillaGlobal name' ty' idinfo
453
454     subst_env' = extendVarEnv subst_env2 id id'
455
456     maybe_external = lookupVarEnv ext_ids id
457     is_external    = isJust maybe_external
458
459     -- Expose an unfolding if ext_ids tells us to
460     -- Remember that ext_ids maps an Id to a Bool: 
461     --  True to show the unfolding, False to hide it
462     show_unfold = maybe_external `orElse` False
463     unfold_info | show_unfold = mkTopUnfolding tidy_rhs
464                 | otherwise   = noUnfolding
465
466     -- Usually the Id will have an accurate arity on it, because
467     -- the simplifier has just run, but not always. 
468     -- One case I found was when the last thing the simplifier
469     -- did was to let-bind a non-atomic argument and then float
470     -- it to the top level. So it seems more robust just to
471     -- fix it here.
472     arity = exprArity rhs
473
474
475
476 -- tidyTopIdInfo creates the final IdInfo for top-level
477 -- binders.  There are two delicate pieces:
478 --
479 --  * Arity.  After CoreTidy, this arity must not change any more.
480 --      Indeed, CorePrep must eta expand where necessary to make
481 --      the manifest arity equal to the claimed arity.
482 --
483 -- * CAF info, which comes from the CoreToStg pass via a knot.
484 --      The CAF info will not be looked at by the downstream stuff:
485 --      it *generates* it, and knot-ties it back.  It will only be
486 --      looked at by (a) MkIface when generating an interface file
487 --                   (b) In GHCi, importing modules
488 --      Nevertheless, we add the info here so that it propagates to all
489 --      occurrences of the binders in RHSs, and hence to occurrences in
490 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
491 --     
492 --      An alterative would be to do a second pass over the unfoldings 
493 --      of Ids, and rules, right at the top, but that would be a pain.
494
495 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity cg_info
496   | opt_OmitInterfacePragmas || not is_external
497         -- Only basic info if the Id isn't external, or if we don't have -O
498   = basic_info
499
500   | otherwise   -- Add extra optimisation info
501   = basic_info
502         `setInlinePragInfo`    inlinePragInfo idinfo
503         `setUnfoldingInfo`     unfold_info
504         `setWorkerInfo`        tidyWorker tidy_env (workerInfo idinfo)
505                 -- NB: we throw away the Rules
506                 -- They have already been extracted by findExternalRules
507   
508   where
509         -- baasic_info is attached to every top-level binder
510     basic_info = vanillaIdInfo 
511                         `setCgInfo`            cg_info
512                         `setArityInfo`         arity
513                         `setAllStrictnessInfo` newStrictnessInfo idinfo
514
515 -- This is where we set names to local/global based on whether they really are 
516 -- externally visible (see comment at the top of this module).  If the name
517 -- was previously local, we have to give it a unique occurrence name if
518 -- we intend to externalise it.
519 tidyTopName mod ns occ_env external name
520   | global && internal = (ns, occ_env, localiseName name)
521
522   | global && external = (ns, occ_env, name)
523         -- Global names are assumed to have been allocated by the renamer,
524         -- so they already have the "right" unique
525         -- And it's a system-wide unique too
526
527   | local  && internal = (ns_w_local, occ_env', new_local_name)
528         -- Even local, internal names must get a unique occurrence, because
529         -- if we do -split-objs we externalise the name later, in the code generator
530         --
531         -- Similarly, we must make sure it has a system-wide Unique, because
532         -- the byte-code generator builds a system-wide Name->BCO symbol table
533
534   | local  && external = case lookupFM ns_names key of
535                            Just orig -> (ns,          occ_env', orig)
536                            Nothing   -> (ns_w_global, occ_env', new_external_name)
537         -- If we want to externalise a currently-local name, check
538         -- whether we have already assigned a unique for it.
539         -- If so, use it; if not, extend the table (ns_w_global).
540         -- This is needed when *re*-compiling a module in GHCi; we want to
541         -- use the same name for externally-visible things as we did before.
542
543   where
544     global           = isExternalName name
545     local            = not global
546     internal         = not external
547
548     (occ_env', occ') = tidyOccName occ_env (nameOccName name)
549     key              = (moduleName mod, occ')
550     ns_names         = nsNames ns
551     ns_uniqs         = nsUniqs ns
552     (us1, us2)       = splitUniqSupply ns_uniqs
553     uniq             = uniqFromSupply us1
554     loc              = nameSrcLoc name
555
556     new_local_name     = mkInternalName  uniq     occ' loc
557     new_external_name  = mkExternalName uniq mod occ' loc  
558
559     ns_w_local       = ns { nsUniqs = us2 }
560     ns_w_global      = ns { nsUniqs = us2, nsNames = addToFM ns_names key new_external_name }
561
562
563 ------------  Worker  --------------
564 tidyWorker tidy_env (HasWorker work_id wrap_arity) 
565   = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
566 tidyWorker tidy_env other
567   = NoWorker
568 \end{code}