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