2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Utility functions on @Core@ syntax
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
18 mkInlineMe, mkSCC, mkCoerce, mkCoerceI,
19 bindNonRec, needsCaseBinding,
20 mkIfThenElse, mkAltExpr, mkPiType, mkPiTypes,
22 -- Taking expressions apart
23 findDefault, findAlt, isDefaultAlt, mergeAlts, trimConArgs,
25 -- Properties of expressions
26 exprType, coreAltType,
27 exprIsDupable, exprIsTrivial, exprIsCheap,
28 exprIsHNF,exprOkForSpeculation, exprIsBig,
29 exprIsConApp_maybe, exprIsBottom,
32 -- Arity and eta expansion
33 manifestArity, exprArity,
34 exprEtaExpandArity, etaExpand,
37 coreBindsSize, exprSize,
43 cheapEqExpr, tcEqExpr, tcEqExprX, applyTypeToArgs, applyTypeToArg,
45 dataConOrigInstPat, dataConRepInstPat, dataConRepFSInstPat
48 #include "HsVersions.h"
84 import GHC.Exts -- For `xori`
88 %************************************************************************
90 \subsection{Find the type of a Core atom/expression}
92 %************************************************************************
95 exprType :: CoreExpr -> Type
97 exprType (Var var) = idType var
98 exprType (Lit lit) = literalType lit
99 exprType (Let _ body) = exprType body
100 exprType (Case _ _ ty _) = ty
101 exprType (Cast _ co) = snd (coercionKind co)
102 exprType (Note _ e) = exprType e
103 exprType (Lam binder expr) = mkPiType binder (exprType expr)
105 = case collectArgs e of
106 (fun, args) -> applyTypeToArgs e (exprType fun) args
108 exprType other = pprTrace "exprType" (pprCoreExpr other) alphaTy
110 coreAltType :: CoreAlt -> Type
111 coreAltType (_,_,rhs) = exprType rhs
114 @mkPiType@ makes a (->) type or a forall type, depending on whether
115 it is given a type variable or a term variable. We cleverly use the
116 lbvarinfo field to figure out the right annotation for the arrove in
117 case of a term variable.
120 mkPiType :: Var -> Type -> Type -- The more polymorphic version
121 mkPiTypes :: [Var] -> Type -> Type -- doesn't work...
123 mkPiTypes vs ty = foldr mkPiType ty vs
126 | isId v = mkFunTy (idType v) ty
127 | otherwise = mkForAllTy v ty
131 applyTypeToArg :: Type -> CoreExpr -> Type
132 applyTypeToArg fun_ty (Type arg_ty) = applyTy fun_ty arg_ty
133 applyTypeToArg fun_ty _ = funResultTy fun_ty
135 applyTypeToArgs :: CoreExpr -> Type -> [CoreExpr] -> Type
136 -- A more efficient version of applyTypeToArg
137 -- when we have several args
138 -- The first argument is just for debugging
139 applyTypeToArgs _ op_ty [] = op_ty
141 applyTypeToArgs e op_ty (Type ty : args)
142 = -- Accumulate type arguments so we can instantiate all at once
145 go rev_tys (Type ty : args) = go (ty:rev_tys) args
146 go rev_tys rest_args = applyTypeToArgs e op_ty' rest_args
148 op_ty' = applyTys op_ty (reverse rev_tys)
150 applyTypeToArgs e op_ty (_ : args)
151 = case (splitFunTy_maybe op_ty) of
152 Just (_, res_ty) -> applyTypeToArgs e res_ty args
153 Nothing -> pprPanic "applyTypeToArgs" (pprCoreExpr e $$ ppr op_ty)
158 %************************************************************************
160 \subsection{Attaching notes}
162 %************************************************************************
164 mkNote removes redundant coercions, and SCCs where possible
168 mkNote :: Note -> CoreExpr -> CoreExpr
169 mkNote (SCC cc) expr = mkSCC cc expr
170 mkNote InlineMe expr = mkInlineMe expr
171 mkNote note expr = Note note expr
175 Drop trivial InlineMe's. This is somewhat important, because if we have an unfolding
176 that looks like (Note InlineMe (Var v)), the InlineMe doesn't go away because it may
177 not be *applied* to anything.
179 We don't use exprIsTrivial here, though, because we sometimes generate worker/wrapper
182 f = inline_me (coerce t fw)
183 As usual, the inline_me prevents the worker from getting inlined back into the wrapper.
184 We want the split, so that the coerces can cancel at the call site.
186 However, we can get left with tiresome type applications. Notably, consider
187 f = /\ a -> let t = e in (t, w)
188 Then lifting the let out of the big lambda gives
190 f = /\ a -> let t = inline_me (t' a) in (t, w)
191 The inline_me is to stop the simplifier inlining t' right back
192 into t's RHS. In the next phase we'll substitute for t (since
193 its rhs is trivial) and *then* we could get rid of the inline_me.
194 But it hardly seems worth it, so I don't bother.
197 mkInlineMe :: CoreExpr -> CoreExpr
198 mkInlineMe (Var v) = Var v
199 mkInlineMe e = Note InlineMe e
205 mkCoerceI :: CoercionI -> CoreExpr -> CoreExpr
207 mkCoerceI (ACo co) e = mkCoerce co e
209 mkCoerce :: Coercion -> CoreExpr -> CoreExpr
210 mkCoerce co (Cast expr co2)
211 = ASSERT(let { (from_ty, _to_ty) = coercionKind co;
212 (_from_ty2, to_ty2) = coercionKind co2} in
213 from_ty `coreEqType` to_ty2 )
214 mkCoerce (mkTransCoercion co2 co) expr
217 = let (from_ty, _to_ty) = coercionKind co in
218 -- if to_ty `coreEqType` from_ty
221 ASSERT2(from_ty `coreEqType` (exprType expr), text "Trying to coerce" <+> text "(" <> ppr expr $$ text "::" <+> ppr (exprType expr) <> text ")" $$ ppr co $$ ppr (coercionKindPredTy co))
226 mkSCC :: CostCentre -> Expr b -> Expr b
227 -- Note: Nested SCC's *are* preserved for the benefit of
228 -- cost centre stack profiling
229 mkSCC _ (Lit lit) = Lit lit
230 mkSCC cc (Lam x e) = Lam x (mkSCC cc e) -- Move _scc_ inside lambda
231 mkSCC cc (Note (SCC cc') e) = Note (SCC cc) (Note (SCC cc') e)
232 mkSCC cc (Note n e) = Note n (mkSCC cc e) -- Move _scc_ inside notes
233 mkSCC cc (Cast e co) = Cast (mkSCC cc e) co -- Move _scc_ inside cast
234 mkSCC cc expr = Note (SCC cc) expr
238 %************************************************************************
240 \subsection{Other expression construction}
242 %************************************************************************
245 bindNonRec :: Id -> CoreExpr -> CoreExpr -> CoreExpr
246 -- (bindNonRec x r b) produces either
249 -- case r of x { _DEFAULT_ -> b }
251 -- depending on whether x is unlifted or not
252 -- It's used by the desugarer to avoid building bindings
253 -- that give Core Lint a heart attack. Actually the simplifier
254 -- deals with them perfectly well.
256 bindNonRec bndr rhs body
257 | needsCaseBinding (idType bndr) rhs = Case rhs bndr (exprType body) [(DEFAULT,[],body)]
258 | otherwise = Let (NonRec bndr rhs) body
260 needsCaseBinding :: Type -> CoreExpr -> Bool
261 needsCaseBinding ty rhs = isUnLiftedType ty && not (exprOkForSpeculation rhs)
262 -- Make a case expression instead of a let
263 -- These can arise either from the desugarer,
264 -- or from beta reductions: (\x.e) (x +# y)
268 mkAltExpr :: AltCon -> [CoreBndr] -> [Type] -> CoreExpr
269 -- This guy constructs the value that the scrutinee must have
270 -- when you are in one particular branch of a case
271 mkAltExpr (DataAlt con) args inst_tys
272 = mkConApp con (map Type inst_tys ++ varsToCoreExprs args)
273 mkAltExpr (LitAlt lit) [] []
275 mkAltExpr (LitAlt _) _ _ = panic "mkAltExpr LitAlt"
276 mkAltExpr DEFAULT _ _ = panic "mkAltExpr DEFAULT"
278 mkIfThenElse :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
279 mkIfThenElse guard then_expr else_expr
280 -- Not going to be refining, so okay to take the type of the "then" clause
281 = Case guard (mkWildId boolTy) (exprType then_expr)
282 [ (DataAlt falseDataCon, [], else_expr), -- Increasing order of tag!
283 (DataAlt trueDataCon, [], then_expr) ]
287 %************************************************************************
289 \subsection{Taking expressions apart}
291 %************************************************************************
293 The default alternative must be first, if it exists at all.
294 This makes it easy to find, though it makes matching marginally harder.
297 findDefault :: [CoreAlt] -> ([CoreAlt], Maybe CoreExpr)
298 findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null args ) (alts, Just rhs)
299 findDefault alts = (alts, Nothing)
301 findAlt :: AltCon -> [CoreAlt] -> CoreAlt
304 (deflt@(DEFAULT,_,_):alts) -> go alts deflt
305 _ -> go alts panic_deflt
307 panic_deflt = pprPanic "Missing alternative" (ppr con $$ vcat (map ppr alts))
310 go (alt@(con1,_,_) : alts) deflt
311 = case con `cmpAltCon` con1 of
312 LT -> deflt -- Missed it already; the alts are in increasing order
314 GT -> ASSERT( not (con1 == DEFAULT) ) go alts deflt
316 isDefaultAlt :: CoreAlt -> Bool
317 isDefaultAlt (DEFAULT, _, _) = True
318 isDefaultAlt _ = False
320 ---------------------------------
321 mergeAlts :: [CoreAlt] -> [CoreAlt] -> [CoreAlt]
322 -- Merge preserving order; alternatives in the first arg
323 -- shadow ones in the second
324 mergeAlts [] as2 = as2
325 mergeAlts as1 [] = as1
326 mergeAlts (a1:as1) (a2:as2)
327 = case a1 `cmpAlt` a2 of
328 LT -> a1 : mergeAlts as1 (a2:as2)
329 EQ -> a1 : mergeAlts as1 as2 -- Discard a2
330 GT -> a2 : mergeAlts (a1:as1) as2
333 ---------------------------------
334 trimConArgs :: AltCon -> [CoreArg] -> [CoreArg]
335 -- Given case (C a b x y) of
337 -- we want to drop the leading type argument of the scrutinee
338 -- leaving the arguments to match agains the pattern
340 trimConArgs DEFAULT args = ASSERT( null args ) []
341 trimConArgs (LitAlt _) args = ASSERT( null args ) []
342 trimConArgs (DataAlt dc) args = dropList (dataConUnivTyVars dc) args
346 %************************************************************************
348 \subsection{Figuring out things about expressions}
350 %************************************************************************
352 @exprIsTrivial@ is true of expressions we are unconditionally happy to
353 duplicate; simple variables and constants, and type
354 applications. Note that primop Ids aren't considered
357 @exprIsBottom@ is true of expressions that are guaranteed to diverge
360 There used to be a gruesome test for (hasNoBinding v) in the
362 exprIsTrivial (Var v) | hasNoBinding v = idArity v == 0
363 The idea here is that a constructor worker, like $wJust, is
364 really short for (\x -> $wJust x), becuase $wJust has no binding.
365 So it should be treated like a lambda. Ditto unsaturated primops.
366 But now constructor workers are not "have-no-binding" Ids. And
367 completely un-applied primops and foreign-call Ids are sufficiently
368 rare that I plan to allow them to be duplicated and put up with
371 SCC notes. We do not treat (_scc_ "foo" x) as trivial, because
372 a) it really generates code, (and a heap object when it's
373 a function arg) to capture the cost centre
374 b) see the note [SCC-and-exprIsTrivial] in Simplify.simplLazyBind
377 exprIsTrivial :: CoreExpr -> Bool
378 exprIsTrivial (Var _) = True -- See notes above
379 exprIsTrivial (Type _) = True
380 exprIsTrivial (Lit lit) = litIsTrivial lit
381 exprIsTrivial (App e arg) = not (isRuntimeArg arg) && exprIsTrivial e
382 exprIsTrivial (Note (SCC _) _) = False -- See notes above
383 exprIsTrivial (Note _ e) = exprIsTrivial e
384 exprIsTrivial (Cast e _) = exprIsTrivial e
385 exprIsTrivial (Lam b body) = not (isRuntimeVar b) && exprIsTrivial body
386 exprIsTrivial _ = False
390 @exprIsDupable@ is true of expressions that can be duplicated at a modest
391 cost in code size. This will only happen in different case
392 branches, so there's no issue about duplicating work.
394 That is, exprIsDupable returns True of (f x) even if
395 f is very very expensive to call.
397 Its only purpose is to avoid fruitless let-binding
398 and then inlining of case join points
402 exprIsDupable :: CoreExpr -> Bool
403 exprIsDupable (Type _) = True
404 exprIsDupable (Var _) = True
405 exprIsDupable (Lit lit) = litIsDupable lit
406 exprIsDupable (Note InlineMe _) = True
407 exprIsDupable (Note _ e) = exprIsDupable e
408 exprIsDupable (Cast e _) = exprIsDupable e
413 go (App f a) n_args = n_args < dupAppSize
419 dupAppSize = 4 -- Size of application we are prepared to duplicate
422 @exprIsCheap@ looks at a Core expression and returns \tr{True} if
423 it is obviously in weak head normal form, or is cheap to get to WHNF.
424 [Note that that's not the same as exprIsDupable; an expression might be
425 big, and hence not dupable, but still cheap.]
427 By ``cheap'' we mean a computation we're willing to:
428 push inside a lambda, or
429 inline at more than one place
430 That might mean it gets evaluated more than once, instead of being
431 shared. The main examples of things which aren't WHNF but are
436 (where e, and all the ei are cheap)
439 (where e and b are cheap)
442 (where op is a cheap primitive operator)
445 (because we are happy to substitute it inside a lambda)
447 Notice that a variable is considered 'cheap': we can push it inside a lambda,
448 because sharing will make sure it is only evaluated once.
451 exprIsCheap :: CoreExpr -> Bool
452 exprIsCheap (Lit _) = True
453 exprIsCheap (Type _) = True
454 exprIsCheap (Var _) = True
455 exprIsCheap (Note InlineMe _) = True
456 exprIsCheap (Note _ e) = exprIsCheap e
457 exprIsCheap (Cast e _) = exprIsCheap e
458 exprIsCheap (Lam x e) = isRuntimeVar x || exprIsCheap e
459 exprIsCheap (Case e _ _ alts) = exprIsCheap e &&
460 and [exprIsCheap rhs | (_,_,rhs) <- alts]
461 -- Experimentally, treat (case x of ...) as cheap
462 -- (and case __coerce x etc.)
463 -- This improves arities of overloaded functions where
464 -- there is only dictionary selection (no construction) involved
465 exprIsCheap (Let (NonRec x _) e)
466 | isUnLiftedType (idType x) = exprIsCheap e
468 -- strict lets always have cheap right hand sides,
469 -- and do no allocation.
471 exprIsCheap other_expr -- Applications and variables
474 -- Accumulate value arguments, then decide
475 go (App f a) val_args | isRuntimeArg a = go f (a:val_args)
476 | otherwise = go f val_args
478 go (Var _) [] = True -- Just a type application of a variable
479 -- (f t1 t2 t3) counts as WHNF
481 = case globalIdDetails f of
482 RecordSelId {} -> go_sel args
483 ClassOpId _ -> go_sel args
484 PrimOpId op -> go_primop op args
486 DataConWorkId _ -> go_pap args
487 _ | length args < idArity f -> go_pap args
490 -- Application of a function which
491 -- always gives bottom; we treat this as cheap
492 -- because it certainly doesn't need to be shared!
497 go_pap args = all exprIsTrivial args
498 -- For constructor applications and primops, check that all
499 -- the args are trivial. We don't want to treat as cheap, say,
501 -- We'll put up with one constructor application, but not dozens
504 go_primop op args = primOpIsCheap op && all exprIsCheap args
505 -- In principle we should worry about primops
506 -- that return a type variable, since the result
507 -- might be applied to something, but I'm not going
508 -- to bother to check the number of args
511 go_sel [arg] = exprIsCheap arg -- I'm experimenting with making record selection
512 go_sel _ = False -- look cheap, so we will substitute it inside a
513 -- lambda. Particularly for dictionary field selection.
514 -- BUT: Take care with (sel d x)! The (sel d) might be cheap, but
515 -- there's no guarantee that (sel d x) will be too. Hence (n_val_args == 1)
518 exprOkForSpeculation returns True of an expression that it is
520 * safe to evaluate even if normal order eval might not
521 evaluate the expression at all, or
523 * safe *not* to evaluate even if normal order would do so
527 the expression guarantees to terminate,
529 without raising an exception,
530 without causing a side effect (e.g. writing a mutable variable)
532 NB: if exprIsHNF e, then exprOkForSpecuation e
535 let x = case y# +# 1# of { r# -> I# r# }
538 case y# +# 1# of { r# ->
543 We can only do this if the (y+1) is ok for speculation: it has no
544 side effects, and can't diverge or raise an exception.
547 exprOkForSpeculation :: CoreExpr -> Bool
548 exprOkForSpeculation (Lit _) = True
549 exprOkForSpeculation (Type _) = True
550 -- Tick boxes are *not* suitable for speculation
551 exprOkForSpeculation (Var v) = isUnLiftedType (idType v)
552 && not (isTickBoxOp v)
553 exprOkForSpeculation (Note _ e) = exprOkForSpeculation e
554 exprOkForSpeculation (Cast e _) = exprOkForSpeculation e
555 exprOkForSpeculation other_expr
556 = case collectArgs other_expr of
557 (Var f, args) -> spec_ok (globalIdDetails f) args
561 spec_ok (DataConWorkId _) _
562 = True -- The strictness of the constructor has already
563 -- been expressed by its "wrapper", so we don't need
564 -- to take the arguments into account
566 spec_ok (PrimOpId op) args
567 | isDivOp op, -- Special case for dividing operations that fail
568 [arg1, Lit lit] <- args -- only if the divisor is zero
569 = not (isZeroLit lit) && exprOkForSpeculation arg1
570 -- Often there is a literal divisor, and this
571 -- can get rid of a thunk in an inner looop
574 = primOpOkForSpeculation op &&
575 all exprOkForSpeculation args
576 -- A bit conservative: we don't really need
577 -- to care about lazy arguments, but this is easy
581 isDivOp :: PrimOp -> Bool
582 -- True of dyadic operators that can fail
583 -- only if the second arg is zero
584 -- This function probably belongs in PrimOp, or even in
585 -- an automagically generated file.. but it's such a
586 -- special case I thought I'd leave it here for now.
587 isDivOp IntQuotOp = True
588 isDivOp IntRemOp = True
589 isDivOp WordQuotOp = True
590 isDivOp WordRemOp = True
591 isDivOp IntegerQuotRemOp = True
592 isDivOp IntegerDivModOp = True
593 isDivOp FloatDivOp = True
594 isDivOp DoubleDivOp = True
600 exprIsBottom :: CoreExpr -> Bool -- True => definitely bottom
601 exprIsBottom e = go 0 e
603 -- n is the number of args
604 go n (Note _ e) = go n e
605 go n (Cast e _) = go n e
606 go n (Let _ e) = go n e
607 go _ (Case e _ _ _) = go 0 e -- Just check the scrut
608 go n (App e _) = go (n+1) e
609 go n (Var v) = idAppIsBottom v n
611 go _ (Lam _ _) = False
612 go _ (Type _) = False
614 idAppIsBottom :: Id -> Int -> Bool
615 idAppIsBottom id n_val_args = appIsBottom (idNewStrictness id) n_val_args
618 @exprIsHNF@ returns true for expressions that are certainly *already*
619 evaluated to *head* normal form. This is used to decide whether it's ok
622 case x of _ -> e ===> e
624 and to decide whether it's safe to discard a `seq`
626 So, it does *not* treat variables as evaluated, unless they say they are.
628 But it *does* treat partial applications and constructor applications
629 as values, even if their arguments are non-trivial, provided the argument
631 e.g. (:) (f x) (map f xs) is a value
632 map (...redex...) is a value
633 Because `seq` on such things completes immediately
635 For unlifted argument types, we have to be careful:
637 Suppose (f x) diverges; then C (f x) is not a value. However this can't
638 happen: see CoreSyn Note [CoreSyn let/app invariant]. Args of unboxed
639 type must be ok-for-speculation (or trivial).
642 exprIsHNF :: CoreExpr -> Bool -- True => Value-lambda, constructor, PAP
643 exprIsHNF (Var v) -- NB: There are no value args at this point
644 = isDataConWorkId v -- Catches nullary constructors,
645 -- so that [] and () are values, for example
646 || idArity v > 0 -- Catches (e.g.) primops that don't have unfoldings
647 || isEvaldUnfolding (idUnfolding v)
648 -- Check the thing's unfolding; it might be bound to a value
649 -- A worry: what if an Id's unfolding is just itself:
650 -- then we could get an infinite loop...
652 exprIsHNF (Lit _) = True
653 exprIsHNF (Type _) = True -- Types are honorary Values;
654 -- we don't mind copying them
655 exprIsHNF (Lam b e) = isRuntimeVar b || exprIsHNF e
656 exprIsHNF (Note _ e) = exprIsHNF e
657 exprIsHNF (Cast e _) = exprIsHNF e
658 exprIsHNF (App e (Type _)) = exprIsHNF e
659 exprIsHNF (App e a) = app_is_value e [a]
662 -- There is at least one value argument
663 app_is_value :: CoreExpr -> [CoreArg] -> Bool
664 app_is_value (Var fun) args
665 = idArity fun > valArgCount args -- Under-applied function
666 || isDataConWorkId fun -- or data constructor
667 app_is_value (Note _ f) as = app_is_value f as
668 app_is_value (Cast f _) as = app_is_value f as
669 app_is_value (App f a) as = app_is_value f (a:as)
670 app_is_value _ _ = False
674 dataConRepInstPat, dataConOrigInstPat :: [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
675 dataConRepFSInstPat :: [FastString] -> [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
676 -- These InstPat functions go here to avoid circularity between DataCon and Id
677 dataConRepInstPat = dataConInstPat dataConRepArgTys (repeat (FSLIT("ipv")))
678 dataConRepFSInstPat = dataConInstPat dataConRepArgTys
679 dataConOrigInstPat = dataConInstPat dc_arg_tys (repeat (FSLIT("ipv")))
681 dc_arg_tys dc = map mkPredTy (dataConEqTheta dc) ++ map mkPredTy (dataConDictTheta dc) ++ dataConOrigArgTys dc
682 -- Remember to include the existential dictionaries
684 dataConInstPat :: (DataCon -> [Type]) -- function used to find arg tys
685 -> [FastString] -- A long enough list of FSs to use for names
686 -> [Unique] -- An equally long list of uniques, at least one for each binder
688 -> [Type] -- Types to instantiate the universally quantified tyvars
689 -> ([TyVar], [CoVar], [Id]) -- Return instantiated variables
690 -- dataConInstPat arg_fun fss us con inst_tys returns a triple
691 -- (ex_tvs, co_tvs, arg_ids),
693 -- ex_tvs are intended to be used as binders for existential type args
695 -- co_tvs are intended to be used as binders for coercion args and the kinds
696 -- of these vars have been instantiated by the inst_tys and the ex_tys
697 -- The co_tvs include both GADT equalities (dcEqSpec) and
698 -- programmer-specified equalities (dcEqTheta)
700 -- arg_ids are indended to be used as binders for value arguments,
701 -- and their types have been instantiated with inst_tys and ex_tys
702 -- The arg_ids include both dicts (dcDictTheta) and
703 -- programmer-specified arguments (after rep-ing) (deRepArgTys)
706 -- The following constructor T1
709 -- T1 :: forall b. Int -> b -> T(a,b)
712 -- has representation type
713 -- forall a. forall a1. forall b. (a :=: (a1,b)) =>
716 -- dataConInstPat fss us T1 (a1',b') will return
718 -- ([a1'', b''], [c :: (a1', b'):=:(a1'', b'')], [x :: Int, y :: b''])
720 -- where the double-primed variables are created with the FastStrings and
721 -- Uniques given as fss and us
722 dataConInstPat arg_fun fss uniqs con inst_tys
723 = (ex_bndrs, co_bndrs, arg_ids)
725 univ_tvs = dataConUnivTyVars con
726 ex_tvs = dataConExTyVars con
727 arg_tys = arg_fun con
728 eq_spec = dataConEqSpec con
729 eq_theta = dataConEqTheta con
730 eq_preds = eqSpecPreds eq_spec ++ eq_theta
733 n_co = length eq_preds
735 -- split the Uniques and FastStrings
736 (ex_uniqs, uniqs') = splitAt n_ex uniqs
737 (co_uniqs, id_uniqs) = splitAt n_co uniqs'
739 (ex_fss, fss') = splitAt n_ex fss
740 (co_fss, id_fss) = splitAt n_co fss'
742 -- Make existential type variables
743 ex_bndrs = zipWith3 mk_ex_var ex_uniqs ex_fss ex_tvs
744 mk_ex_var uniq fs var = mkTyVar new_name kind
746 new_name = mkSysTvName uniq fs
749 -- Make the instantiating substitution
750 subst = zipOpenTvSubst (univ_tvs ++ ex_tvs) (inst_tys ++ map mkTyVarTy ex_bndrs)
752 -- Make new coercion vars, instantiating kind
753 co_bndrs = zipWith3 mk_co_var co_uniqs co_fss eq_preds
754 mk_co_var uniq fs eq_pred = mkCoVar new_name co_kind
756 new_name = mkSysTvName uniq fs
757 co_kind = substTy subst (mkPredTy eq_pred)
759 -- make value vars, instantiating types
760 mk_id_var uniq fs ty = mkUserLocal (mkVarOccFS fs) uniq (substTy subst ty) noSrcSpan
761 arg_ids = zipWith3 mk_id_var id_uniqs id_fss arg_tys
763 exprIsConApp_maybe :: CoreExpr -> Maybe (DataCon, [CoreExpr])
764 -- Returns (Just (dc, [x1..xn])) if the argument expression is
765 -- a constructor application of the form (dc x1 .. xn)
766 exprIsConApp_maybe (Cast expr co)
767 = -- Here we do the KPush reduction rule as described in the FC paper
768 case exprIsConApp_maybe expr of {
770 Just (dc, dc_args) ->
772 -- The transformation applies iff we have
773 -- (C e1 ... en) `cast` co
774 -- where co :: (T t1 .. tn) :=: (T s1 ..sn)
775 -- That is, with a T at the top of both sides
776 -- The left-hand one must be a T, because exprIsConApp returned True
777 -- but the right-hand one might not be. (Though it usually will.)
779 let (from_ty, to_ty) = coercionKind co
780 (from_tc, from_tc_arg_tys) = splitTyConApp from_ty
781 -- The inner one must be a TyConApp
783 case splitTyConApp_maybe to_ty of {
785 Just (to_tc, to_tc_arg_tys)
786 | from_tc /= to_tc -> Nothing
787 -- These two Nothing cases are possible; we might see
788 -- (C x y) `cast` (g :: T a ~ S [a]),
789 -- where S is a type function. In fact, exprIsConApp
790 -- will probably not be called in such circumstances,
791 -- but there't nothing wrong with it
795 tc_arity = tyConArity from_tc
797 (univ_args, rest1) = splitAt tc_arity dc_args
798 (ex_args, rest2) = splitAt n_ex_tvs rest1
799 (co_args_spec, rest3) = splitAt n_cos_spec rest2
800 (co_args_theta, val_args) = splitAt n_cos_theta rest3
802 arg_tys = dataConRepArgTys dc
803 dc_univ_tyvars = dataConUnivTyVars dc
804 dc_ex_tyvars = dataConExTyVars dc
805 dc_eq_spec = dataConEqSpec dc
806 dc_eq_theta = dataConEqTheta dc
807 dc_tyvars = dc_univ_tyvars ++ dc_ex_tyvars
808 n_ex_tvs = length dc_ex_tyvars
809 n_cos_spec = length dc_eq_spec
810 n_cos_theta = length dc_eq_theta
812 -- Make the "theta" from Fig 3 of the paper
813 gammas = decomposeCo tc_arity co
814 new_tys = gammas ++ map (\ (Type t) -> t) ex_args
815 theta = zipOpenTvSubst dc_tyvars new_tys
817 -- First we cast the existential coercion arguments
818 cast_co_spec (tv, ty) co
819 = cast_co_theta (mkEqPred (mkTyVarTy tv, ty)) co
820 cast_co_theta eqPred (Type co)
821 | (ty1, ty2) <- getEqPredTys eqPred
822 = Type $ mkSymCoercion (substTy theta ty1)
824 `mkTransCoercion` (substTy theta ty2)
825 new_co_args = zipWith cast_co_spec dc_eq_spec co_args_spec ++
826 zipWith cast_co_theta dc_eq_theta co_args_theta
828 -- ...and now value arguments
829 new_val_args = zipWith cast_arg arg_tys val_args
830 cast_arg arg_ty arg = mkCoerce (substTy theta arg_ty) arg
833 ASSERT( length univ_args == tc_arity )
834 ASSERT( from_tc == dataConTyCon dc )
835 ASSERT( and (zipWith coreEqType [t | Type t <- univ_args] from_tc_arg_tys) )
836 ASSERT( all isTypeArg (univ_args ++ ex_args) )
837 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 )
839 Just (dc, map Type to_tc_arg_tys ++ ex_args ++ new_co_args ++ new_val_args)
843 -- We do not want to tell the world that we have a
844 -- Cons, to *stop* Case of Known Cons, which removes
846 exprIsConApp_maybe (Note (TickBox {}) expr)
848 exprIsConApp_maybe (Note (BinaryTickBox {}) expr)
852 exprIsConApp_maybe (Note _ expr)
853 = exprIsConApp_maybe expr
854 -- We ignore InlineMe notes in case we have
855 -- x = __inline_me__ (a,b)
856 -- All part of making sure that INLINE pragmas never hurt
857 -- Marcin tripped on this one when making dictionaries more inlinable
859 -- In fact, we ignore all notes. For example,
860 -- case _scc_ "foo" (C a b) of
862 -- should be optimised away, but it will be only if we look
863 -- through the SCC note.
865 exprIsConApp_maybe expr = analyse (collectArgs expr)
867 analyse (Var fun, args)
868 | Just con <- isDataConWorkId_maybe fun,
869 args `lengthAtLeast` dataConRepArity con
870 -- Might be > because the arity excludes type args
873 -- Look through unfoldings, but only cheap ones, because
874 -- we are effectively duplicating the unfolding
875 analyse (Var fun, [])
876 | let unf = idUnfolding fun,
878 = exprIsConApp_maybe (unfoldingTemplate unf)
885 %************************************************************************
887 \subsection{Eta reduction and expansion}
889 %************************************************************************
892 exprEtaExpandArity :: DynFlags -> CoreExpr -> Arity
893 {- The Arity returned is the number of value args the
894 thing can be applied to without doing much work
896 exprEtaExpandArity is used when eta expanding
899 It returns 1 (or more) to:
900 case x of p -> \s -> ...
901 because for I/O ish things we really want to get that \s to the top.
902 We are prepared to evaluate x each time round the loop in order to get that
904 It's all a bit more subtle than it looks:
908 Consider one-shot lambdas
909 let x = expensive in \y z -> E
910 We want this to have arity 2 if the \y-abstraction is a 1-shot lambda
911 Hence the ArityType returned by arityType
913 2. The state-transformer hack
915 The one-shot lambda special cause is particularly important/useful for
916 IO state transformers, where we often get
917 let x = E in \ s -> ...
919 and the \s is a real-world state token abstraction. Such abstractions
920 are almost invariably 1-shot, so we want to pull the \s out, past the
921 let x=E, even if E is expensive. So we treat state-token lambdas as
922 one-shot even if they aren't really. The hack is in Id.isOneShotBndr.
924 3. Dealing with bottom
927 f = \x -> error "foo"
928 Here, arity 1 is fine. But if it is
932 then we want to get arity 2. Tecnically, this isn't quite right, because
934 should diverge, but it'll converge if we eta-expand f. Nevertheless, we
935 do so; it improves some programs significantly, and increasing convergence
936 isn't a bad thing. Hence the ABot/ATop in ArityType.
938 Actually, the situation is worse. Consider
942 Can we eta-expand here? At first the answer looks like "yes of course", but
945 This should diverge! But if we eta-expand, it won't. Again, we ignore this
946 "problem", because being scrupulous would lose an important transformation for
952 Non-recursive newtypes are transparent, and should not get in the way.
953 We do (currently) eta-expand recursive newtypes too. So if we have, say
955 newtype T = MkT ([T] -> Int)
959 where f has arity 1. Then: etaExpandArity e = 1;
960 that is, etaExpandArity looks through the coerce.
962 When we eta-expand e to arity 1: eta_expand 1 e T
963 we want to get: coerce T (\x::[T] -> (coerce ([T]->Int) e) x)
965 HOWEVER, note that if you use coerce bogusly you can ge
967 And since negate has arity 2, you might try to eta expand. But you can't
968 decopose Int to a function type. Hence the final case in eta_expand.
972 exprEtaExpandArity dflags e = arityDepth (arityType dflags e)
974 -- A limited sort of function type
975 data ArityType = AFun Bool ArityType -- True <=> one-shot
976 | ATop -- Know nothing
979 arityDepth :: ArityType -> Arity
980 arityDepth (AFun _ ty) = 1 + arityDepth ty
983 andArityType :: ArityType -> ArityType -> ArityType
984 andArityType ABot at2 = at2
985 andArityType ATop _ = ATop
986 andArityType (AFun t1 at1) (AFun t2 at2) = AFun (t1 && t2) (andArityType at1 at2)
987 andArityType at1 at2 = andArityType at2 at1
989 arityType :: DynFlags -> CoreExpr -> ArityType
990 -- (go1 e) = [b1,..,bn]
991 -- means expression can be rewritten \x_b1 -> ... \x_bn -> body
992 -- where bi is True <=> the lambda is one-shot
994 arityType dflags (Note _ e) = arityType dflags e
995 -- Not needed any more: etaExpand is cleverer
996 -- | ok_note n = arityType dflags e
997 -- | otherwise = ATop
999 arityType dflags (Cast e _) = arityType dflags e
1002 = mk (idArity v) (arg_tys (idType v))
1004 mk :: Arity -> [Type] -> ArityType
1005 -- The argument types are only to steer the "state hack"
1006 -- Consider case x of
1008 -- False -> \(s:RealWorld) -> e
1009 -- where foo has arity 1. Then we want the state hack to
1010 -- apply to foo too, so we can eta expand the case.
1011 mk 0 tys | isBottomingId v = ABot
1012 | (ty:_) <- tys, isStateHackType ty = AFun True ATop
1014 mk n (ty:tys) = AFun (isStateHackType ty) (mk (n-1) tys)
1015 mk n [] = AFun False (mk (n-1) [])
1017 arg_tys :: Type -> [Type] -- Ignore for-alls
1019 | Just (_, ty') <- splitForAllTy_maybe ty = arg_tys ty'
1020 | Just (arg,res) <- splitFunTy_maybe ty = arg : arg_tys res
1023 -- Lambdas; increase arity
1024 arityType dflags (Lam x e)
1025 | isId x = AFun (isOneShotBndr x) (arityType dflags e)
1026 | otherwise = arityType dflags e
1028 -- Applications; decrease arity
1029 arityType dflags (App f (Type _)) = arityType dflags f
1030 arityType dflags (App f a)
1031 = case arityType dflags f of
1032 ABot -> ABot -- If function diverges, ignore argument
1033 ATop -> ATop -- No no info about function
1035 | exprIsCheap a -> xs
1038 -- Case/Let; keep arity if either the expression is cheap
1039 -- or it's a 1-shot lambda
1040 -- The former is not really right for Haskell
1041 -- f x = case x of { (a,b) -> \y. e }
1043 -- f x y = case x of { (a,b) -> e }
1044 -- The difference is observable using 'seq'
1045 arityType dflags (Case scrut _ _ alts)
1046 = case foldr1 andArityType [arityType dflags rhs | (_,_,rhs) <- alts] of
1047 xs | exprIsCheap scrut -> xs
1048 AFun one_shot _ | one_shot -> AFun True ATop
1051 arityType dflags (Let b e)
1052 = case arityType dflags e of
1053 xs | cheap_bind b -> xs
1054 AFun one_shot _ | one_shot -> AFun True ATop
1057 cheap_bind (NonRec b e) = is_cheap (b,e)
1058 cheap_bind (Rec prs) = all is_cheap prs
1059 is_cheap (b,e) = (dopt Opt_DictsCheap dflags && isDictId b)
1061 -- If the experimental -fdicts-cheap flag is on, we eta-expand through
1062 -- dictionary bindings. This improves arities. Thereby, it also
1063 -- means that full laziness is less prone to floating out the
1064 -- application of a function to its dictionary arguments, which
1065 -- can thereby lose opportunities for fusion. Example:
1066 -- foo :: Ord a => a -> ...
1067 -- foo = /\a \(d:Ord a). let d' = ...d... in \(x:a). ....
1068 -- -- So foo has arity 1
1070 -- f = \x. foo dInt $ bar x
1072 -- The (foo DInt) is floated out, and makes ineffective a RULE
1073 -- foo (bar x) = ...
1075 -- One could go further and make exprIsCheap reply True to any
1076 -- dictionary-typed expression, but that's more work.
1078 arityType _ _ = ATop
1080 {- NOT NEEDED ANY MORE: etaExpand is cleverer
1081 ok_note InlineMe = False
1082 ok_note other = True
1083 -- Notice that we do not look through __inline_me__
1084 -- This may seem surprising, but consider
1085 -- f = _inline_me (\x -> e)
1086 -- We DO NOT want to eta expand this to
1087 -- f = \x -> (_inline_me (\x -> e)) x
1088 -- because the _inline_me gets dropped now it is applied,
1097 etaExpand :: Arity -- Result should have this number of value args
1099 -> CoreExpr -> Type -- Expression and its type
1101 -- (etaExpand n us e ty) returns an expression with
1102 -- the same meaning as 'e', but with arity 'n'.
1104 -- Given e' = etaExpand n us e ty
1106 -- ty = exprType e = exprType e'
1108 -- Note that SCCs are not treated specially. If we have
1109 -- etaExpand 2 (\x -> scc "foo" e)
1110 -- = (\xy -> (scc "foo" e) y)
1111 -- So the costs of evaluating 'e' (not 'e y') are attributed to "foo"
1113 etaExpand n us expr ty
1114 | manifestArity expr >= n = expr -- The no-op case
1116 = eta_expand n us expr ty
1119 -- manifestArity sees how many leading value lambdas there are
1120 manifestArity :: CoreExpr -> Arity
1121 manifestArity (Lam v e) | isId v = 1 + manifestArity e
1122 | otherwise = manifestArity e
1123 manifestArity (Note _ e) = manifestArity e
1124 manifestArity (Cast e _) = manifestArity e
1127 -- etaExpand deals with for-alls. For example:
1129 -- where E :: forall a. a -> a
1131 -- (/\b. \y::a -> E b y)
1133 -- It deals with coerces too, though they are now rare
1134 -- so perhaps the extra code isn't worth it
1135 eta_expand :: Int -> [Unique] -> CoreExpr -> Type -> CoreExpr
1137 eta_expand n _ expr ty
1139 -- The ILX code generator requires eta expansion for type arguments
1140 -- too, but alas the 'n' doesn't tell us how many of them there
1141 -- may be. So we eagerly eta expand any big lambdas, and just
1142 -- cross our fingers about possible loss of sharing in the ILX case.
1143 -- The Right Thing is probably to make 'arity' include
1144 -- type variables throughout the compiler. (ToDo.)
1146 -- Saturated, so nothing to do
1149 -- Short cut for the case where there already
1150 -- is a lambda; no point in gratuitously adding more
1151 eta_expand n us (Lam v body) ty
1153 = Lam v (eta_expand n us body (applyTy ty (mkTyVarTy v)))
1156 = Lam v (eta_expand (n-1) us body (funResultTy ty))
1158 -- We used to have a special case that stepped inside Coerces here,
1159 -- thus: eta_expand n us (Note note@(Coerce _ ty) e) _
1160 -- = Note note (eta_expand n us e ty)
1161 -- BUT this led to an infinite loop
1162 -- Example: newtype T = MkT (Int -> Int)
1163 -- eta_expand 1 (coerce (Int->Int) e)
1164 -- --> coerce (Int->Int) (eta_expand 1 T e)
1166 -- --> coerce (Int->Int) (coerce T
1167 -- (\x::Int -> eta_expand 1 (coerce (Int->Int) e)))
1168 -- by the splitNewType_maybe case below
1171 eta_expand n us expr ty
1172 = ASSERT2 (exprType expr `coreEqType` ty, ppr (exprType expr) $$ ppr ty)
1173 case splitForAllTy_maybe ty of {
1176 Lam lam_tv (eta_expand n us2 (App expr (Type (mkTyVarTy lam_tv))) (substTyWith [tv] [mkTyVarTy lam_tv] ty'))
1178 lam_tv = setVarName tv (mkSysTvName uniq FSLIT("etaT"))
1179 -- Using tv as a base retains its tyvar/covar-ness
1183 case splitFunTy_maybe ty of {
1184 Just (arg_ty, res_ty) -> Lam arg1 (eta_expand (n-1) us2 (App expr (Var arg1)) res_ty)
1186 arg1 = mkSysLocal FSLIT("eta") uniq arg_ty
1192 -- newtype T = MkT ([T] -> Int)
1193 -- Consider eta-expanding this
1196 -- coerce T (\x::[T] -> (coerce ([T]->Int) e) x)
1198 case splitNewTypeRepCo_maybe ty of {
1199 Just(ty1,co) -> mkCoerce (mkSymCoercion co)
1200 (eta_expand n us (mkCoerce co expr) ty1) ;
1203 -- We have an expression of arity > 0, but its type isn't a function
1204 -- This *can* legitmately happen: e.g. coerce Int (\x. x)
1205 -- Essentially the programmer is playing fast and loose with types
1206 -- (Happy does this a lot). So we simply decline to eta-expand.
1211 exprArity is a cheap-and-cheerful version of exprEtaExpandArity.
1212 It tells how many things the expression can be applied to before doing
1213 any work. It doesn't look inside cases, lets, etc. The idea is that
1214 exprEtaExpandArity will do the hard work, leaving something that's easy
1215 for exprArity to grapple with. In particular, Simplify uses exprArity to
1216 compute the ArityInfo for the Id.
1218 Originally I thought that it was enough just to look for top-level lambdas, but
1219 it isn't. I've seen this
1221 foo = PrelBase.timesInt
1223 We want foo to get arity 2 even though the eta-expander will leave it
1224 unchanged, in the expectation that it'll be inlined. But occasionally it
1225 isn't, because foo is blacklisted (used in a rule).
1227 Similarly, see the ok_note check in exprEtaExpandArity. So
1228 f = __inline_me (\x -> e)
1229 won't be eta-expanded.
1231 And in any case it seems more robust to have exprArity be a bit more intelligent.
1232 But note that (\x y z -> f x y z)
1233 should have arity 3, regardless of f's arity.
1236 exprArity :: CoreExpr -> Arity
1239 go (Var v) = idArity v
1240 go (Lam x e) | isId x = go e + 1
1242 go (Note _ e) = go e
1243 go (Cast e _) = go e
1244 go (App e (Type _)) = go e
1245 go (App f a) | exprIsCheap a = (go f - 1) `max` 0
1246 -- NB: exprIsCheap a!
1247 -- f (fac x) does not have arity 2,
1248 -- even if f has arity 3!
1249 -- NB: `max 0`! (\x y -> f x) has arity 2, even if f is
1250 -- unknown, hence arity 0
1254 %************************************************************************
1256 \subsection{Equality}
1258 %************************************************************************
1260 @cheapEqExpr@ is a cheap equality test which bales out fast!
1261 True => definitely equal
1262 False => may or may not be equal
1265 cheapEqExpr :: Expr b -> Expr b -> Bool
1267 cheapEqExpr (Var v1) (Var v2) = v1==v2
1268 cheapEqExpr (Lit lit1) (Lit lit2) = lit1 == lit2
1269 cheapEqExpr (Type t1) (Type t2) = t1 `coreEqType` t2
1271 cheapEqExpr (App f1 a1) (App f2 a2)
1272 = f1 `cheapEqExpr` f2 && a1 `cheapEqExpr` a2
1274 cheapEqExpr (Cast e1 t1) (Cast e2 t2)
1275 = e1 `cheapEqExpr` e2 && t1 `coreEqCoercion` t2
1277 cheapEqExpr _ _ = False
1279 exprIsBig :: Expr b -> Bool
1280 -- Returns True of expressions that are too big to be compared by cheapEqExpr
1281 exprIsBig (Lit _) = False
1282 exprIsBig (Var _) = False
1283 exprIsBig (Type _) = False
1284 exprIsBig (App f a) = exprIsBig f || exprIsBig a
1285 exprIsBig (Cast e _) = exprIsBig e -- Hopefully coercions are not too big!
1291 tcEqExpr :: CoreExpr -> CoreExpr -> Bool
1292 -- Used in rule matching, so does *not* look through
1293 -- newtypes, predicate types; hence tcEqExpr
1295 tcEqExpr e1 e2 = tcEqExprX rn_env e1 e2
1297 rn_env = mkRnEnv2 (mkInScopeSet (exprFreeVars e1 `unionVarSet` exprFreeVars e2))
1299 tcEqExprX :: RnEnv2 -> CoreExpr -> CoreExpr -> Bool
1300 tcEqExprX env (Var v1) (Var v2) = rnOccL env v1 == rnOccR env v2
1301 tcEqExprX _ (Lit lit1) (Lit lit2) = lit1 == lit2
1302 tcEqExprX env (App f1 a1) (App f2 a2) = tcEqExprX env f1 f2 && tcEqExprX env a1 a2
1303 tcEqExprX env (Lam v1 e1) (Lam v2 e2) = tcEqExprX (rnBndr2 env v1 v2) e1 e2
1304 tcEqExprX env (Let (NonRec v1 r1) e1)
1305 (Let (NonRec v2 r2) e2) = tcEqExprX env r1 r2
1306 && tcEqExprX (rnBndr2 env v1 v2) e1 e2
1307 tcEqExprX env (Let (Rec ps1) e1)
1308 (Let (Rec ps2) e2) = equalLength ps1 ps2
1309 && and (zipWith eq_rhs ps1 ps2)
1310 && tcEqExprX env' e1 e2
1312 env' = foldl2 rn_bndr2 env ps2 ps2
1313 rn_bndr2 env (b1,_) (b2,_) = rnBndr2 env b1 b2
1314 eq_rhs (_,r1) (_,r2) = tcEqExprX env' r1 r2
1315 tcEqExprX env (Case e1 v1 t1 a1)
1316 (Case e2 v2 t2 a2) = tcEqExprX env e1 e2
1317 && tcEqTypeX env t1 t2
1318 && equalLength a1 a2
1319 && and (zipWith (eq_alt env') a1 a2)
1321 env' = rnBndr2 env v1 v2
1323 tcEqExprX env (Note n1 e1) (Note n2 e2) = eq_note env n1 n2 && tcEqExprX env e1 e2
1324 tcEqExprX env (Cast e1 co1) (Cast e2 co2) = tcEqTypeX env co1 co2 && tcEqExprX env e1 e2
1325 tcEqExprX env (Type t1) (Type t2) = tcEqTypeX env t1 t2
1326 tcEqExprX _ _ _ = False
1328 eq_alt :: RnEnv2 -> CoreAlt -> CoreAlt -> Bool
1329 eq_alt env (c1,vs1,r1) (c2,vs2,r2) = c1==c2 && tcEqExprX (rnBndrs2 env vs1 vs2) r1 r2
1331 eq_note :: RnEnv2 -> Note -> Note -> Bool
1332 eq_note _ (SCC cc1) (SCC cc2) = cc1 == cc2
1333 eq_note _ (CoreNote s1) (CoreNote s2) = s1 == s2
1334 eq_note _ _ _ = False
1338 %************************************************************************
1340 \subsection{The size of an expression}
1342 %************************************************************************
1345 coreBindsSize :: [CoreBind] -> Int
1346 coreBindsSize bs = foldr ((+) . bindSize) 0 bs
1348 exprSize :: CoreExpr -> Int
1349 -- A measure of the size of the expressions
1350 -- It also forces the expression pretty drastically as a side effect
1351 exprSize (Var v) = v `seq` 1
1352 exprSize (Lit lit) = lit `seq` 1
1353 exprSize (App f a) = exprSize f + exprSize a
1354 exprSize (Lam b e) = varSize b + exprSize e
1355 exprSize (Let b e) = bindSize b + exprSize e
1356 exprSize (Case e b t as) = seqType t `seq` exprSize e + varSize b + 1 + foldr ((+) . altSize) 0 as
1357 exprSize (Cast e co) = (seqType co `seq` 1) + exprSize e
1358 exprSize (Note n e) = noteSize n + exprSize e
1359 exprSize (Type t) = seqType t `seq` 1
1361 noteSize :: Note -> Int
1362 noteSize (SCC cc) = cc `seq` 1
1363 noteSize InlineMe = 1
1364 noteSize (CoreNote s) = s `seq` 1 -- hdaume: core annotations
1366 varSize :: Var -> Int
1367 varSize b | isTyVar b = 1
1368 | otherwise = seqType (idType b) `seq`
1369 megaSeqIdInfo (idInfo b) `seq`
1372 varsSize :: [Var] -> Int
1373 varsSize = sum . map varSize
1375 bindSize :: CoreBind -> Int
1376 bindSize (NonRec b e) = varSize b + exprSize e
1377 bindSize (Rec prs) = foldr ((+) . pairSize) 0 prs
1379 pairSize :: (Var, CoreExpr) -> Int
1380 pairSize (b,e) = varSize b + exprSize e
1382 altSize :: CoreAlt -> Int
1383 altSize (c,bs,e) = c `seq` varsSize bs + exprSize e
1387 %************************************************************************
1389 \subsection{Hashing}
1391 %************************************************************************
1394 hashExpr :: CoreExpr -> Int
1395 -- Two expressions that hash to the same Int may be equal (but may not be)
1396 -- Two expressions that hash to the different Ints are definitely unequal
1398 -- But "unequal" here means "not identical"; two alpha-equivalent
1399 -- expressions may hash to the different Ints
1401 -- The emphasis is on a crude, fast hash, rather than on high precision
1403 -- We must be careful that \x.x and \y.y map to the same hash code,
1404 -- (at least if we want the above invariant to be true)
1406 hashExpr e = fromIntegral (hash_expr (1,emptyVarEnv) e .&. 0x7fffffff)
1407 -- UniqFM doesn't like negative Ints
1409 type HashEnv = (Int, VarEnv Int) -- Hash code for bound variables
1411 hash_expr :: HashEnv -> CoreExpr -> Word32
1412 -- Word32, because we're expecting overflows here, and overflowing
1413 -- signed types just isn't cool. In C it's even undefined.
1414 hash_expr env (Note _ e) = hash_expr env e
1415 hash_expr env (Cast e _) = hash_expr env e
1416 hash_expr env (Var v) = hashVar env v
1417 hash_expr _ (Lit lit) = fromIntegral (hashLiteral lit)
1418 hash_expr env (App f e) = hash_expr env f * fast_hash_expr env e
1419 hash_expr env (Let (NonRec b r) e) = hash_expr (extend_env env b) e * fast_hash_expr env r
1420 hash_expr env (Let (Rec ((b,_):_)) e) = hash_expr (extend_env env b) e
1421 hash_expr env (Case e _ _ _) = hash_expr env e
1422 hash_expr env (Lam b e) = hash_expr (extend_env env b) e
1423 hash_expr _ (Type _) = WARN(True, text "hash_expr: type") 1
1424 -- Shouldn't happen. Better to use WARN than trace, because trace
1425 -- prevents the CPR optimisation kicking in for hash_expr.
1427 fast_hash_expr :: HashEnv -> CoreExpr -> Word32
1428 fast_hash_expr env (Var v) = hashVar env v
1429 fast_hash_expr env (Type t) = fast_hash_type env t
1430 fast_hash_expr _ (Lit lit) = fromIntegral (hashLiteral lit)
1431 fast_hash_expr env (Cast e _) = fast_hash_expr env e
1432 fast_hash_expr env (Note _ e) = fast_hash_expr env e
1433 fast_hash_expr env (App _ a) = fast_hash_expr env a -- A bit idiosyncratic ('a' not 'f')!
1434 fast_hash_expr _ _ = 1
1436 fast_hash_type :: HashEnv -> Type -> Word32
1437 fast_hash_type env ty
1438 | Just tv <- getTyVar_maybe ty = hashVar env tv
1439 | Just (tc,tys) <- splitTyConApp_maybe ty = let hash_tc = fromIntegral (hashName (tyConName tc))
1440 in foldr (\t n -> fast_hash_type env t + n) hash_tc tys
1443 extend_env :: HashEnv -> Var -> (Int, VarEnv Int)
1444 extend_env (n,env) b = (n+1, extendVarEnv env b n)
1446 hashVar :: HashEnv -> Var -> Word32
1448 = fromIntegral (lookupVarEnv env v `orElse` hashName (idName v))
1451 %************************************************************************
1453 \subsection{Determining non-updatable right-hand-sides}
1455 %************************************************************************
1457 Top-level constructor applications can usually be allocated
1458 statically, but they can't if the constructor, or any of the
1459 arguments, come from another DLL (because we can't refer to static
1460 labels in other DLLs).
1462 If this happens we simply make the RHS into an updatable thunk,
1463 and 'exectute' it rather than allocating it statically.
1466 rhsIsStatic :: PackageId -> CoreExpr -> Bool
1467 -- This function is called only on *top-level* right-hand sides
1468 -- Returns True if the RHS can be allocated statically, with
1469 -- no thunks involved at all.
1471 -- It's called (i) in TidyPgm.hasCafRefs to decide if the rhs is, or
1472 -- refers to, CAFs; (ii) in CoreToStg to decide whether to put an
1473 -- update flag on it and (iii) in DsExpr to decide how to expand
1476 -- The basic idea is that rhsIsStatic returns True only if the RHS is
1477 -- (a) a value lambda
1478 -- (b) a saturated constructor application with static args
1480 -- BUT watch out for
1481 -- (i) Any cross-DLL references kill static-ness completely
1482 -- because they must be 'executed' not statically allocated
1483 -- ("DLL" here really only refers to Windows DLLs, on other platforms,
1484 -- this is not necessary)
1486 -- (ii) We treat partial applications as redexes, because in fact we
1487 -- make a thunk for them that runs and builds a PAP
1488 -- at run-time. The only appliations that are treated as
1489 -- static are *saturated* applications of constructors.
1491 -- We used to try to be clever with nested structures like this:
1492 -- ys = (:) w ((:) w [])
1493 -- on the grounds that CorePrep will flatten ANF-ise it later.
1494 -- But supporting this special case made the function much more
1495 -- complicated, because the special case only applies if there are no
1496 -- enclosing type lambdas:
1497 -- ys = /\ a -> Foo (Baz ([] a))
1498 -- Here the nested (Baz []) won't float out to top level in CorePrep.
1500 -- But in fact, even without -O, nested structures at top level are
1501 -- flattened by the simplifier, so we don't need to be super-clever here.
1505 -- f = \x::Int. x+7 TRUE
1506 -- p = (True,False) TRUE
1508 -- d = (fst p, False) FALSE because there's a redex inside
1509 -- (this particular one doesn't happen but...)
1511 -- h = D# (1.0## /## 2.0##) FALSE (redex again)
1512 -- n = /\a. Nil a TRUE
1514 -- t = /\a. (:) (case w a of ...) (Nil a) FALSE (redex)
1517 -- This is a bit like CoreUtils.exprIsHNF, with the following differences:
1518 -- a) scc "foo" (\x -> ...) is updatable (so we catch the right SCC)
1520 -- b) (C x xs), where C is a contructors is updatable if the application is
1523 -- c) don't look through unfolding of f in (f x).
1525 -- When opt_RuntimeTypes is on, we keep type lambdas and treat
1526 -- them as making the RHS re-entrant (non-updatable).
1528 rhsIsStatic _this_pkg rhs = is_static False rhs
1530 is_static :: Bool -- True <=> in a constructor argument; must be atomic
1533 is_static False (Lam b e) = isRuntimeVar b || is_static False e
1535 is_static _ (Note (SCC _) _) = False
1536 is_static in_arg (Note _ e) = is_static in_arg e
1537 is_static in_arg (Cast e _) = is_static in_arg e
1539 is_static _ (Lit lit)
1541 MachLabel _ _ -> False
1543 -- A MachLabel (foreign import "&foo") in an argument
1544 -- prevents a constructor application from being static. The
1545 -- reason is that it might give rise to unresolvable symbols
1546 -- in the object file: under Linux, references to "weak"
1547 -- symbols from the data segment give rise to "unresolvable
1548 -- relocation" errors at link time This might be due to a bug
1549 -- in the linker, but we'll work around it here anyway.
1552 is_static in_arg other_expr = go other_expr 0
1554 go (Var f) n_val_args
1555 #if mingw32_TARGET_OS
1556 | not (isDllName _this_pkg (idName f))
1558 = saturated_data_con f n_val_args
1559 || (in_arg && n_val_args == 0)
1560 -- A naked un-applied variable is *not* deemed a static RHS
1562 -- Reason: better to update so that the indirection gets shorted
1563 -- out, and the true value will be seen
1564 -- NB: if you change this, you'll break the invariant that THUNK_STATICs
1565 -- are always updatable. If you do so, make sure that non-updatable
1566 -- ones have enough space for their static link field!
1568 go (App f a) n_val_args
1569 | isTypeArg a = go f n_val_args
1570 | not in_arg && is_static True a = go f (n_val_args + 1)
1571 -- The (not in_arg) checks that we aren't in a constructor argument;
1572 -- if we are, we don't allow (value) applications of any sort
1574 -- NB. In case you wonder, args are sometimes not atomic. eg.
1575 -- x = D# (1.0## /## 2.0##)
1576 -- can't float because /## can fail.
1578 go (Note (SCC _) _) _ = False
1579 go (Note _ f) n_val_args = go f n_val_args
1580 go (Cast e _) n_val_args = go e n_val_args
1584 saturated_data_con f n_val_args
1585 = case isDataConWorkId_maybe f of
1586 Just dc -> n_val_args == dataConRepArity dc