Minor tidying up
[ghc-hetmet.git] / compiler / coreSyn / CoreUtils.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[CoreUtils]{Utility functions on @Core@ syntax}
5
6 \begin{code}
7 module CoreUtils (
8         -- Construction
9         mkInlineMe, mkSCC, mkCoerce, 
10         bindNonRec, needsCaseBinding,
11         mkIfThenElse, mkAltExpr, mkPiType, mkPiTypes,
12
13         -- Taking expressions apart
14         findDefault, findAlt, isDefaultAlt, mergeAlts,
15
16         -- Properties of expressions
17         exprType, coreAltType,
18         exprIsDupable, exprIsTrivial, exprIsCheap, 
19         exprIsHNF,exprOkForSpeculation, exprIsBig, 
20         exprIsConApp_maybe, exprIsBottom,
21         rhsIsStatic,
22
23         -- Arity and eta expansion
24         manifestArity, exprArity, 
25         exprEtaExpandArity, etaExpand, 
26
27         -- Size
28         coreBindsSize,
29
30         -- Hashing
31         hashExpr,
32
33         -- Equality
34         cheapEqExpr, tcEqExpr, tcEqExprX, applyTypeToArgs, applyTypeToArg,
35
36         dataConInstPat, dataConOccInstPat
37     ) where
38
39 #include "HsVersions.h"
40
41
42 import GLAEXTS          -- For `xori` 
43
44 import CoreSyn
45 import CoreFVs          ( exprFreeVars )
46 import PprCore          ( pprCoreExpr )
47 import Var              ( Var, TyVar, CoVar, isCoVar, tyVarKind, setVarUnique,
48                           mkCoVar, mkTyVar, mkCoVar )
49 import OccName          ( OccName, occNameFS, mkVarOcc )
50 import VarSet           ( unionVarSet )
51 import VarEnv
52 import Name             ( hashName, mkSysTvName )
53 #if mingw32_TARGET_OS
54 import Packages         ( isDllName )
55 #endif
56 import Literal          ( hashLiteral, literalType, litIsDupable, 
57                           litIsTrivial, isZeroLit, Literal( MachLabel ) )
58 import DataCon          ( DataCon, dataConRepArity, eqSpecPreds, 
59                           isVanillaDataCon, dataConTyCon, dataConRepArgTys,
60                           dataConUnivTyVars, dataConExTyVars, dataConEqSpec )
61 import PrimOp           ( PrimOp(..), primOpOkForSpeculation, primOpIsCheap )
62 import Id               ( Id, idType, globalIdDetails, idNewStrictness, 
63                           mkWildId, idArity, idName, idUnfolding, idInfo,
64                           isOneShotBndr, isStateHackType, isDataConWorkId_maybe, mkSysLocal,
65                           isDataConWorkId, isBottomingId, isDictId
66                         )
67 import IdInfo           ( GlobalIdDetails(..), megaSeqIdInfo )
68 import NewDemand        ( appIsBottom )
69 import Type             ( Type, mkFunTy, mkForAllTy, splitFunTy_maybe,
70                           splitFunTy, tcEqTypeX,
71                           applyTys, isUnLiftedType, seqType, mkTyVarTy,
72                           splitForAllTy_maybe, isForAllTy, splitRecNewType_maybe, 
73                           splitTyConApp_maybe, coreEqType, funResultTy, applyTy,
74                           substTyWith, mkPredTy
75                         )
76 import Coercion         ( Coercion, mkTransCoercion, coercionKind,
77                           splitNewTypeRepCo_maybe, mkSymCoercion, mkLeftCoercion,
78                           mkRightCoercion, decomposeCo, coercionKindPredTy,
79                           splitCoercionKind, mkEqPred )
80 import TyCon            ( tyConArity )
81 import TysWiredIn       ( boolTy, trueDataCon, falseDataCon )
82 import CostCentre       ( CostCentre )
83 import BasicTypes       ( Arity )
84 import PackageConfig    ( PackageId )
85 import Unique           ( Unique )
86 import Outputable
87 import DynFlags         ( DynFlags, DynFlag(Opt_DictsCheap), dopt )
88 import TysPrim          ( alphaTy )     -- Debugging only
89 import Util             ( equalLength, lengthAtLeast, foldl2 )
90 import FastString       ( mkFastString )
91 \end{code}
92
93
94 %************************************************************************
95 %*                                                                      *
96 \subsection{Find the type of a Core atom/expression}
97 %*                                                                      *
98 %************************************************************************
99
100 \begin{code}
101 exprType :: CoreExpr -> Type
102
103 exprType (Var var)              = idType var
104 exprType (Lit lit)              = literalType lit
105 exprType (Let _ body)           = exprType body
106 exprType (Case _ _ ty alts)     = ty
107 exprType (Cast e co) 
108   = let (_, ty) = coercionKind co in ty
109 exprType (Note other_note e)    = exprType e
110 exprType (Lam binder expr)      = mkPiType binder (exprType expr)
111 exprType e@(App _ _)
112   = case collectArgs e of
113         (fun, args) -> applyTypeToArgs e (exprType fun) args
114
115 exprType other = pprTrace "exprType" (pprCoreExpr other) alphaTy
116
117 coreAltType :: CoreAlt -> Type
118 coreAltType (_,_,rhs) = exprType rhs
119 \end{code}
120
121 @mkPiType@ makes a (->) type or a forall type, depending on whether
122 it is given a type variable or a term variable.  We cleverly use the
123 lbvarinfo field to figure out the right annotation for the arrove in
124 case of a term variable.
125
126 \begin{code}
127 mkPiType  :: Var   -> Type -> Type      -- The more polymorphic version
128 mkPiTypes :: [Var] -> Type -> Type      --    doesn't work...
129
130 mkPiTypes vs ty = foldr mkPiType ty vs
131
132 mkPiType v ty
133    | isId v    = mkFunTy (idType v) ty
134    | otherwise = mkForAllTy v ty
135 \end{code}
136
137 \begin{code}
138 applyTypeToArg :: Type -> CoreExpr -> Type
139 applyTypeToArg fun_ty (Type arg_ty) = applyTy fun_ty arg_ty
140 applyTypeToArg fun_ty other_arg     = funResultTy fun_ty
141
142 applyTypeToArgs :: CoreExpr -> Type -> [CoreExpr] -> Type
143 -- A more efficient version of applyTypeToArg 
144 -- when we have several args
145 -- The first argument is just for debugging
146 applyTypeToArgs e op_ty [] = op_ty
147
148 applyTypeToArgs e op_ty (Type ty : args)
149   =     -- Accumulate type arguments so we can instantiate all at once
150     go [ty] args
151   where
152     go rev_tys (Type ty : args) = go (ty:rev_tys) args
153     go rev_tys rest_args        = applyTypeToArgs e op_ty' rest_args
154                                 where
155                                   op_ty' = applyTys op_ty (reverse rev_tys)
156
157 applyTypeToArgs e op_ty (other_arg : args)
158   = case (splitFunTy_maybe op_ty) of
159         Just (_, res_ty) -> applyTypeToArgs e res_ty args
160         Nothing -> pprPanic "applyTypeToArgs" (pprCoreExpr e $$ ppr op_ty)
161 \end{code}
162
163
164
165 %************************************************************************
166 %*                                                                      *
167 \subsection{Attaching notes}
168 %*                                                                      *
169 %************************************************************************
170
171 mkNote removes redundant coercions, and SCCs where possible
172
173 \begin{code}
174 #ifdef UNUSED
175 mkNote :: Note -> CoreExpr -> CoreExpr
176 mkNote (SCC cc) expr               = mkSCC cc expr
177 mkNote InlineMe expr               = mkInlineMe expr
178 mkNote note     expr               = Note note expr
179 #endif
180 \end{code}
181
182 Drop trivial InlineMe's.  This is somewhat important, because if we have an unfolding
183 that looks like (Note InlineMe (Var v)), the InlineMe doesn't go away because it may
184 not be *applied* to anything.
185
186 We don't use exprIsTrivial here, though, because we sometimes generate worker/wrapper
187 bindings like
188         fw = ...
189         f  = inline_me (coerce t fw)
190 As usual, the inline_me prevents the worker from getting inlined back into the wrapper.
191 We want the split, so that the coerces can cancel at the call site.  
192
193 However, we can get left with tiresome type applications.  Notably, consider
194         f = /\ a -> let t = e in (t, w)
195 Then lifting the let out of the big lambda gives
196         t' = /\a -> e
197         f = /\ a -> let t = inline_me (t' a) in (t, w)
198 The inline_me is to stop the simplifier inlining t' right back
199 into t's RHS.  In the next phase we'll substitute for t (since
200 its rhs is trivial) and *then* we could get rid of the inline_me.
201 But it hardly seems worth it, so I don't bother.
202
203 \begin{code}
204 mkInlineMe (Var v) = Var v
205 mkInlineMe e       = Note InlineMe e
206 \end{code}
207
208
209
210 \begin{code}
211 mkCoerce :: Coercion -> CoreExpr -> CoreExpr
212 mkCoerce co (Cast expr co2)
213   = ASSERT(let { (from_ty, to_ty) = coercionKind co; 
214                  (from_ty2, to_ty2) = coercionKind co2} in
215            from_ty `coreEqType` to_ty2 )
216     mkCoerce (mkTransCoercion co2 co) expr
217
218 mkCoerce co expr 
219   = let (from_ty, to_ty) = coercionKind co in
220 --    if to_ty `coreEqType` from_ty
221 --    then expr
222 --    else 
223         ASSERT2(from_ty `coreEqType` (exprType expr), text "Trying to coerce" <+> text "(" <> ppr expr $$ text "::" <+> ppr (exprType expr) <> text ")" $$ ppr co $$ ppr (coercionKindPredTy co))
224          (Cast expr co)
225 \end{code}
226
227 \begin{code}
228 mkSCC :: CostCentre -> Expr b -> Expr b
229         -- Note: Nested SCC's *are* preserved for the benefit of
230         --       cost centre stack profiling
231 mkSCC cc (Lit lit)          = Lit lit
232 mkSCC cc (Lam x e)          = Lam x (mkSCC cc e)  -- Move _scc_ inside lambda
233 mkSCC cc (Note (SCC cc') e) = Note (SCC cc) (Note (SCC cc') e)
234 mkSCC cc (Note n e)         = Note n (mkSCC cc e) -- Move _scc_ inside notes
235 mkSCC cc (Cast e co)        = Cast (mkSCC cc e) co -- Move _scc_ inside cast
236 mkSCC cc expr               = Note (SCC cc) expr
237 \end{code}
238
239
240 %************************************************************************
241 %*                                                                      *
242 \subsection{Other expression construction}
243 %*                                                                      *
244 %************************************************************************
245
246 \begin{code}
247 bindNonRec :: Id -> CoreExpr -> CoreExpr -> CoreExpr
248 -- (bindNonRec x r b) produces either
249 --      let x = r in b
250 -- or
251 --      case r of x { _DEFAULT_ -> b }
252 --
253 -- depending on whether x is unlifted or not
254 -- It's used by the desugarer to avoid building bindings
255 -- that give Core Lint a heart attack.  Actually the simplifier
256 -- deals with them perfectly well.
257
258 bindNonRec bndr rhs body 
259   | needsCaseBinding (idType bndr) rhs = Case rhs bndr (exprType body) [(DEFAULT,[],body)]
260   | otherwise                          = Let (NonRec bndr rhs) body
261
262 needsCaseBinding ty rhs = isUnLiftedType ty && not (exprOkForSpeculation rhs)
263         -- Make a case expression instead of a let
264         -- These can arise either from the desugarer,
265         -- or from beta reductions: (\x.e) (x +# y)
266 \end{code}
267
268 \begin{code}
269 mkAltExpr :: AltCon -> [CoreBndr] -> [Type] -> CoreExpr
270         -- This guy constructs the value that the scrutinee must have
271         -- when you are in one particular branch of a case
272 mkAltExpr (DataAlt con) args inst_tys
273   = mkConApp con (map Type inst_tys ++ varsToCoreExprs args)
274 mkAltExpr (LitAlt lit) [] []
275   = Lit lit
276
277 mkIfThenElse :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
278 mkIfThenElse guard then_expr else_expr
279 -- Not going to be refining, so okay to take the type of the "then" clause
280   = Case guard (mkWildId boolTy) (exprType then_expr) 
281          [ (DataAlt falseDataCon, [], else_expr),       -- Increasing order of tag!
282            (DataAlt trueDataCon,  [], then_expr) ]
283 \end{code}
284
285
286 %************************************************************************
287 %*                                                                      *
288 \subsection{Taking expressions apart}
289 %*                                                                      *
290 %************************************************************************
291
292 The default alternative must be first, if it exists at all.
293 This makes it easy to find, though it makes matching marginally harder.
294
295 \begin{code}
296 findDefault :: [CoreAlt] -> ([CoreAlt], Maybe CoreExpr)
297 findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null args ) (alts, Just rhs)
298 findDefault alts                        =                     (alts, Nothing)
299
300 findAlt :: AltCon -> [CoreAlt] -> CoreAlt
301 findAlt con alts
302   = case alts of
303         (deflt@(DEFAULT,_,_):alts) -> go alts deflt
304         other                      -> go alts panic_deflt
305   where
306     panic_deflt = pprPanic "Missing alternative" (ppr con $$ vcat (map ppr alts))
307
308     go []                      deflt = deflt
309     go (alt@(con1,_,_) : alts) deflt
310       = case con `cmpAltCon` con1 of
311           LT -> deflt   -- Missed it already; the alts are in increasing order
312           EQ -> alt
313           GT -> ASSERT( not (con1 == DEFAULT) ) go alts deflt
314
315 isDefaultAlt :: CoreAlt -> Bool
316 isDefaultAlt (DEFAULT, _, _) = True
317 isDefaultAlt other           = False
318
319 ---------------------------------
320 mergeAlts :: [CoreAlt] -> [CoreAlt] -> [CoreAlt]
321 -- Merge preserving order; alternatives in the first arg
322 -- shadow ones in the second
323 mergeAlts [] as2 = as2
324 mergeAlts as1 [] = as1
325 mergeAlts (a1:as1) (a2:as2)
326   = case a1 `cmpAlt` a2 of
327         LT -> a1 : mergeAlts as1      (a2:as2)
328         EQ -> a1 : mergeAlts as1      as2       -- Discard a2
329         GT -> a2 : mergeAlts (a1:as1) as2
330 \end{code}
331
332
333 %************************************************************************
334 %*                                                                      *
335 \subsection{Figuring out things about expressions}
336 %*                                                                      *
337 %************************************************************************
338
339 @exprIsTrivial@ is true of expressions we are unconditionally happy to
340                 duplicate; simple variables and constants, and type
341                 applications.  Note that primop Ids aren't considered
342                 trivial unless 
343
344 @exprIsBottom@  is true of expressions that are guaranteed to diverge
345
346
347 There used to be a gruesome test for (hasNoBinding v) in the
348 Var case:
349         exprIsTrivial (Var v) | hasNoBinding v = idArity v == 0
350 The idea here is that a constructor worker, like $wJust, is
351 really short for (\x -> $wJust x), becuase $wJust has no binding.
352 So it should be treated like a lambda.  Ditto unsaturated primops.
353 But now constructor workers are not "have-no-binding" Ids.  And
354 completely un-applied primops and foreign-call Ids are sufficiently
355 rare that I plan to allow them to be duplicated and put up with
356 saturating them.
357
358 SCC notes.  We do not treat (_scc_ "foo" x) as trivial, because 
359   a) it really generates code, (and a heap object when it's 
360      a function arg) to capture the cost centre
361   b) see the note [SCC-and-exprIsTrivial] in Simplify.simplLazyBind
362
363 \begin{code}
364 exprIsTrivial (Var v)      = True       -- See notes above
365 exprIsTrivial (Type _)     = True
366 exprIsTrivial (Lit lit)    = litIsTrivial lit
367 exprIsTrivial (App e arg)  = not (isRuntimeArg arg) && exprIsTrivial e
368 exprIsTrivial (Note (SCC _) e) = False          -- See notes above
369 exprIsTrivial (Note _       e) = exprIsTrivial e
370 exprIsTrivial (Cast e co)  = exprIsTrivial e
371 exprIsTrivial (Lam b body) = not (isRuntimeVar b) && exprIsTrivial body
372 exprIsTrivial other        = False
373 \end{code}
374
375
376 @exprIsDupable@ is true of expressions that can be duplicated at a modest
377                 cost in code size.  This will only happen in different case
378                 branches, so there's no issue about duplicating work.
379
380                 That is, exprIsDupable returns True of (f x) even if
381                 f is very very expensive to call.
382
383                 Its only purpose is to avoid fruitless let-binding
384                 and then inlining of case join points
385
386
387 \begin{code}
388 exprIsDupable (Type _)          = True
389 exprIsDupable (Var v)           = True
390 exprIsDupable (Lit lit)         = litIsDupable lit
391 exprIsDupable (Note InlineMe e) = True
392 exprIsDupable (Note _ e)        = exprIsDupable e
393 exprIsDupable (Cast e co)       = exprIsDupable e
394 exprIsDupable expr           
395   = go expr 0
396   where
397     go (Var v)   n_args = True
398     go (App f a) n_args =  n_args < dupAppSize
399                         && exprIsDupable a
400                         && go f (n_args+1)
401     go other n_args     = False
402
403 dupAppSize :: Int
404 dupAppSize = 4          -- Size of application we are prepared to duplicate
405 \end{code}
406
407 @exprIsCheap@ looks at a Core expression and returns \tr{True} if
408 it is obviously in weak head normal form, or is cheap to get to WHNF.
409 [Note that that's not the same as exprIsDupable; an expression might be
410 big, and hence not dupable, but still cheap.]
411
412 By ``cheap'' we mean a computation we're willing to:
413         push inside a lambda, or
414         inline at more than one place
415 That might mean it gets evaluated more than once, instead of being
416 shared.  The main examples of things which aren't WHNF but are
417 ``cheap'' are:
418
419   *     case e of
420           pi -> ei
421         (where e, and all the ei are cheap)
422
423   *     let x = e in b
424         (where e and b are cheap)
425
426   *     op x1 ... xn
427         (where op is a cheap primitive operator)
428
429   *     error "foo"
430         (because we are happy to substitute it inside a lambda)
431
432 Notice that a variable is considered 'cheap': we can push it inside a lambda,
433 because sharing will make sure it is only evaluated once.
434
435 \begin{code}
436 exprIsCheap :: CoreExpr -> Bool
437 exprIsCheap (Lit lit)         = True
438 exprIsCheap (Type _)          = True
439 exprIsCheap (Var _)           = True
440 exprIsCheap (Note InlineMe e) = True
441 exprIsCheap (Note _ e)        = exprIsCheap e
442 exprIsCheap (Cast e co)       = exprIsCheap e
443 exprIsCheap (Lam x e)         = isRuntimeVar x || exprIsCheap e
444 exprIsCheap (Case e _ _ alts) = exprIsCheap e && 
445                                 and [exprIsCheap rhs | (_,_,rhs) <- alts]
446         -- Experimentally, treat (case x of ...) as cheap
447         -- (and case __coerce x etc.)
448         -- This improves arities of overloaded functions where
449         -- there is only dictionary selection (no construction) involved
450 exprIsCheap (Let (NonRec x _) e)  
451       | isUnLiftedType (idType x) = exprIsCheap e
452       | otherwise                 = False
453         -- strict lets always have cheap right hand sides,
454         -- and do no allocation.
455
456 exprIsCheap other_expr  -- Applications and variables
457   = go other_expr []
458   where
459         -- Accumulate value arguments, then decide
460     go (App f a) val_args | isRuntimeArg a = go f (a:val_args)
461                           | otherwise      = go f val_args
462
463     go (Var f) [] = True        -- Just a type application of a variable
464                                 -- (f t1 t2 t3) counts as WHNF
465     go (Var f) args
466         = case globalIdDetails f of
467                 RecordSelId {} -> go_sel args
468                 ClassOpId _    -> go_sel args
469                 PrimOpId op    -> go_primop op args
470
471                 DataConWorkId _ -> go_pap args
472                 other | length args < idArity f -> go_pap args
473
474                 other -> isBottomingId f
475                         -- Application of a function which
476                         -- always gives bottom; we treat this as cheap
477                         -- because it certainly doesn't need to be shared!
478         
479     go other args = False
480  
481     --------------
482     go_pap args = all exprIsTrivial args
483         -- For constructor applications and primops, check that all
484         -- the args are trivial.  We don't want to treat as cheap, say,
485         --      (1:2:3:4:5:[])
486         -- We'll put up with one constructor application, but not dozens
487         
488     --------------
489     go_primop op args = primOpIsCheap op && all exprIsCheap args
490         -- In principle we should worry about primops
491         -- that return a type variable, since the result
492         -- might be applied to something, but I'm not going
493         -- to bother to check the number of args
494  
495     --------------
496     go_sel [arg] = exprIsCheap arg      -- I'm experimenting with making record selection
497     go_sel other = False                -- look cheap, so we will substitute it inside a
498                                         -- lambda.  Particularly for dictionary field selection.
499                 -- BUT: Take care with (sel d x)!  The (sel d) might be cheap, but
500                 --      there's no guarantee that (sel d x) will be too.  Hence (n_val_args == 1)
501 \end{code}
502
503 exprOkForSpeculation returns True of an expression that it is
504
505         * safe to evaluate even if normal order eval might not 
506           evaluate the expression at all, or
507
508         * safe *not* to evaluate even if normal order would do so
509
510 It returns True iff
511
512         the expression guarantees to terminate, 
513         soon, 
514         without raising an exception,
515         without causing a side effect (e.g. writing a mutable variable)
516
517 NB: if exprIsHNF e, then exprOkForSpecuation e
518
519 E.G.
520         let x = case y# +# 1# of { r# -> I# r# }
521         in E
522 ==>
523         case y# +# 1# of { r# -> 
524         let x = I# r#
525         in E 
526         }
527
528 We can only do this if the (y+1) is ok for speculation: it has no
529 side effects, and can't diverge or raise an exception.
530
531 \begin{code}
532 exprOkForSpeculation :: CoreExpr -> Bool
533 exprOkForSpeculation (Lit _)     = True
534 exprOkForSpeculation (Type _)    = True
535 exprOkForSpeculation (Var v)     = isUnLiftedType (idType v)
536 exprOkForSpeculation (Note _ e)  = exprOkForSpeculation e
537 exprOkForSpeculation (Cast e co) = exprOkForSpeculation e
538 exprOkForSpeculation other_expr
539   = case collectArgs other_expr of
540         (Var f, args) -> spec_ok (globalIdDetails f) args
541         other         -> False
542  
543   where
544     spec_ok (DataConWorkId _) args
545       = True    -- The strictness of the constructor has already
546                 -- been expressed by its "wrapper", so we don't need
547                 -- to take the arguments into account
548
549     spec_ok (PrimOpId op) args
550       | isDivOp op,             -- Special case for dividing operations that fail
551         [arg1, Lit lit] <- args -- only if the divisor is zero
552       = not (isZeroLit lit) && exprOkForSpeculation arg1
553                 -- Often there is a literal divisor, and this 
554                 -- can get rid of a thunk in an inner looop
555
556       | otherwise
557       = primOpOkForSpeculation op && 
558         all exprOkForSpeculation args
559                                 -- A bit conservative: we don't really need
560                                 -- to care about lazy arguments, but this is easy
561
562     spec_ok other args = False
563
564 isDivOp :: PrimOp -> Bool
565 -- True of dyadic operators that can fail 
566 -- only if the second arg is zero
567 -- This function probably belongs in PrimOp, or even in 
568 -- an automagically generated file.. but it's such a 
569 -- special case I thought I'd leave it here for now.
570 isDivOp IntQuotOp        = True
571 isDivOp IntRemOp         = True
572 isDivOp WordQuotOp       = True
573 isDivOp WordRemOp        = True
574 isDivOp IntegerQuotRemOp = True
575 isDivOp IntegerDivModOp  = True
576 isDivOp FloatDivOp       = True
577 isDivOp DoubleDivOp      = True
578 isDivOp other            = False
579 \end{code}
580
581
582 \begin{code}
583 exprIsBottom :: CoreExpr -> Bool        -- True => definitely bottom
584 exprIsBottom e = go 0 e
585                where
586                 -- n is the number of args
587                  go n (Note _ e)     = go n e
588                  go n (Cast e co)    = go n e
589                  go n (Let _ e)      = go n e
590                  go n (Case e _ _ _) = go 0 e   -- Just check the scrut
591                  go n (App e _)      = go (n+1) e
592                  go n (Var v)        = idAppIsBottom v n
593                  go n (Lit _)        = False
594                  go n (Lam _ _)      = False
595                  go n (Type _)       = False
596
597 idAppIsBottom :: Id -> Int -> Bool
598 idAppIsBottom id n_val_args = appIsBottom (idNewStrictness id) n_val_args
599 \end{code}
600
601 @exprIsHNF@ returns true for expressions that are certainly *already* 
602 evaluated to *head* normal form.  This is used to decide whether it's ok 
603 to change
604
605         case x of _ -> e   ===>   e
606
607 and to decide whether it's safe to discard a `seq`
608
609 So, it does *not* treat variables as evaluated, unless they say they are.
610
611 But it *does* treat partial applications and constructor applications
612 as values, even if their arguments are non-trivial, provided the argument
613 type is lifted; 
614         e.g.  (:) (f x) (map f xs)      is a value
615               map (...redex...)         is a value
616 Because `seq` on such things completes immediately
617
618 For unlifted argument types, we have to be careful:
619                 C (f x :: Int#)
620 Suppose (f x) diverges; then C (f x) is not a value.  True, but
621 this form is illegal (see the invariants in CoreSyn).  Args of unboxed
622 type must be ok-for-speculation (or trivial).
623
624 \begin{code}
625 exprIsHNF :: CoreExpr -> Bool           -- True => Value-lambda, constructor, PAP
626 exprIsHNF (Var v)       -- NB: There are no value args at this point
627   =  isDataConWorkId v  -- Catches nullary constructors, 
628                         --      so that [] and () are values, for example
629   || idArity v > 0      -- Catches (e.g.) primops that don't have unfoldings
630   || isEvaldUnfolding (idUnfolding v)
631         -- Check the thing's unfolding; it might be bound to a value
632         -- A worry: what if an Id's unfolding is just itself: 
633         -- then we could get an infinite loop...
634
635 exprIsHNF (Lit l)            = True
636 exprIsHNF (Type ty)          = True     -- Types are honorary Values; 
637                                         -- we don't mind copying them
638 exprIsHNF (Lam b e)          = isRuntimeVar b || exprIsHNF e
639 exprIsHNF (Note _ e)         = exprIsHNF e
640 exprIsHNF (Cast e co)        = exprIsHNF e
641 exprIsHNF (App e (Type _)) = exprIsHNF e
642 exprIsHNF (App e a)        = app_is_value e [a]
643 exprIsHNF other      = False
644
645 -- There is at least one value argument
646 app_is_value (Var fun) args
647   |  isDataConWorkId fun                -- Constructor apps are values
648   || idArity fun > valArgCount args     -- Under-applied function
649   = check_args (idType fun) args
650 app_is_value (App f a) as = app_is_value f (a:as)
651 app_is_value other     as = False
652
653         -- 'check_args' checks that unlifted-type args
654         -- are in fact guaranteed non-divergent
655 check_args fun_ty []              = True
656 check_args fun_ty (Type _ : args) = case splitForAllTy_maybe fun_ty of
657                                       Just (_, ty) -> check_args ty args
658 check_args fun_ty (arg : args)
659   | isUnLiftedType arg_ty = exprOkForSpeculation arg
660   | otherwise             = check_args res_ty args
661   where
662     (arg_ty, res_ty) = splitFunTy fun_ty
663 \end{code}
664
665 \begin{code}
666 -- deep applies a TyConApp coercion as a substitution to a reflexive coercion
667 -- deepCast t [a1,...,an] co corresponds to deep(t, [a1,...,an], co) from
668 -- FC paper
669 deepCast :: Type -> [TyVar] -> Coercion -> Coercion
670 deepCast ty tyVars co 
671   = ASSERT( let {(lty, rty) = coercionKind co;
672                  Just (tc1, lArgs) = splitTyConApp_maybe lty;
673                  Just (tc2, rArgs) = splitTyConApp_maybe rty} 
674             in
675               tc1 == tc2 && length lArgs == length rArgs &&
676               length lArgs == length tyVars )
677     substTyWith tyVars coArgs ty
678   where
679     -- coArgs = [right (left (left co)), right (left co), right co]
680     coArgs = decomposeCo (length tyVars) co
681
682 -- This goes here to avoid circularity between DataCon and Id
683 dataConInstPat :: [Unique]                  -- A long enough list of uniques, at least one for each binder
684                -> DataCon
685                -> [Type]                    -- Types to instantiate the universally quantified tyvars
686                -> ([TyVar], [CoVar], [Id])  -- Return instantiated variables
687 -- dataConInstPat us con inst_tys returns a triple (ex_tvs, co_tvs, arg_ids),
688 --
689 --   ex_tvs are intended to be used as binders for existential type args
690 --
691 --   co_tvs are intended to be used as binders for coercion args and the kinds
692 --     of these vars have been instantiated by the inst_tys and the ex_tys
693 --
694 --   arg_ids are indended to be used as binders for value arguments, including
695 --     dicts, and have their types instantiated with inst_tys and ex_tys
696 --
697 -- Example.
698 --  The following constructor T1
699 --
700 --  data T a where
701 --    T1 :: forall b. Int -> b -> T(a,b)
702 --    ...
703 --
704 --  has representation type 
705 --   forall a. forall a1. forall a2. forall b. (a :=: (a1,a2)) => 
706 --     Int -> b -> T a
707 --
708 --  dataConInstPat us T1 (a1',a2') will return
709 --
710 --  ([a1'', a2'', b''],[c :: (a1',a2'):=:(a1'',a2'')],[x :: Int,y :: b''])
711 --
712 --  where the double-primed variables are created from the unique list input
713 dataConInstPat uniqs con inst_tys 
714   = dataConOccInstPat uniqs occs con inst_tys
715   where
716      -- dataConOccInstPat doesn't actually make use of the OccName directly for
717      -- existential and coercion variable binders, so it is right to just
718      -- use the VarName namespace for all of the OccNames
719     occs      = mk_occs 1
720     mk_occs n = mkVarOcc ("ipv" ++ show n) : mk_occs (n+1)
721
722 dataConOccInstPat :: [Unique]                  -- A long enough list of uniques, at least one for each binder
723                   -> [OccName]                 -- An equally long list of OccNames to use
724                   -> DataCon
725                   -> [Type]                    -- Types to instantiate the universally quantified tyvars
726                -> ([TyVar], [CoVar], [Id])  -- Return instantiated variables
727 -- This function actually does the job specified in the comment for 
728 -- dataConInstPat, but uses the specified list of OccNames.  This is 
729 -- is necessary for use in e.g. tcIfaceDataAlt
730 dataConOccInstPat uniqs occs con inst_tys 
731   = (ex_bndrs, co_bndrs, id_bndrs)
732   where 
733     univ_tvs = dataConUnivTyVars con
734     ex_tvs   = dataConExTyVars con
735     arg_tys  = dataConRepArgTys con
736     eq_spec  = dataConEqSpec con
737     eq_preds = eqSpecPreds eq_spec
738
739     n_ex = length ex_tvs
740     n_co = length eq_spec
741     n_id = length arg_tys
742
743       -- split the Uniques and OccNames
744     (ex_uniqs, uniqs')   = splitAt n_ex uniqs
745     (co_uniqs, id_uniqs) = splitAt n_co uniqs'
746
747     (ex_occs, occs')     = splitAt n_ex occs
748     (co_occs, id_occs)   = splitAt n_co occs'
749
750       -- make existential type variables
751     mk_ex_var uniq occ var = mkTyVar new_name kind
752       where
753         new_name = mkSysTvName uniq (occNameFS occ)
754         kind     = tyVarKind var
755
756     ex_bndrs = zipWith3 mk_ex_var ex_uniqs ex_occs ex_tvs
757
758       -- make the instantiation substitution
759     inst_subst = substTyWith (univ_tvs ++ ex_tvs) (inst_tys ++ map mkTyVarTy ex_bndrs)
760
761       -- make new coercion vars, instantiating kind
762     mk_co_var uniq occ eq_pred = mkCoVar new_name (inst_subst (mkPredTy eq_pred))
763        where
764          new_name = mkSysTvName uniq (occNameFS occ)
765
766     co_bndrs = zipWith3 mk_co_var co_uniqs co_occs eq_preds
767
768       -- make value vars, instantiating types
769     mk_id_var uniq occ ty = mkUserLocal occ uniq (inst_subst ty) noSrcLoc
770     id_bndrs = zipWith3 mk_id_var id_uniqs id_occs arg_tys
771
772 exprIsConApp_maybe :: CoreExpr -> Maybe (DataCon, [CoreExpr])
773 -- Returns (Just (dc, [x1..xn])) if the argument expression is 
774 -- a constructor application of the form (dc x1 .. xn)
775
776 exprIsConApp_maybe (Cast expr co)
777   =     -- Maybe this is over the top, but here we try to turn
778         --      coerce (S,T) ( x, y )
779         -- effectively into 
780         --      ( coerce S x, coerce T y )
781         -- This happens in anger in PrelArrExts which has a coerce
782         --      case coerce memcpy a b of
783         --        (# r, s #) -> ...
784         -- where the memcpy is in the IO monad, but the call is in
785         -- the (ST s) monad
786     case exprIsConApp_maybe expr of {
787         Nothing           -> Nothing ;
788         Just (dc, args)   -> 
789
790     let (from_ty, to_ty) = coercionKind co in
791   
792     case splitTyConApp_maybe to_ty of {
793         Nothing -> Nothing ;
794         Just (tc, tc_arg_tys) | tc /= dataConTyCon dc     -> Nothing
795                             --  | not (isVanillaDataCon dc) -> Nothing
796                               | otherwise                 ->
797                 -- Type constructor must match datacon
798
799     case splitTyConApp_maybe from_ty of {
800         Nothing -> Nothing ;
801         Just (tc', tc_arg_tys') | tc /= tc' -> Nothing 
802                 -- Both sides of coercion must have the same type constructor
803                                | otherwise ->
804
805     let
806         -- here we do the PushC reduction rule as described in the FC paper
807         arity               = tyConArity tc
808         n_ex_tvs            = length dc_ex_tyvars
809
810         (univ_args, rest)   = splitAt arity args
811         (ex_args, val_args) = splitAt n_ex_tvs rest
812
813         arg_tys             = dataConRepArgTys dc
814         dc_tyvars           = dataConUnivTyVars dc
815         dc_ex_tyvars        = dataConExTyVars dc
816
817         deep arg_ty         = deepCast arg_ty dc_tyvars co
818
819           -- first we appropriately cast the value arguments
820         arg_cos             = map deep arg_tys 
821         new_val_args        = zipWith mkCoerce (map deep arg_tys) val_args
822
823           -- then we cast the existential coercion arguments
824         orig_tvs            = dc_tyvars ++ dc_ex_tyvars
825         gammas              = decomposeCo arity co
826         new_tys             = gammas ++ (map (\ (Type t) -> t) ex_args)
827         theta               = substTyWith orig_tvs new_tys
828         cast_ty tv (Type ty) 
829           | isCoVar tv
830           , (ty1, ty2) <- splitCoercionKind (tyVarKind tv)
831           = Type $ mkTransCoercion (mkSymCoercion (theta ty1)) 
832             (mkTransCoercion ty (theta ty2))
833           | otherwise       
834           = Type ty
835         new_ex_args         = zipWith cast_ty dc_ex_tyvars ex_args
836   
837     in
838     ASSERT( all isTypeArg (take arity args) )
839     ASSERT( equalLength val_args arg_tys )
840     Just (dc, map Type tc_arg_tys ++ new_ex_args ++ new_val_args)
841     }}}
842
843 exprIsConApp_maybe (Note _ expr)
844   = exprIsConApp_maybe expr
845     -- We ignore InlineMe notes in case we have
846     --  x = __inline_me__ (a,b)
847     -- All part of making sure that INLINE pragmas never hurt
848     -- Marcin tripped on this one when making dictionaries more inlinable
849     --
850     -- In fact, we ignore all notes.  For example,
851     --          case _scc_ "foo" (C a b) of
852     --                  C a b -> e
853     -- should be optimised away, but it will be only if we look
854     -- through the SCC note.
855
856 exprIsConApp_maybe expr = analyse (collectArgs expr)
857   where
858     analyse (Var fun, args)
859         | Just con <- isDataConWorkId_maybe fun,
860           args `lengthAtLeast` dataConRepArity con
861                 -- Might be > because the arity excludes type args
862         = Just (con,args)
863
864         -- Look through unfoldings, but only cheap ones, because
865         -- we are effectively duplicating the unfolding
866     analyse (Var fun, [])
867         | let unf = idUnfolding fun,
868           isCheapUnfolding unf
869         = exprIsConApp_maybe (unfoldingTemplate unf)
870
871     analyse other = Nothing
872 \end{code}
873
874
875
876 %************************************************************************
877 %*                                                                      *
878 \subsection{Eta reduction and expansion}
879 %*                                                                      *
880 %************************************************************************
881
882 \begin{code}
883 exprEtaExpandArity :: DynFlags -> CoreExpr -> Arity
884 {- The Arity returned is the number of value args the 
885    thing can be applied to without doing much work
886
887 exprEtaExpandArity is used when eta expanding
888         e  ==>  \xy -> e x y
889
890 It returns 1 (or more) to:
891         case x of p -> \s -> ...
892 because for I/O ish things we really want to get that \s to the top.
893 We are prepared to evaluate x each time round the loop in order to get that
894
895 It's all a bit more subtle than it looks:
896
897 1.  One-shot lambdas
898
899 Consider one-shot lambdas
900                 let x = expensive in \y z -> E
901 We want this to have arity 2 if the \y-abstraction is a 1-shot lambda
902 Hence the ArityType returned by arityType
903
904 2.  The state-transformer hack
905
906 The one-shot lambda special cause is particularly important/useful for
907 IO state transformers, where we often get
908         let x = E in \ s -> ...
909
910 and the \s is a real-world state token abstraction.  Such abstractions
911 are almost invariably 1-shot, so we want to pull the \s out, past the
912 let x=E, even if E is expensive.  So we treat state-token lambdas as 
913 one-shot even if they aren't really.  The hack is in Id.isOneShotBndr.
914
915 3.  Dealing with bottom
916
917 Consider also 
918         f = \x -> error "foo"
919 Here, arity 1 is fine.  But if it is
920         f = \x -> case x of 
921                         True  -> error "foo"
922                         False -> \y -> x+y
923 then we want to get arity 2.  Tecnically, this isn't quite right, because
924         (f True) `seq` 1
925 should diverge, but it'll converge if we eta-expand f.  Nevertheless, we
926 do so; it improves some programs significantly, and increasing convergence
927 isn't a bad thing.  Hence the ABot/ATop in ArityType.
928
929 Actually, the situation is worse.  Consider
930         f = \x -> case x of
931                         True  -> \y -> x+y
932                         False -> \y -> x-y
933 Can we eta-expand here?  At first the answer looks like "yes of course", but
934 consider
935         (f bot) `seq` 1
936 This should diverge!  But if we eta-expand, it won't.   Again, we ignore this
937 "problem", because being scrupulous would lose an important transformation for
938 many programs.
939
940
941 4. Newtypes
942
943 Non-recursive newtypes are transparent, and should not get in the way.
944 We do (currently) eta-expand recursive newtypes too.  So if we have, say
945
946         newtype T = MkT ([T] -> Int)
947
948 Suppose we have
949         e = coerce T f
950 where f has arity 1.  Then: etaExpandArity e = 1; 
951 that is, etaExpandArity looks through the coerce.
952
953 When we eta-expand e to arity 1: eta_expand 1 e T
954 we want to get:                  coerce T (\x::[T] -> (coerce ([T]->Int) e) x)
955
956 HOWEVER, note that if you use coerce bogusly you can ge
957         coerce Int negate
958 And since negate has arity 2, you might try to eta expand.  But you can't
959 decopose Int to a function type.   Hence the final case in eta_expand.
960 -}
961
962
963 exprEtaExpandArity dflags e = arityDepth (arityType dflags e)
964
965 -- A limited sort of function type
966 data ArityType = AFun Bool ArityType    -- True <=> one-shot
967                | ATop                   -- Know nothing
968                | ABot                   -- Diverges
969
970 arityDepth :: ArityType -> Arity
971 arityDepth (AFun _ ty) = 1 + arityDepth ty
972 arityDepth ty          = 0
973
974 andArityType ABot           at2           = at2
975 andArityType ATop           at2           = ATop
976 andArityType (AFun t1 at1)  (AFun t2 at2) = AFun (t1 && t2) (andArityType at1 at2)
977 andArityType at1            at2           = andArityType at2 at1
978
979 arityType :: DynFlags -> CoreExpr -> ArityType
980         -- (go1 e) = [b1,..,bn]
981         -- means expression can be rewritten \x_b1 -> ... \x_bn -> body
982         -- where bi is True <=> the lambda is one-shot
983
984 arityType dflags (Note n e) = arityType dflags e
985 --      Not needed any more: etaExpand is cleverer
986 --  | ok_note n = arityType dflags e
987 --  | otherwise = ATop
988
989 arityType dflags (Cast e co) = arityType dflags e
990
991 arityType dflags (Var v) 
992   = mk (idArity v) (arg_tys (idType v))
993   where
994     mk :: Arity -> [Type] -> ArityType
995         -- The argument types are only to steer the "state hack"
996         -- Consider case x of
997         --              True  -> foo
998         --              False -> \(s:RealWorld) -> e
999         -- where foo has arity 1.  Then we want the state hack to
1000         -- apply to foo too, so we can eta expand the case.
1001     mk 0 tys | isBottomingId v                     = ABot
1002              | (ty:tys) <- tys, isStateHackType ty = AFun True ATop
1003              | otherwise                           = ATop
1004     mk n (ty:tys) = AFun (isStateHackType ty) (mk (n-1) tys)
1005     mk n []       = AFun False                (mk (n-1) [])
1006
1007     arg_tys :: Type -> [Type]   -- Ignore for-alls
1008     arg_tys ty 
1009         | Just (_, ty')  <- splitForAllTy_maybe ty = arg_tys ty'
1010         | Just (arg,res) <- splitFunTy_maybe ty    = arg : arg_tys res
1011         | otherwise                                = []
1012
1013         -- Lambdas; increase arity
1014 arityType dflags (Lam x e)
1015   | isId x    = AFun (isOneShotBndr x) (arityType dflags e)
1016   | otherwise = arityType dflags e
1017
1018         -- Applications; decrease arity
1019 arityType dflags (App f (Type _)) = arityType dflags f
1020 arityType dflags (App f a)        = case arityType dflags f of
1021                                         AFun one_shot xs | exprIsCheap a -> xs
1022                                         other                            -> ATop
1023                                                            
1024         -- Case/Let; keep arity if either the expression is cheap
1025         -- or it's a 1-shot lambda
1026         -- The former is not really right for Haskell
1027         --      f x = case x of { (a,b) -> \y. e }
1028         --  ===>
1029         --      f x y = case x of { (a,b) -> e }
1030         -- The difference is observable using 'seq'
1031 arityType dflags (Case scrut _ _ alts)
1032   = case foldr1 andArityType [arityType dflags rhs | (_,_,rhs) <- alts] of
1033         xs | exprIsCheap scrut          -> xs
1034         xs@(AFun one_shot _) | one_shot -> AFun True ATop
1035         other                           -> ATop
1036
1037 arityType dflags (Let b e) 
1038   = case arityType dflags e of
1039         xs                   | cheap_bind b -> xs
1040         xs@(AFun one_shot _) | one_shot     -> AFun True ATop
1041         other                               -> ATop
1042   where
1043     cheap_bind (NonRec b e) = is_cheap (b,e)
1044     cheap_bind (Rec prs)    = all is_cheap prs
1045     is_cheap (b,e) = (dopt Opt_DictsCheap dflags && isDictId b)
1046                    || exprIsCheap e
1047         -- If the experimental -fdicts-cheap flag is on, we eta-expand through
1048         -- dictionary bindings.  This improves arities. Thereby, it also
1049         -- means that full laziness is less prone to floating out the
1050         -- application of a function to its dictionary arguments, which
1051         -- can thereby lose opportunities for fusion.  Example:
1052         --      foo :: Ord a => a -> ...
1053         --      foo = /\a \(d:Ord a). let d' = ...d... in \(x:a). ....
1054         --              -- So foo has arity 1
1055         --
1056         --      f = \x. foo dInt $ bar x
1057         --
1058         -- The (foo DInt) is floated out, and makes ineffective a RULE 
1059         --      foo (bar x) = ...
1060         --
1061         -- One could go further and make exprIsCheap reply True to any
1062         -- dictionary-typed expression, but that's more work.
1063
1064 arityType dflags other = ATop
1065
1066 {- NOT NEEDED ANY MORE: etaExpand is cleverer
1067 ok_note InlineMe = False
1068 ok_note other    = True
1069     -- Notice that we do not look through __inline_me__
1070     -- This may seem surprising, but consider
1071     --          f = _inline_me (\x -> e)
1072     -- We DO NOT want to eta expand this to
1073     --          f = \x -> (_inline_me (\x -> e)) x
1074     -- because the _inline_me gets dropped now it is applied, 
1075     -- giving just
1076     --          f = \x -> e
1077     -- A Bad Idea
1078 -}
1079 \end{code}
1080
1081
1082 \begin{code}
1083 etaExpand :: Arity              -- Result should have this number of value args
1084           -> [Unique]
1085           -> CoreExpr -> Type   -- Expression and its type
1086           -> CoreExpr
1087 -- (etaExpand n us e ty) returns an expression with 
1088 -- the same meaning as 'e', but with arity 'n'.  
1089 --
1090 -- Given e' = etaExpand n us e ty
1091 -- We should have
1092 --      ty = exprType e = exprType e'
1093 --
1094 -- Note that SCCs are not treated specially.  If we have
1095 --      etaExpand 2 (\x -> scc "foo" e)
1096 --      = (\xy -> (scc "foo" e) y)
1097 -- So the costs of evaluating 'e' (not 'e y') are attributed to "foo"
1098
1099 etaExpand n us expr ty
1100   | manifestArity expr >= n = expr              -- The no-op case
1101   | otherwise               
1102   = eta_expand n us expr ty
1103   where
1104
1105 -- manifestArity sees how many leading value lambdas there are
1106 manifestArity :: CoreExpr -> Arity
1107 manifestArity (Lam v e) | isId v    = 1 + manifestArity e
1108                         | otherwise = manifestArity e
1109 manifestArity (Note _ e)            = manifestArity e
1110 manifestArity (Cast e _)            = manifestArity e
1111 manifestArity e                     = 0
1112
1113 -- etaExpand deals with for-alls. For example:
1114 --              etaExpand 1 E
1115 -- where  E :: forall a. a -> a
1116 -- would return
1117 --      (/\b. \y::a -> E b y)
1118 --
1119 -- It deals with coerces too, though they are now rare
1120 -- so perhaps the extra code isn't worth it
1121
1122 eta_expand n us expr ty
1123   | n == 0 && 
1124     -- The ILX code generator requires eta expansion for type arguments
1125     -- too, but alas the 'n' doesn't tell us how many of them there 
1126     -- may be.  So we eagerly eta expand any big lambdas, and just
1127     -- cross our fingers about possible loss of sharing in the ILX case. 
1128     -- The Right Thing is probably to make 'arity' include
1129     -- type variables throughout the compiler.  (ToDo.)
1130     not (isForAllTy ty) 
1131     -- Saturated, so nothing to do
1132   = expr
1133
1134         -- Short cut for the case where there already
1135         -- is a lambda; no point in gratuitously adding more
1136 eta_expand n us (Lam v body) ty
1137   | isTyVar v
1138   = Lam v (eta_expand n us body (applyTy ty (mkTyVarTy v)))
1139
1140   | otherwise
1141   = Lam v (eta_expand (n-1) us body (funResultTy ty))
1142
1143 -- We used to have a special case that stepped inside Coerces here,
1144 -- thus:  eta_expand n us (Note note@(Coerce _ ty) e) _  
1145 --              = Note note (eta_expand n us e ty)
1146 -- BUT this led to an infinite loop
1147 -- Example:     newtype T = MkT (Int -> Int)
1148 --      eta_expand 1 (coerce (Int->Int) e)
1149 --      --> coerce (Int->Int) (eta_expand 1 T e)
1150 --              by the bogus eqn
1151 --      --> coerce (Int->Int) (coerce T 
1152 --              (\x::Int -> eta_expand 1 (coerce (Int->Int) e)))
1153 --              by the splitNewType_maybe case below
1154 --      and round we go
1155
1156 eta_expand n us expr ty
1157   = ASSERT2 (exprType expr `coreEqType` ty, ppr (exprType expr) $$ ppr ty)
1158     case splitForAllTy_maybe ty of { 
1159           Just (tv,ty') -> 
1160
1161               Lam lam_tv (eta_expand n us2 (App expr (Type (mkTyVarTy lam_tv))) (substTyWith [tv] [mkTyVarTy lam_tv] ty'))
1162                   where 
1163                     lam_tv = mkTyVar (mkSysTvName uniq FSLIT("etaT")) (tyVarKind tv)
1164                     (uniq:us2) = us
1165
1166         ; Nothing ->
1167   
1168         case splitFunTy_maybe ty of {
1169           Just (arg_ty, res_ty) -> Lam arg1 (eta_expand (n-1) us2 (App expr (Var arg1)) res_ty)
1170                                 where
1171                                    arg1       = mkSysLocal FSLIT("eta") uniq arg_ty
1172                                    (uniq:us2) = us
1173                                    
1174         ; Nothing ->
1175
1176                 -- Given this:
1177                 --      newtype T = MkT ([T] -> Int)
1178                 -- Consider eta-expanding this
1179                 --      eta_expand 1 e T
1180                 -- We want to get
1181                 --      coerce T (\x::[T] -> (coerce ([T]->Int) e) x)
1182
1183         case splitNewTypeRepCo_maybe ty of {
1184           Just(ty1,co) -> 
1185               mkCoerce co (eta_expand n us (mkCoerce (mkSymCoercion co) expr) ty1) ;
1186           Nothing  -> 
1187
1188         -- We have an expression of arity > 0, but its type isn't a function
1189         -- This *can* legitmately happen: e.g.  coerce Int (\x. x)
1190         -- Essentially the programmer is playing fast and loose with types
1191         -- (Happy does this a lot).  So we simply decline to eta-expand.
1192         expr
1193         }}}
1194 \end{code}
1195
1196 exprArity is a cheap-and-cheerful version of exprEtaExpandArity.
1197 It tells how many things the expression can be applied to before doing
1198 any work.  It doesn't look inside cases, lets, etc.  The idea is that
1199 exprEtaExpandArity will do the hard work, leaving something that's easy
1200 for exprArity to grapple with.  In particular, Simplify uses exprArity to
1201 compute the ArityInfo for the Id. 
1202
1203 Originally I thought that it was enough just to look for top-level lambdas, but
1204 it isn't.  I've seen this
1205
1206         foo = PrelBase.timesInt
1207
1208 We want foo to get arity 2 even though the eta-expander will leave it
1209 unchanged, in the expectation that it'll be inlined.  But occasionally it
1210 isn't, because foo is blacklisted (used in a rule).  
1211
1212 Similarly, see the ok_note check in exprEtaExpandArity.  So 
1213         f = __inline_me (\x -> e)
1214 won't be eta-expanded.
1215
1216 And in any case it seems more robust to have exprArity be a bit more intelligent.
1217 But note that   (\x y z -> f x y z)
1218 should have arity 3, regardless of f's arity.
1219
1220 \begin{code}
1221 exprArity :: CoreExpr -> Arity
1222 exprArity e = go e
1223             where
1224               go (Var v)                   = idArity v
1225               go (Lam x e) | isId x        = go e + 1
1226                            | otherwise     = go e
1227               go (Note n e)                = go e
1228               go (Cast e _)                = go e
1229               go (App e (Type t))          = go e
1230               go (App f a) | exprIsCheap a = (go f - 1) `max` 0
1231                 -- NB: exprIsCheap a!  
1232                 --      f (fac x) does not have arity 2, 
1233                 --      even if f has arity 3!
1234                 -- NB: `max 0`!  (\x y -> f x) has arity 2, even if f is
1235                 --               unknown, hence arity 0
1236               go _                         = 0
1237 \end{code}
1238
1239 %************************************************************************
1240 %*                                                                      *
1241 \subsection{Equality}
1242 %*                                                                      *
1243 %************************************************************************
1244
1245 @cheapEqExpr@ is a cheap equality test which bales out fast!
1246         True  => definitely equal
1247         False => may or may not be equal
1248
1249 \begin{code}
1250 cheapEqExpr :: Expr b -> Expr b -> Bool
1251
1252 cheapEqExpr (Var v1)   (Var v2)   = v1==v2
1253 cheapEqExpr (Lit lit1) (Lit lit2) = lit1 == lit2
1254 cheapEqExpr (Type t1)  (Type t2)  = t1 `coreEqType` t2
1255
1256 cheapEqExpr (App f1 a1) (App f2 a2)
1257   = f1 `cheapEqExpr` f2 && a1 `cheapEqExpr` a2
1258
1259 cheapEqExpr _ _ = False
1260
1261 exprIsBig :: Expr b -> Bool
1262 -- Returns True of expressions that are too big to be compared by cheapEqExpr
1263 exprIsBig (Lit _)      = False
1264 exprIsBig (Var v)      = False
1265 exprIsBig (Type t)     = False
1266 exprIsBig (App f a)    = exprIsBig f || exprIsBig a
1267 exprIsBig other        = True
1268 \end{code}
1269
1270
1271 \begin{code}
1272 tcEqExpr :: CoreExpr -> CoreExpr -> Bool
1273 -- Used in rule matching, so does *not* look through 
1274 -- newtypes, predicate types; hence tcEqExpr
1275
1276 tcEqExpr e1 e2 = tcEqExprX rn_env e1 e2
1277   where
1278     rn_env = mkRnEnv2 (mkInScopeSet (exprFreeVars e1 `unionVarSet` exprFreeVars e2))
1279
1280 tcEqExprX :: RnEnv2 -> CoreExpr -> CoreExpr -> Bool
1281 tcEqExprX env (Var v1)     (Var v2)     = rnOccL env v1 == rnOccR env v2
1282 tcEqExprX env (Lit lit1)   (Lit lit2)   = lit1 == lit2
1283 tcEqExprX env (App f1 a1)  (App f2 a2)  = tcEqExprX env f1 f2 && tcEqExprX env a1 a2
1284 tcEqExprX env (Lam v1 e1)  (Lam v2 e2)  = tcEqExprX (rnBndr2 env v1 v2) e1 e2
1285 tcEqExprX env (Let (NonRec v1 r1) e1)
1286               (Let (NonRec v2 r2) e2)   = tcEqExprX env r1 r2 
1287                                        && tcEqExprX (rnBndr2 env v1 v2) e1 e2
1288 tcEqExprX env (Let (Rec ps1) e1)
1289               (Let (Rec ps2) e2)        =  equalLength ps1 ps2
1290                                         && and (zipWith eq_rhs ps1 ps2)
1291                                         && tcEqExprX env' e1 e2
1292                                      where
1293                                        env' = foldl2 rn_bndr2 env ps2 ps2
1294                                        rn_bndr2 env (b1,_) (b2,_) = rnBndr2 env b1 b2
1295                                        eq_rhs       (_,r1) (_,r2) = tcEqExprX env' r1 r2
1296 tcEqExprX env (Case e1 v1 t1 a1)
1297               (Case e2 v2 t2 a2)     =  tcEqExprX env e1 e2
1298                                      && tcEqTypeX env t1 t2                      
1299                                      && equalLength a1 a2
1300                                      && and (zipWith (eq_alt env') a1 a2)
1301                                      where
1302                                        env' = rnBndr2 env v1 v2
1303
1304 tcEqExprX env (Note n1 e1) (Note n2 e2) = eq_note env n1 n2 && tcEqExprX env e1 e2
1305 tcEqExprX env (Cast e1 co1) (Cast e2 co2) = tcEqTypeX env co1 co2 && tcEqExprX env e1 e2
1306 tcEqExprX env (Type t1)    (Type t2)    = tcEqTypeX env t1 t2
1307 tcEqExprX env e1                e2      = False
1308                                          
1309 eq_alt env (c1,vs1,r1) (c2,vs2,r2) = c1==c2 && tcEqExprX (rnBndrs2 env vs1  vs2) r1 r2
1310
1311 eq_note env (SCC cc1)      (SCC cc2)      = cc1 == cc2
1312 eq_note env (CoreNote s1)  (CoreNote s2)  = s1 == s2
1313 eq_note env other1             other2     = False
1314 \end{code}
1315
1316
1317 %************************************************************************
1318 %*                                                                      *
1319 \subsection{The size of an expression}
1320 %*                                                                      *
1321 %************************************************************************
1322
1323 \begin{code}
1324 coreBindsSize :: [CoreBind] -> Int
1325 coreBindsSize bs = foldr ((+) . bindSize) 0 bs
1326
1327 exprSize :: CoreExpr -> Int
1328         -- A measure of the size of the expressions
1329         -- It also forces the expression pretty drastically as a side effect
1330 exprSize (Var v)         = v `seq` 1
1331 exprSize (Lit lit)       = lit `seq` 1
1332 exprSize (App f a)       = exprSize f + exprSize a
1333 exprSize (Lam b e)       = varSize b + exprSize e
1334 exprSize (Let b e)       = bindSize b + exprSize e
1335 exprSize (Case e b t as) = seqType t `seq` exprSize e + varSize b + 1 + foldr ((+) . altSize) 0 as
1336 exprSize (Cast e co)     = (seqType co `seq` 1) + exprSize e
1337 exprSize (Note n e)      = noteSize n + exprSize e
1338 exprSize (Type t)        = seqType t `seq` 1
1339
1340 noteSize (SCC cc)       = cc `seq` 1
1341 noteSize InlineMe       = 1
1342 noteSize (CoreNote s)   = s `seq` 1  -- hdaume: core annotations
1343
1344 varSize :: Var -> Int
1345 varSize b  | isTyVar b = 1
1346            | otherwise = seqType (idType b)             `seq`
1347                          megaSeqIdInfo (idInfo b)       `seq`
1348                          1
1349
1350 varsSize = foldr ((+) . varSize) 0
1351
1352 bindSize (NonRec b e) = varSize b + exprSize e
1353 bindSize (Rec prs)    = foldr ((+) . pairSize) 0 prs
1354
1355 pairSize (b,e) = varSize b + exprSize e
1356
1357 altSize (c,bs,e) = c `seq` varsSize bs + exprSize e
1358 \end{code}
1359
1360
1361 %************************************************************************
1362 %*                                                                      *
1363 \subsection{Hashing}
1364 %*                                                                      *
1365 %************************************************************************
1366
1367 \begin{code}
1368 hashExpr :: CoreExpr -> Int
1369 -- Two expressions that hash to the same Int may be equal (but may not be)
1370 -- Two expressions that hash to the different Ints are definitely unequal
1371 -- 
1372 -- But "unequal" here means "not identical"; two alpha-equivalent 
1373 -- expressions may hash to the different Ints
1374 --
1375 -- The emphasis is on a crude, fast hash, rather than on high precision
1376
1377 hashExpr e | hash < 0  = 77     -- Just in case we hit -maxInt
1378            | otherwise = hash
1379            where
1380              hash = abs (hash_expr e)   -- Negative numbers kill UniqFM
1381
1382 hash_expr (Note _ e)              = hash_expr e
1383 hash_expr (Cast e co)             = hash_expr e
1384 hash_expr (Let (NonRec b r) e)    = hashId b
1385 hash_expr (Let (Rec ((b,r):_)) e) = hashId b
1386 hash_expr (Case _ b _ _)          = hashId b
1387 hash_expr (App f e)               = hash_expr f * fast_hash_expr e
1388 hash_expr (Var v)                 = hashId v
1389 hash_expr (Lit lit)               = hashLiteral lit
1390 hash_expr (Lam b _)               = hashId b
1391 hash_expr (Type t)                = trace "hash_expr: type" 1           -- Shouldn't happen
1392
1393 fast_hash_expr (Var v)          = hashId v
1394 fast_hash_expr (Lit lit)        = hashLiteral lit
1395 fast_hash_expr (App f (Type _)) = fast_hash_expr f
1396 fast_hash_expr (App f a)        = fast_hash_expr a
1397 fast_hash_expr (Lam b _)        = hashId b
1398 fast_hash_expr other            = 1
1399
1400 hashId :: Id -> Int
1401 hashId id = hashName (idName id)
1402 \end{code}
1403
1404 %************************************************************************
1405 %*                                                                      *
1406 \subsection{Determining non-updatable right-hand-sides}
1407 %*                                                                      *
1408 %************************************************************************
1409
1410 Top-level constructor applications can usually be allocated
1411 statically, but they can't if the constructor, or any of the
1412 arguments, come from another DLL (because we can't refer to static
1413 labels in other DLLs).
1414
1415 If this happens we simply make the RHS into an updatable thunk, 
1416 and 'exectute' it rather than allocating it statically.
1417
1418 \begin{code}
1419 rhsIsStatic :: PackageId -> CoreExpr -> Bool
1420 -- This function is called only on *top-level* right-hand sides
1421 -- Returns True if the RHS can be allocated statically, with
1422 -- no thunks involved at all.
1423 --
1424 -- It's called (i) in TidyPgm.hasCafRefs to decide if the rhs is, or
1425 -- refers to, CAFs; and (ii) in CoreToStg to decide whether to put an
1426 -- update flag on it.
1427 --
1428 -- The basic idea is that rhsIsStatic returns True only if the RHS is
1429 --      (a) a value lambda
1430 --      (b) a saturated constructor application with static args
1431 --
1432 -- BUT watch out for
1433 --  (i) Any cross-DLL references kill static-ness completely
1434 --      because they must be 'executed' not statically allocated
1435 --      ("DLL" here really only refers to Windows DLLs, on other platforms,
1436 --      this is not necessary)
1437 --
1438 -- (ii) We treat partial applications as redexes, because in fact we 
1439 --      make a thunk for them that runs and builds a PAP
1440 --      at run-time.  The only appliations that are treated as 
1441 --      static are *saturated* applications of constructors.
1442
1443 -- We used to try to be clever with nested structures like this:
1444 --              ys = (:) w ((:) w [])
1445 -- on the grounds that CorePrep will flatten ANF-ise it later.
1446 -- But supporting this special case made the function much more 
1447 -- complicated, because the special case only applies if there are no 
1448 -- enclosing type lambdas:
1449 --              ys = /\ a -> Foo (Baz ([] a))
1450 -- Here the nested (Baz []) won't float out to top level in CorePrep.
1451 --
1452 -- But in fact, even without -O, nested structures at top level are 
1453 -- flattened by the simplifier, so we don't need to be super-clever here.
1454 --
1455 -- Examples
1456 --
1457 --      f = \x::Int. x+7        TRUE
1458 --      p = (True,False)        TRUE
1459 --
1460 --      d = (fst p, False)      FALSE because there's a redex inside
1461 --                              (this particular one doesn't happen but...)
1462 --
1463 --      h = D# (1.0## /## 2.0##)        FALSE (redex again)
1464 --      n = /\a. Nil a                  TRUE
1465 --
1466 --      t = /\a. (:) (case w a of ...) (Nil a)  FALSE (redex)
1467 --
1468 --
1469 -- This is a bit like CoreUtils.exprIsHNF, with the following differences:
1470 --    a) scc "foo" (\x -> ...) is updatable (so we catch the right SCC)
1471 --
1472 --    b) (C x xs), where C is a contructors is updatable if the application is
1473 --         dynamic
1474 -- 
1475 --    c) don't look through unfolding of f in (f x).
1476 --
1477 -- When opt_RuntimeTypes is on, we keep type lambdas and treat
1478 -- them as making the RHS re-entrant (non-updatable).
1479
1480 rhsIsStatic this_pkg rhs = is_static False rhs
1481   where
1482   is_static :: Bool     -- True <=> in a constructor argument; must be atomic
1483           -> CoreExpr -> Bool
1484   
1485   is_static False (Lam b e) = isRuntimeVar b || is_static False e
1486   
1487   is_static in_arg (Note (SCC _) e) = False
1488   is_static in_arg (Note _ e)       = is_static in_arg e
1489   is_static in_arg (Cast e co)      = is_static in_arg e
1490   
1491   is_static in_arg (Lit lit)
1492     = case lit of
1493         MachLabel _ _ -> False
1494         other         -> True
1495         -- A MachLabel (foreign import "&foo") in an argument
1496         -- prevents a constructor application from being static.  The
1497         -- reason is that it might give rise to unresolvable symbols
1498         -- in the object file: under Linux, references to "weak"
1499         -- symbols from the data segment give rise to "unresolvable
1500         -- relocation" errors at link time This might be due to a bug
1501         -- in the linker, but we'll work around it here anyway. 
1502         -- SDM 24/2/2004
1503   
1504   is_static in_arg other_expr = go other_expr 0
1505    where
1506     go (Var f) n_val_args
1507 #if mingw32_TARGET_OS
1508         | not (isDllName this_pkg (idName f))
1509 #endif
1510         =  saturated_data_con f n_val_args
1511         || (in_arg && n_val_args == 0)  
1512                 -- A naked un-applied variable is *not* deemed a static RHS
1513                 -- E.g.         f = g
1514                 -- Reason: better to update so that the indirection gets shorted
1515                 --         out, and the true value will be seen
1516                 -- NB: if you change this, you'll break the invariant that THUNK_STATICs
1517                 --     are always updatable.  If you do so, make sure that non-updatable
1518                 --     ones have enough space for their static link field!
1519
1520     go (App f a) n_val_args
1521         | isTypeArg a                    = go f n_val_args
1522         | not in_arg && is_static True a = go f (n_val_args + 1)
1523         -- The (not in_arg) checks that we aren't in a constructor argument;
1524         -- if we are, we don't allow (value) applications of any sort
1525         -- 
1526         -- NB. In case you wonder, args are sometimes not atomic.  eg.
1527         --   x = D# (1.0## /## 2.0##)
1528         -- can't float because /## can fail.
1529
1530     go (Note (SCC _) f) n_val_args = False
1531     go (Note _ f) n_val_args       = go f n_val_args
1532     go (Cast e co) n_val_args      = go e n_val_args
1533
1534     go other n_val_args = False
1535
1536     saturated_data_con f n_val_args
1537         = case isDataConWorkId_maybe f of
1538             Just dc -> n_val_args == dataConRepArity dc
1539             Nothing -> False
1540 \end{code}