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
16 -- | Commonly useful utilites for manipulating the Core language
18 -- * Constructing expressions
19 mkSCC, mkCoerce, mkCoerceI,
20 bindNonRec, needsCaseBinding,
21 mkAltExpr, mkPiType, mkPiTypes,
23 -- * Taking expressions apart
24 findDefault, findAlt, isDefaultAlt, mergeAlts, trimConArgs,
26 -- * Properties of expressions
27 exprType, coreAltType, coreAltsType,
28 exprIsDupable, exprIsTrivial, exprIsCheap,
29 exprIsHNF,exprOkForSpeculation, exprIsBig,
31 exprBotStrictness_maybe,
34 -- * Arity and eta expansion
35 -- exprIsBottom, Not used
36 manifestArity, exprArity,
37 exprEtaExpandArity, etaExpand,
39 -- * Expression and bindings size
40 coreBindsSize, exprSize,
46 cheapEqExpr, tcEqExpr, tcEqExprX,
48 -- * Manipulating data constructors and types
49 applyTypeToArgs, applyTypeToArg,
50 dataConOrigInstPat, dataConRepInstPat, dataConRepFSInstPat
53 #include "HsVersions.h"
55 import StaticFlags ( opt_NoStateHack )
89 import GHC.Exts -- For `xori`
93 %************************************************************************
95 \subsection{Find the type of a Core atom/expression}
97 %************************************************************************
100 exprType :: CoreExpr -> Type
101 -- ^ Recover the type of a well-typed Core expression. Fails when
102 -- applied to the actual 'CoreSyn.Type' expression as it cannot
103 -- really be said to have a type
104 exprType (Var var) = idType var
105 exprType (Lit lit) = literalType lit
106 exprType (Let _ body) = exprType body
107 exprType (Case _ _ ty _) = ty
108 exprType (Cast _ co) = snd (coercionKind co)
109 exprType (Note _ e) = exprType e
110 exprType (Lam binder expr) = mkPiType binder (exprType expr)
112 = case collectArgs e of
113 (fun, args) -> applyTypeToArgs e (exprType fun) args
115 exprType other = pprTrace "exprType" (pprCoreExpr other) alphaTy
117 coreAltType :: CoreAlt -> Type
118 -- ^ Returns the type of the alternatives right hand side
119 coreAltType (_,_,rhs) = exprType rhs
121 coreAltsType :: [CoreAlt] -> Type
122 -- ^ Returns the type of the first alternative, which should be the same as for all alternatives
123 coreAltsType (alt:_) = coreAltType alt
124 coreAltsType [] = panic "corAltsType"
128 mkPiType :: Var -> Type -> Type
129 -- ^ Makes a @(->)@ type or a forall type, depending
130 -- on whether it is given a type variable or a term variable.
131 mkPiTypes :: [Var] -> Type -> Type
132 -- ^ 'mkPiType' for multiple type or value arguments
135 | isId v = mkFunTy (idType v) ty
136 | otherwise = mkForAllTy v ty
138 mkPiTypes vs ty = foldr mkPiType ty vs
142 applyTypeToArg :: Type -> CoreExpr -> Type
143 -- ^ Determines the type resulting from applying an expression to a function with the given type
144 applyTypeToArg fun_ty (Type arg_ty) = applyTy fun_ty arg_ty
145 applyTypeToArg fun_ty _ = funResultTy fun_ty
147 applyTypeToArgs :: CoreExpr -> Type -> [CoreExpr] -> Type
148 -- ^ A more efficient version of 'applyTypeToArg' when we have several arguments.
149 -- The first argument is just for debugging, and gives some context
150 applyTypeToArgs _ op_ty [] = op_ty
152 applyTypeToArgs e op_ty (Type ty : args)
153 = -- Accumulate type arguments so we can instantiate all at once
156 go rev_tys (Type ty : args) = go (ty:rev_tys) args
157 go rev_tys rest_args = applyTypeToArgs e op_ty' rest_args
159 op_ty' = applyTysD msg op_ty (reverse rev_tys)
160 msg = ptext (sLit "applyTypeToArgs") <+>
163 applyTypeToArgs e op_ty (_ : args)
164 = case (splitFunTy_maybe op_ty) of
165 Just (_, res_ty) -> applyTypeToArgs e res_ty args
166 Nothing -> pprPanic "applyTypeToArgs" (panic_msg e op_ty)
168 panic_msg :: CoreExpr -> Type -> SDoc
169 panic_msg e op_ty = pprCoreExpr e $$ ppr op_ty
172 %************************************************************************
174 \subsection{Attaching notes}
176 %************************************************************************
179 -- | Wrap the given expression in the coercion, dropping identity coercions and coalescing nested coercions
180 mkCoerceI :: CoercionI -> CoreExpr -> CoreExpr
182 mkCoerceI (ACo co) e = mkCoerce co e
184 -- | Wrap the given expression in the coercion safely, coalescing nested coercions
185 mkCoerce :: Coercion -> CoreExpr -> CoreExpr
186 mkCoerce co (Cast expr co2)
187 = ASSERT(let { (from_ty, _to_ty) = coercionKind co;
188 (_from_ty2, to_ty2) = coercionKind co2} in
189 from_ty `coreEqType` to_ty2 )
190 mkCoerce (mkTransCoercion co2 co) expr
193 = let (from_ty, _to_ty) = coercionKind co in
194 -- if to_ty `coreEqType` from_ty
197 ASSERT2(from_ty `coreEqType` (exprType expr), text "Trying to coerce" <+> text "(" <> ppr expr $$ text "::" <+> ppr (exprType expr) <> text ")" $$ ppr co $$ ppr (coercionKindPredTy co))
202 -- | Wraps the given expression in the cost centre unless
203 -- in a way that maximises their utility to the user
204 mkSCC :: CostCentre -> Expr b -> Expr b
205 -- Note: Nested SCC's *are* preserved for the benefit of
206 -- cost centre stack profiling
207 mkSCC _ (Lit lit) = Lit lit
208 mkSCC cc (Lam x e) = Lam x (mkSCC cc e) -- Move _scc_ inside lambda
209 mkSCC cc (Note (SCC cc') e) = Note (SCC cc) (Note (SCC cc') e)
210 mkSCC cc (Note n e) = Note n (mkSCC cc e) -- Move _scc_ inside notes
211 mkSCC cc (Cast e co) = Cast (mkSCC cc e) co -- Move _scc_ inside cast
212 mkSCC cc expr = Note (SCC cc) expr
216 %************************************************************************
218 \subsection{Other expression construction}
220 %************************************************************************
223 bindNonRec :: Id -> CoreExpr -> CoreExpr -> CoreExpr
224 -- ^ @bindNonRec x r b@ produces either:
230 -- > case r of x { _DEFAULT_ -> b }
232 -- depending on whether we have to use a @case@ or @let@
233 -- binding for the expression (see 'needsCaseBinding').
234 -- It's used by the desugarer to avoid building bindings
235 -- that give Core Lint a heart attack, although actually
236 -- the simplifier deals with them perfectly well. See
237 -- also 'MkCore.mkCoreLet'
238 bindNonRec bndr rhs body
239 | needsCaseBinding (idType bndr) rhs = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
240 | otherwise = Let (NonRec bndr rhs) body
242 -- | Tests whether we have to use a @case@ rather than @let@ binding for this expression
243 -- as per the invariants of 'CoreExpr': see "CoreSyn#let_app_invariant"
244 needsCaseBinding :: Type -> CoreExpr -> Bool
245 needsCaseBinding ty rhs = isUnLiftedType ty && not (exprOkForSpeculation rhs)
246 -- Make a case expression instead of a let
247 -- These can arise either from the desugarer,
248 -- or from beta reductions: (\x.e) (x +# y)
252 mkAltExpr :: AltCon -- ^ Case alternative constructor
253 -> [CoreBndr] -- ^ Things bound by the pattern match
254 -> [Type] -- ^ The type arguments to the case alternative
256 -- ^ This guy constructs the value that the scrutinee must have
257 -- given that you are in one particular branch of a case
258 mkAltExpr (DataAlt con) args inst_tys
259 = mkConApp con (map Type inst_tys ++ varsToCoreExprs args)
260 mkAltExpr (LitAlt lit) [] []
262 mkAltExpr (LitAlt _) _ _ = panic "mkAltExpr LitAlt"
263 mkAltExpr DEFAULT _ _ = panic "mkAltExpr DEFAULT"
267 %************************************************************************
269 \subsection{Taking expressions apart}
271 %************************************************************************
273 The default alternative must be first, if it exists at all.
274 This makes it easy to find, though it makes matching marginally harder.
277 -- | Extract the default case alternative
278 findDefault :: [CoreAlt] -> ([CoreAlt], Maybe CoreExpr)
279 findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null args ) (alts, Just rhs)
280 findDefault alts = (alts, Nothing)
282 -- | Find the case alternative corresponding to a particular
283 -- constructor: panics if no such constructor exists
284 findAlt :: AltCon -> [CoreAlt] -> CoreAlt
287 (deflt@(DEFAULT,_,_):alts) -> go alts deflt
288 _ -> go alts panic_deflt
290 panic_deflt = pprPanic "Missing alternative" (ppr con $$ vcat (map ppr alts))
293 go (alt@(con1,_,_) : alts) deflt
294 = case con `cmpAltCon` con1 of
295 LT -> deflt -- Missed it already; the alts are in increasing order
297 GT -> ASSERT( not (con1 == DEFAULT) ) go alts deflt
299 isDefaultAlt :: CoreAlt -> Bool
300 isDefaultAlt (DEFAULT, _, _) = True
301 isDefaultAlt _ = False
303 ---------------------------------
304 mergeAlts :: [CoreAlt] -> [CoreAlt] -> [CoreAlt]
305 -- ^ Merge alternatives preserving order; alternatives in
306 -- the first argument shadow ones in the second
307 mergeAlts [] as2 = as2
308 mergeAlts as1 [] = as1
309 mergeAlts (a1:as1) (a2:as2)
310 = case a1 `cmpAlt` a2 of
311 LT -> a1 : mergeAlts as1 (a2:as2)
312 EQ -> a1 : mergeAlts as1 as2 -- Discard a2
313 GT -> a2 : mergeAlts (a1:as1) as2
316 ---------------------------------
317 trimConArgs :: AltCon -> [CoreArg] -> [CoreArg]
320 -- > case (C a b x y) of
323 -- We want to drop the leading type argument of the scrutinee
324 -- leaving the arguments to match agains the pattern
326 trimConArgs DEFAULT args = ASSERT( null args ) []
327 trimConArgs (LitAlt _) args = ASSERT( null args ) []
328 trimConArgs (DataAlt dc) args = dropList (dataConUnivTyVars dc) args
332 %************************************************************************
334 \subsection{Figuring out things about expressions}
336 %************************************************************************
338 @exprIsTrivial@ is true of expressions we are unconditionally happy to
339 duplicate; simple variables and constants, and type
340 applications. Note that primop Ids aren't considered
343 There used to be a gruesome test for (hasNoBinding v) in the
345 exprIsTrivial (Var v) | hasNoBinding v = idArity v == 0
346 The idea here is that a constructor worker, like \$wJust, is
347 really short for (\x -> \$wJust x), becuase \$wJust has no binding.
348 So it should be treated like a lambda. Ditto unsaturated primops.
349 But now constructor workers are not "have-no-binding" Ids. And
350 completely un-applied primops and foreign-call Ids are sufficiently
351 rare that I plan to allow them to be duplicated and put up with
354 SCC notes. We do not treat (_scc_ "foo" x) as trivial, because
355 a) it really generates code, (and a heap object when it's
356 a function arg) to capture the cost centre
357 b) see the note [SCC-and-exprIsTrivial] in Simplify.simplLazyBind
360 exprIsTrivial :: CoreExpr -> Bool
361 exprIsTrivial (Var _) = True -- See notes above
362 exprIsTrivial (Type _) = True
363 exprIsTrivial (Lit lit) = litIsTrivial lit
364 exprIsTrivial (App e arg) = not (isRuntimeArg arg) && exprIsTrivial e
365 exprIsTrivial (Note (SCC _) _) = False -- See notes above
366 exprIsTrivial (Note _ e) = exprIsTrivial e
367 exprIsTrivial (Cast e _) = exprIsTrivial e
368 exprIsTrivial (Lam b body) = not (isRuntimeVar b) && exprIsTrivial body
369 exprIsTrivial _ = False
373 @exprIsDupable@ is true of expressions that can be duplicated at a modest
374 cost in code size. This will only happen in different case
375 branches, so there's no issue about duplicating work.
377 That is, exprIsDupable returns True of (f x) even if
378 f is very very expensive to call.
380 Its only purpose is to avoid fruitless let-binding
381 and then inlining of case join points
385 exprIsDupable :: CoreExpr -> Bool
386 exprIsDupable (Type _) = True
387 exprIsDupable (Var _) = True
388 exprIsDupable (Lit lit) = litIsDupable lit
389 exprIsDupable (Note _ e) = exprIsDupable e
390 exprIsDupable (Cast e _) = exprIsDupable e
395 go (App f a) n_args = n_args < dupAppSize
401 dupAppSize = 4 -- Size of application we are prepared to duplicate
404 @exprIsCheap@ looks at a Core expression and returns \tr{True} if
405 it is obviously in weak head normal form, or is cheap to get to WHNF.
406 [Note that that's not the same as exprIsDupable; an expression might be
407 big, and hence not dupable, but still cheap.]
409 By ``cheap'' we mean a computation we're willing to:
410 push inside a lambda, or
411 inline at more than one place
412 That might mean it gets evaluated more than once, instead of being
413 shared. The main examples of things which aren't WHNF but are
418 (where e, and all the ei are cheap)
421 (where e and b are cheap)
424 (where op is a cheap primitive operator)
427 (because we are happy to substitute it inside a lambda)
429 Notice that a variable is considered 'cheap': we can push it inside a lambda,
430 because sharing will make sure it is only evaluated once.
433 exprIsCheap :: CoreExpr -> Bool
434 exprIsCheap (Lit _) = True
435 exprIsCheap (Type _) = True
436 exprIsCheap (Var _) = True
437 exprIsCheap (Note _ e) = exprIsCheap e
438 exprIsCheap (Cast e _) = exprIsCheap e
439 exprIsCheap (Lam x e) = isRuntimeVar x || exprIsCheap e
440 exprIsCheap (Case e _ _ alts) = exprIsCheap e &&
441 and [exprIsCheap rhs | (_,_,rhs) <- alts]
442 -- Experimentally, treat (case x of ...) as cheap
443 -- (and case __coerce x etc.)
444 -- This improves arities of overloaded functions where
445 -- there is only dictionary selection (no construction) involved
446 exprIsCheap (Let (NonRec x _) e)
447 | isUnLiftedType (idType x) = exprIsCheap e
449 -- strict lets always have cheap right hand sides,
450 -- and do no allocation.
452 exprIsCheap other_expr -- Applications and variables
455 -- Accumulate value arguments, then decide
456 go (App f a) val_args | isRuntimeArg a = go f (a:val_args)
457 | otherwise = go f val_args
459 go (Var _) [] = True -- Just a type application of a variable
460 -- (f t1 t2 t3) counts as WHNF
462 = case globalIdDetails f of
463 RecordSelId {} -> go_sel args
464 ClassOpId _ -> go_sel args
465 PrimOpId op -> go_primop op args
467 DataConWorkId _ -> go_pap args
468 _ | length args < idArity f -> go_pap args
471 -- Application of a function which
472 -- always gives bottom; we treat this as cheap
473 -- because it certainly doesn't need to be shared!
478 go_pap args = all exprIsTrivial args
479 -- For constructor applications and primops, check that all
480 -- the args are trivial. We don't want to treat as cheap, say,
482 -- We'll put up with one constructor application, but not dozens
485 go_primop op args = primOpIsCheap op && all exprIsCheap args
486 -- In principle we should worry about primops
487 -- that return a type variable, since the result
488 -- might be applied to something, but I'm not going
489 -- to bother to check the number of args
492 go_sel [arg] = exprIsCheap arg -- I'm experimenting with making record selection
493 go_sel _ = False -- look cheap, so we will substitute it inside a
494 -- lambda. Particularly for dictionary field selection.
495 -- BUT: Take care with (sel d x)! The (sel d) might be cheap, but
496 -- there's no guarantee that (sel d x) will be too. Hence (n_val_args == 1)
500 -- | 'exprOkForSpeculation' returns True of an expression that is:
502 -- * Safe to evaluate even if normal order eval might not
503 -- evaluate the expression at all, or
505 -- * Safe /not/ to evaluate even if normal order would do so
507 -- Precisely, it returns @True@ iff:
509 -- * The expression guarantees to terminate,
513 -- * without raising an exception,
515 -- * without causing a side effect (e.g. writing a mutable variable)
517 -- Note that if @exprIsHNF e@, then @exprOkForSpecuation e@.
518 -- As an example of the considerations in this test, consider:
520 -- > let x = case y# +# 1# of { r# -> I# r# }
523 -- being translated to:
525 -- > case y# +# 1# of { r# ->
530 -- We can only do this if the @y + 1@ is ok for speculation: it has no
531 -- side effects, and can't diverge or raise an exception.
532 exprOkForSpeculation :: CoreExpr -> Bool
533 exprOkForSpeculation (Lit _) = True
534 exprOkForSpeculation (Type _) = True
535 -- Tick boxes are *not* suitable for speculation
536 exprOkForSpeculation (Var v) = isUnLiftedType (idType v)
537 && not (isTickBoxOp v)
538 exprOkForSpeculation (Note _ e) = exprOkForSpeculation e
539 exprOkForSpeculation (Cast e _) = exprOkForSpeculation e
540 exprOkForSpeculation other_expr
541 = case collectArgs other_expr of
542 (Var f, args) -> spec_ok (globalIdDetails f) args
546 spec_ok (DataConWorkId _) _
547 = True -- The strictness of the constructor has already
548 -- been expressed by its "wrapper", so we don't need
549 -- to take the arguments into account
551 spec_ok (PrimOpId op) args
552 | isDivOp op, -- Special case for dividing operations that fail
553 [arg1, Lit lit] <- args -- only if the divisor is zero
554 = not (isZeroLit lit) && exprOkForSpeculation arg1
555 -- Often there is a literal divisor, and this
556 -- can get rid of a thunk in an inner looop
559 = primOpOkForSpeculation op &&
560 all exprOkForSpeculation args
561 -- A bit conservative: we don't really need
562 -- to care about lazy arguments, but this is easy
566 -- | True of dyadic operators that can fail only if the second arg is zero!
567 isDivOp :: PrimOp -> Bool
568 -- This function probably belongs in PrimOp, or even in
569 -- an automagically generated file.. but it's such a
570 -- special case I thought I'd leave it here for now.
571 isDivOp IntQuotOp = True
572 isDivOp IntRemOp = True
573 isDivOp WordQuotOp = True
574 isDivOp WordRemOp = True
575 isDivOp IntegerQuotRemOp = True
576 isDivOp IntegerDivModOp = True
577 isDivOp FloatDivOp = True
578 isDivOp DoubleDivOp = True
583 {- Never used -- omitting
584 -- | True of expressions that are guaranteed to diverge upon execution
585 exprIsBottom :: CoreExpr -> Bool -- True => definitely bottom
586 exprIsBottom e = go 0 e
588 -- n is the number of args
589 go n (Note _ e) = go n e
590 go n (Cast e _) = go n e
591 go n (Let _ e) = go n e
592 go _ (Case e _ _ _) = go 0 e -- Just check the scrut
593 go n (App e _) = go (n+1) e
594 go n (Var v) = idAppIsBottom v n
596 go _ (Lam _ _) = False
597 go _ (Type _) = False
599 idAppIsBottom :: Id -> Int -> Bool
600 idAppIsBottom id n_val_args = appIsBottom (idNewStrictness id) n_val_args
606 -- | This returns true for expressions that are certainly /already/
607 -- evaluated to /head/ normal form. This is used to decide whether it's ok
610 -- > case x of _ -> e
616 -- and to decide whether it's safe to discard a 'seq'.
617 -- So, it does /not/ treat variables as evaluated, unless they say they are.
618 -- However, it /does/ treat partial applications and constructor applications
619 -- as values, even if their arguments are non-trivial, provided the argument
620 -- type is lifted. For example, both of these are values:
622 -- > (:) (f x) (map f xs)
623 -- > map (...redex...)
625 -- Because 'seq' on such things completes immediately.
627 -- For unlifted argument types, we have to be careful:
631 -- Suppose @f x@ diverges; then @C (f x)@ is not a value. However this can't
632 -- happen: see "CoreSyn#let_app_invariant". This invariant states that arguments of
633 -- unboxed type must be ok-for-speculation (or trivial).
634 exprIsHNF :: CoreExpr -> Bool -- True => Value-lambda, constructor, PAP
635 exprIsHNF (Var v) -- NB: There are no value args at this point
636 = isDataConWorkId v -- Catches nullary constructors,
637 -- so that [] and () are values, for example
638 || idArity v > 0 -- Catches (e.g.) primops that don't have unfoldings
639 || isEvaldUnfolding (idUnfolding v)
640 -- Check the thing's unfolding; it might be bound to a value
641 -- A worry: what if an Id's unfolding is just itself:
642 -- then we could get an infinite loop...
644 exprIsHNF (Lit _) = True
645 exprIsHNF (Type _) = True -- Types are honorary Values;
646 -- we don't mind copying them
647 exprIsHNF (Lam b e) = isRuntimeVar b || exprIsHNF e
648 exprIsHNF (Note _ e) = exprIsHNF e
649 exprIsHNF (Cast e _) = exprIsHNF e
650 exprIsHNF (App e (Type _)) = exprIsHNF e
651 exprIsHNF (App e a) = app_is_value e [a]
654 -- There is at least one value argument
655 app_is_value :: CoreExpr -> [CoreArg] -> Bool
656 app_is_value (Var fun) args
657 = idArity fun > valArgCount args -- Under-applied function
658 || isDataConWorkId fun -- or data constructor
659 app_is_value (Note _ f) as = app_is_value f as
660 app_is_value (Cast f _) as = app_is_value f as
661 app_is_value (App f a) as = app_is_value f (a:as)
662 app_is_value _ _ = False
665 These InstPat functions go here to avoid circularity between DataCon and Id
668 dataConRepInstPat, dataConOrigInstPat :: [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
669 dataConRepFSInstPat :: [FastString] -> [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
671 dataConRepInstPat = dataConInstPat dataConRepArgTys (repeat ((fsLit "ipv")))
672 dataConRepFSInstPat = dataConInstPat dataConRepArgTys
673 dataConOrigInstPat = dataConInstPat dc_arg_tys (repeat ((fsLit "ipv")))
675 dc_arg_tys dc = map mkPredTy (dataConEqTheta dc) ++ map mkPredTy (dataConDictTheta dc) ++ dataConOrigArgTys dc
676 -- Remember to include the existential dictionaries
678 dataConInstPat :: (DataCon -> [Type]) -- function used to find arg tys
679 -> [FastString] -- A long enough list of FSs to use for names
680 -> [Unique] -- An equally long list of uniques, at least one for each binder
682 -> [Type] -- Types to instantiate the universally quantified tyvars
683 -> ([TyVar], [CoVar], [Id]) -- Return instantiated variables
684 -- dataConInstPat arg_fun fss us con inst_tys returns a triple
685 -- (ex_tvs, co_tvs, arg_ids),
687 -- ex_tvs are intended to be used as binders for existential type args
689 -- co_tvs are intended to be used as binders for coercion args and the kinds
690 -- of these vars have been instantiated by the inst_tys and the ex_tys
691 -- The co_tvs include both GADT equalities (dcEqSpec) and
692 -- programmer-specified equalities (dcEqTheta)
694 -- arg_ids are indended to be used as binders for value arguments,
695 -- and their types have been instantiated with inst_tys and ex_tys
696 -- The arg_ids include both dicts (dcDictTheta) and
697 -- programmer-specified arguments (after rep-ing) (deRepArgTys)
700 -- The following constructor T1
703 -- T1 :: forall b. Int -> b -> T(a,b)
706 -- has representation type
707 -- forall a. forall a1. forall b. (a ~ (a1,b)) =>
710 -- dataConInstPat fss us T1 (a1',b') will return
712 -- ([a1'', b''], [c :: (a1', b')~(a1'', b'')], [x :: Int, y :: b''])
714 -- where the double-primed variables are created with the FastStrings and
715 -- Uniques given as fss and us
716 dataConInstPat arg_fun fss uniqs con inst_tys
717 = (ex_bndrs, co_bndrs, arg_ids)
719 univ_tvs = dataConUnivTyVars con
720 ex_tvs = dataConExTyVars con
721 arg_tys = arg_fun con
722 eq_spec = dataConEqSpec con
723 eq_theta = dataConEqTheta con
724 eq_preds = eqSpecPreds eq_spec ++ eq_theta
727 n_co = length eq_preds
729 -- split the Uniques and FastStrings
730 (ex_uniqs, uniqs') = splitAt n_ex uniqs
731 (co_uniqs, id_uniqs) = splitAt n_co uniqs'
733 (ex_fss, fss') = splitAt n_ex fss
734 (co_fss, id_fss) = splitAt n_co fss'
736 -- Make existential type variables
737 ex_bndrs = zipWith3 mk_ex_var ex_uniqs ex_fss ex_tvs
738 mk_ex_var uniq fs var = mkTyVar new_name kind
740 new_name = mkSysTvName uniq fs
743 -- Make the instantiating substitution
744 subst = zipOpenTvSubst (univ_tvs ++ ex_tvs) (inst_tys ++ map mkTyVarTy ex_bndrs)
746 -- Make new coercion vars, instantiating kind
747 co_bndrs = zipWith3 mk_co_var co_uniqs co_fss eq_preds
748 mk_co_var uniq fs eq_pred = mkCoVar new_name co_kind
750 new_name = mkSysTvName uniq fs
751 co_kind = substTy subst (mkPredTy eq_pred)
753 -- make value vars, instantiating types
754 mk_id_var uniq fs ty = mkUserLocal (mkVarOccFS fs) uniq (substTy subst ty) noSrcSpan
755 arg_ids = zipWith3 mk_id_var id_uniqs id_fss arg_tys
757 -- | Returns @Just (dc, [x1..xn])@ if the argument expression is
758 -- a constructor application of the form @dc x1 .. xn@
759 exprIsConApp_maybe :: CoreExpr -> Maybe (DataCon, [CoreExpr])
760 exprIsConApp_maybe (Cast expr co)
761 = -- Here we do the KPush reduction rule as described in the FC paper
762 case exprIsConApp_maybe expr of {
764 Just (dc, dc_args) ->
766 -- The transformation applies iff we have
767 -- (C e1 ... en) `cast` co
768 -- where co :: (T t1 .. tn) ~ (T s1 ..sn)
769 -- That is, with a T at the top of both sides
770 -- The left-hand one must be a T, because exprIsConApp returned True
771 -- but the right-hand one might not be. (Though it usually will.)
773 let (from_ty, to_ty) = coercionKind co
774 (from_tc, from_tc_arg_tys) = splitTyConApp from_ty
775 -- The inner one must be a TyConApp
777 case splitTyConApp_maybe to_ty of {
779 Just (to_tc, to_tc_arg_tys)
780 | from_tc /= to_tc -> Nothing
781 -- These two Nothing cases are possible; we might see
782 -- (C x y) `cast` (g :: T a ~ S [a]),
783 -- where S is a type function. In fact, exprIsConApp
784 -- will probably not be called in such circumstances,
785 -- but there't nothing wrong with it
789 tc_arity = tyConArity from_tc
791 (univ_args, rest1) = splitAt tc_arity dc_args
792 (ex_args, rest2) = splitAt n_ex_tvs rest1
793 (co_args_spec, rest3) = splitAt n_cos_spec rest2
794 (co_args_theta, val_args) = splitAt n_cos_theta rest3
796 arg_tys = dataConRepArgTys dc
797 dc_univ_tyvars = dataConUnivTyVars dc
798 dc_ex_tyvars = dataConExTyVars dc
799 dc_eq_spec = dataConEqSpec dc
800 dc_eq_theta = dataConEqTheta dc
801 dc_tyvars = dc_univ_tyvars ++ dc_ex_tyvars
802 n_ex_tvs = length dc_ex_tyvars
803 n_cos_spec = length dc_eq_spec
804 n_cos_theta = length dc_eq_theta
806 -- Make the "theta" from Fig 3 of the paper
807 gammas = decomposeCo tc_arity co
808 new_tys = gammas ++ map (\ (Type t) -> t) ex_args
809 theta = zipOpenTvSubst dc_tyvars new_tys
811 -- First we cast the existential coercion arguments
812 cast_co_spec (tv, ty) co
813 = cast_co_theta (mkEqPred (mkTyVarTy tv, ty)) co
814 cast_co_theta eqPred (Type co)
815 | (ty1, ty2) <- getEqPredTys eqPred
816 = Type $ mkSymCoercion (substTy theta ty1)
818 `mkTransCoercion` (substTy theta ty2)
819 new_co_args = zipWith cast_co_spec dc_eq_spec co_args_spec ++
820 zipWith cast_co_theta dc_eq_theta co_args_theta
822 -- ...and now value arguments
823 new_val_args = zipWith cast_arg arg_tys val_args
824 cast_arg arg_ty arg = mkCoerce (substTy theta arg_ty) arg
827 ASSERT( length univ_args == tc_arity )
828 ASSERT( from_tc == dataConTyCon dc )
829 ASSERT( and (zipWith coreEqType [t | Type t <- univ_args] from_tc_arg_tys) )
830 ASSERT( all isTypeArg (univ_args ++ ex_args) )
831 ASSERT2( equalLength val_args arg_tys, ppr dc $$ ppr dc_tyvars $$ ppr dc_ex_tyvars $$ ppr arg_tys $$ ppr dc_args $$ ppr univ_args $$ ppr ex_args $$ ppr val_args $$ ppr arg_tys )
833 Just (dc, map Type to_tc_arg_tys ++ ex_args ++ new_co_args ++ new_val_args)
837 -- We do not want to tell the world that we have a
838 -- Cons, to *stop* Case of Known Cons, which removes
840 exprIsConApp_maybe (Note (TickBox {}) expr)
842 exprIsConApp_maybe (Note (BinaryTickBox {}) expr)
846 exprIsConApp_maybe (Note _ expr)
847 = exprIsConApp_maybe expr
848 -- We ignore all notes. For example,
849 -- case _scc_ "foo" (C a b) of
851 -- should be optimised away, but it will be only if we look
852 -- through the SCC note.
854 exprIsConApp_maybe expr = analyse (collectArgs expr)
856 analyse (Var fun, args)
857 | Just con <- isDataConWorkId_maybe fun,
858 args `lengthAtLeast` dataConRepArity con
859 -- Might be > because the arity excludes type args
862 -- Look through unfoldings, but only cheap ones, because
863 -- we are effectively duplicating the unfolding
864 analyse (Var fun, [])
865 | let unf = idUnfolding fun,
867 = exprIsConApp_maybe (unfoldingTemplate unf)
874 %************************************************************************
876 \subsection{Eta reduction and expansion}
878 %************************************************************************
881 -- ^ The Arity returned is the number of value args the
882 -- expression can be applied to without doing much work
883 exprEtaExpandArity :: DynFlags -> CoreExpr -> Arity
884 -- exprEtaExpandArity is used when eta expanding
885 -- e ==> \xy -> e x y
886 exprEtaExpandArity dflags e
887 = applyStateHack (exprType e) (arityDepth (arityType dicts_cheap e))
889 dicts_cheap = dopt Opt_DictsCheap dflags
891 exprBotStrictness_maybe :: CoreExpr -> Maybe (Arity, StrictSig)
892 -- A cheap and cheerful function that identifies bottoming functions
893 -- and gives them a suitable strictness signatures. It's used during
895 exprBotStrictness_maybe e
896 = case arityType False e of
898 AT a ABot -> Just (a, mkStrictSig (mkTopDmdType (replicate a topDmd) BotRes))
902 Note [Definition of arity]
903 ~~~~~~~~~~~~~~~~~~~~~~~~~~
904 The "arity" of an expression 'e' is n if
905 applying 'e' to *fewer* than n *value* arguments
908 Or, to put it another way
910 there is no work lost in duplicating the partial
911 application (e x1 .. x(n-1))
913 In the divegent case, no work is lost by duplicating because if the thing
914 is evaluated once, that's the end of the program.
916 Or, to put it another way, in any context C
918 C[ (\x1 .. xn. e x1 .. xn) ]
923 It's all a bit more subtle than it looks:
925 Note [Arity of case expressions]
926 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
927 We treat the arity of
928 case x of p -> \s -> ...
929 as 1 (or more) because for I/O ish things we really want to get that
930 \s to the top. We are prepared to evaluate x each time round the loop
931 in order to get that.
933 This isn't really right in the presence of seq. Consider
937 Can we eta-expand here? At first the answer looks like "yes of course", but
940 This should diverge! But if we eta-expand, it won't. Again, we ignore this
941 "problem", because being scrupulous would lose an important transformation for
945 1. Note [One-shot lambdas]
946 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
947 Consider one-shot lambdas
948 let x = expensive in \y z -> E
949 We want this to have arity 1 if the \y-abstraction is a 1-shot lambda.
951 3. Note [Dealing with bottom]
952 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
954 f = \x -> error "foo"
955 Here, arity 1 is fine. But if it is
959 then we want to get arity 2. Technically, this isn't quite right, because
961 should diverge, but it'll converge if we eta-expand f. Nevertheless, we
962 do so; it improves some programs significantly, and increasing convergence
963 isn't a bad thing. Hence the ABot/ATop in ArityType.
966 4. Note [Newtype arity]
967 ~~~~~~~~~~~~~~~~~~~~~~~~
968 Non-recursive newtypes are transparent, and should not get in the way.
969 We do (currently) eta-expand recursive newtypes too. So if we have, say
971 newtype T = MkT ([T] -> Int)
975 where f has arity 1. Then: etaExpandArity e = 1;
976 that is, etaExpandArity looks through the coerce.
978 When we eta-expand e to arity 1: eta_expand 1 e T
979 we want to get: coerce T (\x::[T] -> (coerce ([T]->Int) e) x)
981 HOWEVER, note that if you use coerce bogusly you can ge
983 And since negate has arity 2, you might try to eta expand. But you can't
984 decopose Int to a function type. Hence the final case in eta_expand.
987 Note [The state-transformer hack]
988 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
991 where e has arity n. Then, if we know from the context that f has
993 t1 -> ... -> tn -1-> t(n+1) -1-> ... -1-> tm -> ...
994 then we can expand the arity to m. This usage type says that
995 any application (x e1 .. en) will be applied to uniquely to (m-n) more args
996 Consider f = \x. let y = <expensive>
999 False -> \(s:RealWorld) -> e
1000 where foo has arity 1. Then we want the state hack to
1001 apply to foo too, so we can eta expand the case.
1003 Then we expect that if f is applied to one arg, it'll be applied to two
1004 (that's the hack -- we don't really know, and sometimes it's false)
1005 See also Id.isOneShotBndr.
1008 applyStateHack :: Type -> Arity -> Arity
1009 applyStateHack ty arity -- Note [The state-transformer hack]
1010 | opt_NoStateHack = arity
1011 | otherwise = go ty arity
1013 go :: Type -> Arity -> Arity
1014 go ty arity -- This case analysis should match that in eta_expand
1015 | Just (_, ty') <- splitForAllTy_maybe ty = go ty' arity
1017 | Just (tc,tys) <- splitTyConApp_maybe ty
1018 , Just (ty', _) <- instNewTyCon_maybe tc tys
1019 , not (isRecursiveTyCon tc) = go ty' arity
1020 -- Important to look through non-recursive newtypes, so that, eg
1021 -- (f x) where f has arity 2, f :: Int -> IO ()
1022 -- Here we want to get arity 1 for the result!
1024 | Just (arg,res) <- splitFunTy_maybe ty
1025 , arity > 0 || isStateHackType arg = 1 + go res (arity-1)
1027 | otherwise = WARN( arity > 0, ppr arity ) 0
1031 -------------------- Main arity code ----------------------------
1033 -- If e has ArityType (AT as r), then the term 'e'
1034 -- * Must be applied to at least (length as) *value* args
1035 -- before doing any significant work
1036 -- * It will not diverge before being applied to (length as)
1038 -- * If 'r' is ABot, then it guarantees to eventually diverge if
1039 -- applied to enough arguments (perhaps more than (length as)
1041 data ArityType = AT Arity ArityRes
1042 data ArityRes = ATop -- Know nothing
1045 vanillaArityType :: ArityType
1046 vanillaArityType = AT 0 ATop -- Totally uninformative
1048 arityDepth :: ArityType -> Arity
1049 arityDepth (AT a _) = a
1051 incArity :: ArityType -> ArityType
1052 incArity (AT a r) = AT (a+1) r
1054 decArity :: ArityType -> ArityType
1055 decArity (AT 0 r) = AT 0 r
1056 decArity (AT a r) = AT (a-1) r
1058 andArityType :: ArityType -> ArityType -> ArityType -- Used for branches of a 'case'
1059 andArityType (AT a1 ATop) (AT a2 ATop) = AT (a1 `min` a2) ATop
1060 andArityType (AT _ ABot) (AT a2 ATop) = AT a2 ATop
1061 andArityType (AT a1 ATop) (AT _ ABot) = AT a1 ATop
1062 andArityType (AT a1 ABot) (AT a2 ABot) = AT (a1 `max` a2) ABot
1064 trimArity :: Bool -> ArityType -> ArityType
1065 -- We have something like (let x = E in b), where b has the given
1067 -- * If E is cheap we can push it inside as far as we like
1068 -- * If b eventually diverges, we allow ourselves to push inside
1069 -- arbitrarily, even though that is not quite right
1070 trimArity _cheap (AT a ABot) = AT a ABot
1071 trimArity True (AT a ATop) = AT a ATop
1072 trimArity False (AT _ ATop) = AT 0 ATop -- Bale out
1074 ---------------------------
1075 arityType :: Bool -> CoreExpr -> ArityType
1077 | Just strict_sig <- idNewStrictness_maybe v
1078 , (ds, res) <- splitStrictSig strict_sig
1080 = AT (length ds) ABot -- Function diverges
1082 = AT (idArity v) ATop
1084 -- Lambdas; increase arity
1085 arityType dicts_cheap (Lam x e)
1086 | isId x = incArity (arityType dicts_cheap e)
1087 | otherwise = arityType dicts_cheap e
1089 -- Applications; decrease arity
1090 arityType dicts_cheap (App fun (Type _))
1091 = arityType dicts_cheap fun
1092 arityType dicts_cheap (App fun arg )
1093 = trimArity (exprIsCheap arg) (decArity (arityType dicts_cheap fun))
1095 -- Case/Let; keep arity if either the expression is cheap
1096 -- or it's a 1-shot lambda
1097 -- The former is not really right for Haskell
1098 -- f x = case x of { (a,b) -> \y. e }
1100 -- f x y = case x of { (a,b) -> e }
1101 -- The difference is observable using 'seq'
1102 arityType dicts_cheap (Case scrut _ _ alts)
1103 = trimArity (exprIsCheap scrut)
1104 (foldr1 andArityType [arityType dicts_cheap rhs | (_,_,rhs) <- alts])
1106 arityType dicts_cheap (Let b e)
1107 = trimArity (cheap_bind b) (arityType dicts_cheap e)
1109 cheap_bind (NonRec b e) = is_cheap (b,e)
1110 cheap_bind (Rec prs) = all is_cheap prs
1111 is_cheap (b,e) = (dicts_cheap && isDictId b) || exprIsCheap e
1112 -- If the experimental -fdicts-cheap flag is on, we eta-expand through
1113 -- dictionary bindings. This improves arities. Thereby, it also
1114 -- means that full laziness is less prone to floating out the
1115 -- application of a function to its dictionary arguments, which
1116 -- can thereby lose opportunities for fusion. Example:
1117 -- foo :: Ord a => a -> ...
1118 -- foo = /\a \(d:Ord a). let d' = ...d... in \(x:a). ....
1119 -- -- So foo has arity 1
1121 -- f = \x. foo dInt $ bar x
1123 -- The (foo DInt) is floated out, and makes ineffective a RULE
1124 -- foo (bar x) = ...
1126 -- One could go further and make exprIsCheap reply True to any
1127 -- dictionary-typed expression, but that's more work.
1129 arityType dicts_cheap (Note _ e) = arityType dicts_cheap e
1130 arityType dicts_cheap (Cast e _) = arityType dicts_cheap e
1131 arityType _ _ = vanillaArityType
1136 -- | @etaExpand n us e ty@ returns an expression with
1137 -- the same meaning as @e@, but with arity @n@.
1141 -- > e' = etaExpand n us e ty
1143 -- We should have that:
1145 -- > ty = exprType e = exprType e'
1146 etaExpand :: Arity -- ^ Result should have this number of value args
1147 -> [Unique] -- ^ Uniques to assign to the new binders
1148 -> CoreExpr -- ^ Expression to expand
1149 -> Type -- ^ Type of expression to expand
1151 -- Note that SCCs are not treated specially. If we have
1152 -- etaExpand 2 (\x -> scc "foo" e)
1153 -- = (\xy -> (scc "foo" e) y)
1154 -- So the costs of evaluating 'e' (not 'e y') are attributed to "foo"
1156 etaExpand n us expr ty
1157 | manifestArity expr >= n = expr -- The no-op case
1158 | otherwise = eta_expand n us expr ty
1160 -- manifestArity sees how many leading value lambdas there are
1161 manifestArity :: CoreExpr -> Arity
1162 manifestArity (Lam v e) | isId v = 1 + manifestArity e
1163 | otherwise = manifestArity e
1164 manifestArity (Note _ e) = manifestArity e
1165 manifestArity (Cast e _) = manifestArity e
1168 -- etaExpand deals with for-alls. For example:
1170 -- where E :: forall a. a -> a
1172 -- (/\b. \y::a -> E b y)
1174 -- It deals with coerces too, though they are now rare
1175 -- so perhaps the extra code isn't worth it
1176 eta_expand :: Int -> [Unique] -> CoreExpr -> Type -> CoreExpr
1178 eta_expand n _ expr _
1179 | n == 0 -- Saturated, so nothing to do
1182 -- Short cut for the case where there already
1183 -- is a lambda; no point in gratuitously adding more
1184 eta_expand n us (Lam v body) ty
1186 = Lam v (eta_expand n us body (applyTy ty (mkTyVarTy v)))
1189 = Lam v (eta_expand (n-1) us body (funResultTy ty))
1191 -- We used to have a special case that stepped inside Coerces here,
1192 -- thus: eta_expand n us (Note note@(Coerce _ ty) e) _
1193 -- = Note note (eta_expand n us e ty)
1194 -- BUT this led to an infinite loop
1195 -- Example: newtype T = MkT (Int -> Int)
1196 -- eta_expand 1 (coerce (Int->Int) e)
1197 -- --> coerce (Int->Int) (eta_expand 1 T e)
1199 -- --> coerce (Int->Int) (coerce T
1200 -- (\x::Int -> eta_expand 1 (coerce (Int->Int) e)))
1201 -- by the splitNewType_maybe case below
1204 eta_expand n us expr ty
1205 = ASSERT2 (exprType expr `coreEqType` ty, ppr (exprType expr) $$ ppr ty)
1206 case splitForAllTy_maybe ty of {
1209 Lam lam_tv (eta_expand n us2 (App expr (Type (mkTyVarTy lam_tv))) (substTyWith [tv] [mkTyVarTy lam_tv] ty'))
1211 lam_tv = setVarName tv (mkSysTvName uniq (fsLit "etaT"))
1212 -- Using tv as a base retains its tyvar/covar-ness
1216 case splitFunTy_maybe ty of {
1217 Just (arg_ty, res_ty) -> Lam arg1 (eta_expand (n-1) us2 (App expr (Var arg1)) res_ty)
1219 arg1 = mkSysLocal (fsLit "eta") uniq arg_ty
1225 -- newtype T = MkT ([T] -> Int)
1226 -- Consider eta-expanding this
1229 -- coerce T (\x::[T] -> (coerce ([T]->Int) e) x)
1231 case splitNewTypeRepCo_maybe ty of {
1232 Just(ty1,co) -> mkCoerce (mkSymCoercion co)
1233 (eta_expand n us (mkCoerce co expr) ty1) ;
1236 -- We have an expression of arity > 0, but its type isn't a function
1237 -- This *can* legitmately happen: e.g. coerce Int (\x. x)
1238 -- Essentially the programmer is playing fast and loose with types
1239 -- (Happy does this a lot). So we simply decline to eta-expand.
1240 -- Otherwise we'd end up with an explicit lambda having a non-function type
1245 exprArity is a cheap-and-cheerful version of exprEtaExpandArity.
1246 It tells how many things the expression can be applied to before doing
1247 any work. It doesn't look inside cases, lets, etc. The idea is that
1248 exprEtaExpandArity will do the hard work, leaving something that's easy
1249 for exprArity to grapple with. In particular, Simplify uses exprArity to
1250 compute the ArityInfo for the Id.
1252 Originally I thought that it was enough just to look for top-level lambdas, but
1253 it isn't. I've seen this
1255 foo = PrelBase.timesInt
1257 We want foo to get arity 2 even though the eta-expander will leave it
1258 unchanged, in the expectation that it'll be inlined. But occasionally it
1259 isn't, because foo is blacklisted (used in a rule).
1261 Similarly, see the ok_note check in exprEtaExpandArity. So
1262 f = __inline_me (\x -> e)
1263 won't be eta-expanded.
1265 And in any case it seems more robust to have exprArity be a bit more intelligent.
1266 But note that (\x y z -> f x y z)
1267 should have arity 3, regardless of f's arity.
1269 Note [exprArity invariant]
1270 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1271 exprArity has the following invariant:
1272 (exprArity e) = n, then manifestArity (etaExpand e n) = n
1274 That is, if exprArity says "the arity is n" then etaExpand really can get
1275 "n" manifest lambdas to the top.
1277 Why is this important? Because
1278 - In TidyPgm we use exprArity to fix the *final arity* of
1279 each top-level Id, and in
1280 - In CorePrep we use etaExpand on each rhs, so that the visible lambdas
1281 actually match that arity, which in turn means
1282 that the StgRhs has the right number of lambdas
1284 An alternative would be to do the eta-expansion in TidyPgm, at least
1285 for top-level bindings, in which case we would not need the trim_arity
1286 in exprArity. That is a less local change, so I'm going to leave it for today!
1290 -- | An approximate, fast, version of 'exprEtaExpandArity'
1291 exprArity :: CoreExpr -> Arity
1294 go (Var v) = idArity v
1295 go (Lam x e) | isId x = go e + 1
1297 go (Note _ e) = go e
1298 go (Cast e co) = trim_arity (go e) 0 (snd (coercionKind co))
1299 go (App e (Type _)) = go e
1300 go (App f a) | exprIsCheap a = (go f - 1) `max` 0
1301 -- NB: exprIsCheap a!
1302 -- f (fac x) does not have arity 2,
1303 -- even if f has arity 3!
1304 -- NB: `max 0`! (\x y -> f x) has arity 2, even if f is
1305 -- unknown, hence arity 0
1308 -- Note [exprArity invariant]
1311 | Just (_, ty') <- splitForAllTy_maybe ty = trim_arity n a ty'
1312 | Just (_, ty') <- splitFunTy_maybe ty = trim_arity n (a+1) ty'
1313 | Just (ty',_) <- splitNewTypeRepCo_maybe ty = trim_arity n a ty'
1317 %************************************************************************
1319 \subsection{Equality}
1321 %************************************************************************
1324 -- | A cheap equality test which bales out fast!
1325 -- If it returns @True@ the arguments are definitely equal,
1326 -- otherwise, they may or may not be equal.
1328 -- See also 'exprIsBig'
1329 cheapEqExpr :: Expr b -> Expr b -> Bool
1331 cheapEqExpr (Var v1) (Var v2) = v1==v2
1332 cheapEqExpr (Lit lit1) (Lit lit2) = lit1 == lit2
1333 cheapEqExpr (Type t1) (Type t2) = t1 `coreEqType` t2
1335 cheapEqExpr (App f1 a1) (App f2 a2)
1336 = f1 `cheapEqExpr` f2 && a1 `cheapEqExpr` a2
1338 cheapEqExpr (Cast e1 t1) (Cast e2 t2)
1339 = e1 `cheapEqExpr` e2 && t1 `coreEqCoercion` t2
1341 cheapEqExpr _ _ = False
1343 exprIsBig :: Expr b -> Bool
1344 -- ^ Returns @True@ of expressions that are too big to be compared by 'cheapEqExpr'
1345 exprIsBig (Lit _) = False
1346 exprIsBig (Var _) = False
1347 exprIsBig (Type _) = False
1348 exprIsBig (Lam _ e) = exprIsBig e
1349 exprIsBig (App f a) = exprIsBig f || exprIsBig a
1350 exprIsBig (Cast e _) = exprIsBig e -- Hopefully coercions are not too big!
1356 tcEqExpr :: CoreExpr -> CoreExpr -> Bool
1357 -- ^ A kind of shallow equality used in rule matching, so does
1358 -- /not/ look through newtypes or predicate types
1360 tcEqExpr e1 e2 = tcEqExprX rn_env e1 e2
1362 rn_env = mkRnEnv2 (mkInScopeSet (exprFreeVars e1 `unionVarSet` exprFreeVars e2))
1364 tcEqExprX :: RnEnv2 -> CoreExpr -> CoreExpr -> Bool
1365 tcEqExprX env (Var v1) (Var v2) = rnOccL env v1 == rnOccR env v2
1366 tcEqExprX _ (Lit lit1) (Lit lit2) = lit1 == lit2
1367 tcEqExprX env (App f1 a1) (App f2 a2) = tcEqExprX env f1 f2 && tcEqExprX env a1 a2
1368 tcEqExprX env (Lam v1 e1) (Lam v2 e2) = tcEqExprX (rnBndr2 env v1 v2) e1 e2
1369 tcEqExprX env (Let (NonRec v1 r1) e1)
1370 (Let (NonRec v2 r2) e2) = tcEqExprX env r1 r2
1371 && tcEqExprX (rnBndr2 env v1 v2) e1 e2
1372 tcEqExprX env (Let (Rec ps1) e1)
1373 (Let (Rec ps2) e2) = equalLength ps1 ps2
1374 && and (zipWith eq_rhs ps1 ps2)
1375 && tcEqExprX env' e1 e2
1377 env' = foldl2 rn_bndr2 env ps2 ps2
1378 rn_bndr2 env (b1,_) (b2,_) = rnBndr2 env b1 b2
1379 eq_rhs (_,r1) (_,r2) = tcEqExprX env' r1 r2
1380 tcEqExprX env (Case e1 v1 t1 a1)
1381 (Case e2 v2 t2 a2) = tcEqExprX env e1 e2
1382 && tcEqTypeX env t1 t2
1383 && equalLength a1 a2
1384 && and (zipWith (eq_alt env') a1 a2)
1386 env' = rnBndr2 env v1 v2
1388 tcEqExprX env (Note n1 e1) (Note n2 e2) = eq_note env n1 n2 && tcEqExprX env e1 e2
1389 tcEqExprX env (Cast e1 co1) (Cast e2 co2) = tcEqTypeX env co1 co2 && tcEqExprX env e1 e2
1390 tcEqExprX env (Type t1) (Type t2) = tcEqTypeX env t1 t2
1391 tcEqExprX _ _ _ = False
1393 eq_alt :: RnEnv2 -> CoreAlt -> CoreAlt -> Bool
1394 eq_alt env (c1,vs1,r1) (c2,vs2,r2) = c1==c2 && tcEqExprX (rnBndrs2 env vs1 vs2) r1 r2
1396 eq_note :: RnEnv2 -> Note -> Note -> Bool
1397 eq_note _ (SCC cc1) (SCC cc2) = cc1 == cc2
1398 eq_note _ (CoreNote s1) (CoreNote s2) = s1 == s2
1399 eq_note _ _ _ = False
1403 %************************************************************************
1405 \subsection{The size of an expression}
1407 %************************************************************************
1410 coreBindsSize :: [CoreBind] -> Int
1411 coreBindsSize bs = foldr ((+) . bindSize) 0 bs
1413 exprSize :: CoreExpr -> Int
1414 -- ^ A measure of the size of the expressions, strictly greater than 0
1415 -- It also forces the expression pretty drastically as a side effect
1416 exprSize (Var v) = v `seq` 1
1417 exprSize (Lit lit) = lit `seq` 1
1418 exprSize (App f a) = exprSize f + exprSize a
1419 exprSize (Lam b e) = varSize b + exprSize e
1420 exprSize (Let b e) = bindSize b + exprSize e
1421 exprSize (Case e b t as) = seqType t `seq` exprSize e + varSize b + 1 + foldr ((+) . altSize) 0 as
1422 exprSize (Cast e co) = (seqType co `seq` 1) + exprSize e
1423 exprSize (Note n e) = noteSize n + exprSize e
1424 exprSize (Type t) = seqType t `seq` 1
1426 noteSize :: Note -> Int
1427 noteSize (SCC cc) = cc `seq` 1
1428 noteSize (CoreNote s) = s `seq` 1 -- hdaume: core annotations
1430 varSize :: Var -> Int
1431 varSize b | isTyVar b = 1
1432 | otherwise = seqType (idType b) `seq`
1433 megaSeqIdInfo (idInfo b) `seq`
1436 varsSize :: [Var] -> Int
1437 varsSize = sum . map varSize
1439 bindSize :: CoreBind -> Int
1440 bindSize (NonRec b e) = varSize b + exprSize e
1441 bindSize (Rec prs) = foldr ((+) . pairSize) 0 prs
1443 pairSize :: (Var, CoreExpr) -> Int
1444 pairSize (b,e) = varSize b + exprSize e
1446 altSize :: CoreAlt -> Int
1447 altSize (c,bs,e) = c `seq` varsSize bs + exprSize e
1451 %************************************************************************
1453 \subsection{Hashing}
1455 %************************************************************************
1458 hashExpr :: CoreExpr -> Int
1459 -- ^ Two expressions that hash to the same @Int@ may be equal (but may not be)
1460 -- Two expressions that hash to the different Ints are definitely unequal.
1462 -- The emphasis is on a crude, fast hash, rather than on high precision.
1464 -- But unequal here means \"not identical\"; two alpha-equivalent
1465 -- expressions may hash to the different Ints.
1467 -- We must be careful that @\\x.x@ and @\\y.y@ map to the same hash code,
1468 -- (at least if we want the above invariant to be true).
1470 hashExpr e = fromIntegral (hash_expr (1,emptyVarEnv) e .&. 0x7fffffff)
1471 -- UniqFM doesn't like negative Ints
1473 type HashEnv = (Int, VarEnv Int) -- Hash code for bound variables
1475 hash_expr :: HashEnv -> CoreExpr -> Word32
1476 -- Word32, because we're expecting overflows here, and overflowing
1477 -- signed types just isn't cool. In C it's even undefined.
1478 hash_expr env (Note _ e) = hash_expr env e
1479 hash_expr env (Cast e _) = hash_expr env e
1480 hash_expr env (Var v) = hashVar env v
1481 hash_expr _ (Lit lit) = fromIntegral (hashLiteral lit)
1482 hash_expr env (App f e) = hash_expr env f * fast_hash_expr env e
1483 hash_expr env (Let (NonRec b r) e) = hash_expr (extend_env env b) e * fast_hash_expr env r
1484 hash_expr env (Let (Rec ((b,_):_)) e) = hash_expr (extend_env env b) e
1485 hash_expr env (Case e _ _ _) = hash_expr env e
1486 hash_expr env (Lam b e) = hash_expr (extend_env env b) e
1487 hash_expr _ (Type _) = WARN(True, text "hash_expr: type") 1
1488 -- Shouldn't happen. Better to use WARN than trace, because trace
1489 -- prevents the CPR optimisation kicking in for hash_expr.
1491 fast_hash_expr :: HashEnv -> CoreExpr -> Word32
1492 fast_hash_expr env (Var v) = hashVar env v
1493 fast_hash_expr env (Type t) = fast_hash_type env t
1494 fast_hash_expr _ (Lit lit) = fromIntegral (hashLiteral lit)
1495 fast_hash_expr env (Cast e _) = fast_hash_expr env e
1496 fast_hash_expr env (Note _ e) = fast_hash_expr env e
1497 fast_hash_expr env (App _ a) = fast_hash_expr env a -- A bit idiosyncratic ('a' not 'f')!
1498 fast_hash_expr _ _ = 1
1500 fast_hash_type :: HashEnv -> Type -> Word32
1501 fast_hash_type env ty
1502 | Just tv <- getTyVar_maybe ty = hashVar env tv
1503 | Just (tc,tys) <- splitTyConApp_maybe ty = let hash_tc = fromIntegral (hashName (tyConName tc))
1504 in foldr (\t n -> fast_hash_type env t + n) hash_tc tys
1507 extend_env :: HashEnv -> Var -> (Int, VarEnv Int)
1508 extend_env (n,env) b = (n+1, extendVarEnv env b n)
1510 hashVar :: HashEnv -> Var -> Word32
1512 = fromIntegral (lookupVarEnv env v `orElse` hashName (idName v))
1515 %************************************************************************
1517 \subsection{Determining non-updatable right-hand-sides}
1519 %************************************************************************
1521 Top-level constructor applications can usually be allocated
1522 statically, but they can't if the constructor, or any of the
1523 arguments, come from another DLL (because we can't refer to static
1524 labels in other DLLs).
1526 If this happens we simply make the RHS into an updatable thunk,
1527 and 'execute' it rather than allocating it statically.
1530 -- | This function is called only on *top-level* right-hand sides.
1531 -- Returns @True@ if the RHS can be allocated statically in the output,
1532 -- with no thunks involved at all.
1533 rhsIsStatic :: PackageId -> CoreExpr -> Bool
1534 -- It's called (i) in TidyPgm.hasCafRefs to decide if the rhs is, or
1535 -- refers to, CAFs; (ii) in CoreToStg to decide whether to put an
1536 -- update flag on it and (iii) in DsExpr to decide how to expand
1539 -- The basic idea is that rhsIsStatic returns True only if the RHS is
1540 -- (a) a value lambda
1541 -- (b) a saturated constructor application with static args
1543 -- BUT watch out for
1544 -- (i) Any cross-DLL references kill static-ness completely
1545 -- because they must be 'executed' not statically allocated
1546 -- ("DLL" here really only refers to Windows DLLs, on other platforms,
1547 -- this is not necessary)
1549 -- (ii) We treat partial applications as redexes, because in fact we
1550 -- make a thunk for them that runs and builds a PAP
1551 -- at run-time. The only appliations that are treated as
1552 -- static are *saturated* applications of constructors.
1554 -- We used to try to be clever with nested structures like this:
1555 -- ys = (:) w ((:) w [])
1556 -- on the grounds that CorePrep will flatten ANF-ise it later.
1557 -- But supporting this special case made the function much more
1558 -- complicated, because the special case only applies if there are no
1559 -- enclosing type lambdas:
1560 -- ys = /\ a -> Foo (Baz ([] a))
1561 -- Here the nested (Baz []) won't float out to top level in CorePrep.
1563 -- But in fact, even without -O, nested structures at top level are
1564 -- flattened by the simplifier, so we don't need to be super-clever here.
1568 -- f = \x::Int. x+7 TRUE
1569 -- p = (True,False) TRUE
1571 -- d = (fst p, False) FALSE because there's a redex inside
1572 -- (this particular one doesn't happen but...)
1574 -- h = D# (1.0## /## 2.0##) FALSE (redex again)
1575 -- n = /\a. Nil a TRUE
1577 -- t = /\a. (:) (case w a of ...) (Nil a) FALSE (redex)
1580 -- This is a bit like CoreUtils.exprIsHNF, with the following differences:
1581 -- a) scc "foo" (\x -> ...) is updatable (so we catch the right SCC)
1583 -- b) (C x xs), where C is a contructor is updatable if the application is
1586 -- c) don't look through unfolding of f in (f x).
1588 rhsIsStatic _this_pkg rhs = is_static False rhs
1590 is_static :: Bool -- True <=> in a constructor argument; must be atomic
1593 is_static False (Lam b e) = isRuntimeVar b || is_static False e
1595 is_static _ (Note (SCC _) _) = False
1596 is_static in_arg (Note _ e) = is_static in_arg e
1597 is_static in_arg (Cast e _) = is_static in_arg e
1599 is_static _ (Lit lit)
1601 MachLabel _ _ -> False
1603 -- A MachLabel (foreign import "&foo") in an argument
1604 -- prevents a constructor application from being static. The
1605 -- reason is that it might give rise to unresolvable symbols
1606 -- in the object file: under Linux, references to "weak"
1607 -- symbols from the data segment give rise to "unresolvable
1608 -- relocation" errors at link time This might be due to a bug
1609 -- in the linker, but we'll work around it here anyway.
1612 is_static in_arg other_expr = go other_expr 0
1614 go (Var f) n_val_args
1615 #if mingw32_TARGET_OS
1616 | not (isDllName _this_pkg (idName f))
1618 = saturated_data_con f n_val_args
1619 || (in_arg && n_val_args == 0)
1620 -- A naked un-applied variable is *not* deemed a static RHS
1622 -- Reason: better to update so that the indirection gets shorted
1623 -- out, and the true value will be seen
1624 -- NB: if you change this, you'll break the invariant that THUNK_STATICs
1625 -- are always updatable. If you do so, make sure that non-updatable
1626 -- ones have enough space for their static link field!
1628 go (App f a) n_val_args
1629 | isTypeArg a = go f n_val_args
1630 | not in_arg && is_static True a = go f (n_val_args + 1)
1631 -- The (not in_arg) checks that we aren't in a constructor argument;
1632 -- if we are, we don't allow (value) applications of any sort
1634 -- NB. In case you wonder, args are sometimes not atomic. eg.
1635 -- x = D# (1.0## /## 2.0##)
1636 -- can't float because /## can fail.
1638 go (Note (SCC _) _) _ = False
1639 go (Note _ f) n_val_args = go f n_val_args
1640 go (Cast e _) n_val_args = go e n_val_args
1644 saturated_data_con f n_val_args
1645 = case isDataConWorkId_maybe f of
1646 Just dc -> n_val_args == dataConRepArity dc