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