2 % (c) The AQUA Project, Glasgow University, 1993-1995
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)
34 import AbsPrel ( primOpIsCheap, realWorldStateTy, buildId
35 IF_ATTACK_PRAGMAS(COMMA realWorldTy)
36 IF_ATTACK_PRAGMAS(COMMA tagOf_PrimOp)
37 IF_ATTACK_PRAGMAS(COMMA pprPrimOp)
39 import AbsUniType ( extractTyVarsFromTy, getTyVarMaybe, isPrimType,
40 splitTypeWithDictsAsArgs, getUniDataTyCon_maybe,
41 applyTy, isFunType, TyVar, TyVarTemplate
42 IF_ATTACK_PRAGMAS(COMMA cmpTyVar COMMA cmpClass)
44 import Id ( getInstantiatedDataConSig, isDataCon, getIdUniType,
45 getIdArity, isBottomingId, idWantsToBeINLINEd,
49 import CmdLineOpts ( SimplifierSwitch(..) )
50 import Maybes ( maybeToBool, Maybe(..) )
51 import Outputable -- isExported ...
58 The function @floatExposesHNF@ tells whether let/case floating will
59 expose a head normal form. It is passed booleans indicating the
64 :: Bool -- Float let(rec)s out of rhs
65 -> Bool -- Float cheap primops out of rhs
66 -> Bool -- OK to duplicate code
70 floatExposesHNF float_lets float_primops ok_to_dup rhs
73 try (CoCase (CoPrim _ _ _) (CoPrimAlts alts deflt) )
74 | float_primops && (null alts || ok_to_dup)
75 = or (try_deflt deflt : map try_alt alts)
77 try (CoLet bind body) | float_lets = try body
81 -- because it *will* become one.
82 try (CoApp (CoTyApp (CoVar bld) _) _) | bld == buildId = True
84 try other = manifestlyWHNF other
85 {- but *not* necessarily "manifestlyBottom other"...
87 We may want to float a let out of a let to expose WHNFs,
88 but to do that to expose a "bottom" is a Bad Idea:
90 in ...error ...y... -- manifestly bottom using y
94 in let x = ...error ...y...
97 as y is only used in case of an error, we do not want
98 to allocate it eagerly as that's a waste.
101 try_alt (lit,rhs) = try rhs
103 try_deflt CoNoDefault = False
104 try_deflt (CoBindDefault _ rhs) = try rhs
108 Eta reduction on ordinary lambdas
109 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
110 We have a go at doing
112 \ x y -> f x y ===> f
114 But we only do this if it gets rid of a whole lambda, not part.
115 The idea is that lambdas are often quite helpful: they indicate
116 head normal forms, so we don't want to chuck them away lightly.
117 But if they expose a simple variable then we definitely win. Even
118 if they expose a type application we win. So we check for this special
123 f xs = [y | (y,_) <- xs]
125 gives rise to a recursive function for the list comprehension, and
126 f turns out to be just a single call to this recursive function.
129 mkCoLamTryingEta :: [Id] -- Args to the lambda
130 -> PlainCoreExpr -- Lambda body
133 mkCoLamTryingEta [] body = body
135 mkCoLamTryingEta orig_ids body
136 = reduce_it (reverse orig_ids) body
138 bale_out = mkCoLam orig_ids body
140 reduce_it [] residual
141 | residual_ok residual = residual
142 | otherwise = bale_out
144 reduce_it (id:ids) (CoApp fun (CoVarAtom arg))
146 && getIdUniType id /= realWorldStateTy
147 -- *never* eta-reduce away a PrimIO state token! (WDP 94/11)
150 reduce_it ids other = bale_out
152 is_elem = isIn "mkCoLamTryingEta"
155 residual_ok :: PlainCoreExpr -> Bool -- Checks for type application
156 -- and function not one of the
158 residual_ok (CoTyApp fun ty) = residual_ok fun
159 residual_ok (CoVar v) = not (v `is_elem` orig_ids) -- Fun mustn't be one of
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 not
172 cause work to be duplicated, unless it is ``cheap'' (see @manifestlyCheap@ below).
174 @etaExpandCount@ errs on the conservative side. It is always safe to return 0.
176 An application of @error@ is special, because it can absorb as many
177 arguments as you care to give it. For this special case we return 100,
178 to represent "infinity", which is a bit of a hack.
181 etaExpandCount :: CoreExpr bdr Id
182 -> Int -- Number of extra args you can safely abstract
184 etaExpandCount (CoLam ids body)
185 = length ids + etaExpandCount body
187 etaExpandCount (CoLet bind body)
188 | all manifestlyCheap (rhssOfBind bind)
189 = etaExpandCount body
191 etaExpandCount (CoCase scrut alts)
192 | manifestlyCheap scrut
193 = minimum [etaExpandCount rhs | rhs <- rhssOfAlts alts]
195 etaExpandCount (CoApp fun _) = case etaExpandCount fun of
197 n -> n-1 -- Knock off one
199 etaExpandCount fun@(CoTyApp _ _) = eta_fun fun
200 etaExpandCount fun@(CoVar _) = eta_fun fun
202 etaExpandCount other = 0 -- Give up
203 -- CoLit, CoCon, CoPrim,
205 -- CoScc (pessimistic; ToDo),
206 -- CoLet with non-whnf rhs(s),
207 -- CoCase with non-whnf scrutinee
209 eta_fun :: CoreExpr bdr Id -- The function
210 -> Int -- How many args it can safely be applied to
212 eta_fun (CoTyApp fun ty) = eta_fun fun
214 eta_fun expr@(CoVar v)
215 | isBottomingId v -- Bottoming ids have "infinite arity"
216 = 10000 -- Blargh. Infinite enough!
218 eta_fun expr@(CoVar v)
219 | maybeToBool arity_maybe -- We know the arity
222 arity_maybe = arityMaybe (getIdArity v)
223 arity = case arity_maybe of { Just arity -> arity }
225 eta_fun other = 0 -- Give up
228 @manifestlyCheap@ looks at a Core expression and returns \tr{True} if
229 it is obviously in weak head normal form, or is cheap to get to WHNF.
230 By ``cheap'' we mean a computation we're willing to duplicate in order
231 to bring a couple of lambdas together. The main examples of things
232 which aren't WHNF but are ``cheap'' are:
237 where e, and all the ei are cheap; and
242 where e and b are cheap; and
246 where op is a cheap primitive operator
249 manifestlyCheap :: CoreExpr bndr Id -> Bool
251 manifestlyCheap (CoVar _) = True
252 manifestlyCheap (CoLit _) = True
253 manifestlyCheap (CoCon _ _ _) = True
254 manifestlyCheap (CoLam _ _) = True
255 manifestlyCheap (CoTyLam _ e) = manifestlyCheap e
256 manifestlyCheap (CoSCC _ e) = manifestlyCheap e
258 manifestlyCheap (CoPrim op _ _) = primOpIsCheap op
260 manifestlyCheap (CoLet bind body)
261 = manifestlyCheap body && all manifestlyCheap (rhssOfBind bind)
263 manifestlyCheap (CoCase scrut alts)
264 = manifestlyCheap scrut && all manifestlyCheap (rhssOfAlts alts)
266 manifestlyCheap other_expr -- look for manifest partial application
267 = case (collectArgs other_expr) of { (fun, args) ->
270 CoVar f | isBottomingId f -> True -- Application of a function which
271 -- always gives bottom; we treat this as
272 -- a WHNF, because it certainly doesn't
273 -- need to be shared!
276 num_val_args = length [ a | (ValArg a) <- args ]
278 num_val_args == 0 || -- Just a type application of
279 -- a variable (f t1 t2 t3)
281 case (arityMaybe (getIdArity f)) of
283 Just arity -> num_val_args < arity
289 -- ToDo: Move to CoreFuns
291 rhssOfBind :: CoreBinding bndr bdee -> [CoreExpr bndr bdee]
293 rhssOfBind (CoNonRec _ rhs) = [rhs]
294 rhssOfBind (CoRec pairs) = [rhs | (_,rhs) <- pairs]
296 rhssOfAlts :: CoreCaseAlternatives bndr bdee -> [CoreExpr bndr bdee]
298 rhssOfAlts (CoAlgAlts alts deflt) = rhssOfDeflt deflt ++
299 [rhs | (_,_,rhs) <- alts]
300 rhssOfAlts (CoPrimAlts alts deflt) = rhssOfDeflt deflt ++
301 [rhs | (_,rhs) <- alts]
302 rhssOfDeflt CoNoDefault = []
303 rhssOfDeflt (CoBindDefault _ rhs) = [rhs]
306 Eta reduction on type lambdas
307 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
308 We have a go at doing
310 /\a -> <expr> a ===> <expr>
312 where <expr> doesn't mention a.
313 This is sometimes quite useful, because we can get the sequence:
315 f ab d = let d1 = ...d... in
316 letrec f' b x = ...d...(f' b)... in
320 f.Int b = letrec f' b x = ...dInt...(f' b)... in
325 f' b x = ...dInt...(f' b)...
328 Now we really want to simplify to
332 and then replace all the f's with f.Ints.
334 N.B. We are careful not to partially eta-reduce a sequence of type
335 applications since this breaks the specialiser:
337 /\ a -> f Char# a =NO=> f Char#
340 mkCoTyLamTryingEta :: [TyVar] -> PlainCoreExpr -> PlainCoreExpr
342 mkCoTyLamTryingEta tyvars tylam_body
344 tyvars == tyvar_args && -- Same args in same order
345 check_fun fun -- Function left is ok
347 -- Eta reduction worked
350 -- The vastly common case
351 mkCoTyLam tyvars tylam_body
353 (tyvar_args, fun) = strip_tyvar_args [] tylam_body
355 strip_tyvar_args args_so_far tyapp@(CoTyApp fun ty)
356 = case getTyVarMaybe ty of
357 Just tyvar_arg -> strip_tyvar_args (tyvar_arg:args_so_far) fun
358 Nothing -> (args_so_far, tyapp)
360 strip_tyvar_args args_so_far fun
363 check_fun (CoVar f) = True -- Claim: tyvars not mentioned by type of f
364 check_fun other = False
367 mkCoTyLamTryingEta :: TyVar -> PlainCoreExpr -> PlainCoreExpr
369 mkCoTyLamTryingEta tyvar body
372 case getTyVarMaybe ty of
373 Just tyvar' | tyvar == tyvar' &&
375 -- Ha! So it's /\ a -> fun a, and fun is "ok"
377 other -> CoTyLam tyvar body
378 other -> CoTyLam tyvar body
380 is_elem = isIn "mkCoTyLamTryingEta"
382 ok :: PlainCoreExpr -> Bool -- Returns True iff the expression doesn't
385 ok (CoVar v) = True -- Claim: tyvar not mentioned by type of v
386 ok (CoApp fun arg) = ok fun -- Claim: tyvar not mentioned by type of arg
387 ok (CoTyApp fun ty) = not (tyvar `is_elem` extractTyVarsFromTy ty) &&
396 Given a type generate the case alternatives
400 if there's one constructor, or
404 if there's many, or if it's a primitive type.
409 :: UniType -- type of RHS
410 -> SmplM InAlts -- result
412 mkIdentityAlts rhs_ty
414 = newId rhs_ty `thenSmpl` \ binder ->
415 returnSmpl (CoPrimAlts [] (CoBindDefault (binder, bad_occ_info) (CoVar binder)))
418 = case getUniDataTyCon_maybe rhs_ty of
419 Just (tycon, ty_args, [data_con]) -> -- algebraic type suitable for unpacking
421 (_,inst_con_arg_tys,_) = getInstantiatedDataConSig data_con ty_args
423 newIds inst_con_arg_tys `thenSmpl` \ new_bindees ->
425 new_binders = [ (b, bad_occ_info) | b <- new_bindees ]
429 [(data_con, new_binders, CoCon data_con ty_args (map CoVarAtom new_bindees))]
433 _ -> -- Multi-constructor or abstract algebraic type
434 newId rhs_ty `thenSmpl` \ binder ->
435 returnSmpl (CoAlgAlts [] (CoBindDefault (binder,bad_occ_info) (CoVar binder)))
437 bad_occ_info = ManyOcc 0 -- Non-committal!
441 simplIdWantsToBeINLINEd :: Id -> SimplEnv -> Bool
443 simplIdWantsToBeINLINEd id env
444 = if switchIsSet env IgnoreINLINEPragma
446 else idWantsToBeINLINEd id
448 type_ok_for_let_to_case :: UniType -> Bool
450 type_ok_for_let_to_case ty
451 = case getUniDataTyCon_maybe ty of
453 Just (tycon, ty_args, []) -> False
454 Just (tycon, ty_args, non_null_data_cons) -> True
455 -- Null data cons => type is abstract