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