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