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