2 % (c) The AQUA Project, Glasgow University, 1993-1996
4 \section[SimplUtils]{The simplifier utilities}
7 #include "HsVersions.h"
13 mkCoTyLamTryingEta, mkCoLamTryingEta,
19 simplIdWantsToBeINLINEd,
21 type_ok_for_let_to_case
24 IMPORT_Trace -- ToDo: rm (debugging)
32 import PrelInfo ( primOpIsCheap, realWorldStateTy,
34 IF_ATTACK_PRAGMAS(COMMA realWorldTy)
35 IF_ATTACK_PRAGMAS(COMMA tagOf_PrimOp)
36 IF_ATTACK_PRAGMAS(COMMA pprPrimOp)
38 import Type ( extractTyVarsFromTy, getTyVarMaybe, isPrimType,
39 splitTypeWithDictsAsArgs, maybeDataTyCon,
40 applyTy, isFunType, TyVar, TyVarTemplate
42 import Id ( getInstantiatedDataConSig, isDataCon, idType,
43 getIdArity, isBottomingId, idWantsToBeINLINEd,
47 import CmdLineOpts ( SimplifierSwitch(..) )
48 import Maybes ( maybeToBool, Maybe(..) )
49 import Outputable -- isExported ...
56 The function @floatExposesHNF@ tells whether let/case floating will
57 expose a head normal form. It is passed booleans indicating the
62 :: Bool -- Float let(rec)s out of rhs
63 -> Bool -- Float cheap primops out of rhs
64 -> Bool -- OK to duplicate code
68 floatExposesHNF float_lets float_primops ok_to_dup rhs
71 try (Case (Prim _ _ _) (PrimAlts alts deflt) )
72 | float_primops && (null alts || ok_to_dup)
73 = or (try_deflt deflt : map try_alt alts)
75 try (Let bind body) | float_lets = try body
79 -- because it *will* become one.
80 -- likewise for `augment g h'
82 try (App (CoTyApp (Var bld) _) _) | bld == buildId = True
83 try (App (App (CoTyApp (Var bld) _) _) _) | bld == augmentId = True
85 try other = manifestlyWHNF other
86 {- but *not* necessarily "manifestlyBottom other"...
88 We may want to float a let out of a let to expose WHNFs,
89 but to do that to expose a "bottom" is a Bad Idea:
91 in ...error ...y... -- manifestly bottom using y
95 in let x = ...error ...y...
98 as y is only used in case of an error, we do not want
99 to allocate it eagerly as that's a waste.
102 try_alt (lit,rhs) = try rhs
104 try_deflt NoDefault = False
105 try_deflt (BindDefault _ rhs) = try rhs
109 Eta reduction on ordinary lambdas
110 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
111 We have a go at doing
113 \ x y -> f x y ===> f
115 But we only do this if it gets rid of a whole lambda, not part.
116 The idea is that lambdas are often quite helpful: they indicate
117 head normal forms, so we don't want to chuck them away lightly.
118 But if they expose a simple variable then we definitely win. Even
119 if they expose a type application we win. So we check for this special
124 f xs = [y | (y,_) <- xs]
126 gives rise to a recursive function for the list comprehension, and
127 f turns out to be just a single call to this recursive function.
130 mkCoLamTryingEta :: [Id] -- Args to the lambda
131 -> CoreExpr -- Lambda body
134 mkCoLamTryingEta [] body = body
136 mkCoLamTryingEta orig_ids body
137 = reduce_it (reverse orig_ids) body
139 bale_out = mkValLam orig_ids body
141 reduce_it [] residual
142 | residual_ok residual = residual
143 | otherwise = bale_out
145 reduce_it (id:ids) (App fun (VarArg arg))
147 && idType id /= realWorldStateTy
148 -- *never* eta-reduce away a PrimIO state token! (WDP 94/11)
151 reduce_it ids other = bale_out
153 is_elem = isIn "mkCoLamTryingEta"
156 residual_ok :: CoreExpr -> Bool -- Checks for type application
157 -- and function not one of the
159 residual_ok (CoTyApp fun ty) = residual_ok fun
160 residual_ok (Var v) = not (v `is_elem` orig_ids) -- Fun mustn't be one of
162 residual_ok other = False
167 @etaExpandCount@ takes an expression, E, and returns an integer n,
170 E ===> (\x1::t1 x1::t2 ... xn::tn -> E x1 x2 ... xn)
172 is a safe transformation. In particular, the transformation should not
173 cause work to be duplicated, unless it is ``cheap'' (see @manifestlyCheap@ below).
175 @etaExpandCount@ errs on the conservative side. It is always safe to return 0.
177 An application of @error@ is special, because it can absorb as many
178 arguments as you care to give it. For this special case we return 100,
179 to represent "infinity", which is a bit of a hack.
182 etaExpandCount :: GenCoreExpr bdr Id
183 -> Int -- Number of extra args you can safely abstract
185 etaExpandCount (Lam _ body)
186 = 1 + etaExpandCount body
188 etaExpandCount (Let bind body)
189 | all manifestlyCheap (rhssOfBind bind)
190 = etaExpandCount body
192 etaExpandCount (Case scrut alts)
193 | manifestlyCheap scrut
194 = minimum [etaExpandCount rhs | rhs <- rhssOfAlts alts]
196 etaExpandCount (App fun _) = case etaExpandCount fun of
198 n -> n-1 -- Knock off one
200 etaExpandCount fun@(CoTyApp _ _) = eta_fun fun
201 etaExpandCount fun@(Var _) = eta_fun fun
203 etaExpandCount other = 0 -- Give up
206 -- Scc (pessimistic; ToDo),
207 -- Let with non-whnf rhs(s),
208 -- Case with non-whnf scrutinee
210 eta_fun :: GenCoreExpr bdr Id -- The function
211 -> Int -- How many args it can safely be applied to
213 eta_fun (CoTyApp fun ty) = eta_fun fun
216 | isBottomingId v -- Bottoming ids have "infinite arity"
217 = 10000 -- Blargh. Infinite enough!
220 | maybeToBool arity_maybe -- We know the arity
223 arity_maybe = arityMaybe (getIdArity v)
224 arity = case arity_maybe of { Just arity -> arity }
226 eta_fun other = 0 -- Give up
229 @manifestlyCheap@ looks at a Core expression and returns \tr{True} if
230 it is obviously in weak head normal form, or is cheap to get to WHNF.
231 By ``cheap'' we mean a computation we're willing to duplicate in order
232 to bring a couple of lambdas together. The main examples of things
233 which aren't WHNF but are ``cheap'' are:
238 where e, and all the ei are cheap; and
243 where e and b are cheap; and
247 where op is a cheap primitive operator
250 manifestlyCheap :: GenCoreExpr bndr Id -> Bool
252 manifestlyCheap (Var _) = True
253 manifestlyCheap (Lit _) = True
254 manifestlyCheap (Con _ _ _) = True
255 manifestlyCheap (Lam _ _) = True
256 manifestlyCheap (CoTyLam _ e) = manifestlyCheap e
257 manifestlyCheap (SCC _ e) = manifestlyCheap e
259 manifestlyCheap (Prim op _ _) = primOpIsCheap op
261 manifestlyCheap (Let bind body)
262 = manifestlyCheap body && all manifestlyCheap (rhssOfBind bind)
264 manifestlyCheap (Case scrut alts)
265 = manifestlyCheap scrut && all manifestlyCheap (rhssOfAlts alts)
267 manifestlyCheap other_expr -- look for manifest partial application
268 = case (collectArgs other_expr) of { (fun, args) ->
271 Var f | isBottomingId f -> True -- Application of a function which
272 -- always gives bottom; we treat this as
273 -- a WHNF, because it certainly doesn't
274 -- need to be shared!
277 num_val_args = length [ a | (ValArg a) <- args ]
279 num_val_args == 0 || -- Just a type application of
280 -- a variable (f t1 t2 t3)
282 case (arityMaybe (getIdArity f)) of
284 Just arity -> num_val_args < arity
290 Eta reduction on type lambdas
291 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
292 We have a go at doing
294 /\a -> <expr> a ===> <expr>
296 where <expr> doesn't mention a.
297 This is sometimes quite useful, because we can get the sequence:
299 f ab d = let d1 = ...d... in
300 letrec f' b x = ...d...(f' b)... in
304 f.Int b = letrec f' b x = ...dInt...(f' b)... in
309 f' b x = ...dInt...(f' b)...
312 Now we really want to simplify to
316 and then replace all the f's with f.Ints.
318 N.B. We are careful not to partially eta-reduce a sequence of type
319 applications since this breaks the specialiser:
321 /\ a -> f Char# a =NO=> f Char#
324 mkCoTyLamTryingEta :: [TyVar] -> CoreExpr -> CoreExpr
326 mkCoTyLamTryingEta tyvars tylam_body
328 tyvars == tyvar_args && -- Same args in same order
329 check_fun fun -- Function left is ok
331 -- Eta reduction worked
334 -- The vastly common case
335 mkCoTyLam tyvars tylam_body
337 (tyvar_args, fun) = strip_tyvar_args [] tylam_body
339 strip_tyvar_args args_so_far tyapp@(CoTyApp fun ty)
340 = case getTyVarMaybe ty of
341 Just tyvar_arg -> strip_tyvar_args (tyvar_arg:args_so_far) fun
342 Nothing -> (args_so_far, tyapp)
344 strip_tyvar_args args_so_far fun
347 check_fun (Var f) = True -- Claim: tyvars not mentioned by type of f
348 check_fun other = False
354 Given a type generate the case alternatives
358 if there's one constructor, or
362 if there's many, or if it's a primitive type.
367 :: Type -- type of RHS
368 -> SmplM InAlts -- result
370 mkIdentityAlts rhs_ty
372 = newId rhs_ty `thenSmpl` \ binder ->
373 returnSmpl (PrimAlts [] (BindDefault (binder, bad_occ_info) (Var binder)))
376 = case maybeDataTyCon rhs_ty of
377 Just (tycon, ty_args, [data_con]) -> -- algebraic type suitable for unpacking
379 (_,inst_con_arg_tys,_) = getInstantiatedDataConSig data_con ty_args
381 newIds inst_con_arg_tys `thenSmpl` \ new_bindees ->
383 new_binders = [ (b, bad_occ_info) | b <- new_bindees ]
387 [(data_con, new_binders, Con data_con ty_args (map VarArg new_bindees))]
391 _ -> -- Multi-constructor or abstract algebraic type
392 newId rhs_ty `thenSmpl` \ binder ->
393 returnSmpl (AlgAlts [] (BindDefault (binder,bad_occ_info) (Var binder)))
395 bad_occ_info = ManyOcc 0 -- Non-committal!
399 simplIdWantsToBeINLINEd :: Id -> SimplEnv -> Bool
401 simplIdWantsToBeINLINEd id env
402 = if switchIsSet env IgnoreINLINEPragma
404 else idWantsToBeINLINEd id
406 type_ok_for_let_to_case :: Type -> Bool
408 type_ok_for_let_to_case ty
409 = case maybeDataTyCon ty of
411 Just (tycon, ty_args, []) -> False
412 Just (tycon, ty_args, non_null_data_cons) -> True
413 -- Null data cons => type is abstract