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