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