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