Fix Trac #3717 by making exprOkForSpeculation a bit cleverer
[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         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, 
29         exprIsCheap, exprIsExpandable, exprIsCheap', CheapAppFun,
30         exprIsHNF, exprOkForSpeculation, exprIsBig, exprIsConLike,
31         rhsIsStatic, isCheapApp, isExpandableApp,
32
33         -- * Expression and bindings size
34         coreBindsSize, exprSize,
35
36         -- * Hashing
37         hashExpr,
38
39         -- * Equality
40         cheapEqExpr, eqExpr, eqExprX,
41
42         -- * Eta reduction
43         tryEtaReduce,
44
45         -- * Manipulating data constructors and types
46         applyTypeToArgs, applyTypeToArg,
47         dataConOrigInstPat, dataConRepInstPat, dataConRepFSInstPat
48     ) where
49
50 #include "HsVersions.h"
51
52 import CoreSyn
53 import PprCore
54 import Var
55 import SrcLoc
56 import VarEnv
57 import VarSet
58 import Name
59 import Literal
60 import DataCon
61 import PrimOp
62 import Id
63 import IdInfo
64 import TcType   ( isPredTy )
65 import Type
66 import Coercion
67 import TyCon
68 import CostCentre
69 import Unique
70 import Outputable
71 import TysPrim
72 import PrelNames( absentErrorIdKey )
73 import FastString
74 import Maybes
75 import Util
76 import Data.Word
77 import Data.Bits
78 \end{code}
79
80
81 %************************************************************************
82 %*                                                                      *
83 \subsection{Find the type of a Core atom/expression}
84 %*                                                                      *
85 %************************************************************************
86
87 \begin{code}
88 exprType :: CoreExpr -> Type
89 -- ^ Recover the type of a well-typed Core expression. Fails when
90 -- applied to the actual 'CoreSyn.Type' expression as it cannot
91 -- really be said to have a type
92 exprType (Var var)           = idType var
93 exprType (Lit lit)           = literalType lit
94 exprType (Let _ body)        = exprType body
95 exprType (Case _ _ ty _)     = ty
96 exprType (Cast _ co)         = snd (coercionKind co)
97 exprType (Note _ e)          = exprType e
98 exprType (Lam binder expr)   = mkPiType binder (exprType expr)
99 exprType e@(App _ _)
100   = case collectArgs e of
101         (fun, args) -> applyTypeToArgs e (exprType fun) args
102
103 exprType other = pprTrace "exprType" (pprCoreExpr other) alphaTy
104
105 coreAltType :: CoreAlt -> Type
106 -- ^ Returns the type of the alternatives right hand side
107 coreAltType (_,bs,rhs) 
108   | any bad_binder bs = expandTypeSynonyms ty
109   | otherwise         = ty    -- Note [Existential variables and silly type synonyms]
110   where
111     ty           = exprType rhs
112     free_tvs     = tyVarsOfType ty
113     bad_binder b = isTyCoVar b && b `elemVarSet` free_tvs
114
115 coreAltsType :: [CoreAlt] -> Type
116 -- ^ Returns the type of the first alternative, which should be the same as for all alternatives
117 coreAltsType (alt:_) = coreAltType alt
118 coreAltsType []      = panic "corAltsType"
119 \end{code}
120
121 Note [Existential variables and silly type synonyms]
122 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
123 Consider
124         data T = forall a. T (Funny a)
125         type Funny a = Bool
126         f :: T -> Bool
127         f (T x) = x
128
129 Now, the type of 'x' is (Funny a), where 'a' is existentially quantified.
130 That means that 'exprType' and 'coreAltsType' may give a result that *appears*
131 to mention an out-of-scope type variable.  See Trac #3409 for a more real-world
132 example.
133
134 Various possibilities suggest themselves:
135
136  - Ignore the problem, and make Lint not complain about such variables
137
138  - Expand all type synonyms (or at least all those that discard arguments)
139       This is tricky, because at least for top-level things we want to
140       retain the type the user originally specified.
141
142  - Expand synonyms on the fly, when the problem arises. That is what
143    we are doing here.  It's not too expensive, I think.
144
145 \begin{code}
146 mkPiType  :: EvVar -> Type -> Type
147 -- ^ Makes a @(->)@ type or a forall type, depending
148 -- on whether it is given a type variable or a term variable.
149 mkPiTypes :: [EvVar] -> Type -> Type
150 -- ^ 'mkPiType' for multiple type or value arguments
151
152 mkPiType v ty
153    | isId v    = mkFunTy (idType v) ty
154    | otherwise = mkForAllTy v ty
155
156 mkPiTypes vs ty = foldr mkPiType ty vs
157 \end{code}
158
159 \begin{code}
160 applyTypeToArg :: Type -> CoreExpr -> Type
161 -- ^ Determines the type resulting from applying an expression to a function with the given type
162 applyTypeToArg fun_ty (Type arg_ty) = applyTy fun_ty arg_ty
163 applyTypeToArg fun_ty _             = funResultTy fun_ty
164
165 applyTypeToArgs :: CoreExpr -> Type -> [CoreExpr] -> Type
166 -- ^ A more efficient version of 'applyTypeToArg' when we have several arguments.
167 -- The first argument is just for debugging, and gives some context
168 applyTypeToArgs _ op_ty [] = op_ty
169
170 applyTypeToArgs e op_ty (Type ty : args)
171   =     -- Accumulate type arguments so we can instantiate all at once
172     go [ty] args
173   where
174     go rev_tys (Type ty : args) = go (ty:rev_tys) args
175     go rev_tys rest_args        = applyTypeToArgs e op_ty' rest_args
176                                 where
177                                   op_ty' = applyTysD msg op_ty (reverse rev_tys)
178                                   msg = ptext (sLit "applyTypeToArgs") <+> 
179                                         panic_msg e op_ty
180
181 applyTypeToArgs e op_ty (_ : args)
182   = case (splitFunTy_maybe op_ty) of
183         Just (_, res_ty) -> applyTypeToArgs e res_ty args
184         Nothing -> pprPanic "applyTypeToArgs" (panic_msg e op_ty)
185
186 panic_msg :: CoreExpr -> Type -> SDoc
187 panic_msg e op_ty = pprCoreExpr e $$ ppr op_ty
188 \end{code}
189
190 %************************************************************************
191 %*                                                                      *
192 \subsection{Attaching notes}
193 %*                                                                      *
194 %************************************************************************
195
196 \begin{code}
197 -- | Wrap the given expression in the coercion, dropping identity coercions and coalescing nested coercions
198 mkCoerceI :: CoercionI -> CoreExpr -> CoreExpr
199 mkCoerceI (IdCo _) e = e
200 mkCoerceI (ACo co) e = mkCoerce co e
201
202 -- | Wrap the given expression in the coercion safely, coalescing nested coercions
203 mkCoerce :: Coercion -> CoreExpr -> CoreExpr
204 mkCoerce co (Cast expr co2)
205   = ASSERT(let { (from_ty, _to_ty) = coercionKind co; 
206                  (_from_ty2, to_ty2) = coercionKind co2} in
207            from_ty `coreEqType` to_ty2 )
208     mkCoerce (mkTransCoercion co2 co) expr
209
210 mkCoerce co expr 
211   = let (from_ty, _to_ty) = coercionKind co in
212 --    if to_ty `coreEqType` from_ty
213 --    then expr
214 --    else 
215         WARN(not (from_ty `coreEqType` exprType expr), text "Trying to coerce" <+> text "(" <> ppr expr $$ text "::" <+> ppr (exprType expr) <> text ")" $$ ppr co $$ pprEqPred (coercionKind co))
216          (Cast expr co)
217 \end{code}
218
219 \begin{code}
220 -- | Wraps the given expression in the cost centre unless
221 -- in a way that maximises their utility to the user
222 mkSCC :: CostCentre -> Expr b -> Expr b
223         -- Note: Nested SCC's *are* preserved for the benefit of
224         --       cost centre stack profiling
225 mkSCC _  (Lit lit)          = Lit lit
226 mkSCC cc (Lam x e)          = Lam x (mkSCC cc e)  -- Move _scc_ inside lambda
227 mkSCC cc (Note (SCC cc') e) = Note (SCC cc) (Note (SCC cc') e)
228 mkSCC cc (Note n e)         = Note n (mkSCC cc e) -- Move _scc_ inside notes
229 mkSCC cc (Cast e co)        = Cast (mkSCC cc e) co -- Move _scc_ inside cast
230 mkSCC cc expr               = Note (SCC cc) expr
231 \end{code}
232
233
234 %************************************************************************
235 %*                                                                      *
236 \subsection{Other expression construction}
237 %*                                                                      *
238 %************************************************************************
239
240 \begin{code}
241 bindNonRec :: Id -> CoreExpr -> CoreExpr -> CoreExpr
242 -- ^ @bindNonRec x r b@ produces either:
243 --
244 -- > let x = r in b
245 --
246 -- or:
247 --
248 -- > case r of x { _DEFAULT_ -> b }
249 --
250 -- depending on whether we have to use a @case@ or @let@
251 -- binding for the expression (see 'needsCaseBinding').
252 -- It's used by the desugarer to avoid building bindings
253 -- that give Core Lint a heart attack, although actually
254 -- the simplifier deals with them perfectly well. See
255 -- also 'MkCore.mkCoreLet'
256 bindNonRec bndr rhs body 
257   | needsCaseBinding (idType bndr) rhs = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
258   | otherwise                          = Let (NonRec bndr rhs) body
259
260 -- | Tests whether we have to use a @case@ rather than @let@ binding for this expression
261 -- as per the invariants of 'CoreExpr': see "CoreSyn#let_app_invariant"
262 needsCaseBinding :: Type -> CoreExpr -> Bool
263 needsCaseBinding ty rhs = isUnLiftedType ty && not (exprOkForSpeculation rhs)
264         -- Make a case expression instead of a let
265         -- These can arise either from the desugarer,
266         -- or from beta reductions: (\x.e) (x +# y)
267 \end{code}
268
269 \begin{code}
270 mkAltExpr :: AltCon     -- ^ Case alternative constructor
271           -> [CoreBndr] -- ^ Things bound by the pattern match
272           -> [Type]     -- ^ The type arguments to the case alternative
273           -> CoreExpr
274 -- ^ This guy constructs the value that the scrutinee must have
275 -- given that you are in one particular branch of a case
276 mkAltExpr (DataAlt con) args inst_tys
277   = mkConApp con (map Type inst_tys ++ varsToCoreExprs args)
278 mkAltExpr (LitAlt lit) [] []
279   = Lit lit
280 mkAltExpr (LitAlt _) _ _ = panic "mkAltExpr LitAlt"
281 mkAltExpr DEFAULT _ _ = panic "mkAltExpr DEFAULT"
282 \end{code}
283
284
285 %************************************************************************
286 %*                                                                      *
287 \subsection{Taking expressions apart}
288 %*                                                                      *
289 %************************************************************************
290
291 The default alternative must be first, if it exists at all.
292 This makes it easy to find, though it makes matching marginally harder.
293
294 \begin{code}
295 -- | Extract the default case alternative
296 findDefault :: [CoreAlt] -> ([CoreAlt], Maybe CoreExpr)
297 findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null args ) (alts, Just rhs)
298 findDefault alts                        =                     (alts, Nothing)
299
300 isDefaultAlt :: CoreAlt -> Bool
301 isDefaultAlt (DEFAULT, _, _) = True
302 isDefaultAlt _               = False
303
304
305 -- | Find the case alternative corresponding to a particular 
306 -- constructor: panics if no such constructor exists
307 findAlt :: AltCon -> [CoreAlt] -> Maybe CoreAlt
308     -- A "Nothing" result *is* legitmiate
309     -- See Note [Unreachable code]
310 findAlt con alts
311   = case alts of
312         (deflt@(DEFAULT,_,_):alts) -> go alts (Just deflt)
313         _                          -> go alts Nothing
314   where
315     go []                     deflt = deflt
316     go (alt@(con1,_,_) : alts) deflt
317       = case con `cmpAltCon` con1 of
318           LT -> deflt   -- Missed it already; the alts are in increasing order
319           EQ -> Just alt
320           GT -> ASSERT( not (con1 == DEFAULT) ) go alts deflt
321
322 ---------------------------------
323 mergeAlts :: [CoreAlt] -> [CoreAlt] -> [CoreAlt]
324 -- ^ Merge alternatives preserving order; alternatives in
325 -- the first argument shadow ones in the second
326 mergeAlts [] as2 = as2
327 mergeAlts as1 [] = as1
328 mergeAlts (a1:as1) (a2:as2)
329   = case a1 `cmpAlt` a2 of
330         LT -> a1 : mergeAlts as1      (a2:as2)
331         EQ -> a1 : mergeAlts as1      as2       -- Discard a2
332         GT -> a2 : mergeAlts (a1:as1) as2
333
334
335 ---------------------------------
336 trimConArgs :: AltCon -> [CoreArg] -> [CoreArg]
337 -- ^ Given:
338 --
339 -- > case (C a b x y) of
340 -- >        C b x y -> ...
341 --
342 -- We want to drop the leading type argument of the scrutinee
343 -- leaving the arguments to match agains the pattern
344
345 trimConArgs DEFAULT      args = ASSERT( null args ) []
346 trimConArgs (LitAlt _)   args = ASSERT( null args ) []
347 trimConArgs (DataAlt dc) args = dropList (dataConUnivTyVars dc) args
348 \end{code}
349
350 Note [Unreachable code]
351 ~~~~~~~~~~~~~~~~~~~~~~~
352 It is possible (although unusual) for GHC to find a case expression
353 that cannot match.  For example: 
354
355      data Col = Red | Green | Blue
356      x = Red
357      f v = case x of 
358               Red -> ...
359               _ -> ...(case x of { Green -> e1; Blue -> e2 })...
360
361 Suppose that for some silly reason, x isn't substituted in the case
362 expression.  (Perhaps there's a NOINLINE on it, or profiling SCC stuff
363 gets in the way; cf Trac #3118.)  Then the full-lazines pass might produce
364 this
365
366      x = Red
367      lvl = case x of { Green -> e1; Blue -> e2 })
368      f v = case x of 
369              Red -> ...
370              _ -> ...lvl...
371
372 Now if x gets inlined, we won't be able to find a matching alternative
373 for 'Red'.  That's because 'lvl' is unreachable.  So rather than crashing
374 we generate (error "Inaccessible alternative").
375
376 Similar things can happen (augmented by GADTs) when the Simplifier
377 filters down the matching alternatives in Simplify.rebuildCase.
378
379
380 %************************************************************************
381 %*                                                                      *
382              exprIsTrivial
383 %*                                                                      *
384 %************************************************************************
385
386 Note [exprIsTrivial]
387 ~~~~~~~~~~~~~~~~~~~~
388 @exprIsTrivial@ is true of expressions we are unconditionally happy to
389                 duplicate; simple variables and constants, and type
390                 applications.  Note that primop Ids aren't considered
391                 trivial unless 
392
393 Note [Variable are trivial]
394 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
395 There used to be a gruesome test for (hasNoBinding v) in the
396 Var case:
397         exprIsTrivial (Var v) | hasNoBinding v = idArity v == 0
398 The idea here is that a constructor worker, like \$wJust, is
399 really short for (\x -> \$wJust x), becuase \$wJust has no binding.
400 So it should be treated like a lambda.  Ditto unsaturated primops.
401 But now constructor workers are not "have-no-binding" Ids.  And
402 completely un-applied primops and foreign-call Ids are sufficiently
403 rare that I plan to allow them to be duplicated and put up with
404 saturating them.
405
406 Note [SCCs are trivial]
407 ~~~~~~~~~~~~~~~~~~~~~~~
408 We used not to treat (_scc_ "foo" x) as trivial, because it really
409 generates code, (and a heap object when it's a function arg) to
410 capture the cost centre.  However, the profiling system discounts the
411 allocation costs for such "boxing thunks" whereas the extra costs of
412 *not* inlining otherwise-trivial bindings can be high, and are hard to
413 discount.
414
415 \begin{code}
416 exprIsTrivial :: CoreExpr -> Bool
417 exprIsTrivial (Var _)          = True        -- See Note [Variables are trivial]
418 exprIsTrivial (Type _)         = True
419 exprIsTrivial (Lit lit)        = litIsTrivial lit
420 exprIsTrivial (App e arg)      = not (isRuntimeArg arg) && exprIsTrivial e
421 exprIsTrivial (Note _       e) = exprIsTrivial e  -- See Note [SCCs are trivial]
422 exprIsTrivial (Cast e _)       = exprIsTrivial e
423 exprIsTrivial (Lam b body)     = not (isRuntimeVar b) && exprIsTrivial body
424 exprIsTrivial _                = False
425 \end{code}
426
427
428 %************************************************************************
429 %*                                                                      *
430              exprIsDupable
431 %*                                                                      *
432 %************************************************************************
433
434 Note [exprIsDupable]
435 ~~~~~~~~~~~~~~~~~~~~
436 @exprIsDupable@ is true of expressions that can be duplicated at a modest
437                 cost in code size.  This will only happen in different case
438                 branches, so there's no issue about duplicating work.
439
440                 That is, exprIsDupable returns True of (f x) even if
441                 f is very very expensive to call.
442
443                 Its only purpose is to avoid fruitless let-binding
444                 and then inlining of case join points
445
446
447 \begin{code}
448 exprIsDupable :: CoreExpr -> Bool
449 exprIsDupable (Type _)   = True
450 exprIsDupable (Var _)    = True
451 exprIsDupable (Lit lit)  = litIsDupable lit
452 exprIsDupable (Note _ e) = exprIsDupable e
453 exprIsDupable (Cast e _) = exprIsDupable e
454 exprIsDupable expr
455   = go expr 0
456   where
457     go (Var _)   _      = True
458     go (App f a) n_args =  n_args < dupAppSize
459                         && exprIsDupable a
460                         && go f (n_args+1)
461     go _         _      = False
462
463 dupAppSize :: Int
464 dupAppSize = 4          -- Size of application we are prepared to duplicate
465 \end{code}
466
467 %************************************************************************
468 %*                                                                      *
469              exprIsCheap, exprIsExpandable
470 %*                                                                      *
471 %************************************************************************
472
473 Note [exprIsCheap]   See also Note [Interaction of exprIsCheap and lone variables]
474 ~~~~~~~~~~~~~~~~~~   in CoreUnfold.lhs
475 @exprIsCheap@ looks at a Core expression and returns \tr{True} if
476 it is obviously in weak head normal form, or is cheap to get to WHNF.
477 [Note that that's not the same as exprIsDupable; an expression might be
478 big, and hence not dupable, but still cheap.]
479
480 By ``cheap'' we mean a computation we're willing to:
481         push inside a lambda, or
482         inline at more than one place
483 That might mean it gets evaluated more than once, instead of being
484 shared.  The main examples of things which aren't WHNF but are
485 ``cheap'' are:
486
487   *     case e of
488           pi -> ei
489         (where e, and all the ei are cheap)
490
491   *     let x = e in b
492         (where e and b are cheap)
493
494   *     op x1 ... xn
495         (where op is a cheap primitive operator)
496
497   *     error "foo"
498         (because we are happy to substitute it inside a lambda)
499
500 Notice that a variable is considered 'cheap': we can push it inside a lambda,
501 because sharing will make sure it is only evaluated once.
502
503 Note [exprIsCheap and exprIsHNF]
504 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
505 Note that exprIsHNF does not imply exprIsCheap.  Eg
506         let x = fac 20 in Just x
507 This responds True to exprIsHNF (you can discard a seq), but
508 False to exprIsCheap.
509
510 \begin{code}
511 exprIsCheap :: CoreExpr -> Bool
512 exprIsCheap = exprIsCheap' isCheapApp
513
514 exprIsExpandable :: CoreExpr -> Bool
515 exprIsExpandable = exprIsCheap' isExpandableApp -- See Note [CONLIKE pragma] in BasicTypes
516
517 type CheapAppFun = Id -> Int -> Bool
518 exprIsCheap' :: CheapAppFun -> CoreExpr -> Bool
519 exprIsCheap' _          (Lit _)   = True
520 exprIsCheap' _          (Type _)  = True
521 exprIsCheap' _          (Var _)   = True
522 exprIsCheap' good_app (Note _ e)  = exprIsCheap' good_app e
523 exprIsCheap' good_app (Cast e _)  = exprIsCheap' good_app e
524 exprIsCheap' good_app (Lam x e)   = isRuntimeVar x
525                                  || exprIsCheap' good_app e
526
527 exprIsCheap' good_app (Case e _ _ alts) = exprIsCheap' good_app e && 
528                                           and [exprIsCheap' good_app rhs | (_,_,rhs) <- alts]
529         -- Experimentally, treat (case x of ...) as cheap
530         -- (and case __coerce x etc.)
531         -- This improves arities of overloaded functions where
532         -- there is only dictionary selection (no construction) involved
533
534 exprIsCheap' good_app (Let (NonRec x _) e)  
535   | isUnLiftedType (idType x) = exprIsCheap' good_app e
536   | otherwise                 = False
537         -- Strict lets always have cheap right hand sides,
538         -- and do no allocation, so just look at the body
539         -- Non-strict lets do allocation so we don't treat them as cheap
540         -- See also 
541
542 exprIsCheap' good_app other_expr        -- Applications and variables
543   = go other_expr []
544   where
545         -- Accumulate value arguments, then decide
546     go (App f a) val_args | isRuntimeArg a = go f (a:val_args)
547                           | otherwise      = go f val_args
548
549     go (Var _) [] = True        -- Just a type application of a variable
550                                 -- (f t1 t2 t3) counts as WHNF
551     go (Var f) args
552         = case idDetails f of
553                 RecSelId {}                  -> go_sel args
554                 ClassOpId {}                 -> go_sel args
555                 PrimOpId op                  -> go_primop op args
556                 _ | good_app f (length args) -> go_pap args
557                   | isBottomingId f          -> True
558                   | otherwise                -> False
559                         -- Application of a function which
560                         -- always gives bottom; we treat this as cheap
561                         -- because it certainly doesn't need to be shared!
562         
563     go _ _ = False
564  
565     --------------
566     go_pap args = all exprIsTrivial args
567         -- For constructor applications and primops, check that all
568         -- the args are trivial.  We don't want to treat as cheap, say,
569         --      (1:2:3:4:5:[])
570         -- We'll put up with one constructor application, but not dozens
571         
572     --------------
573     go_primop op args = primOpIsCheap op && all (exprIsCheap' good_app) args
574         -- In principle we should worry about primops
575         -- that return a type variable, since the result
576         -- might be applied to something, but I'm not going
577         -- to bother to check the number of args
578  
579     --------------
580     go_sel [arg] = exprIsCheap' good_app arg    -- I'm experimenting with making record selection
581     go_sel _     = False                -- look cheap, so we will substitute it inside a
582                                         -- lambda.  Particularly for dictionary field selection.
583                 -- BUT: Take care with (sel d x)!  The (sel d) might be cheap, but
584                 --      there's no guarantee that (sel d x) will be too.  Hence (n_val_args == 1)
585
586 isCheapApp :: CheapAppFun
587 isCheapApp fn n_val_args
588   = isDataConWorkId fn 
589   || n_val_args < idArity fn
590
591 isExpandableApp :: CheapAppFun
592 isExpandableApp fn n_val_args
593   =  isConLikeId fn
594   || n_val_args < idArity fn
595   || go n_val_args (idType fn)
596   where
597   -- See if all the arguments are PredTys (implicit params or classes)
598   -- If so we'll regard it as expandable; see Note [Expandable overloadings]
599      go 0 _ = True
600      go n_val_args ty 
601        | Just (_, ty) <- splitForAllTy_maybe ty   = go n_val_args ty
602        | Just (arg, ty) <- splitFunTy_maybe ty
603        , isPredTy arg                             = go (n_val_args-1) ty
604        | otherwise                                = False
605 \end{code}
606
607 Note [Expandable overloadings]
608 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
609 Suppose the user wrote this
610    {-# RULE  forall x. foo (negate x) = h x #-}
611    f x = ....(foo (negate x))....
612 He'd expect the rule to fire. But since negate is overloaded, we might
613 get this:
614     f = \d -> let n = negate d in \x -> ...foo (n x)...
615 So we treat the application of a function (negate in this case) to a
616 *dictionary* as expandable.  In effect, every function is CONLIKE when
617 it's applied only to dictionaries.
618
619
620 %************************************************************************
621 %*                                                                      *
622              exprOkForSpeculation
623 %*                                                                      *
624 %************************************************************************
625
626 \begin{code}
627 -- | 'exprOkForSpeculation' returns True of an expression that is:
628 --
629 --  * Safe to evaluate even if normal order eval might not 
630 --    evaluate the expression at all, or
631 --
632 --  * Safe /not/ to evaluate even if normal order would do so
633 --
634 -- It is usually called on arguments of unlifted type, but not always
635 -- In particular, Simplify.rebuildCase calls it on lifted types
636 -- when a 'case' is a plain 'seq'. See the example in 
637 -- Note [exprOkForSpeculation: case expressions] below
638 --
639 -- Precisely, it returns @True@ iff:
640 --
641 --  * The expression guarantees to terminate, 
642 --  * soon, 
643 --  * without raising an exception,
644 --  * without causing a side effect (e.g. writing a mutable variable)
645 --
646 -- Note that if @exprIsHNF e@, then @exprOkForSpecuation e@.
647 -- As an example of the considerations in this test, consider:
648 --
649 -- > let x = case y# +# 1# of { r# -> I# r# }
650 -- > in E
651 --
652 -- being translated to:
653 --
654 -- > case y# +# 1# of { r# -> 
655 -- >    let x = I# r#
656 -- >    in E 
657 -- > }
658 -- 
659 -- We can only do this if the @y + 1@ is ok for speculation: it has no
660 -- side effects, and can't diverge or raise an exception.
661 exprOkForSpeculation :: CoreExpr -> Bool
662 exprOkForSpeculation (Lit _)     = True
663 exprOkForSpeculation (Type _)    = True
664
665 exprOkForSpeculation (Var v)     
666   | isTickBoxOp v = False     -- Tick boxes are *not* suitable for speculation
667   | otherwise     =  isUnLiftedType (idType v)  -- c.f. the Var case of exprIsHNF
668                   || isDataConWorkId v          -- Nullary constructors
669                   || idArity v > 0              -- Functions
670                   || isEvaldUnfolding (idUnfolding v)   -- Let-bound values
671
672 exprOkForSpeculation (Note _ e)  = exprOkForSpeculation e
673 exprOkForSpeculation (Cast e _)  = exprOkForSpeculation e
674
675 exprOkForSpeculation (Case e _ _ alts) 
676   =  exprOkForSpeculation e  -- Note [exprOkForSpeculation: case expressions]
677   && all (\(_,_,rhs) -> exprOkForSpeculation rhs) alts
678
679 exprOkForSpeculation other_expr
680   = case collectArgs other_expr of
681         (Var f, args) | f `hasKey` absentErrorIdKey     -- Note [Absent error Id]
682                       -> all exprOkForSpeculation args  --    in WwLib
683                       | otherwise 
684                       -> spec_ok (idDetails f) args
685         _             -> False
686  
687   where
688     spec_ok (DataConWorkId _) _
689       = True    -- The strictness of the constructor has already
690                 -- been expressed by its "wrapper", so we don't need
691                 -- to take the arguments into account
692
693     spec_ok (PrimOpId op) args
694       | isDivOp op,             -- Special case for dividing operations that fail
695         [arg1, Lit lit] <- args -- only if the divisor is zero
696       = not (isZeroLit lit) && exprOkForSpeculation arg1
697                 -- Often there is a literal divisor, and this 
698                 -- can get rid of a thunk in an inner looop
699
700       | DataToTagOp <- op      -- See Note [dataToTag speculation]
701       = True
702
703       | otherwise
704       = primOpOkForSpeculation op && 
705         all exprOkForSpeculation args
706                                 -- A bit conservative: we don't really need
707                                 -- to care about lazy arguments, but this is easy
708
709     spec_ok (DFunId _ new_type) _ = not new_type
710          -- DFuns terminate, unless the dict is implemented with a newtype
711          -- in which case they may not
712
713     spec_ok _ _ = False
714
715 -- | True of dyadic operators that can fail only if the second arg is zero!
716 isDivOp :: PrimOp -> Bool
717 -- This function probably belongs in PrimOp, or even in 
718 -- an automagically generated file.. but it's such a 
719 -- special case I thought I'd leave it here for now.
720 isDivOp IntQuotOp        = True
721 isDivOp IntRemOp         = True
722 isDivOp WordQuotOp       = True
723 isDivOp WordRemOp        = True
724 isDivOp FloatDivOp       = True
725 isDivOp DoubleDivOp      = True
726 isDivOp _                = False
727 \end{code}
728
729 Note [exprOkForSpeculation: case expressions]
730 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
731 It's always sound for exprOkForSpeculation to return False, and we
732 don't want it to take too long, so it bales out on complicated-looking
733 terms.  Notably lets, which can be stacked very deeply; and in any 
734 case the argument of exprOkForSpeculation is usually in a strict context,
735 so any lets will have been floated away.
736
737 However, we keep going on case-expressions.  An example like this one
738 showed up in DPH code (Trac #3717):
739     foo :: Int -> Int
740     foo 0 = 0
741     foo n = (if n < 5 then 1 else 2) `seq` foo (n-1)
742
743 If exprOkForSpeculation doesn't look through case expressions, you get this:
744     T.$wfoo =
745       \ (ww :: GHC.Prim.Int#) ->
746         case ww of ds {
747           __DEFAULT -> case (case <# ds 5 of _ {
748                           GHC.Types.False -> lvl1;
749                           GHC.Types.True -> lvl})
750                        of _ { __DEFAULT ->
751                        T.$wfoo (GHC.Prim.-# ds_XkE 1) };
752           0 -> 0
753         }
754
755 The inner case is redundant, and should be nuked.
756
757 Note [dataToTag speculation]
758 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
759 Is this OK?
760    f x = let v::Int# = dataToTag# x
761          in ...
762 We say "yes", even though 'x' may not be evaluated.  Reasons
763
764   * dataToTag#'s strictness means that its argument often will be
765     evaluated, but FloatOut makes that temporarily untrue
766          case x of y -> let v = dataToTag# y in ...
767     -->
768          case x of y -> let v = dataToTag# x in ...
769     Note that we look at 'x' instead of 'y' (this is to improve
770     floating in FloatOut).  So Lint complains.    
771  
772     Moreover, it really *might* improve floating to let the
773     v-binding float out
774          
775   * CorePrep makes sure dataToTag#'s argument is evaluated, just
776     before code gen.  Until then, it's not guaranteed
777
778
779 %************************************************************************
780 %*                                                                      *
781              exprIsHNF, exprIsConLike
782 %*                                                                      *
783 %************************************************************************
784
785 \begin{code}
786 -- Note [exprIsHNF]             See also Note [exprIsCheap and exprIsHNF]
787 -- ~~~~~~~~~~~~~~~~
788 -- | exprIsHNF returns true for expressions that are certainly /already/ 
789 -- evaluated to /head/ normal form.  This is used to decide whether it's ok 
790 -- to change:
791 --
792 -- > case x of _ -> e
793 --
794 --    into:
795 --
796 -- > e
797 --
798 -- and to decide whether it's safe to discard a 'seq'.
799 -- 
800 -- So, it does /not/ treat variables as evaluated, unless they say they are.
801 -- However, it /does/ treat partial applications and constructor applications
802 -- as values, even if their arguments are non-trivial, provided the argument
803 -- type is lifted. For example, both of these are values:
804 --
805 -- > (:) (f x) (map f xs)
806 -- > map (...redex...)
807 --
808 -- because 'seq' on such things completes immediately.
809 --
810 -- For unlifted argument types, we have to be careful:
811 --
812 -- > C (f x :: Int#)
813 --
814 -- Suppose @f x@ diverges; then @C (f x)@ is not a value. However this can't 
815 -- happen: see "CoreSyn#let_app_invariant". This invariant states that arguments of
816 -- unboxed type must be ok-for-speculation (or trivial).
817 exprIsHNF :: CoreExpr -> Bool           -- True => Value-lambda, constructor, PAP
818 exprIsHNF = exprIsHNFlike isDataConWorkId isEvaldUnfolding
819 \end{code}
820
821 \begin{code}
822 -- | Similar to 'exprIsHNF' but includes CONLIKE functions as well as
823 -- data constructors. Conlike arguments are considered interesting by the
824 -- inliner.
825 exprIsConLike :: CoreExpr -> Bool       -- True => lambda, conlike, PAP
826 exprIsConLike = exprIsHNFlike isConLikeId isConLikeUnfolding
827
828 -- | Returns true for values or value-like expressions. These are lambdas,
829 -- constructors / CONLIKE functions (as determined by the function argument)
830 -- or PAPs.
831 --
832 exprIsHNFlike :: (Var -> Bool) -> (Unfolding -> Bool) -> CoreExpr -> Bool
833 exprIsHNFlike is_con is_con_unf = is_hnf_like
834   where
835     is_hnf_like (Var v) -- NB: There are no value args at this point
836       =  is_con v       -- Catches nullary constructors, 
837                         --      so that [] and () are values, for example
838       || idArity v > 0  -- Catches (e.g.) primops that don't have unfoldings
839       || is_con_unf (idUnfolding v)
840         -- Check the thing's unfolding; it might be bound to a value
841         -- We don't look through loop breakers here, which is a bit conservative
842         -- but otherwise I worry that if an Id's unfolding is just itself, 
843         -- we could get an infinite loop
844
845     is_hnf_like (Lit _)          = True
846     is_hnf_like (Type _)         = True       -- Types are honorary Values;
847                                               -- we don't mind copying them
848     is_hnf_like (Lam b e)        = isRuntimeVar b || is_hnf_like e
849     is_hnf_like (Note _ e)       = is_hnf_like e
850     is_hnf_like (Cast e _)       = is_hnf_like e
851     is_hnf_like (App e (Type _)) = is_hnf_like e
852     is_hnf_like (App e a)        = app_is_value e [a]
853     is_hnf_like (Let _ e)        = is_hnf_like e  -- Lazy let(rec)s don't affect us
854     is_hnf_like _                = False
855
856     -- There is at least one value argument
857     app_is_value :: CoreExpr -> [CoreArg] -> Bool
858     app_is_value (Var fun) args
859       = idArity fun > valArgCount args    -- Under-applied function
860         || is_con fun                     --  or constructor-like
861     app_is_value (Note _ f) as = app_is_value f as
862     app_is_value (Cast f _) as = app_is_value f as
863     app_is_value (App f a)  as = app_is_value f (a:as)
864     app_is_value _          _  = False
865 \end{code}
866
867
868 %************************************************************************
869 %*                                                                      *
870              Instantiating data constructors
871 %*                                                                      *
872 %************************************************************************
873
874 These InstPat functions go here to avoid circularity between DataCon and Id
875
876 \begin{code}
877 dataConRepInstPat, dataConOrigInstPat :: [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
878 dataConRepFSInstPat :: [FastString] -> [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
879
880 dataConRepInstPat   = dataConInstPat dataConRepArgTys (repeat ((fsLit "ipv")))
881 dataConRepFSInstPat = dataConInstPat dataConRepArgTys
882 dataConOrigInstPat  = dataConInstPat dc_arg_tys       (repeat ((fsLit "ipv")))
883   where 
884     dc_arg_tys dc = map mkPredTy (dataConEqTheta dc) ++ map mkPredTy (dataConDictTheta dc) ++ dataConOrigArgTys dc
885         -- Remember to include the existential dictionaries
886
887 dataConInstPat :: (DataCon -> [Type])      -- function used to find arg tys
888                   -> [FastString]          -- A long enough list of FSs to use for names
889                   -> [Unique]              -- An equally long list of uniques, at least one for each binder
890                   -> DataCon
891                   -> [Type]                -- Types to instantiate the universally quantified tyvars
892                -> ([TyVar], [CoVar], [Id]) -- Return instantiated variables
893 -- dataConInstPat arg_fun fss us con inst_tys returns a triple 
894 -- (ex_tvs, co_tvs, arg_ids),
895 --
896 --   ex_tvs are intended to be used as binders for existential type args
897 --
898 --   co_tvs are intended to be used as binders for coercion args and the kinds
899 --     of these vars have been instantiated by the inst_tys and the ex_tys
900 --     The co_tvs include both GADT equalities (dcEqSpec) and 
901 --     programmer-specified equalities (dcEqTheta)
902 --
903 --   arg_ids are indended to be used as binders for value arguments, 
904 --     and their types have been instantiated with inst_tys and ex_tys
905 --     The arg_ids include both dicts (dcDictTheta) and
906 --     programmer-specified arguments (after rep-ing) (deRepArgTys)
907 --
908 -- Example.
909 --  The following constructor T1
910 --
911 --  data T a where
912 --    T1 :: forall b. Int -> b -> T(a,b)
913 --    ...
914 --
915 --  has representation type 
916 --   forall a. forall a1. forall b. (a ~ (a1,b)) => 
917 --     Int -> b -> T a
918 --
919 --  dataConInstPat fss us T1 (a1',b') will return
920 --
921 --  ([a1'', b''], [c :: (a1', b')~(a1'', b'')], [x :: Int, y :: b''])
922 --
923 --  where the double-primed variables are created with the FastStrings and
924 --  Uniques given as fss and us
925 dataConInstPat arg_fun fss uniqs con inst_tys 
926   = (ex_bndrs, co_bndrs, arg_ids)
927   where 
928     univ_tvs = dataConUnivTyVars con
929     ex_tvs   = dataConExTyVars con
930     arg_tys  = arg_fun con
931     eq_spec  = dataConEqSpec con
932     eq_theta = dataConEqTheta con
933     eq_preds = eqSpecPreds eq_spec ++ eq_theta
934
935     n_ex = length ex_tvs
936     n_co = length eq_preds
937
938       -- split the Uniques and FastStrings
939     (ex_uniqs, uniqs')   = splitAt n_ex uniqs
940     (co_uniqs, id_uniqs) = splitAt n_co uniqs'
941
942     (ex_fss, fss')     = splitAt n_ex fss
943     (co_fss, id_fss)   = splitAt n_co fss'
944
945       -- Make existential type variables
946     ex_bndrs = zipWith3 mk_ex_var ex_uniqs ex_fss ex_tvs
947     mk_ex_var uniq fs var = mkTyVar new_name kind
948       where
949         new_name = mkSysTvName uniq fs
950         kind     = tyVarKind var
951
952       -- Make the instantiating substitution
953     subst = zipOpenTvSubst (univ_tvs ++ ex_tvs) (inst_tys ++ map mkTyVarTy ex_bndrs)
954
955       -- Make new coercion vars, instantiating kind
956     co_bndrs = zipWith3 mk_co_var co_uniqs co_fss eq_preds
957     mk_co_var uniq fs eq_pred = mkCoVar new_name co_kind
958        where
959          new_name = mkSysTvName uniq fs
960          co_kind  = substTy subst (mkPredTy eq_pred)
961
962       -- make value vars, instantiating types
963     mk_id_var uniq fs ty = mkUserLocal (mkVarOccFS fs) uniq (substTy subst ty) noSrcSpan
964     arg_ids = zipWith3 mk_id_var id_uniqs id_fss arg_tys
965
966 \end{code}
967
968 %************************************************************************
969 %*                                                                      *
970          Equality
971 %*                                                                      *
972 %************************************************************************
973
974 \begin{code}
975 -- | A cheap equality test which bales out fast!
976 --      If it returns @True@ the arguments are definitely equal,
977 --      otherwise, they may or may not be equal.
978 --
979 -- See also 'exprIsBig'
980 cheapEqExpr :: Expr b -> Expr b -> Bool
981
982 cheapEqExpr (Var v1)   (Var v2)   = v1==v2
983 cheapEqExpr (Lit lit1) (Lit lit2) = lit1 == lit2
984 cheapEqExpr (Type t1)  (Type t2)  = t1 `coreEqType` t2
985
986 cheapEqExpr (App f1 a1) (App f2 a2)
987   = f1 `cheapEqExpr` f2 && a1 `cheapEqExpr` a2
988
989 cheapEqExpr (Cast e1 t1) (Cast e2 t2)
990   = e1 `cheapEqExpr` e2 && t1 `coreEqCoercion` t2
991
992 cheapEqExpr _ _ = False
993 \end{code}
994
995 \begin{code}
996 exprIsBig :: Expr b -> Bool
997 -- ^ Returns @True@ of expressions that are too big to be compared by 'cheapEqExpr'
998 exprIsBig (Lit _)      = False
999 exprIsBig (Var _)      = False
1000 exprIsBig (Type _)     = False
1001 exprIsBig (Lam _ e)    = exprIsBig e
1002 exprIsBig (App f a)    = exprIsBig f || exprIsBig a
1003 exprIsBig (Cast e _)   = exprIsBig e    -- Hopefully coercions are not too big!
1004 exprIsBig _            = True
1005 \end{code}
1006
1007 \begin{code}
1008 eqExpr :: InScopeSet -> CoreExpr -> CoreExpr -> Bool
1009 -- Compares for equality, modulo alpha
1010 eqExpr in_scope e1 e2
1011   = eqExprX id_unf (mkRnEnv2 in_scope) e1 e2
1012   where
1013     id_unf _ = noUnfolding      -- Don't expand
1014 \end{code}
1015     
1016 \begin{code}
1017 eqExprX :: IdUnfoldingFun -> RnEnv2 -> CoreExpr -> CoreExpr -> Bool
1018 -- ^ Compares expressions for equality, modulo alpha.
1019 -- Does /not/ look through newtypes or predicate types
1020 -- Used in rule matching, and also CSE
1021
1022 eqExprX id_unfolding_fun env e1 e2
1023   = go env e1 e2
1024   where
1025     go env (Var v1) (Var v2)
1026       | rnOccL env v1 == rnOccR env v2
1027       = True
1028
1029     -- The next two rules expand non-local variables
1030     -- C.f. Note [Expanding variables] in Rules.lhs
1031     -- and  Note [Do not expand locally-bound variables] in Rules.lhs
1032     go env (Var v1) e2
1033       | not (locallyBoundL env v1)
1034       , Just e1' <- expandUnfolding_maybe (id_unfolding_fun (lookupRnInScope env v1))
1035       = go (nukeRnEnvL env) e1' e2
1036
1037     go env e1 (Var v2)
1038       | not (locallyBoundR env v2)
1039       , Just e2' <- expandUnfolding_maybe (id_unfolding_fun (lookupRnInScope env v2))
1040       = go (nukeRnEnvR env) e1 e2'
1041
1042     go _   (Lit lit1)    (Lit lit2)    = lit1 == lit2
1043     go env (Type t1)     (Type t2)     = tcEqTypeX env t1 t2
1044     go env (Cast e1 co1) (Cast e2 co2) = tcEqTypeX env co1 co2 && go env e1 e2
1045     go env (App f1 a1)   (App f2 a2)   = go env f1 f2 && go env a1 a2
1046     go env (Note n1 e1)  (Note n2 e2)  = go_note n1 n2 && go env e1 e2
1047
1048     go env (Lam b1 e1)  (Lam b2 e2)  
1049       =  tcEqTypeX env (varType b1) (varType b2)   -- False for Id/TyVar combination
1050       && go (rnBndr2 env b1 b2) e1 e2
1051
1052     go env (Let (NonRec v1 r1) e1) (Let (NonRec v2 r2) e2) 
1053       =  go env r1 r2  -- No need to check binder types, since RHSs match
1054       && go (rnBndr2 env v1 v2) e1 e2
1055
1056     go env (Let (Rec ps1) e1) (Let (Rec ps2) e2) 
1057       = all2 (go env') rs1 rs2 && go env' e1 e2
1058       where
1059         (bs1,rs1) = unzip ps1      
1060         (bs2,rs2) = unzip ps2
1061         env' = rnBndrs2 env bs1 bs2
1062
1063     go env (Case e1 b1 _ a1) (Case e2 b2 _ a2)
1064       =  go env e1 e2
1065       && tcEqTypeX env (idType b1) (idType b2)
1066       && all2 (go_alt (rnBndr2 env b1 b2)) a1 a2
1067
1068     go _ _ _ = False
1069
1070     -----------
1071     go_alt env (c1, bs1, e1) (c2, bs2, e2)
1072       = c1 == c2 && go (rnBndrs2 env bs1 bs2) e1 e2
1073
1074     -----------
1075     go_note (SCC cc1)     (SCC cc2)      = cc1 == cc2
1076     go_note (CoreNote s1) (CoreNote s2)  = s1 == s2
1077     go_note _             _              = False
1078 \end{code}
1079
1080 Auxiliary functions
1081
1082 \begin{code}
1083 locallyBoundL, locallyBoundR :: RnEnv2 -> Var -> Bool
1084 locallyBoundL rn_env v = inRnEnvL rn_env v
1085 locallyBoundR rn_env v = inRnEnvR rn_env v
1086 \end{code}
1087
1088
1089 %************************************************************************
1090 %*                                                                      *
1091 \subsection{The size of an expression}
1092 %*                                                                      *
1093 %************************************************************************
1094
1095 \begin{code}
1096 coreBindsSize :: [CoreBind] -> Int
1097 coreBindsSize bs = foldr ((+) . bindSize) 0 bs
1098
1099 exprSize :: CoreExpr -> Int
1100 -- ^ A measure of the size of the expressions, strictly greater than 0
1101 -- It also forces the expression pretty drastically as a side effect
1102 exprSize (Var v)         = v `seq` 1
1103 exprSize (Lit lit)       = lit `seq` 1
1104 exprSize (App f a)       = exprSize f + exprSize a
1105 exprSize (Lam b e)       = varSize b + exprSize e
1106 exprSize (Let b e)       = bindSize b + exprSize e
1107 exprSize (Case e b t as) = seqType t `seq` exprSize e + varSize b + 1 + foldr ((+) . altSize) 0 as
1108 exprSize (Cast e co)     = (seqType co `seq` 1) + exprSize e
1109 exprSize (Note n e)      = noteSize n + exprSize e
1110 exprSize (Type t)        = seqType t `seq` 1
1111
1112 noteSize :: Note -> Int
1113 noteSize (SCC cc)       = cc `seq` 1
1114 noteSize (CoreNote s)   = s `seq` 1  -- hdaume: core annotations
1115  
1116 varSize :: Var -> Int
1117 varSize b  | isTyCoVar b = 1
1118            | otherwise = seqType (idType b)             `seq`
1119                          megaSeqIdInfo (idInfo b)       `seq`
1120                          1
1121
1122 varsSize :: [Var] -> Int
1123 varsSize = sum . map varSize
1124
1125 bindSize :: CoreBind -> Int
1126 bindSize (NonRec b e) = varSize b + exprSize e
1127 bindSize (Rec prs)    = foldr ((+) . pairSize) 0 prs
1128
1129 pairSize :: (Var, CoreExpr) -> Int
1130 pairSize (b,e) = varSize b + exprSize e
1131
1132 altSize :: CoreAlt -> Int
1133 altSize (c,bs,e) = c `seq` varsSize bs + exprSize e
1134 \end{code}
1135
1136
1137 %************************************************************************
1138 %*                                                                      *
1139 \subsection{Hashing}
1140 %*                                                                      *
1141 %************************************************************************
1142
1143 \begin{code}
1144 hashExpr :: CoreExpr -> Int
1145 -- ^ Two expressions that hash to the same @Int@ may be equal (but may not be)
1146 -- Two expressions that hash to the different Ints are definitely unequal.
1147 --
1148 -- The emphasis is on a crude, fast hash, rather than on high precision.
1149 -- 
1150 -- But unequal here means \"not identical\"; two alpha-equivalent 
1151 -- expressions may hash to the different Ints.
1152 --
1153 -- We must be careful that @\\x.x@ and @\\y.y@ map to the same hash code,
1154 -- (at least if we want the above invariant to be true).
1155
1156 hashExpr e = fromIntegral (hash_expr (1,emptyVarEnv) e .&. 0x7fffffff)
1157              -- UniqFM doesn't like negative Ints
1158
1159 type HashEnv = (Int, VarEnv Int)  -- Hash code for bound variables
1160
1161 hash_expr :: HashEnv -> CoreExpr -> Word32
1162 -- Word32, because we're expecting overflows here, and overflowing
1163 -- signed types just isn't cool.  In C it's even undefined.
1164 hash_expr env (Note _ e)              = hash_expr env e
1165 hash_expr env (Cast e _)              = hash_expr env e
1166 hash_expr env (Var v)                 = hashVar env v
1167 hash_expr _   (Lit lit)               = fromIntegral (hashLiteral lit)
1168 hash_expr env (App f e)               = hash_expr env f * fast_hash_expr env e
1169 hash_expr env (Let (NonRec b r) e)    = hash_expr (extend_env env b) e * fast_hash_expr env r
1170 hash_expr env (Let (Rec ((b,_):_)) e) = hash_expr (extend_env env b) e
1171 hash_expr env (Case e _ _ _)          = hash_expr env e
1172 hash_expr env (Lam b e)               = hash_expr (extend_env env b) e
1173 hash_expr _   (Type _)                = WARN(True, text "hash_expr: type") 1
1174 -- Shouldn't happen.  Better to use WARN than trace, because trace
1175 -- prevents the CPR optimisation kicking in for hash_expr.
1176
1177 fast_hash_expr :: HashEnv -> CoreExpr -> Word32
1178 fast_hash_expr env (Var v)      = hashVar env v
1179 fast_hash_expr env (Type t)     = fast_hash_type env t
1180 fast_hash_expr _   (Lit lit)    = fromIntegral (hashLiteral lit)
1181 fast_hash_expr env (Cast e _)   = fast_hash_expr env e
1182 fast_hash_expr env (Note _ e)   = fast_hash_expr env e
1183 fast_hash_expr env (App _ a)    = fast_hash_expr env a  -- A bit idiosyncratic ('a' not 'f')!
1184 fast_hash_expr _   _            = 1
1185
1186 fast_hash_type :: HashEnv -> Type -> Word32
1187 fast_hash_type env ty 
1188   | Just tv <- getTyVar_maybe ty            = hashVar env tv
1189   | Just (tc,tys) <- splitTyConApp_maybe ty = let hash_tc = fromIntegral (hashName (tyConName tc))
1190                                               in foldr (\t n -> fast_hash_type env t + n) hash_tc tys
1191   | otherwise                               = 1
1192
1193 extend_env :: HashEnv -> Var -> (Int, VarEnv Int)
1194 extend_env (n,env) b = (n+1, extendVarEnv env b n)
1195
1196 hashVar :: HashEnv -> Var -> Word32
1197 hashVar (_,env) v
1198  = fromIntegral (lookupVarEnv env v `orElse` hashName (idName v))
1199 \end{code}
1200
1201
1202 %************************************************************************
1203 %*                                                                      *
1204                 Eta reduction
1205 %*                                                                      *
1206 %************************************************************************
1207
1208 Note [Eta reduction conditions]
1209 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1210 We try for eta reduction here, but *only* if we get all the way to an
1211 trivial expression.  We don't want to remove extra lambdas unless we
1212 are going to avoid allocating this thing altogether.
1213
1214 There are some particularly delicate points here:
1215
1216 * Eta reduction is not valid in general:  
1217         \x. bot  /=  bot
1218   This matters, partly for old-fashioned correctness reasons but,
1219   worse, getting it wrong can yield a seg fault. Consider
1220         f = \x.f x
1221         h y = case (case y of { True -> f `seq` True; False -> False }) of
1222                 True -> ...; False -> ...
1223
1224   If we (unsoundly) eta-reduce f to get f=f, the strictness analyser
1225   says f=bottom, and replaces the (f `seq` True) with just
1226   (f `cast` unsafe-co).  BUT, as thing stand, 'f' got arity 1, and it
1227   *keeps* arity 1 (perhaps also wrongly).  So CorePrep eta-expands 
1228   the definition again, so that it does not termninate after all.
1229   Result: seg-fault because the boolean case actually gets a function value.
1230   See Trac #1947.
1231
1232   So it's important to to the right thing.
1233
1234 * Note [Arity care]: we need to be careful if we just look at f's
1235   arity. Currently (Dec07), f's arity is visible in its own RHS (see
1236   Note [Arity robustness] in SimplEnv) so we must *not* trust the
1237   arity when checking that 'f' is a value.  Otherwise we will
1238   eta-reduce
1239       f = \x. f x
1240   to
1241       f = f
1242   Which might change a terminiating program (think (f `seq` e)) to a 
1243   non-terminating one.  So we check for being a loop breaker first.
1244
1245   However for GlobalIds we can look at the arity; and for primops we
1246   must, since they have no unfolding.  
1247
1248 * Regardless of whether 'f' is a value, we always want to 
1249   reduce (/\a -> f a) to f
1250   This came up in a RULE: foldr (build (/\a -> g a))
1251   did not match           foldr (build (/\b -> ...something complex...))
1252   The type checker can insert these eta-expanded versions,
1253   with both type and dictionary lambdas; hence the slightly 
1254   ad-hoc isDictId
1255
1256 * Never *reduce* arity. For example
1257       f = \xy. g x y
1258   Then if h has arity 1 we don't want to eta-reduce because then
1259   f's arity would decrease, and that is bad
1260
1261 These delicacies are why we don't use exprIsTrivial and exprIsHNF here.
1262 Alas.
1263
1264 Note [Eta reduction with casted arguments]
1265 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1266 Consider  
1267     (\(x:t3). f (x |> g)) :: t3 -> t2
1268   where
1269     f :: t1 -> t2
1270     g :: t3 ~ t1
1271 This should be eta-reduced to
1272
1273     f |> (sym g -> t2)
1274
1275 So we need to accumulate a coercion, pushing it inward (past
1276 variable arguments only) thus:
1277    f (x |> co_arg) |> co  -->  (f |> (sym co_arg -> co)) x
1278    f (x:t)         |> co  -->  (f |> (t -> co)) x
1279    f @ a           |> co  -->  (f |> (forall a.co)) @ a
1280    f @ (g:t1~t2)   |> co  -->  (f |> (t1~t2 => co)) @ (g:t1~t2)
1281 These are the equations for ok_arg.
1282
1283 It's true that we could also hope to eta reduce these:
1284     (\xy. (f x |> g) y)
1285     (\xy. (f x y) |> g)
1286 But the simplifier pushes those casts outwards, so we don't
1287 need to address that here.
1288
1289 \begin{code}
1290 tryEtaReduce :: [Var] -> CoreExpr -> Maybe CoreExpr
1291 tryEtaReduce bndrs body 
1292   = go (reverse bndrs) body (IdCo (exprType body))
1293   where
1294     incoming_arity = count isId bndrs
1295
1296     go :: [Var]            -- Binders, innermost first, types [a3,a2,a1]
1297        -> CoreExpr         -- Of type tr
1298        -> CoercionI        -- Of type tr ~ ts
1299        -> Maybe CoreExpr   -- Of type a1 -> a2 -> a3 -> ts
1300     -- See Note [Eta reduction with casted arguments]
1301     -- for why we have an accumulating coercion
1302     go [] fun co
1303       | ok_fun fun = Just (mkCoerceI co fun)
1304
1305     go (b : bs) (App fun arg) co
1306       | Just co' <- ok_arg b arg co
1307       = go bs fun co'
1308
1309     go _ _ _  = Nothing         -- Failure!
1310
1311     ---------------
1312     -- Note [Eta reduction conditions]
1313     ok_fun (App fun (Type ty)) 
1314         | not (any (`elemVarSet` tyVarsOfType ty) bndrs)
1315         =  ok_fun fun
1316     ok_fun (Var fun_id)
1317         =  not (fun_id `elem` bndrs)
1318         && (ok_fun_id fun_id || all ok_lam bndrs)
1319     ok_fun _fun = False
1320
1321     ---------------
1322     ok_fun_id fun = fun_arity fun >= incoming_arity
1323
1324     ---------------
1325     fun_arity fun             -- See Note [Arity care]
1326        | isLocalId fun && isLoopBreaker (idOccInfo fun) = 0
1327        | otherwise = idArity fun              
1328
1329     ---------------
1330     ok_lam v = isTyCoVar v || isDictId v
1331
1332     ---------------
1333     ok_arg :: Var               -- Of type bndr_t
1334            -> CoreExpr          -- Of type arg_t
1335            -> CoercionI         -- Of kind (t1~t2)
1336            -> Maybe CoercionI   -- Of type (arg_t -> t1 ~  bndr_t -> t2)
1337                                 --   (and similarly for tyvars, coercion args)
1338     -- See Note [Eta reduction with casted arguments]
1339     ok_arg bndr (Type ty) co
1340        | Just tv <- getTyVar_maybe ty
1341        , bndr == tv  = Just (mkForAllTyCoI tv co)
1342     ok_arg bndr (Var v) co
1343        | bndr == v   = Just (mkFunTyCoI (IdCo (idType bndr)) co)
1344     ok_arg bndr (Cast (Var v) co_arg) co
1345        | bndr == v  = Just (mkFunTyCoI (ACo (mkSymCoercion co_arg)) co)
1346        -- The simplifier combines multiple casts into one, 
1347        -- so we can have a simple-minded pattern match here
1348     ok_arg _ _ _ = Nothing
1349 \end{code}
1350
1351
1352 %************************************************************************
1353 %*                                                                      *
1354 \subsection{Determining non-updatable right-hand-sides}
1355 %*                                                                      *
1356 %************************************************************************
1357
1358 Top-level constructor applications can usually be allocated
1359 statically, but they can't if the constructor, or any of the
1360 arguments, come from another DLL (because we can't refer to static
1361 labels in other DLLs).
1362
1363 If this happens we simply make the RHS into an updatable thunk, 
1364 and 'execute' it rather than allocating it statically.
1365
1366 \begin{code}
1367 -- | This function is called only on *top-level* right-hand sides.
1368 -- Returns @True@ if the RHS can be allocated statically in the output,
1369 -- with no thunks involved at all.
1370 rhsIsStatic :: (Name -> Bool) -> CoreExpr -> Bool
1371 -- It's called (i) in TidyPgm.hasCafRefs to decide if the rhs is, or
1372 -- refers to, CAFs; (ii) in CoreToStg to decide whether to put an
1373 -- update flag on it and (iii) in DsExpr to decide how to expand
1374 -- list literals
1375 --
1376 -- The basic idea is that rhsIsStatic returns True only if the RHS is
1377 --      (a) a value lambda
1378 --      (b) a saturated constructor application with static args
1379 --
1380 -- BUT watch out for
1381 --  (i) Any cross-DLL references kill static-ness completely
1382 --      because they must be 'executed' not statically allocated
1383 --      ("DLL" here really only refers to Windows DLLs, on other platforms,
1384 --      this is not necessary)
1385 --
1386 -- (ii) We treat partial applications as redexes, because in fact we 
1387 --      make a thunk for them that runs and builds a PAP
1388 --      at run-time.  The only appliations that are treated as 
1389 --      static are *saturated* applications of constructors.
1390
1391 -- We used to try to be clever with nested structures like this:
1392 --              ys = (:) w ((:) w [])
1393 -- on the grounds that CorePrep will flatten ANF-ise it later.
1394 -- But supporting this special case made the function much more 
1395 -- complicated, because the special case only applies if there are no 
1396 -- enclosing type lambdas:
1397 --              ys = /\ a -> Foo (Baz ([] a))
1398 -- Here the nested (Baz []) won't float out to top level in CorePrep.
1399 --
1400 -- But in fact, even without -O, nested structures at top level are 
1401 -- flattened by the simplifier, so we don't need to be super-clever here.
1402 --
1403 -- Examples
1404 --
1405 --      f = \x::Int. x+7        TRUE
1406 --      p = (True,False)        TRUE
1407 --
1408 --      d = (fst p, False)      FALSE because there's a redex inside
1409 --                              (this particular one doesn't happen but...)
1410 --
1411 --      h = D# (1.0## /## 2.0##)        FALSE (redex again)
1412 --      n = /\a. Nil a                  TRUE
1413 --
1414 --      t = /\a. (:) (case w a of ...) (Nil a)  FALSE (redex)
1415 --
1416 --
1417 -- This is a bit like CoreUtils.exprIsHNF, with the following differences:
1418 --    a) scc "foo" (\x -> ...) is updatable (so we catch the right SCC)
1419 --
1420 --    b) (C x xs), where C is a contructor is updatable if the application is
1421 --         dynamic
1422 -- 
1423 --    c) don't look through unfolding of f in (f x).
1424
1425 rhsIsStatic _is_dynamic_name rhs = is_static False rhs
1426   where
1427   is_static :: Bool     -- True <=> in a constructor argument; must be atomic
1428           -> CoreExpr -> Bool
1429   
1430   is_static False (Lam b e)   = isRuntimeVar b || is_static False e
1431   is_static in_arg (Note n e) = notSccNote n && is_static in_arg e
1432   is_static in_arg (Cast e _) = is_static in_arg e
1433   
1434   is_static _      (Lit lit)
1435     = case lit of
1436         MachLabel _ _ _ -> False
1437         _             -> True
1438         -- A MachLabel (foreign import "&foo") in an argument
1439         -- prevents a constructor application from being static.  The
1440         -- reason is that it might give rise to unresolvable symbols
1441         -- in the object file: under Linux, references to "weak"
1442         -- symbols from the data segment give rise to "unresolvable
1443         -- relocation" errors at link time This might be due to a bug
1444         -- in the linker, but we'll work around it here anyway. 
1445         -- SDM 24/2/2004
1446   
1447   is_static in_arg other_expr = go other_expr 0
1448    where
1449     go (Var f) n_val_args
1450 #if mingw32_TARGET_OS
1451         | not (_is_dynamic_name (idName f))
1452 #endif
1453         =  saturated_data_con f n_val_args
1454         || (in_arg && n_val_args == 0)  
1455                 -- A naked un-applied variable is *not* deemed a static RHS
1456                 -- E.g.         f = g
1457                 -- Reason: better to update so that the indirection gets shorted
1458                 --         out, and the true value will be seen
1459                 -- NB: if you change this, you'll break the invariant that THUNK_STATICs
1460                 --     are always updatable.  If you do so, make sure that non-updatable
1461                 --     ones have enough space for their static link field!
1462
1463     go (App f a) n_val_args
1464         | isTypeArg a                    = go f n_val_args
1465         | not in_arg && is_static True a = go f (n_val_args + 1)
1466         -- The (not in_arg) checks that we aren't in a constructor argument;
1467         -- if we are, we don't allow (value) applications of any sort
1468         -- 
1469         -- NB. In case you wonder, args are sometimes not atomic.  eg.
1470         --   x = D# (1.0## /## 2.0##)
1471         -- can't float because /## can fail.
1472
1473     go (Note n f) n_val_args = notSccNote n && go f n_val_args
1474     go (Cast e _) n_val_args = go e n_val_args
1475     go _          _          = False
1476
1477     saturated_data_con f n_val_args
1478         = case isDataConWorkId_maybe f of
1479             Just dc -> n_val_args == dataConRepArity dc
1480             Nothing -> False
1481 \end{code}