[project @ 1996-04-08 16:15:43 by partain]
[ghc-hetmet.git] / ghc / compiler / simplCore / SimplUtils.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1996
3 %
4 \section[SimplUtils]{The simplifier utilities}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module SimplUtils (
10
11         floatExposesHNF,
12
13         mkTyLamTryingEta, mkValLamTryingEta,
14
15         etaExpandCount,
16
17         mkIdentityAlts,
18
19         simplIdWantsToBeINLINEd,
20
21         type_ok_for_let_to_case
22     ) where
23
24 import Ubiq{-uitous-}
25
26 import BinderInfo
27 import CmdLineOpts      ( SimplifierSwitch(..) )
28 import CoreSyn
29 import CoreUtils        ( manifestlyWHNF )
30 import Id               ( idType, isBottomingId, idWantsToBeINLINEd, dataConArgTys,
31                           getIdArity, GenId{-instance Eq-}
32                         )
33 import IdInfo           ( arityMaybe )
34 import Maybes           ( maybeToBool )
35 import PrelInfo         ( augmentId, buildId, realWorldStateTy )
36 import PrimOp           ( primOpIsCheap )
37 import SimplEnv
38 import SimplMonad
39 import Type             ( eqTy, isPrimType, maybeAppDataTyCon, getTyVar_maybe )
40 import TyVar            ( GenTyVar{-instance Eq-} )
41 import Util             ( isIn, panic )
42
43 \end{code}
44
45
46 Floating
47 ~~~~~~~~
48 The function @floatExposesHNF@ tells whether let/case floating will
49 expose a head normal form.  It is passed booleans indicating the
50 desired strategy.
51
52 \begin{code}
53 floatExposesHNF
54         :: Bool                 -- Float let(rec)s out of rhs
55         -> Bool                 -- Float cheap primops out of rhs
56         -> Bool                 -- OK to duplicate code
57         -> GenCoreExpr bdr Id tyvar uvar
58         -> Bool
59
60 floatExposesHNF float_lets float_primops ok_to_dup rhs
61   = try rhs
62   where
63     try (Case (Prim _ _) (PrimAlts alts deflt) )
64       | float_primops && (null alts || ok_to_dup)
65       = or (try_deflt deflt : map try_alt alts)
66
67     try (Let bind body) | float_lets = try body
68
69     --    `build g'
70     -- is like a HNF,
71     -- because it *will* become one.
72     -- likewise for `augment g h'
73     --
74     try (App (App (Var bld) _) _)         | bld == buildId   = True
75     try (App (App (App (Var aug) _) _) _) | aug == augmentId = True
76
77     try other = manifestlyWHNF other
78         {- but *not* necessarily "manifestlyBottom other"...
79
80            We may want to float a let out of a let to expose WHNFs,
81             but to do that to expose a "bottom" is a Bad Idea:
82             let x = let y = ...
83                     in ...error ...y... --  manifestly bottom using y
84             in ...
85             =/=>
86             let y = ...
87             in let x = ...error ...y...
88                in ...
89
90             as y is only used in case of an error, we do not want
91             to allocate it eagerly as that's a waste.
92         -}
93
94     try_alt (lit,rhs) = try rhs
95
96     try_deflt NoDefault           = False
97     try_deflt (BindDefault _ rhs) = try rhs
98 \end{code}
99
100
101 Eta reduction on ordinary lambdas
102 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
103 We have a go at doing
104
105         \ x y -> f x y  ===>  f
106
107 But we only do this if it gets rid of a whole lambda, not part.
108 The idea is that lambdas are often quite helpful: they indicate
109 head normal forms, so we don't want to chuck them away lightly.
110 But if they expose a simple variable then we definitely win.  Even
111 if they expose a type application we win.  So we check for this special
112 case.
113
114 It does arise:
115
116         f xs = [y | (y,_) <- xs]
117
118 gives rise to a recursive function for the list comprehension, and
119 f turns out to be just a single call to this recursive function.
120
121 \begin{code}
122 mkValLamTryingEta :: [Id]               -- Args to the lambda
123                -> CoreExpr              -- Lambda body
124                -> CoreExpr
125
126 mkValLamTryingEta [] body = body
127
128 mkValLamTryingEta orig_ids body
129   = reduce_it (reverse orig_ids) body
130   where
131     bale_out = mkValLam orig_ids body
132
133     reduce_it [] residual
134       | residual_ok residual = residual
135       | otherwise            = bale_out
136
137     reduce_it (id:ids) (App fun (VarArg arg))
138       | id == arg
139       && not (idType id `eqTy` realWorldStateTy)
140          -- *never* eta-reduce away a PrimIO state token! (WDP 94/11)
141       = reduce_it ids fun
142
143     reduce_it ids other = bale_out
144
145     is_elem = isIn "mkValLamTryingEta"
146
147     -----------
148     residual_ok :: CoreExpr -> Bool     -- Checks for type application
149                                         -- and function not one of the
150                                         -- bound vars
151
152     residual_ok (Var v) = not (v `is_elem` orig_ids)
153                           -- Fun mustn't be one of the bound ids
154     residual_ok (App fun arg)
155       | notValArg arg   = residual_ok fun
156     residual_ok other   = False
157 \end{code}
158
159 Eta expansion
160 ~~~~~~~~~~~~~
161 @etaExpandCount@ takes an expression, E, and returns an integer n,
162 such that
163
164         E  ===>   (\x1::t1 x1::t2 ... xn::tn -> E x1 x2 ... xn)
165
166 is a safe transformation.  In particular, the transformation should
167 not cause work to be duplicated, unless it is ``cheap'' (see
168 @manifestlyCheap@ below).
169
170 @etaExpandCount@ errs on the conservative side.  It is always safe to
171 return 0.
172
173 An application of @error@ is special, because it can absorb as many
174 arguments as you care to give it.  For this special case we return
175 100, to represent "infinity", which is a bit of a hack.
176
177 \begin{code}
178 etaExpandCount :: GenCoreExpr bdr Id tyvar uvar
179                -> Int   -- Number of extra args you can safely abstract
180
181 etaExpandCount (Lam (ValBinder _) body)
182   = 1 + etaExpandCount body
183
184 etaExpandCount (Let bind body)
185   | all manifestlyCheap (rhssOfBind bind)
186   = etaExpandCount body
187
188 etaExpandCount (Case scrut alts)
189   | manifestlyCheap scrut
190   = minimum [etaExpandCount rhs | rhs <- rhssOfAlts alts]
191
192 etaExpandCount fun@(Var _)     = eta_fun fun
193 etaExpandCount (App fun arg)
194   | notValArg arg = eta_fun fun
195   | otherwise     = case etaExpandCount fun of
196                       0 -> 0
197                       n -> n-1  -- Knock off one
198
199 etaExpandCount other = 0    -- Give up
200         -- Lit, Con, Prim,
201         -- non-val Lam,
202         -- Scc (pessimistic; ToDo),
203         -- Let with non-whnf rhs(s),
204         -- Case with non-whnf scrutinee
205
206 -----------------------------
207 eta_fun :: GenCoreExpr bdr Id tv uv -- The function
208         -> Int                      -- How many args it can safely be applied to
209
210 eta_fun (App fun arg) | notValArg arg = eta_fun fun
211
212 eta_fun expr@(Var v)
213   | isBottomingId v             -- Bottoming ids have "infinite arity"
214   = 10000                       -- Blargh.  Infinite enough!
215
216 eta_fun expr@(Var v)
217   | maybeToBool arity_maybe     -- We know the arity
218   = arity
219   where
220     arity_maybe = arityMaybe (getIdArity v)
221     arity       = case arity_maybe of { Just arity -> arity }
222
223 eta_fun other = 0               -- Give up
224 \end{code}
225
226 @manifestlyCheap@ looks at a Core expression and returns \tr{True} if
227 it is obviously in weak head normal form, or is cheap to get to WHNF.
228 By ``cheap'' we mean a computation we're willing to duplicate in order
229 to bring a couple of lambdas together.  The main examples of things
230 which aren't WHNF but are ``cheap'' are:
231
232   *     case e of
233           pi -> ei
234
235         where e, and all the ei are cheap; and
236
237   *     let x = e
238         in b
239
240         where e and b are cheap; and
241
242   *     op x1 ... xn
243
244         where op is a cheap primitive operator
245
246 \begin{code}
247 manifestlyCheap :: GenCoreExpr bndr Id tv uv -> Bool
248
249 manifestlyCheap (Var _)     = True
250 manifestlyCheap (Lit _)     = True
251 manifestlyCheap (Con _ _)   = True
252 manifestlyCheap (SCC _ e)   = manifestlyCheap e
253 manifestlyCheap (Lam x e)   = if isValBinder x then True else manifestlyCheap e
254 manifestlyCheap (Prim op _) = primOpIsCheap op
255
256 manifestlyCheap (Let bind body)
257   = manifestlyCheap body && all manifestlyCheap (rhssOfBind bind)
258
259 manifestlyCheap (Case scrut alts)
260   = manifestlyCheap scrut && all manifestlyCheap (rhssOfAlts alts)
261
262 manifestlyCheap other_expr   -- look for manifest partial application
263   = case (collectArgs other_expr) of { (fun, _, _, vargs) ->
264     case fun of
265
266       Var f | isBottomingId f -> True   -- Application of a function which
267                                         -- always gives bottom; we treat this as
268                                         -- a WHNF, because it certainly doesn't
269                                         -- need to be shared!
270
271       Var f -> let
272                     num_val_args = length vargs
273                in
274                num_val_args == 0 ||     -- Just a type application of
275                                         -- a variable (f t1 t2 t3)
276                                         -- counts as WHNF
277                case (arityMaybe (getIdArity f)) of
278                  Nothing     -> False
279                  Just arity  -> num_val_args < arity
280
281       _ -> False
282     }
283 \end{code}
284
285 Eta reduction on type lambdas
286 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
287 We have a go at doing
288
289         /\a -> <expr> a    ===>     <expr>
290
291 where <expr> doesn't mention a.
292 This is sometimes quite useful, because we can get the sequence:
293
294         f ab d = let d1 = ...d... in
295                  letrec f' b x = ...d...(f' b)... in
296                  f' b
297 specialise ==>
298
299         f.Int b = letrec f' b x = ...dInt...(f' b)... in
300                   f' b
301
302 float ==>
303
304         f' b x = ...dInt...(f' b)...
305         f.Int b = f' b
306
307 Now we really want to simplify to
308
309         f.Int = f'
310
311 and then replace all the f's with f.Ints.
312
313 N.B. We are careful not to partially eta-reduce a sequence of type
314 applications since this breaks the specialiser:
315
316         /\ a -> f Char# a       =NO=> f Char#
317
318 \begin{code}
319 mkTyLamTryingEta :: [TyVar] -> CoreExpr -> CoreExpr
320
321 mkTyLamTryingEta tyvars tylam_body
322   = if
323         tyvars == tyvar_args && -- Same args in same order
324         check_fun fun           -- Function left is ok
325     then
326         -- Eta reduction worked
327         fun
328     else
329         -- The vastly common case
330         mkTyLam tyvars tylam_body
331   where
332     (tyvar_args, fun) = strip_tyvar_args [] tylam_body
333
334     strip_tyvar_args args_so_far tyapp@(App fun (TyArg ty))
335       = case getTyVar_maybe ty of
336           Just tyvar_arg -> strip_tyvar_args (tyvar_arg:args_so_far) fun
337           Nothing        -> (args_so_far, tyapp)
338
339     strip_tyvar_args args_so_far (App _ (UsageArg _))
340       = panic "SimplUtils.mkTyLamTryingEta: strip_tyvar_args UsageArg"
341
342     strip_tyvar_args args_so_far fun
343       = (args_so_far, fun)
344
345     check_fun (Var f) = True     -- Claim: tyvars not mentioned by type of f
346     check_fun other     = False
347 \end{code}
348
349 Let to case
350 ~~~~~~~~~~~
351
352 Given a type generate the case alternatives
353
354         C a b -> C a b
355
356 if there's one constructor, or
357
358         x -> x
359
360 if there's many, or if it's a primitive type.
361
362
363 \begin{code}
364 mkIdentityAlts
365         :: Type         -- type of RHS
366         -> SmplM InAlts         -- result
367
368 mkIdentityAlts rhs_ty
369   | isPrimType rhs_ty
370   = newId rhs_ty        `thenSmpl` \ binder ->
371     returnSmpl (PrimAlts [] (BindDefault (binder, bad_occ_info) (Var binder)))
372
373   | otherwise
374   = case (maybeAppDataTyCon rhs_ty) of
375         Just (tycon, ty_args, [data_con]) ->  -- algebraic type suitable for unpacking
376             let
377                 inst_con_arg_tys = dataConArgTys data_con ty_args
378             in
379             newIds inst_con_arg_tys     `thenSmpl` \ new_bindees ->
380             let
381                 new_binders = [ (b, bad_occ_info) | b <- new_bindees ]
382             in
383             returnSmpl (
384               AlgAlts
385                 [(data_con, new_binders, mkCon data_con [] ty_args (map VarArg new_bindees))]
386                 NoDefault
387             )
388
389         _ -> -- Multi-constructor or abstract algebraic type
390              newId rhs_ty       `thenSmpl` \ binder ->
391              returnSmpl (AlgAlts [] (BindDefault (binder,bad_occ_info) (Var binder)))
392   where
393     bad_occ_info = ManyOcc 0    -- Non-committal!
394 \end{code}
395
396 \begin{code}
397 simplIdWantsToBeINLINEd :: Id -> SimplEnv -> Bool
398
399 simplIdWantsToBeINLINEd id env
400   = if switchIsSet env IgnoreINLINEPragma
401     then False
402     else idWantsToBeINLINEd id
403
404 type_ok_for_let_to_case :: Type -> Bool
405
406 type_ok_for_let_to_case ty
407   = case (maybeAppDataTyCon ty) of
408       Nothing                                   -> False
409       Just (tycon, ty_args, [])                 -> False
410       Just (tycon, ty_args, non_null_data_cons) -> True
411       -- Null data cons => type is abstract
412 \end{code}