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