2 % (c) The AQUA Project, Glasgow University, 1993-1996
4 \section[SimplUtils]{The simplifier utilities}
7 #include "HsVersions.h"
13 mkTyLamTryingEta, mkValLamTryingEta,
19 simplIdWantsToBeINLINEd,
21 type_ok_for_let_to_case
25 IMPORT_DELOOPER(SmplLoop) -- paranoia checking
28 import CmdLineOpts ( SimplifierSwitch(..) )
30 import CoreUnfold ( SimpleUnfolding, mkFormSummary, FormSummary(..) )
31 import Id ( idType, isBottomingId, idWantsToBeINLINEd, dataConArgTys,
32 getIdArity, GenId{-instance Eq-}
34 import IdInfo ( ArityInfo(..) )
35 import Maybes ( maybeToBool )
36 import PrelVals ( augmentId, buildId )
37 import PrimOp ( primOpIsCheap )
40 import Type ( eqTy, isPrimType, maybeAppDataTyConExpandingDicts, getTyVar_maybe )
41 import TysWiredIn ( realWorldStateTy )
42 import TyVar ( GenTyVar{-instance Eq-} )
43 import Util ( isIn, panic )
50 The function @floatExposesHNF@ tells whether let/case floating will
51 expose a head normal form. It is passed booleans indicating the
56 :: Bool -- Float let(rec)s out of rhs
57 -> Bool -- Float cheap primops out of rhs
58 -> Bool -- OK to duplicate code
59 -> GenCoreExpr bdr Id tyvar uvar
62 floatExposesHNF float_lets float_primops ok_to_dup rhs
65 try (Case (Prim _ _) (PrimAlts alts deflt) )
66 | float_primops && (null alts || ok_to_dup)
67 = or (try_deflt deflt : map try_alt alts)
69 try (Let bind body) | float_lets = try body
73 -- because it *will* become one.
74 -- likewise for `augment g h'
76 try (App (App (Var bld) _) _) | bld == buildId = True
77 try (App (App (App (Var aug) _) _) _) | aug == augmentId = True
79 try other = case mkFormSummary other of
83 {- but *not* necessarily "BottomForm"...
85 We may want to float a let out of a let to expose WHNFs,
86 but to do that to expose a "bottom" is a Bad Idea:
88 in ...error ...y... -- manifestly bottom using y
92 in let x = ...error ...y...
95 as y is only used in case of an error, we do not want
96 to allocate it eagerly as that's a waste.
99 try_alt (lit,rhs) = try rhs
101 try_deflt NoDefault = False
102 try_deflt (BindDefault _ rhs) = try rhs
106 Eta reduction on ordinary lambdas
107 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
108 We have a go at doing
110 \ x y -> f x y ===> f
112 But we only do this if it gets rid of a whole lambda, not part.
113 The idea is that lambdas are often quite helpful: they indicate
114 head normal forms, so we don't want to chuck them away lightly.
115 But if they expose a simple variable then we definitely win. Even
116 if they expose a type application we win. So we check for this special
121 f xs = [y | (y,_) <- xs]
123 gives rise to a recursive function for the list comprehension, and
124 f turns out to be just a single call to this recursive function.
127 mkValLamTryingEta :: [Id] -- Args to the lambda
128 -> CoreExpr -- Lambda body
131 mkValLamTryingEta [] body = body
133 mkValLamTryingEta orig_ids body
134 = reduce_it (reverse orig_ids) body
136 bale_out = mkValLam orig_ids body
138 reduce_it [] residual
139 | residual_ok residual = residual
140 | otherwise = bale_out
142 reduce_it (id:ids) (App fun (VarArg arg))
144 && not (idType id `eqTy` realWorldStateTy)
145 -- *never* eta-reduce away a PrimIO state token! (WDP 94/11)
148 reduce_it ids other = bale_out
150 is_elem = isIn "mkValLamTryingEta"
153 residual_ok :: CoreExpr -> Bool -- Checks for type application
154 -- and function not one of the
157 residual_ok (Var v) = not (v `is_elem` orig_ids)
158 -- Fun mustn't be one of the bound ids
159 residual_ok (App fun arg)
160 | notValArg arg = residual_ok fun
161 residual_ok other = False
166 @etaExpandCount@ takes an expression, E, and returns an integer n,
169 E ===> (\x1::t1 x1::t2 ... xn::tn -> E x1 x2 ... xn)
171 is a safe transformation. In particular, the transformation should
172 not cause work to be duplicated, unless it is ``cheap'' (see
173 @manifestlyCheap@ below).
175 @etaExpandCount@ errs on the conservative side. It is always safe to
178 An application of @error@ is special, because it can absorb as many
179 arguments as you care to give it. For this special case we return
180 100, to represent "infinity", which is a bit of a hack.
183 etaExpandCount :: GenCoreExpr bdr Id tyvar uvar
184 -> Int -- Number of extra args you can safely abstract
186 etaExpandCount (Lam (ValBinder _) body)
187 = 1 + etaExpandCount body
189 etaExpandCount (Let bind body)
190 | all manifestlyCheap (rhssOfBind bind)
191 = etaExpandCount body
193 etaExpandCount (Case scrut alts)
194 | manifestlyCheap scrut
195 = minimum [etaExpandCount rhs | rhs <- rhssOfAlts alts]
197 etaExpandCount fun@(Var _) = eta_fun fun
198 etaExpandCount (App fun arg)
199 | notValArg arg = eta_fun fun
200 | otherwise = case etaExpandCount fun of
202 n -> n-1 -- Knock off one
204 etaExpandCount other = 0 -- Give up
207 -- Scc (pessimistic; ToDo),
208 -- Let with non-whnf rhs(s),
209 -- Case with non-whnf scrutinee
211 -----------------------------
212 eta_fun :: GenCoreExpr bdr Id tv uv -- The function
213 -> Int -- How many args it can safely be applied to
215 eta_fun (App fun arg) | notValArg arg = eta_fun fun
218 | isBottomingId v -- Bottoming ids have "infinite arity"
219 = 10000 -- Blargh. Infinite enough!
221 eta_fun expr@(Var v) = idMinArity v
223 eta_fun other = 0 -- Give up
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:
235 where e, and all the ei are cheap; and
240 where e and b are cheap; and
244 where op is a cheap primitive operator
247 manifestlyCheap :: GenCoreExpr bndr Id tv uv -> Bool
249 manifestlyCheap (Var _) = True
250 manifestlyCheap (Lit _) = True
251 manifestlyCheap (Con _ _) = True
252 manifestlyCheap (SCC _ e) = manifestlyCheap e
253 manifestlyCheap (Coerce _ _ e) = manifestlyCheap e
254 manifestlyCheap (Lam x e) = if isValBinder x then True else manifestlyCheap e
255 manifestlyCheap (Prim op _) = primOpIsCheap op
257 manifestlyCheap (Let bind body)
258 = manifestlyCheap body && all manifestlyCheap (rhssOfBind bind)
260 manifestlyCheap (Case scrut alts)
261 = manifestlyCheap scrut && all manifestlyCheap (rhssOfAlts alts)
263 manifestlyCheap other_expr -- look for manifest partial application
264 = case (collectArgs other_expr) of { (fun, _, _, vargs) ->
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!
273 num_val_args = length vargs
275 num_val_args == 0 || -- Just a type application of
276 -- a variable (f t1 t2 t3)
278 num_val_args < idMinArity f
285 Eta reduction on type lambdas
286 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
287 We have a go at doing
289 /\a -> <expr> a ===> <expr>
291 where <expr> doesn't mention a.
292 This is sometimes quite useful, because we can get the sequence:
294 f ab d = let d1 = ...d... in
295 letrec f' b x = ...d...(f' b)... in
299 f.Int b = letrec f' b x = ...dInt...(f' b)... in
304 f' b x = ...dInt...(f' b)...
307 Now we really want to simplify to
311 and then replace all the f's with f.Ints.
313 N.B. We are careful not to partially eta-reduce a sequence of type
314 applications since this breaks the specialiser:
316 /\ a -> f Char# a =NO=> f Char#
319 mkTyLamTryingEta :: [TyVar] -> CoreExpr -> CoreExpr
321 mkTyLamTryingEta tyvars tylam_body
323 tyvars == tyvar_args && -- Same args in same order
324 check_fun fun -- Function left is ok
326 -- Eta reduction worked
329 -- The vastly common case
330 mkTyLam tyvars tylam_body
332 (tyvar_args, fun) = strip_tyvar_args [] tylam_body
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)
339 strip_tyvar_args args_so_far (App _ (UsageArg _))
340 = panic "SimplUtils.mkTyLamTryingEta: strip_tyvar_args UsageArg"
342 strip_tyvar_args args_so_far fun
345 check_fun (Var f) = True -- Claim: tyvars not mentioned by type of f
346 check_fun other = False
352 Given a type generate the case alternatives
356 if there's one constructor, or
360 if there's many, or if it's a primitive type.
365 :: Type -- type of RHS
366 -> SmplM InAlts -- result
368 mkIdentityAlts rhs_ty
370 = newId rhs_ty `thenSmpl` \ binder ->
371 returnSmpl (PrimAlts [] (BindDefault (binder, bad_occ_info) (Var binder)))
374 = case (maybeAppDataTyConExpandingDicts rhs_ty) of
375 Just (tycon, ty_args, [data_con]) -> -- algebraic type suitable for unpacking
377 inst_con_arg_tys = dataConArgTys data_con ty_args
379 newIds inst_con_arg_tys `thenSmpl` \ new_bindees ->
381 new_binders = [ (b, bad_occ_info) | b <- new_bindees ]
385 [(data_con, new_binders, mkCon data_con [] ty_args (map VarArg new_bindees))]
389 _ -> -- Multi-constructor or abstract algebraic type
390 newId rhs_ty `thenSmpl` \ binder ->
391 returnSmpl (AlgAlts [] (BindDefault (binder,bad_occ_info) (Var binder)))
393 bad_occ_info = ManyOcc 0 -- Non-committal!
397 simplIdWantsToBeINLINEd :: Id -> SimplEnv -> Bool
399 simplIdWantsToBeINLINEd id env
400 = if switchIsSet env IgnoreINLINEPragma
402 else idWantsToBeINLINEd id
404 idMinArity id = case getIdArity id of
409 type_ok_for_let_to_case :: Type -> Bool
411 type_ok_for_let_to_case ty
412 = case (maybeAppDataTyConExpandingDicts ty) of
414 Just (tycon, ty_args, []) -> False
415 Just (tycon, ty_args, non_null_data_cons) -> True
416 -- Null data cons => type is abstract