Rewrite CorePrep and improve 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         mkInlineMe, mkSCC, mkCoerce, mkCoerceI,
20         bindNonRec, needsCaseBinding,
21         mkAltExpr, mkPiType, mkPiTypes,
22
23         -- * Taking expressions apart
24         findDefault, findAlt, isDefaultAlt, mergeAlts, trimConArgs,
25
26         -- * Properties of expressions
27         exprType, coreAltType, coreAltsType,
28         exprIsDupable, exprIsTrivial, exprIsCheap, 
29         exprIsHNF,exprOkForSpeculation, exprIsBig, 
30         exprIsConApp_maybe, exprIsBottom,
31         rhsIsStatic,
32
33         -- * Expression and bindings size
34         coreBindsSize, exprSize,
35
36         -- * Hashing
37         hashExpr,
38
39         -- * Equality
40         cheapEqExpr, tcEqExpr, tcEqExprX,
41
42         -- * Manipulating data constructors and types
43         applyTypeToArgs, applyTypeToArg,
44         dataConOrigInstPat, dataConRepInstPat, dataConRepFSInstPat
45     ) where
46
47 #include "HsVersions.h"
48
49 import CoreSyn
50 import CoreFVs
51 import PprCore
52 import Var
53 import SrcLoc
54 import VarSet
55 import VarEnv
56 import Name
57 import Module
58 #if mingw32_TARGET_OS
59 import Packages
60 #endif
61 import Literal
62 import DataCon
63 import PrimOp
64 import Id
65 import IdInfo
66 import NewDemand
67 import Type
68 import Coercion
69 import TyCon
70 import CostCentre
71 import Unique
72 import Outputable
73 import TysPrim
74 import FastString
75 import Maybes
76 import Util
77 import Data.Word
78 import Data.Bits
79
80 import GHC.Exts         -- For `xori` 
81 \end{code}
82
83
84 %************************************************************************
85 %*                                                                      *
86 \subsection{Find the type of a Core atom/expression}
87 %*                                                                      *
88 %************************************************************************
89
90 \begin{code}
91 exprType :: CoreExpr -> Type
92 -- ^ Recover the type of a well-typed Core expression. Fails when
93 -- applied to the actual 'CoreSyn.Type' expression as it cannot
94 -- really be said to have a type
95 exprType (Var var)           = idType var
96 exprType (Lit lit)           = literalType lit
97 exprType (Let _ body)        = exprType body
98 exprType (Case _ _ ty _)     = ty
99 exprType (Cast _ co)         = snd (coercionKind co)
100 exprType (Note _ e)          = exprType e
101 exprType (Lam binder expr)   = mkPiType binder (exprType expr)
102 exprType e@(App _ _)
103   = case collectArgs e of
104         (fun, args) -> applyTypeToArgs e (exprType fun) args
105
106 exprType other = pprTrace "exprType" (pprCoreExpr other) alphaTy
107
108 coreAltType :: CoreAlt -> Type
109 -- ^ Returns the type of the alternatives right hand side
110 coreAltType (_,_,rhs) = exprType rhs
111
112 coreAltsType :: [CoreAlt] -> Type
113 -- ^ Returns the type of the first alternative, which should be the same as for all alternatives
114 coreAltsType (alt:_) = coreAltType alt
115 coreAltsType []      = panic "corAltsType"
116 \end{code}
117
118 \begin{code}
119 mkPiType  :: Var   -> Type -> Type
120 -- ^ Makes a @(->)@ type or a forall type, depending
121 -- on whether it is given a type variable or a term variable.
122 mkPiTypes :: [Var] -> Type -> Type
123 -- ^ 'mkPiType' for multiple type or value arguments
124
125 mkPiType v ty
126    | isId v    = mkFunTy (idType v) ty
127    | otherwise = mkForAllTy v ty
128
129 mkPiTypes vs ty = foldr mkPiType ty vs
130 \end{code}
131
132 \begin{code}
133 applyTypeToArg :: Type -> CoreExpr -> Type
134 -- ^ Determines the type resulting from applying an expression to a function with the given type
135 applyTypeToArg fun_ty (Type arg_ty) = applyTy fun_ty arg_ty
136 applyTypeToArg fun_ty _             = funResultTy fun_ty
137
138 applyTypeToArgs :: CoreExpr -> Type -> [CoreExpr] -> Type
139 -- ^ A more efficient version of 'applyTypeToArg' when we have several arguments.
140 -- The first argument is just for debugging, and gives some context
141 applyTypeToArgs _ op_ty [] = op_ty
142
143 applyTypeToArgs e op_ty (Type ty : args)
144   =     -- Accumulate type arguments so we can instantiate all at once
145     go [ty] args
146   where
147     go rev_tys (Type ty : args) = go (ty:rev_tys) args
148     go rev_tys rest_args        = applyTypeToArgs e op_ty' rest_args
149                                 where
150                                   op_ty' = applyTysD msg op_ty (reverse rev_tys)
151                                   msg = ptext (sLit "applyTypeToArgs") <+> 
152                                         panic_msg e op_ty
153
154 applyTypeToArgs e op_ty (_ : args)
155   = case (splitFunTy_maybe op_ty) of
156         Just (_, res_ty) -> applyTypeToArgs e res_ty args
157         Nothing -> pprPanic "applyTypeToArgs" (panic_msg e op_ty)
158
159 panic_msg :: CoreExpr -> Type -> SDoc
160 panic_msg e op_ty = pprCoreExpr e $$ ppr op_ty
161 \end{code}
162
163 %************************************************************************
164 %*                                                                      *
165 \subsection{Attaching notes}
166 %*                                                                      *
167 %************************************************************************
168
169 mkNote removes redundant coercions, and SCCs where possible
170
171 \begin{code}
172 #ifdef UNUSED
173 mkNote :: Note -> CoreExpr -> CoreExpr
174 mkNote (SCC cc) expr               = mkSCC cc expr
175 mkNote InlineMe expr               = mkInlineMe expr
176 mkNote note     expr               = Note note expr
177 #endif
178 \end{code}
179
180 Drop trivial InlineMe's.  This is somewhat important, because if we have an unfolding
181 that looks like (Note InlineMe (Var v)), the InlineMe doesn't go away because it may
182 not be *applied* to anything.
183
184 We don't use exprIsTrivial here, though, because we sometimes generate worker/wrapper
185 bindings like
186         fw = ...
187         f  = inline_me (coerce t fw)
188 As usual, the inline_me prevents the worker from getting inlined back into the wrapper.
189 We want the split, so that the coerces can cancel at the call site.  
190
191 However, we can get left with tiresome type applications.  Notably, consider
192         f = /\ a -> let t = e in (t, w)
193 Then lifting the let out of the big lambda gives
194         t' = /\a -> e
195         f = /\ a -> let t = inline_me (t' a) in (t, w)
196 The inline_me is to stop the simplifier inlining t' right back
197 into t's RHS.  In the next phase we'll substitute for t (since
198 its rhs is trivial) and *then* we could get rid of the inline_me.
199 But it hardly seems worth it, so I don't bother.
200
201 \begin{code}
202 -- | Wraps the given expression in an inlining hint unless the expression
203 -- is trivial in some sense, so that doing so would usually hurt us
204 mkInlineMe :: CoreExpr -> CoreExpr
205 mkInlineMe (Var v) = Var v
206 mkInlineMe e       = Note InlineMe e
207 \end{code}
208
209 \begin{code}
210 -- | Wrap the given expression in the coercion, dropping identity coercions and coalescing nested coercions
211 mkCoerceI :: CoercionI -> CoreExpr -> CoreExpr
212 mkCoerceI IdCo e = e
213 mkCoerceI (ACo co) e = mkCoerce co e
214
215 -- | Wrap the given expression in the coercion safely, coalescing nested coercions
216 mkCoerce :: Coercion -> CoreExpr -> CoreExpr
217 mkCoerce co (Cast expr co2)
218   = ASSERT(let { (from_ty, _to_ty) = coercionKind co; 
219                  (_from_ty2, to_ty2) = coercionKind co2} in
220            from_ty `coreEqType` to_ty2 )
221     mkCoerce (mkTransCoercion co2 co) expr
222
223 mkCoerce co expr 
224   = let (from_ty, _to_ty) = coercionKind co in
225 --    if to_ty `coreEqType` from_ty
226 --    then expr
227 --    else 
228         ASSERT2(from_ty `coreEqType` (exprType expr), text "Trying to coerce" <+> text "(" <> ppr expr $$ text "::" <+> ppr (exprType expr) <> text ")" $$ ppr co $$ ppr (coercionKindPredTy co))
229          (Cast expr co)
230 \end{code}
231
232 \begin{code}
233 -- | Wraps the given expression in the cost centre unless
234 -- in a way that maximises their utility to the user
235 mkSCC :: CostCentre -> Expr b -> Expr b
236         -- Note: Nested SCC's *are* preserved for the benefit of
237         --       cost centre stack profiling
238 mkSCC _  (Lit lit)          = Lit lit
239 mkSCC cc (Lam x e)          = Lam x (mkSCC cc e)  -- Move _scc_ inside lambda
240 mkSCC cc (Note (SCC cc') e) = Note (SCC cc) (Note (SCC cc') e)
241 mkSCC cc (Note n e)         = Note n (mkSCC cc e) -- Move _scc_ inside notes
242 mkSCC cc (Cast e co)        = Cast (mkSCC cc e) co -- Move _scc_ inside cast
243 mkSCC cc expr               = Note (SCC cc) expr
244 \end{code}
245
246
247 %************************************************************************
248 %*                                                                      *
249 \subsection{Other expression construction}
250 %*                                                                      *
251 %************************************************************************
252
253 \begin{code}
254 bindNonRec :: Id -> CoreExpr -> CoreExpr -> CoreExpr
255 -- ^ @bindNonRec x r b@ produces either:
256 --
257 -- > let x = r in b
258 --
259 -- or:
260 --
261 -- > case r of x { _DEFAULT_ -> b }
262 --
263 -- depending on whether we have to use a @case@ or @let@
264 -- binding for the expression (see 'needsCaseBinding').
265 -- It's used by the desugarer to avoid building bindings
266 -- that give Core Lint a heart attack, although actually
267 -- the simplifier deals with them perfectly well. See
268 -- also 'MkCore.mkCoreLet'
269 bindNonRec bndr rhs body 
270   | needsCaseBinding (idType bndr) rhs = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
271   | otherwise                          = Let (NonRec bndr rhs) body
272
273 -- | Tests whether we have to use a @case@ rather than @let@ binding for this expression
274 -- as per the invariants of 'CoreExpr': see "CoreSyn#let_app_invariant"
275 needsCaseBinding :: Type -> CoreExpr -> Bool
276 needsCaseBinding ty rhs = isUnLiftedType ty && not (exprOkForSpeculation rhs)
277         -- Make a case expression instead of a let
278         -- These can arise either from the desugarer,
279         -- or from beta reductions: (\x.e) (x +# y)
280 \end{code}
281
282 \begin{code}
283 mkAltExpr :: AltCon     -- ^ Case alternative constructor
284           -> [CoreBndr] -- ^ Things bound by the pattern match
285           -> [Type]     -- ^ The type arguments to the case alternative
286           -> CoreExpr
287 -- ^ This guy constructs the value that the scrutinee must have
288 -- given that you are in one particular branch of a case
289 mkAltExpr (DataAlt con) args inst_tys
290   = mkConApp con (map Type inst_tys ++ varsToCoreExprs args)
291 mkAltExpr (LitAlt lit) [] []
292   = Lit lit
293 mkAltExpr (LitAlt _) _ _ = panic "mkAltExpr LitAlt"
294 mkAltExpr DEFAULT _ _ = panic "mkAltExpr DEFAULT"
295 \end{code}
296
297
298 %************************************************************************
299 %*                                                                      *
300 \subsection{Taking expressions apart}
301 %*                                                                      *
302 %************************************************************************
303
304 The default alternative must be first, if it exists at all.
305 This makes it easy to find, though it makes matching marginally harder.
306
307 \begin{code}
308 -- | Extract the default case alternative
309 findDefault :: [CoreAlt] -> ([CoreAlt], Maybe CoreExpr)
310 findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null args ) (alts, Just rhs)
311 findDefault alts                        =                     (alts, Nothing)
312
313 -- | Find the case alternative corresponding to a particular 
314 -- constructor: panics if no such constructor exists
315 findAlt :: AltCon -> [CoreAlt] -> CoreAlt
316 findAlt con alts
317   = case alts of
318         (deflt@(DEFAULT,_,_):alts) -> go alts deflt
319         _                          -> go alts panic_deflt
320   where
321     panic_deflt = pprPanic "Missing alternative" (ppr con $$ vcat (map ppr alts))
322
323     go []                      deflt = deflt
324     go (alt@(con1,_,_) : alts) deflt
325       = case con `cmpAltCon` con1 of
326           LT -> deflt   -- Missed it already; the alts are in increasing order
327           EQ -> alt
328           GT -> ASSERT( not (con1 == DEFAULT) ) go alts deflt
329
330 isDefaultAlt :: CoreAlt -> Bool
331 isDefaultAlt (DEFAULT, _, _) = True
332 isDefaultAlt _               = False
333
334 ---------------------------------
335 mergeAlts :: [CoreAlt] -> [CoreAlt] -> [CoreAlt]
336 -- ^ Merge alternatives preserving order; alternatives in
337 -- the first argument shadow ones in the second
338 mergeAlts [] as2 = as2
339 mergeAlts as1 [] = as1
340 mergeAlts (a1:as1) (a2:as2)
341   = case a1 `cmpAlt` a2 of
342         LT -> a1 : mergeAlts as1      (a2:as2)
343         EQ -> a1 : mergeAlts as1      as2       -- Discard a2
344         GT -> a2 : mergeAlts (a1:as1) as2
345
346
347 ---------------------------------
348 trimConArgs :: AltCon -> [CoreArg] -> [CoreArg]
349 -- ^ Given:
350 --
351 -- > case (C a b x y) of
352 -- >        C b x y -> ...
353 --
354 -- We want to drop the leading type argument of the scrutinee
355 -- leaving the arguments to match agains the pattern
356
357 trimConArgs DEFAULT      args = ASSERT( null args ) []
358 trimConArgs (LitAlt _)   args = ASSERT( null args ) []
359 trimConArgs (DataAlt dc) args = dropList (dataConUnivTyVars dc) args
360 \end{code}
361
362
363 %************************************************************************
364 %*                                                                      *
365 \subsection{Figuring out things about expressions}
366 %*                                                                      *
367 %************************************************************************
368
369 @exprIsTrivial@ is true of expressions we are unconditionally happy to
370                 duplicate; simple variables and constants, and type
371                 applications.  Note that primop Ids aren't considered
372                 trivial unless 
373
374 There used to be a gruesome test for (hasNoBinding v) in the
375 Var case:
376         exprIsTrivial (Var v) | hasNoBinding v = idArity v == 0
377 The idea here is that a constructor worker, like \$wJust, is
378 really short for (\x -> \$wJust x), becuase \$wJust has no binding.
379 So it should be treated like a lambda.  Ditto unsaturated primops.
380 But now constructor workers are not "have-no-binding" Ids.  And
381 completely un-applied primops and foreign-call Ids are sufficiently
382 rare that I plan to allow them to be duplicated and put up with
383 saturating them.
384
385 SCC notes.  We do not treat (_scc_ "foo" x) as trivial, because 
386   a) it really generates code, (and a heap object when it's 
387      a function arg) to capture the cost centre
388   b) see the note [SCC-and-exprIsTrivial] in Simplify.simplLazyBind
389
390 \begin{code}
391 exprIsTrivial :: CoreExpr -> Bool
392 exprIsTrivial (Var _)          = True        -- See notes above
393 exprIsTrivial (Type _)         = True
394 exprIsTrivial (Lit lit)        = litIsTrivial lit
395 exprIsTrivial (App e arg)      = not (isRuntimeArg arg) && exprIsTrivial e
396 exprIsTrivial (Note (SCC _) _) = False       -- See notes above
397 exprIsTrivial (Note _       e) = exprIsTrivial e
398 exprIsTrivial (Cast e _)       = exprIsTrivial e
399 exprIsTrivial (Lam b body)     = not (isRuntimeVar b) && exprIsTrivial body
400 exprIsTrivial _                = False
401 \end{code}
402
403
404 @exprIsDupable@ is true of expressions that can be duplicated at a modest
405                 cost in code size.  This will only happen in different case
406                 branches, so there's no issue about duplicating work.
407
408                 That is, exprIsDupable returns True of (f x) even if
409                 f is very very expensive to call.
410
411                 Its only purpose is to avoid fruitless let-binding
412                 and then inlining of case join points
413
414
415 \begin{code}
416 exprIsDupable :: CoreExpr -> Bool
417 exprIsDupable (Type _)          = True
418 exprIsDupable (Var _)           = True
419 exprIsDupable (Lit lit)         = litIsDupable lit
420 exprIsDupable (Note InlineMe _) = True
421 exprIsDupable (Note _ e)        = exprIsDupable e
422 exprIsDupable (Cast e _)        = exprIsDupable e
423 exprIsDupable expr
424   = go expr 0
425   where
426     go (Var _)   _      = True
427     go (App f a) n_args =  n_args < dupAppSize
428                         && exprIsDupable a
429                         && go f (n_args+1)
430     go _         _      = False
431
432 dupAppSize :: Int
433 dupAppSize = 4          -- Size of application we are prepared to duplicate
434 \end{code}
435
436 @exprIsCheap@ looks at a Core expression and returns \tr{True} if
437 it is obviously in weak head normal form, or is cheap to get to WHNF.
438 [Note that that's not the same as exprIsDupable; an expression might be
439 big, and hence not dupable, but still cheap.]
440
441 By ``cheap'' we mean a computation we're willing to:
442         push inside a lambda, or
443         inline at more than one place
444 That might mean it gets evaluated more than once, instead of being
445 shared.  The main examples of things which aren't WHNF but are
446 ``cheap'' are:
447
448   *     case e of
449           pi -> ei
450         (where e, and all the ei are cheap)
451
452   *     let x = e in b
453         (where e and b are cheap)
454
455   *     op x1 ... xn
456         (where op is a cheap primitive operator)
457
458   *     error "foo"
459         (because we are happy to substitute it inside a lambda)
460
461 Notice that a variable is considered 'cheap': we can push it inside a lambda,
462 because sharing will make sure it is only evaluated once.
463
464 \begin{code}
465 exprIsCheap :: CoreExpr -> Bool
466 exprIsCheap (Lit _)           = True
467 exprIsCheap (Type _)          = True
468 exprIsCheap (Var _)           = True
469 exprIsCheap (Note InlineMe _) = True
470 exprIsCheap (Note _ e)        = exprIsCheap e
471 exprIsCheap (Cast e _)        = exprIsCheap e
472 exprIsCheap (Lam x e)         = isRuntimeVar x || exprIsCheap e
473 exprIsCheap (Case e _ _ alts) = exprIsCheap e && 
474                                 and [exprIsCheap rhs | (_,_,rhs) <- alts]
475         -- Experimentally, treat (case x of ...) as cheap
476         -- (and case __coerce x etc.)
477         -- This improves arities of overloaded functions where
478         -- there is only dictionary selection (no construction) involved
479 exprIsCheap (Let (NonRec x _) e)  
480       | isUnLiftedType (idType x) = exprIsCheap e
481       | otherwise                 = False
482         -- strict lets always have cheap right hand sides,
483         -- and do no allocation.
484
485 exprIsCheap other_expr  -- Applications and variables
486   = go other_expr []
487   where
488         -- Accumulate value arguments, then decide
489     go (App f a) val_args | isRuntimeArg a = go f (a:val_args)
490                           | otherwise      = go f val_args
491
492     go (Var _) [] = True        -- Just a type application of a variable
493                                 -- (f t1 t2 t3) counts as WHNF
494     go (Var f) args
495         = case idDetails f of
496                 RecSelId {}  -> go_sel args
497                 ClassOpId _  -> go_sel args
498                 PrimOpId op  -> go_primop op args
499
500                 DataConWorkId _ -> go_pap args
501                 _ | length args < idArity f -> go_pap args
502
503                 _ -> isBottomingId f
504                         -- Application of a function which
505                         -- always gives bottom; we treat this as cheap
506                         -- because it certainly doesn't need to be shared!
507         
508     go _ _ = False
509  
510     --------------
511     go_pap args = all exprIsTrivial args
512         -- For constructor applications and primops, check that all
513         -- the args are trivial.  We don't want to treat as cheap, say,
514         --      (1:2:3:4:5:[])
515         -- We'll put up with one constructor application, but not dozens
516         
517     --------------
518     go_primop op args = primOpIsCheap op && all exprIsCheap args
519         -- In principle we should worry about primops
520         -- that return a type variable, since the result
521         -- might be applied to something, but I'm not going
522         -- to bother to check the number of args
523  
524     --------------
525     go_sel [arg] = exprIsCheap arg      -- I'm experimenting with making record selection
526     go_sel _     = False                -- look cheap, so we will substitute it inside a
527                                         -- lambda.  Particularly for dictionary field selection.
528                 -- BUT: Take care with (sel d x)!  The (sel d) might be cheap, but
529                 --      there's no guarantee that (sel d x) will be too.  Hence (n_val_args == 1)
530 \end{code}
531
532 \begin{code}
533 -- | 'exprOkForSpeculation' returns True of an expression that is:
534 --
535 --  * Safe to evaluate even if normal order eval might not 
536 --    evaluate the expression at all, or
537 --
538 --  * Safe /not/ to evaluate even if normal order would do so
539 --
540 -- Precisely, it returns @True@ iff:
541 --
542 --  * The expression guarantees to terminate, 
543 --
544 --  * soon, 
545 --
546 --  * without raising an exception,
547 --
548 --  * without causing a side effect (e.g. writing a mutable variable)
549 --
550 -- Note that if @exprIsHNF e@, then @exprOkForSpecuation e@.
551 -- As an example of the considerations in this test, consider:
552 --
553 -- > let x = case y# +# 1# of { r# -> I# r# }
554 -- > in E
555 --
556 -- being translated to:
557 --
558 -- > case y# +# 1# of { r# -> 
559 -- >    let x = I# r#
560 -- >    in E 
561 -- > }
562 -- 
563 -- We can only do this if the @y + 1@ is ok for speculation: it has no
564 -- side effects, and can't diverge or raise an exception.
565 exprOkForSpeculation :: CoreExpr -> Bool
566 exprOkForSpeculation (Lit _)     = True
567 exprOkForSpeculation (Type _)    = True
568     -- Tick boxes are *not* suitable for speculation
569 exprOkForSpeculation (Var v)     = isUnLiftedType (idType v)
570                                  && not (isTickBoxOp v)
571 exprOkForSpeculation (Note _ e)  = exprOkForSpeculation e
572 exprOkForSpeculation (Cast e _)  = exprOkForSpeculation e
573 exprOkForSpeculation other_expr
574   = case collectArgs other_expr of
575         (Var f, args) -> spec_ok (idDetails f) args
576         _             -> False
577  
578   where
579     spec_ok (DataConWorkId _) _
580       = True    -- The strictness of the constructor has already
581                 -- been expressed by its "wrapper", so we don't need
582                 -- to take the arguments into account
583
584     spec_ok (PrimOpId op) args
585       | isDivOp op,             -- Special case for dividing operations that fail
586         [arg1, Lit lit] <- args -- only if the divisor is zero
587       = not (isZeroLit lit) && exprOkForSpeculation arg1
588                 -- Often there is a literal divisor, and this 
589                 -- can get rid of a thunk in an inner looop
590
591       | otherwise
592       = primOpOkForSpeculation op && 
593         all exprOkForSpeculation args
594                                 -- A bit conservative: we don't really need
595                                 -- to care about lazy arguments, but this is easy
596
597     spec_ok _ _ = False
598
599 -- | True of dyadic operators that can fail only if the second arg is zero!
600 isDivOp :: PrimOp -> Bool
601 -- This function probably belongs in PrimOp, or even in 
602 -- an automagically generated file.. but it's such a 
603 -- special case I thought I'd leave it here for now.
604 isDivOp IntQuotOp        = True
605 isDivOp IntRemOp         = True
606 isDivOp WordQuotOp       = True
607 isDivOp WordRemOp        = True
608 isDivOp IntegerQuotRemOp = True
609 isDivOp IntegerDivModOp  = True
610 isDivOp FloatDivOp       = True
611 isDivOp DoubleDivOp      = True
612 isDivOp _                = False
613 \end{code}
614
615 \begin{code}
616 -- | True of expressions that are guaranteed to diverge upon execution
617 exprIsBottom :: CoreExpr -> Bool
618 exprIsBottom e = go 0 e
619                where
620                 -- n is the number of args
621                  go n (Note _ e)     = go n e
622                  go n (Cast e _)     = go n e
623                  go n (Let _ e)      = go n e
624                  go _ (Case e _ _ _) = go 0 e   -- Just check the scrut
625                  go n (App e _)      = go (n+1) e
626                  go n (Var v)        = idAppIsBottom v n
627                  go _ (Lit _)        = False
628                  go _ (Lam _ _)      = False
629                  go _ (Type _)       = False
630
631 idAppIsBottom :: Id -> Int -> Bool
632 idAppIsBottom id n_val_args = appIsBottom (idNewStrictness id) n_val_args
633 \end{code}
634
635 \begin{code}
636
637 -- | This returns true for expressions that are certainly /already/ 
638 -- evaluated to /head/ normal form.  This is used to decide whether it's ok 
639 -- to change:
640 --
641 -- > case x of _ -> e
642 --
643 -- into:
644 --
645 -- > e
646 --
647 -- and to decide whether it's safe to discard a 'seq'.
648 -- So, it does /not/ treat variables as evaluated, unless they say they are.
649 -- However, it /does/ treat partial applications and constructor applications
650 -- as values, even if their arguments are non-trivial, provided the argument
651 -- type is lifted. For example, both of these are values:
652 --
653 -- > (:) (f x) (map f xs)
654 -- > map (...redex...)
655 --
656 -- Because 'seq' on such things completes immediately.
657 --
658 -- For unlifted argument types, we have to be careful:
659 --
660 -- > C (f x :: Int#)
661 --
662 -- Suppose @f x@ diverges; then @C (f x)@ is not a value. However this can't 
663 -- happen: see "CoreSyn#let_app_invariant". This invariant states that arguments of
664 -- unboxed type must be ok-for-speculation (or trivial).
665 exprIsHNF :: CoreExpr -> Bool           -- True => Value-lambda, constructor, PAP
666 exprIsHNF (Var v)       -- NB: There are no value args at this point
667   =  isDataConWorkId v  -- Catches nullary constructors, 
668                         --      so that [] and () are values, for example
669   || idArity v > 0      -- Catches (e.g.) primops that don't have unfoldings
670   || isEvaldUnfolding (idUnfolding v)
671         -- Check the thing's unfolding; it might be bound to a value
672         -- A worry: what if an Id's unfolding is just itself: 
673         -- then we could get an infinite loop...
674
675 exprIsHNF (Lit _)          = True
676 exprIsHNF (Type _)         = True       -- Types are honorary Values;
677                                         -- we don't mind copying them
678 exprIsHNF (Lam b e)        = isRuntimeVar b || exprIsHNF e
679 exprIsHNF (Note _ e)       = exprIsHNF e
680 exprIsHNF (Cast e _)       = exprIsHNF e
681 exprIsHNF (App e (Type _)) = exprIsHNF e
682 exprIsHNF (App e a)        = app_is_value e [a]
683 exprIsHNF _                = False
684
685 -- There is at least one value argument
686 app_is_value :: CoreExpr -> [CoreArg] -> Bool
687 app_is_value (Var fun) args
688   = idArity fun > valArgCount args      -- Under-applied function
689     ||  isDataConWorkId fun             --  or data constructor
690 app_is_value (Note _ f) as = app_is_value f as
691 app_is_value (Cast f _) as = app_is_value f as
692 app_is_value (App f a)  as = app_is_value f (a:as)
693 app_is_value _          _  = False
694 \end{code}
695
696 These InstPat functions go here to avoid circularity between DataCon and Id
697
698 \begin{code}
699 dataConRepInstPat, dataConOrigInstPat :: [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
700 dataConRepFSInstPat :: [FastString] -> [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
701
702 dataConRepInstPat   = dataConInstPat dataConRepArgTys (repeat ((fsLit "ipv")))
703 dataConRepFSInstPat = dataConInstPat dataConRepArgTys
704 dataConOrigInstPat  = dataConInstPat dc_arg_tys       (repeat ((fsLit "ipv")))
705   where 
706     dc_arg_tys dc = map mkPredTy (dataConEqTheta dc) ++ map mkPredTy (dataConDictTheta dc) ++ dataConOrigArgTys dc
707         -- Remember to include the existential dictionaries
708
709 dataConInstPat :: (DataCon -> [Type])      -- function used to find arg tys
710                   -> [FastString]          -- A long enough list of FSs to use for names
711                   -> [Unique]              -- An equally long list of uniques, at least one for each binder
712                   -> DataCon
713                   -> [Type]                -- Types to instantiate the universally quantified tyvars
714                -> ([TyVar], [CoVar], [Id]) -- Return instantiated variables
715 -- dataConInstPat arg_fun fss us con inst_tys returns a triple 
716 -- (ex_tvs, co_tvs, arg_ids),
717 --
718 --   ex_tvs are intended to be used as binders for existential type args
719 --
720 --   co_tvs are intended to be used as binders for coercion args and the kinds
721 --     of these vars have been instantiated by the inst_tys and the ex_tys
722 --     The co_tvs include both GADT equalities (dcEqSpec) and 
723 --     programmer-specified equalities (dcEqTheta)
724 --
725 --   arg_ids are indended to be used as binders for value arguments, 
726 --     and their types have been instantiated with inst_tys and ex_tys
727 --     The arg_ids include both dicts (dcDictTheta) and
728 --     programmer-specified arguments (after rep-ing) (deRepArgTys)
729 --
730 -- Example.
731 --  The following constructor T1
732 --
733 --  data T a where
734 --    T1 :: forall b. Int -> b -> T(a,b)
735 --    ...
736 --
737 --  has representation type 
738 --   forall a. forall a1. forall b. (a ~ (a1,b)) => 
739 --     Int -> b -> T a
740 --
741 --  dataConInstPat fss us T1 (a1',b') will return
742 --
743 --  ([a1'', b''], [c :: (a1', b')~(a1'', b'')], [x :: Int, y :: b''])
744 --
745 --  where the double-primed variables are created with the FastStrings and
746 --  Uniques given as fss and us
747 dataConInstPat arg_fun fss uniqs con inst_tys 
748   = (ex_bndrs, co_bndrs, arg_ids)
749   where 
750     univ_tvs = dataConUnivTyVars con
751     ex_tvs   = dataConExTyVars con
752     arg_tys  = arg_fun con
753     eq_spec  = dataConEqSpec con
754     eq_theta = dataConEqTheta con
755     eq_preds = eqSpecPreds eq_spec ++ eq_theta
756
757     n_ex = length ex_tvs
758     n_co = length eq_preds
759
760       -- split the Uniques and FastStrings
761     (ex_uniqs, uniqs')   = splitAt n_ex uniqs
762     (co_uniqs, id_uniqs) = splitAt n_co uniqs'
763
764     (ex_fss, fss')     = splitAt n_ex fss
765     (co_fss, id_fss)   = splitAt n_co fss'
766
767       -- Make existential type variables
768     ex_bndrs = zipWith3 mk_ex_var ex_uniqs ex_fss ex_tvs
769     mk_ex_var uniq fs var = mkTyVar new_name kind
770       where
771         new_name = mkSysTvName uniq fs
772         kind     = tyVarKind var
773
774       -- Make the instantiating substitution
775     subst = zipOpenTvSubst (univ_tvs ++ ex_tvs) (inst_tys ++ map mkTyVarTy ex_bndrs)
776
777       -- Make new coercion vars, instantiating kind
778     co_bndrs = zipWith3 mk_co_var co_uniqs co_fss eq_preds
779     mk_co_var uniq fs eq_pred = mkCoVar new_name co_kind
780        where
781          new_name = mkSysTvName uniq fs
782          co_kind  = substTy subst (mkPredTy eq_pred)
783
784       -- make value vars, instantiating types
785     mk_id_var uniq fs ty = mkUserLocal (mkVarOccFS fs) uniq (substTy subst ty) noSrcSpan
786     arg_ids = zipWith3 mk_id_var id_uniqs id_fss arg_tys
787
788 -- | Returns @Just (dc, [x1..xn])@ if the argument expression is 
789 -- a constructor application of the form @dc x1 .. xn@
790 exprIsConApp_maybe :: CoreExpr -> Maybe (DataCon, [CoreExpr])
791 exprIsConApp_maybe (Cast expr co)
792   =     -- Here we do the KPush reduction rule as described in the FC paper
793     case exprIsConApp_maybe expr of {
794         Nothing            -> Nothing ;
795         Just (dc, dc_args) -> 
796
797         -- The transformation applies iff we have
798         --      (C e1 ... en) `cast` co
799         -- where co :: (T t1 .. tn) ~ (T s1 ..sn)
800         -- That is, with a T at the top of both sides
801         -- The left-hand one must be a T, because exprIsConApp returned True
802         -- but the right-hand one might not be.  (Though it usually will.)
803
804     let (from_ty, to_ty)           = coercionKind co
805         (from_tc, from_tc_arg_tys) = splitTyConApp from_ty
806                 -- The inner one must be a TyConApp
807     in
808     case splitTyConApp_maybe to_ty of {
809         Nothing -> Nothing ;
810         Just (to_tc, to_tc_arg_tys) 
811                 | from_tc /= to_tc -> Nothing
812                 -- These two Nothing cases are possible; we might see 
813                 --      (C x y) `cast` (g :: T a ~ S [a]),
814                 -- where S is a type function.  In fact, exprIsConApp
815                 -- will probably not be called in such circumstances,
816                 -- but there't nothing wrong with it 
817
818                 | otherwise  ->
819     let
820         tc_arity = tyConArity from_tc
821
822         (univ_args, rest1)        = splitAt tc_arity dc_args
823         (ex_args, rest2)          = splitAt n_ex_tvs rest1
824         (co_args_spec, rest3)     = splitAt n_cos_spec rest2
825         (co_args_theta, val_args) = splitAt n_cos_theta rest3
826
827         arg_tys             = dataConRepArgTys dc
828         dc_univ_tyvars      = dataConUnivTyVars dc
829         dc_ex_tyvars        = dataConExTyVars dc
830         dc_eq_spec          = dataConEqSpec dc
831         dc_eq_theta         = dataConEqTheta dc
832         dc_tyvars           = dc_univ_tyvars ++ dc_ex_tyvars
833         n_ex_tvs            = length dc_ex_tyvars
834         n_cos_spec          = length dc_eq_spec
835         n_cos_theta         = length dc_eq_theta
836
837         -- Make the "theta" from Fig 3 of the paper
838         gammas              = decomposeCo tc_arity co
839         new_tys             = gammas ++ map (\ (Type t) -> t) ex_args
840         theta               = zipOpenTvSubst dc_tyvars new_tys
841
842           -- First we cast the existential coercion arguments
843         cast_co_spec (tv, ty) co 
844           = cast_co_theta (mkEqPred (mkTyVarTy tv, ty)) co
845         cast_co_theta eqPred (Type co) 
846           | (ty1, ty2) <- getEqPredTys eqPred
847           = Type $ mkSymCoercion (substTy theta ty1)
848                    `mkTransCoercion` co
849                    `mkTransCoercion` (substTy theta ty2)
850         new_co_args = zipWith cast_co_spec  dc_eq_spec  co_args_spec ++
851                       zipWith cast_co_theta dc_eq_theta co_args_theta
852   
853           -- ...and now value arguments
854         new_val_args = zipWith cast_arg arg_tys val_args
855         cast_arg arg_ty arg = mkCoerce (substTy theta arg_ty) arg
856
857     in
858     ASSERT( length univ_args == tc_arity )
859     ASSERT( from_tc == dataConTyCon dc )
860     ASSERT( and (zipWith coreEqType [t | Type t <- univ_args] from_tc_arg_tys) )
861     ASSERT( all isTypeArg (univ_args ++ ex_args) )
862     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  )
863
864     Just (dc, map Type to_tc_arg_tys ++ ex_args ++ new_co_args ++ new_val_args)
865     }}
866
867 {-
868 -- We do not want to tell the world that we have a
869 -- Cons, to *stop* Case of Known Cons, which removes
870 -- the TickBox.
871 exprIsConApp_maybe (Note (TickBox {}) expr)
872   = Nothing
873 exprIsConApp_maybe (Note (BinaryTickBox {}) expr)
874   = Nothing
875 -}
876
877 exprIsConApp_maybe (Note _ expr)
878   = exprIsConApp_maybe expr
879     -- We ignore InlineMe notes in case we have
880     --  x = __inline_me__ (a,b)
881     -- All part of making sure that INLINE pragmas never hurt
882     -- Marcin tripped on this one when making dictionaries more inlinable
883     --
884     -- In fact, we ignore all notes.  For example,
885     --          case _scc_ "foo" (C a b) of
886     --                  C a b -> e
887     -- should be optimised away, but it will be only if we look
888     -- through the SCC note.
889
890 exprIsConApp_maybe expr = analyse (collectArgs expr)
891   where
892     analyse (Var fun, args)
893         | Just con <- isDataConWorkId_maybe fun,
894           args `lengthAtLeast` dataConRepArity con
895                 -- Might be > because the arity excludes type args
896         = Just (con,args)
897
898         -- Look through unfoldings, but only cheap ones, because
899         -- we are effectively duplicating the unfolding
900     analyse (Var fun, [])
901         | let unf = idUnfolding fun,
902           isCheapUnfolding unf
903         = exprIsConApp_maybe (unfoldingTemplate unf)
904
905     analyse _ = Nothing
906 \end{code}
907
908
909
910 %************************************************************************
911 %*                                                                      *
912 \subsection{Equality}
913 %*                                                                      *
914 %************************************************************************
915
916 \begin{code}
917 -- | A cheap equality test which bales out fast!
918 --      If it returns @True@ the arguments are definitely equal,
919 --      otherwise, they may or may not be equal.
920 --
921 -- See also 'exprIsBig'
922 cheapEqExpr :: Expr b -> Expr b -> Bool
923
924 cheapEqExpr (Var v1)   (Var v2)   = v1==v2
925 cheapEqExpr (Lit lit1) (Lit lit2) = lit1 == lit2
926 cheapEqExpr (Type t1)  (Type t2)  = t1 `coreEqType` t2
927
928 cheapEqExpr (App f1 a1) (App f2 a2)
929   = f1 `cheapEqExpr` f2 && a1 `cheapEqExpr` a2
930
931 cheapEqExpr (Cast e1 t1) (Cast e2 t2)
932   = e1 `cheapEqExpr` e2 && t1 `coreEqCoercion` t2
933
934 cheapEqExpr _ _ = False
935
936 exprIsBig :: Expr b -> Bool
937 -- ^ Returns @True@ of expressions that are too big to be compared by 'cheapEqExpr'
938 exprIsBig (Lit _)      = False
939 exprIsBig (Var _)      = False
940 exprIsBig (Type _)     = False
941 exprIsBig (App f a)    = exprIsBig f || exprIsBig a
942 exprIsBig (Cast e _)   = exprIsBig e    -- Hopefully coercions are not too big!
943 exprIsBig _            = True
944 \end{code}
945
946
947 \begin{code}
948 tcEqExpr :: CoreExpr -> CoreExpr -> Bool
949 -- ^ A kind of shallow equality used in rule matching, so does 
950 -- /not/ look through newtypes or predicate types
951
952 tcEqExpr e1 e2 = tcEqExprX rn_env e1 e2
953   where
954     rn_env = mkRnEnv2 (mkInScopeSet (exprFreeVars e1 `unionVarSet` exprFreeVars e2))
955
956 tcEqExprX :: RnEnv2 -> CoreExpr -> CoreExpr -> Bool
957 tcEqExprX env (Var v1)     (Var v2)     = rnOccL env v1 == rnOccR env v2
958 tcEqExprX _   (Lit lit1)   (Lit lit2)   = lit1 == lit2
959 tcEqExprX env (App f1 a1)  (App f2 a2)  = tcEqExprX env f1 f2 && tcEqExprX env a1 a2
960 tcEqExprX env (Lam v1 e1)  (Lam v2 e2)  = tcEqExprX (rnBndr2 env v1 v2) e1 e2
961 tcEqExprX env (Let (NonRec v1 r1) e1)
962               (Let (NonRec v2 r2) e2)   = tcEqExprX env r1 r2 
963                                        && tcEqExprX (rnBndr2 env v1 v2) e1 e2
964 tcEqExprX env (Let (Rec ps1) e1)
965               (Let (Rec ps2) e2)        =  equalLength ps1 ps2
966                                         && and (zipWith eq_rhs ps1 ps2)
967                                         && tcEqExprX env' e1 e2
968                                      where
969                                        env' = foldl2 rn_bndr2 env ps2 ps2
970                                        rn_bndr2 env (b1,_) (b2,_) = rnBndr2 env b1 b2
971                                        eq_rhs       (_,r1) (_,r2) = tcEqExprX env' r1 r2
972 tcEqExprX env (Case e1 v1 t1 a1)
973               (Case e2 v2 t2 a2)     =  tcEqExprX env e1 e2
974                                      && tcEqTypeX env t1 t2                      
975                                      && equalLength a1 a2
976                                      && and (zipWith (eq_alt env') a1 a2)
977                                      where
978                                        env' = rnBndr2 env v1 v2
979
980 tcEqExprX env (Note n1 e1)  (Note n2 e2)  = eq_note env n1 n2 && tcEqExprX env e1 e2
981 tcEqExprX env (Cast e1 co1) (Cast e2 co2) = tcEqTypeX env co1 co2 && tcEqExprX env e1 e2
982 tcEqExprX env (Type t1)     (Type t2)     = tcEqTypeX env t1 t2
983 tcEqExprX _   _             _             = False
984
985 eq_alt :: RnEnv2 -> CoreAlt -> CoreAlt -> Bool
986 eq_alt env (c1,vs1,r1) (c2,vs2,r2) = c1==c2 && tcEqExprX (rnBndrs2 env vs1  vs2) r1 r2
987
988 eq_note :: RnEnv2 -> Note -> Note -> Bool
989 eq_note _ (SCC cc1)     (SCC cc2)      = cc1 == cc2
990 eq_note _ (CoreNote s1) (CoreNote s2)  = s1 == s2
991 eq_note _ _             _              = False
992 \end{code}
993
994
995 %************************************************************************
996 %*                                                                      *
997 \subsection{The size of an expression}
998 %*                                                                      *
999 %************************************************************************
1000
1001 \begin{code}
1002 coreBindsSize :: [CoreBind] -> Int
1003 coreBindsSize bs = foldr ((+) . bindSize) 0 bs
1004
1005 exprSize :: CoreExpr -> Int
1006 -- ^ A measure of the size of the expressions, strictly greater than 0
1007 -- It also forces the expression pretty drastically as a side effect
1008 exprSize (Var v)         = v `seq` 1
1009 exprSize (Lit lit)       = lit `seq` 1
1010 exprSize (App f a)       = exprSize f + exprSize a
1011 exprSize (Lam b e)       = varSize b + exprSize e
1012 exprSize (Let b e)       = bindSize b + exprSize e
1013 exprSize (Case e b t as) = seqType t `seq` exprSize e + varSize b + 1 + foldr ((+) . altSize) 0 as
1014 exprSize (Cast e co)     = (seqType co `seq` 1) + exprSize e
1015 exprSize (Note n e)      = noteSize n + exprSize e
1016 exprSize (Type t)        = seqType t `seq` 1
1017
1018 noteSize :: Note -> Int
1019 noteSize (SCC cc)       = cc `seq` 1
1020 noteSize InlineMe       = 1
1021 noteSize (CoreNote s)   = s `seq` 1  -- hdaume: core annotations
1022  
1023 varSize :: Var -> Int
1024 varSize b  | isTyVar b = 1
1025            | otherwise = seqType (idType b)             `seq`
1026                          megaSeqIdInfo (idInfo b)       `seq`
1027                          1
1028
1029 varsSize :: [Var] -> Int
1030 varsSize = sum . map varSize
1031
1032 bindSize :: CoreBind -> Int
1033 bindSize (NonRec b e) = varSize b + exprSize e
1034 bindSize (Rec prs)    = foldr ((+) . pairSize) 0 prs
1035
1036 pairSize :: (Var, CoreExpr) -> Int
1037 pairSize (b,e) = varSize b + exprSize e
1038
1039 altSize :: CoreAlt -> Int
1040 altSize (c,bs,e) = c `seq` varsSize bs + exprSize e
1041 \end{code}
1042
1043
1044 %************************************************************************
1045 %*                                                                      *
1046 \subsection{Hashing}
1047 %*                                                                      *
1048 %************************************************************************
1049
1050 \begin{code}
1051 hashExpr :: CoreExpr -> Int
1052 -- ^ Two expressions that hash to the same @Int@ may be equal (but may not be)
1053 -- Two expressions that hash to the different Ints are definitely unequal.
1054 --
1055 -- The emphasis is on a crude, fast hash, rather than on high precision.
1056 -- 
1057 -- But unequal here means \"not identical\"; two alpha-equivalent 
1058 -- expressions may hash to the different Ints.
1059 --
1060 -- We must be careful that @\\x.x@ and @\\y.y@ map to the same hash code,
1061 -- (at least if we want the above invariant to be true).
1062
1063 hashExpr e = fromIntegral (hash_expr (1,emptyVarEnv) e .&. 0x7fffffff)
1064              -- UniqFM doesn't like negative Ints
1065
1066 type HashEnv = (Int, VarEnv Int)  -- Hash code for bound variables
1067
1068 hash_expr :: HashEnv -> CoreExpr -> Word32
1069 -- Word32, because we're expecting overflows here, and overflowing
1070 -- signed types just isn't cool.  In C it's even undefined.
1071 hash_expr env (Note _ e)              = hash_expr env e
1072 hash_expr env (Cast e _)              = hash_expr env e
1073 hash_expr env (Var v)                 = hashVar env v
1074 hash_expr _   (Lit lit)               = fromIntegral (hashLiteral lit)
1075 hash_expr env (App f e)               = hash_expr env f * fast_hash_expr env e
1076 hash_expr env (Let (NonRec b r) e)    = hash_expr (extend_env env b) e * fast_hash_expr env r
1077 hash_expr env (Let (Rec ((b,_):_)) e) = hash_expr (extend_env env b) e
1078 hash_expr env (Case e _ _ _)          = hash_expr env e
1079 hash_expr env (Lam b e)               = hash_expr (extend_env env b) e
1080 hash_expr _   (Type _)                = WARN(True, text "hash_expr: type") 1
1081 -- Shouldn't happen.  Better to use WARN than trace, because trace
1082 -- prevents the CPR optimisation kicking in for hash_expr.
1083
1084 fast_hash_expr :: HashEnv -> CoreExpr -> Word32
1085 fast_hash_expr env (Var v)      = hashVar env v
1086 fast_hash_expr env (Type t)     = fast_hash_type env t
1087 fast_hash_expr _   (Lit lit)    = fromIntegral (hashLiteral lit)
1088 fast_hash_expr env (Cast e _)   = fast_hash_expr env e
1089 fast_hash_expr env (Note _ e)   = fast_hash_expr env e
1090 fast_hash_expr env (App _ a)    = fast_hash_expr env a  -- A bit idiosyncratic ('a' not 'f')!
1091 fast_hash_expr _   _            = 1
1092
1093 fast_hash_type :: HashEnv -> Type -> Word32
1094 fast_hash_type env ty 
1095   | Just tv <- getTyVar_maybe ty            = hashVar env tv
1096   | Just (tc,tys) <- splitTyConApp_maybe ty = let hash_tc = fromIntegral (hashName (tyConName tc))
1097                                               in foldr (\t n -> fast_hash_type env t + n) hash_tc tys
1098   | otherwise                               = 1
1099
1100 extend_env :: HashEnv -> Var -> (Int, VarEnv Int)
1101 extend_env (n,env) b = (n+1, extendVarEnv env b n)
1102
1103 hashVar :: HashEnv -> Var -> Word32
1104 hashVar (_,env) v
1105  = fromIntegral (lookupVarEnv env v `orElse` hashName (idName v))
1106 \end{code}
1107
1108 %************************************************************************
1109 %*                                                                      *
1110 \subsection{Determining non-updatable right-hand-sides}
1111 %*                                                                      *
1112 %************************************************************************
1113
1114 Top-level constructor applications can usually be allocated
1115 statically, but they can't if the constructor, or any of the
1116 arguments, come from another DLL (because we can't refer to static
1117 labels in other DLLs).
1118
1119 If this happens we simply make the RHS into an updatable thunk, 
1120 and 'execute' it rather than allocating it statically.
1121
1122 \begin{code}
1123 -- | This function is called only on *top-level* right-hand sides.
1124 -- Returns @True@ if the RHS can be allocated statically in the output,
1125 -- with no thunks involved at all.
1126 rhsIsStatic :: PackageId -> CoreExpr -> Bool
1127 -- It's called (i) in TidyPgm.hasCafRefs to decide if the rhs is, or
1128 -- refers to, CAFs; (ii) in CoreToStg to decide whether to put an
1129 -- update flag on it and (iii) in DsExpr to decide how to expand
1130 -- list literals
1131 --
1132 -- The basic idea is that rhsIsStatic returns True only if the RHS is
1133 --      (a) a value lambda
1134 --      (b) a saturated constructor application with static args
1135 --
1136 -- BUT watch out for
1137 --  (i) Any cross-DLL references kill static-ness completely
1138 --      because they must be 'executed' not statically allocated
1139 --      ("DLL" here really only refers to Windows DLLs, on other platforms,
1140 --      this is not necessary)
1141 --
1142 -- (ii) We treat partial applications as redexes, because in fact we 
1143 --      make a thunk for them that runs and builds a PAP
1144 --      at run-time.  The only appliations that are treated as 
1145 --      static are *saturated* applications of constructors.
1146
1147 -- We used to try to be clever with nested structures like this:
1148 --              ys = (:) w ((:) w [])
1149 -- on the grounds that CorePrep will flatten ANF-ise it later.
1150 -- But supporting this special case made the function much more 
1151 -- complicated, because the special case only applies if there are no 
1152 -- enclosing type lambdas:
1153 --              ys = /\ a -> Foo (Baz ([] a))
1154 -- Here the nested (Baz []) won't float out to top level in CorePrep.
1155 --
1156 -- But in fact, even without -O, nested structures at top level are 
1157 -- flattened by the simplifier, so we don't need to be super-clever here.
1158 --
1159 -- Examples
1160 --
1161 --      f = \x::Int. x+7        TRUE
1162 --      p = (True,False)        TRUE
1163 --
1164 --      d = (fst p, False)      FALSE because there's a redex inside
1165 --                              (this particular one doesn't happen but...)
1166 --
1167 --      h = D# (1.0## /## 2.0##)        FALSE (redex again)
1168 --      n = /\a. Nil a                  TRUE
1169 --
1170 --      t = /\a. (:) (case w a of ...) (Nil a)  FALSE (redex)
1171 --
1172 --
1173 -- This is a bit like CoreUtils.exprIsHNF, with the following differences:
1174 --    a) scc "foo" (\x -> ...) is updatable (so we catch the right SCC)
1175 --
1176 --    b) (C x xs), where C is a contructors is updatable if the application is
1177 --         dynamic
1178 -- 
1179 --    c) don't look through unfolding of f in (f x).
1180
1181 rhsIsStatic _this_pkg rhs = is_static False rhs
1182   where
1183   is_static :: Bool     -- True <=> in a constructor argument; must be atomic
1184           -> CoreExpr -> Bool
1185   
1186   is_static False (Lam b e) = isRuntimeVar b || is_static False e
1187   
1188   is_static _      (Note (SCC _) _) = False
1189   is_static in_arg (Note _ e)       = is_static in_arg e
1190   is_static in_arg (Cast e _)       = is_static in_arg e
1191   
1192   is_static _      (Lit lit)
1193     = case lit of
1194         MachLabel _ _ -> False
1195         _             -> True
1196         -- A MachLabel (foreign import "&foo") in an argument
1197         -- prevents a constructor application from being static.  The
1198         -- reason is that it might give rise to unresolvable symbols
1199         -- in the object file: under Linux, references to "weak"
1200         -- symbols from the data segment give rise to "unresolvable
1201         -- relocation" errors at link time This might be due to a bug
1202         -- in the linker, but we'll work around it here anyway. 
1203         -- SDM 24/2/2004
1204   
1205   is_static in_arg other_expr = go other_expr 0
1206    where
1207     go (Var f) n_val_args
1208 #if mingw32_TARGET_OS
1209         | not (isDllName _this_pkg (idName f))
1210 #endif
1211         =  saturated_data_con f n_val_args
1212         || (in_arg && n_val_args == 0)  
1213                 -- A naked un-applied variable is *not* deemed a static RHS
1214                 -- E.g.         f = g
1215                 -- Reason: better to update so that the indirection gets shorted
1216                 --         out, and the true value will be seen
1217                 -- NB: if you change this, you'll break the invariant that THUNK_STATICs
1218                 --     are always updatable.  If you do so, make sure that non-updatable
1219                 --     ones have enough space for their static link field!
1220
1221     go (App f a) n_val_args
1222         | isTypeArg a                    = go f n_val_args
1223         | not in_arg && is_static True a = go f (n_val_args + 1)
1224         -- The (not in_arg) checks that we aren't in a constructor argument;
1225         -- if we are, we don't allow (value) applications of any sort
1226         -- 
1227         -- NB. In case you wonder, args are sometimes not atomic.  eg.
1228         --   x = D# (1.0## /## 2.0##)
1229         -- can't float because /## can fail.
1230
1231     go (Note (SCC _) _) _          = False
1232     go (Note _ f)       n_val_args = go f n_val_args
1233     go (Cast e _)       n_val_args = go e n_val_args
1234
1235     go _                _          = False
1236
1237     saturated_data_con f n_val_args
1238         = case isDataConWorkId_maybe f of
1239             Just dc -> n_val_args == dataConRepArity dc
1240             Nothing -> False
1241 \end{code}