4665bd2d83c62f8de29e7e4b934a0338f7e73907
[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' 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' top_tidy_env bndr
410
411         rhs' = tidyExpr rec_tidy_env rhs
412
413 tidyTopBinder :: Module -> IdEnv Bool -> CgInfoEnv
414               -> TidyEnv -> CoreExpr
415                         -- The TidyEnv is used to tidy the IdInfo
416                         -- The expr is the already-tided RHS
417                         -- Both are knot-tied: don't look at them!
418               -> TopTidyEnv -> Id -> (TopTidyEnv, Id)
419   -- NB: tidyTopBinder doesn't affect the unique supply
420
421 tidyTopBinder mod ext_ids cg_info_env rec_tidy_env rhs
422               env@(ns2, occ_env2, subst_env2) id
423         -- This function is the heart of Step 2
424         -- The rec_tidy_env is the one to use for the IdInfo
425         -- It's necessary because when we are dealing with a recursive
426         -- group, a variable late in the group might be mentioned
427         -- in the IdInfo of one early in the group
428
429         -- The rhs is already tidied
430         
431   = ((orig_env', occ_env', subst_env'), id')
432   where
433     (orig_env', occ_env', name') = tidyTopName mod ns2 occ_env2
434                                                is_external
435                                                (idName id)
436     ty'    = tidyTopType (idType id)
437     idinfo = tidyTopIdInfo rec_tidy_env is_external 
438                            (idInfo id) unfold_info arity
439                            (lookupCgInfo cg_info_env name')
440
441     id' = mkVanillaGlobal name' ty' idinfo
442
443     subst_env' = extendVarEnv subst_env2 id id'
444
445     maybe_external = lookupVarEnv ext_ids id
446     is_external    = isJust maybe_external
447
448     -- Expose an unfolding if ext_ids tells us to
449     -- Remember that ext_ids maps an Id to a Bool: 
450     --  True to show the unfolding, False to hide it
451     show_unfold = maybe_external `orElse` False
452     unfold_info | show_unfold = mkTopUnfolding rhs
453                 | otherwise   = noUnfolding
454
455     -- Usually the Id will have an accurate arity on it, because
456     -- the simplifier has just run, but not always. 
457     -- One case I found was when the last thing the simplifier
458     -- did was to let-bind a non-atomic argument and then float
459     -- it to the top level. So it seems more robust just to
460     -- fix it here.
461     arity = exprArity rhs
462
463
464
465 -- tidyTopIdInfo creates the final IdInfo for top-level
466 -- binders.  There are two delicate pieces:
467 --
468 --  * Arity.  After CoreTidy, this arity must not change any more.
469 --      Indeed, CorePrep must eta expand where necessary to make
470 --      the manifest arity equal to the claimed arity.
471 --
472 -- * CAF info, which comes from the CoreToStg pass via a knot.
473 --      The CAF info will not be looked at by the downstream stuff:
474 --      it *generates* it, and knot-ties it back.  It will only be
475 --      looked at by (a) MkIface when generating an interface file
476 --                   (b) In GHCi, importing modules
477 --      Nevertheless, we add the info here so that it propagates to all
478 --      occurrences of the binders in RHSs, and hence to occurrences in
479 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
480 --     
481 --      An alterative would be to do a second pass over the unfoldings 
482 --      of Ids, and rules, right at the top, but that would be a pain.
483
484 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity cg_info
485   | opt_OmitInterfacePragmas || not is_external
486         -- Only basic info if the Id isn't external, or if we don't have -O
487   = basic_info
488
489   | otherwise   -- Add extra optimisation info
490   = basic_info
491         `setInlinePragInfo`    inlinePragInfo idinfo
492         `setUnfoldingInfo`     unfold_info
493         `setWorkerInfo`        tidyWorker tidy_env (workerInfo idinfo)
494                 -- NB: we throw away the Rules
495                 -- They have already been extracted by findExternalRules
496   
497   where
498         -- baasic_info is attached to every top-level binder
499     basic_info = vanillaIdInfo 
500                         `setCgInfo`            cg_info
501                         `setArityInfo`         arity
502                         `setNewStrictnessInfo` newStrictnessInfo idinfo
503
504 -- This is where we set names to local/global based on whether they really are 
505 -- externally visible (see comment at the top of this module).  If the name
506 -- was previously local, we have to give it a unique occurrence name if
507 -- we intend to globalise it.
508 tidyTopName mod ns occ_env external name
509   | global && internal = (ns, occ_env, localiseName name)
510
511   | global && external = (ns, occ_env, name)
512         -- Global names are assumed to have been allocated by the renamer,
513         -- so they already have the "right" unique
514         -- And it's a system-wide unique too
515
516   | local  && internal = (ns_w_local, occ_env', new_local_name)
517         -- Even local, internal names must get a unique occurrence, because
518         -- if we do -split-objs we globalise the name later, in the code generator
519         --
520         -- Similarly, we must make sure it has a system-wide Unique, because
521         -- the byte-code generator builds a system-wide Name->BCO symbol table
522
523   | local  && external = case lookupFM ns_names key of
524                            Just orig -> (ns,          occ_env', orig)
525                            Nothing   -> (ns_w_global, occ_env', new_global_name)
526         -- If we want to globalise a currently-local name, check
527         -- whether we have already assigned a unique for it.
528         -- If so, use it; if not, extend the table (ns_w_global).
529         -- This is needed when *re*-compiling a module in GHCi; we want to
530         -- use the same name for externally-visible things as we did before.
531
532   where
533     global           = isGlobalName name
534     local            = not global
535     internal         = not external
536
537     (occ_env', occ') = tidyOccName occ_env (nameOccName name)
538     key              = (moduleName mod, occ')
539     ns_names         = nsNames ns
540     ns_uniqs         = nsUniqs ns
541     (us1, us2)       = splitUniqSupply ns_uniqs
542     uniq             = uniqFromSupply us1
543     loc              = nameSrcLoc name
544
545     new_local_name   = mkLocalName  uniq     occ' loc
546     new_global_name  = mkGlobalName uniq mod occ' loc  
547
548     ns_w_local       = ns { nsUniqs = us2 }
549     ns_w_global      = ns { nsUniqs = us2, nsNames = addToFM ns_names key new_global_name }
550
551
552 ------------  Worker  --------------
553 tidyWorker tidy_env (HasWorker work_id wrap_arity) 
554   = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
555 tidyWorker tidy_env other
556   = NoWorker
557
558 ------------  Rules  --------------
559 tidyIdRules :: TidyEnv -> [IdCoreRule] -> [IdCoreRule]
560 tidyIdRules env [] = []
561 tidyIdRules env ((fn,rule) : rules)
562   = tidyRule env rule           =: \ rule ->
563     tidyIdRules env rules       =: \ rules ->
564      ((tidyVarOcc env fn, rule) : rules)
565
566 tidyRule :: TidyEnv -> CoreRule -> CoreRule
567 tidyRule env rule@(BuiltinRule _ _) = rule
568 tidyRule env (Rule name act vars tpl_args rhs)
569   = tidyBndrs env vars                  =: \ (env', vars) ->
570     map (tidyExpr env') tpl_args        =: \ tpl_args ->
571      (Rule name act vars tpl_args (tidyExpr env' rhs))
572 \end{code}
573
574 %************************************************************************
575 %*                                                                      *
576 \subsection{Step 2: inner tidying
577 %*                                                                      *
578 %************************************************************************
579
580 \begin{code}
581 tidyBind :: TidyEnv
582          -> CoreBind
583          ->  (TidyEnv, CoreBind)
584
585 tidyBind env (NonRec bndr rhs)
586   = tidyLetBndr env (bndr,rhs)          =: \ (env', bndr') ->
587     (env', NonRec bndr' (tidyExpr env' rhs))
588
589 tidyBind env (Rec prs)
590   = mapAccumL tidyLetBndr env prs       =: \ (env', bndrs') ->
591     map (tidyExpr env') (map snd prs)   =: \ rhss' ->
592     (env', Rec (zip bndrs' rhss'))
593
594
595 tidyExpr env (Var v)    =  Var (tidyVarOcc env v)
596 tidyExpr env (Type ty)  =  Type (tidyType env ty)
597 tidyExpr env (Lit lit)  =  Lit lit
598 tidyExpr env (App f a)  =  App (tidyExpr env f) (tidyExpr env a)
599 tidyExpr env (Note n e) =  Note (tidyNote env n) (tidyExpr env e)
600
601 tidyExpr env (Let b e) 
602   = tidyBind env b      =: \ (env', b') ->
603     Let b' (tidyExpr env' e)
604
605 tidyExpr env (Case e b alts)
606   = tidyBndr env b      =: \ (env', b) ->
607     Case (tidyExpr env e) b (map (tidyAlt env') alts)
608
609 tidyExpr env (Lam b e)
610   = tidyBndr env b      =: \ (env', b) ->
611     Lam b (tidyExpr env' e)
612
613
614 tidyAlt env (con, vs, rhs)
615   = tidyBndrs env vs    =: \ (env', vs) ->
616     (con, vs, tidyExpr env' rhs)
617
618 tidyNote env (Coerce t1 t2)  = Coerce (tidyType env t1) (tidyType env t2)
619 tidyNote env note            = note
620 \end{code}
621
622
623 %************************************************************************
624 %*                                                                      *
625 \subsection{Tidying up non-top-level binders}
626 %*                                                                      *
627 %************************************************************************
628
629 \begin{code}
630 tidyVarOcc (_, var_env) v = case lookupVarEnv var_env v of
631                                   Just v' -> v'
632                                   Nothing -> v
633
634 -- tidyBndr is used for lambda and case binders
635 tidyBndr :: TidyEnv -> Var -> (TidyEnv, Var)
636 tidyBndr env var
637   | isTyVar var = tidyTyVarBndr env var
638   | otherwise   = tidyIdBndr env var
639
640 tidyBndrs :: TidyEnv -> [Var] -> (TidyEnv, [Var])
641 tidyBndrs env vars = mapAccumL tidyBndr env vars
642
643 tidyLetBndr :: TidyEnv -> (Id, CoreExpr) -> (TidyEnv, Var)
644 -- Used for local (non-top-level) let(rec)s
645 tidyLetBndr env (id,rhs) 
646   = ((tidy_env,new_var_env), final_id)
647   where
648     ((tidy_env,var_env), new_id) = tidyIdBndr env id
649
650         -- We need to keep around any interesting strictness and demand info
651         -- because later on we may need to use it when converting to A-normal form.
652         -- eg.
653         --      f (g x),  where f is strict in its argument, will be converted
654         --      into  case (g x) of z -> f z  by CorePrep, but only if f still
655         --      has its strictness info.
656         --
657         -- Similarly for the demand info - on a let binder, this tells 
658         -- CorePrep to turn the let into a case.
659         --
660         -- Similarly arity info for eta expansion in CorePrep
661     final_id = new_id `setIdInfo` new_info
662     idinfo   = idInfo id
663     new_info = vanillaIdInfo 
664                 `setArityInfo`          exprArity rhs
665                 `setNewStrictnessInfo`  newStrictnessInfo idinfo
666                 `setNewDemandInfo`      newDemandInfo idinfo
667
668     -- Override the env we get back from tidyId with the new IdInfo
669     -- so it gets propagated to the usage sites.
670     new_var_env = extendVarEnv var_env id final_id
671
672 tidyIdBndr :: TidyEnv -> Id -> (TidyEnv, Id)
673 tidyIdBndr env@(tidy_env, var_env) id
674   =     -- Non-top-level variables
675     let 
676         -- Give the Id a fresh print-name, *and* rename its type
677         -- The SrcLoc isn't important now, 
678         -- though we could extract it from the Id
679         -- 
680         -- All nested Ids now have the same IdInfo, namely none,
681         -- which should save some space.
682         (tidy_env', occ') = tidyOccName tidy_env (getOccName id)
683         ty'               = tidyType env (idType id)
684         id'               = mkUserLocal occ' (idUnique id) ty' noSrcLoc
685         var_env'          = extendVarEnv var_env id id'
686     in
687      ((tidy_env', var_env'), id')
688 \end{code}
689
690 \begin{code}
691 m =: k = m `seq` k m
692 \end{code}