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