[project @ 1999-07-12 14:40:08 by simonmar]
[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, 
9         tidyBndr, tidyBndrs
10     ) where
11
12 #include "HsVersions.h"
13
14 import CmdLineOpts      ( opt_D_dump_simpl, opt_D_verbose_core2core, opt_UsageSPOn )
15 import CoreSyn
16 import CoreUnfold       ( noUnfolding )
17 import CoreLint         ( beginPass, endPass )
18 import Rules            ( ProtoCoreRule(..) )
19 import UsageSPInf       ( doUsageSPInf )
20 import VarEnv
21 import VarSet
22 import Var              ( Id, IdOrTyVar )
23 import Id               ( idType, idInfo, idName, 
24                           mkVanillaId, mkId, exportWithOrigOccName,
25                           getIdStrictness, setIdStrictness,
26                           getIdDemandInfo, setIdDemandInfo,
27                         ) 
28 import IdInfo           ( specInfo, setSpecInfo, 
29                           inlinePragInfo, setInlinePragInfo, InlinePragInfo(..),
30                           setUnfoldingInfo, setDemandInfo,
31                           workerInfo, setWorkerInfo
32                         )
33 import Demand           ( wwLazy )
34 import Name             ( getOccName, tidyTopName, mkLocalName, isLocallyDefined )
35 import OccName          ( initTidyOccEnv, tidyOccName )
36 import Type             ( tidyTopType, tidyType, tidyTypes, tidyTyVar, tidyTyVars )
37 import Module           ( Module )
38 import UniqSupply       ( UniqSupply )
39 import Unique           ( Uniquable(..) )
40 import SrcLoc           ( noSrcLoc )
41 import Util             ( mapAccumL )
42 import Outputable
43 \end{code}
44
45
46
47 %************************************************************************
48 %*                                                                      *
49 \subsection{Tidying core}
50 %*                                                                      *
51 %************************************************************************
52
53 Several tasks are done by @tidyCorePgm@
54
55 1.  Make certain top-level bindings into Globals. The point is that 
56     Global things get externally-visible labels at code generation
57     time
58
59
60 2. Give all binders a nice print-name.  Their uniques aren't changed;
61    rather we give them lexically unique occ-names, so that we can
62    safely print the OccNae only in the interface file.  [Bad idea to
63    change the uniques, because the code generator makes global labels
64    from the uniques for local thunks etc.]
65
66
67 3. If @opt_UsageSPOn@ then compute usage information (which is
68    needed by Core2Stg).  ** NOTE _scc_ HERE **
69
70 \begin{code}
71 tidyCorePgm :: UniqSupply -> Module -> [CoreBind] -> [ProtoCoreRule]
72             -> IO ([CoreBind], [ProtoCoreRule])
73 tidyCorePgm us module_name binds_in rules
74   = do
75         beginPass "Tidy Core"
76
77         let (tidy_env1, binds_tidy) = mapAccumL (tidyBind (Just module_name)) init_tidy_env binds_in
78             rules_out               = tidyProtoRules tidy_env1 rules
79
80         binds_out <- if opt_UsageSPOn
81                      then _scc_ "CoreUsageSPInf" doUsageSPInf us binds_tidy
82                      else return binds_tidy
83
84         endPass "Tidy Core" (opt_D_dump_simpl || opt_D_verbose_core2core) binds_out
85         return (binds_out, rules_out)
86   where
87         -- We also make sure to avoid any exported binders.  Consider
88         --      f{-u1-} = 1     -- Local decl
89         --      ...
90         --      f{-u2-} = 2     -- Exported decl
91         --
92         -- The second exported decl must 'get' the name 'f', so we
93         -- have to put 'f' in the avoids list before we get to the first
94         -- decl.  tidyTopId then does a no-op on exported binders.
95     init_tidy_env = (initTidyOccEnv avoids, emptyVarEnv)
96     avoids        = [getOccName bndr | bndr <- bindersOfBinds binds_in,
97                                        exportWithOrigOccName bndr]
98
99 tidyBind :: Maybe Module                -- (Just m) for top level, Nothing for nested
100          -> TidyEnv
101          -> CoreBind
102          -> (TidyEnv, CoreBind)
103 tidyBind maybe_mod env (NonRec bndr rhs)
104   = let
105         (env', bndr') = tidy_bndr maybe_mod env env bndr
106         rhs'          = tidyExpr env rhs
107     in
108     (env', NonRec bndr' rhs')
109
110 tidyBind maybe_mod env (Rec pairs)
111   = let
112         -- We use env' when tidying the rhss
113         -- When tidying the binder itself we may tidy it's
114         -- specialisations; if any of these mention other binders
115         -- in the group we should really feed env' to them too;
116         -- but that seems (a) unlikely and (b) a bit tiresome.
117         -- So I left it out for now
118
119         (bndrs, rhss)  = unzip pairs
120         (env', bndrs') = mapAccumL (tidy_bndr maybe_mod env') env bndrs
121         rhss'          = map (tidyExpr env') rhss
122   in
123   (env', Rec (zip bndrs' rhss'))
124
125 tidyExpr env (Type ty)       = Type (tidyType env ty)
126 tidyExpr env (Con con args)  = Con con (map (tidyExpr env) args)
127 tidyExpr env (App f a)       = App (tidyExpr env f) (tidyExpr env a)
128 tidyExpr env (Note n e)      = Note (tidyNote env n) (tidyExpr env e)
129
130 tidyExpr env (Let b e)       = Let b' (tidyExpr env' e)
131                              where
132                                (env', b') = tidyBind Nothing env b
133
134 tidyExpr env (Case e b alts) = Case (tidyExpr env e) b' (map (tidyAlt env') alts)
135                              where
136                                (env', b') = tidyBndr env b
137
138 tidyExpr env (Var v)         = Var (tidyVarOcc env v)
139
140 tidyExpr env (Lam b e)       = Lam b' (tidyExpr env' e)
141                              where
142                                (env', b') = tidyBndr env b
143
144 tidyAlt env (con, vs, rhs)   = (con, vs', tidyExpr env' rhs)
145                              where
146                                (env', vs') = tidyBndrs env vs
147
148 tidyNote env (Coerce t1 t2)  = Coerce (tidyType env t1) (tidyType env t2)
149
150 tidyNote env note            = note
151
152 tidyVarOcc (_, var_env) v = case lookupVarEnv var_env v of
153                                   Just v' -> v'
154                                   Nothing -> v
155 \end{code}
156
157 \begin{code}
158 tidy_bndr (Just mod) env_idinfo env var = tidyTopId mod env env_idinfo var
159 tidy_bndr Nothing    env_idinfo env var = tidyBndr      env            var
160 \end{code}
161
162
163
164 %************************************************************************
165 %*                                                                      *
166 \subsection{Tidying up a binder}
167 %*                                                                      *
168 %************************************************************************
169
170 \begin{code}
171 tidyBndr :: TidyEnv -> IdOrTyVar -> (TidyEnv, IdOrTyVar)
172 tidyBndr env var | isTyVar var = tidyTyVar env var
173                  | otherwise   = tidyId    env var
174
175 tidyBndrs :: TidyEnv -> [IdOrTyVar] -> (TidyEnv, [IdOrTyVar])
176 tidyBndrs env vars = mapAccumL tidyBndr env vars
177
178 tidyId :: TidyEnv -> Id -> (TidyEnv, Id)
179 tidyId env@(tidy_env, var_env) id
180   =     -- Non-top-level variables
181     let 
182         -- Give the Id a fresh print-name, *and* rename its type
183         -- The SrcLoc isn't important now, though we could extract it from the Id
184         name'             = mkLocalName (getUnique id) occ' noSrcLoc
185         (tidy_env', occ') = tidyOccName tidy_env (getOccName id)
186         ty'               = tidyType env (idType id)
187         id'               = mkVanillaId name' ty'
188                             `setIdStrictness` getIdStrictness id
189                             `setIdDemandInfo` getIdDemandInfo id
190                         -- NB: This throws away the IdInfo of the Id, which we
191                         -- no longer need.  That means we don't need to
192                         -- run over it with env, nor renumber it.
193                         --
194                         -- The exception is strictness and demand info, which 
195                         -- is used to decide whether to use let or case for
196                         -- function arguments and let bindings
197
198         var_env'          = extendVarEnv var_env id id'
199     in
200     ((tidy_env', var_env'), id')
201
202 tidyTopId :: Module -> TidyEnv -> TidyEnv -> Id -> (TidyEnv, Id)
203         -- The second env is the one to use for the IdInfo
204         -- It's necessary because when we are dealing with a recursive
205         -- group, a variable late in the group might be mentioned
206         -- in the IdInfo of one early in the group
207 tidyTopId mod env@(tidy_env, var_env) env_idinfo id
208   =     -- Top level variables
209     let
210         (tidy_env', name') | exportWithOrigOccName id = (tidy_env, idName id)
211                            | otherwise                = tidyTopName mod tidy_env (idName id)
212         ty'                = tidyTopType (idType id)
213         idinfo'            = tidyIdInfo env_idinfo (idInfo id)
214         id'                = mkId name' ty' idinfo'
215         var_env'           = extendVarEnv var_env id id'
216     in
217     ((tidy_env', var_env'), id')
218 \end{code}
219
220 \begin{code}
221 -- tidyIdInfo does these things:
222 --      a) tidy the specialisation info (if any)
223 --      b) zap a complicated ICanSafelyBeINLINEd pragma,
224 --      c) zap the unfolding
225 -- The latter two are to avoid space leaks
226
227 tidyIdInfo env info
228   = info5
229   where
230     rules = specInfo info
231
232     info1 | isEmptyCoreRules rules = info 
233           | otherwise              = info `setSpecInfo` tidyRules env rules
234                 
235     info2 = case inlinePragInfo info of
236                 ICanSafelyBeINLINEd _ _ -> info1 `setInlinePragInfo` NoInlinePragInfo 
237                 other                   -> info1
238
239     info3 = info2 `setUnfoldingInfo` noUnfolding 
240     info4 = info3 `setDemandInfo`    wwLazy             -- I don't understand why...
241
242     info5 = case workerInfo info of
243                 Nothing -> info4
244                 Just w  -> info4 `setWorkerInfo` Just (tidyVarOcc env w)
245
246 tidyProtoRules :: TidyEnv -> [ProtoCoreRule] -> [ProtoCoreRule]
247 tidyProtoRules env rules
248   = [ ProtoCoreRule is_local (tidyVarOcc env fn) (tidyRule env rule)
249     | ProtoCoreRule is_local fn rule <- rules
250     ]
251
252 tidyRules :: TidyEnv -> CoreRules -> CoreRules
253 tidyRules env (Rules rules fvs) 
254   = Rules (map (tidyRule env) rules)
255           (foldVarSet tidy_set_elem emptyVarSet fvs)
256   where
257     tidy_set_elem var new_set = extendVarSet new_set (tidyVarOcc env var)
258
259 tidyRule :: TidyEnv -> CoreRule -> CoreRule
260 tidyRule env (Rule name vars tpl_args rhs)
261   = (Rule name vars' (map (tidyExpr env') tpl_args) (tidyExpr env' rhs))
262   where
263     (env', vars') = tidyBndrs env vars
264 \end{code}