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 e (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))
901 Note [Definition of arity]
902 ~~~~~~~~~~~~~~~~~~~~~~~~~~
903 The "arity" of an expression 'e' is n if
904 applying 'e' to *fewer* than n *value* arguments
907 Or, to put it another way
909 there is no work lost in duplicating the partial
910 application (e x1 .. x(n-1))
912 In the divegent case, no work is lost by duplicating because if the thing
913 is evaluated once, that's the end of the program.
915 Or, to put it another way, in any context C
917 C[ (\x1 .. xn. e x1 .. xn) ]
922 It's all a bit more subtle than it looks:
924 Note [Arity of case expressions]
925 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
926 We treat the arity of
927 case x of p -> \s -> ...
928 as 1 (or more) because for I/O ish things we really want to get that
929 \s to the top. We are prepared to evaluate x each time round the loop
930 in order to get that.
932 This isn't really right in the presence of seq. Consider
936 Can we eta-expand here? At first the answer looks like "yes of course", but
939 This should diverge! But if we eta-expand, it won't. Again, we ignore this
940 "problem", because being scrupulous would lose an important transformation for
944 1. Note [One-shot lambdas]
945 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
946 Consider one-shot lambdas
947 let x = expensive in \y z -> E
948 We want this to have arity 1 if the \y-abstraction is a 1-shot lambda.
950 3. Note [Dealing with bottom]
951 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
953 f = \x -> error "foo"
954 Here, arity 1 is fine. But if it is
958 then we want to get arity 2. Technically, this isn't quite right, because
960 should diverge, but it'll converge if we eta-expand f. Nevertheless, we
961 do so; it improves some programs significantly, and increasing convergence
962 isn't a bad thing. Hence the ABot/ATop in ArityType.
965 4. Note [Newtype arity]
966 ~~~~~~~~~~~~~~~~~~~~~~~~
967 Non-recursive newtypes are transparent, and should not get in the way.
968 We do (currently) eta-expand recursive newtypes too. So if we have, say
970 newtype T = MkT ([T] -> Int)
974 where f has arity 1. Then: etaExpandArity e = 1;
975 that is, etaExpandArity looks through the coerce.
977 When we eta-expand e to arity 1: eta_expand 1 e T
978 we want to get: coerce T (\x::[T] -> (coerce ([T]->Int) e) x)
980 HOWEVER, note that if you use coerce bogusly you can ge
982 And since negate has arity 2, you might try to eta expand. But you can't
983 decopose Int to a function type. Hence the final case in eta_expand.
986 Note [The state-transformer hack]
987 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
990 where e has arity n. Then, if we know from the context that f has
992 t1 -> ... -> tn -1-> t(n+1) -1-> ... -1-> tm -> ...
993 then we can expand the arity to m. This usage type says that
994 any application (x e1 .. en) will be applied to uniquely to (m-n) more args
995 Consider f = \x. let y = <expensive>
998 False -> \(s:RealWorld) -> e
999 where foo has arity 1. Then we want the state hack to
1000 apply to foo too, so we can eta expand the case.
1002 Then we expect that if f is applied to one arg, it'll be applied to two
1003 (that's the hack -- we don't really know, and sometimes it's false)
1004 See also Id.isOneShotBndr.
1007 applyStateHack :: CoreExpr -> ArityType -> Arity
1008 applyStateHack e (AT orig_arity is_bot)
1009 | opt_NoStateHack = orig_arity
1010 | ABot <- is_bot = orig_arity -- Note [State hack and bottoming functions]
1011 | otherwise = go orig_ty orig_arity
1012 where -- Note [The state-transformer hack]
1013 orig_ty = exprType e
1014 go :: Type -> Arity -> Arity
1015 go ty arity -- This case analysis should match that in eta_expand
1016 | Just (_, ty') <- splitForAllTy_maybe ty = go ty' arity
1018 | Just (tc,tys) <- splitTyConApp_maybe ty
1019 , Just (ty', _) <- instNewTyCon_maybe tc tys
1020 , not (isRecursiveTyCon tc) = go ty' arity
1021 -- Important to look through non-recursive newtypes, so that, eg
1022 -- (f x) where f has arity 2, f :: Int -> IO ()
1023 -- Here we want to get arity 1 for the result!
1025 | Just (arg,res) <- splitFunTy_maybe ty
1026 , arity > 0 || isStateHackType arg = 1 + go res (arity-1)
1028 = if arity > 0 then 1 + go res (arity-1)
1029 else if isStateHackType arg then
1030 pprTrace "applystatehack" (vcat [ppr orig_arity, ppr orig_ty,
1031 ppr ty, ppr res, ppr e]) $
1032 1 + go res (arity-1)
1033 else WARN( arity > 0, ppr arity ) 0
1035 | otherwise = WARN( arity > 0, ppr arity ) 0
1038 Note [State hack and bottoming functions]
1039 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1040 It's a terrible idea to use the state hack on a bottoming function.
1041 Here's what happens (Trac #2861):
1046 Eta-expand, using the state hack:
1048 f = \p. (\s. ((error "...") |> g1) s) |> g2
1049 g1 :: IO T ~ (S -> (S,T))
1050 g2 :: (S -> (S,T)) ~ IO T
1054 f' = \p. \s. ((error "...") |> g1) s
1055 f = f' |> (String -> g2)
1057 Discard args for bottomming function
1059 f' = \p. \s. ((error "...") |> g1 |> g3
1060 g3 :: (S -> (S,T)) ~ (S,T)
1064 f'' = \p. \s. (error "...")
1065 f' = f'' |> (String -> S -> g1.g3)
1067 And now we can repeat the whole loop. Aargh! The bug is in applying the
1068 state hack to a function which then swallows the argument.
1071 -------------------- Main arity code ----------------------------
1073 -- If e has ArityType (AT n r), then the term 'e'
1074 -- * Must be applied to at least n *value* args
1075 -- before doing any significant work
1076 -- * It will not diverge before being applied to n
1078 -- * If 'r' is ABot, then it guarantees to diverge if
1079 -- applied to n arguments (or more)
1081 data ArityType = AT Arity ArityRes
1082 data ArityRes = ATop -- Know nothing
1085 vanillaArityType :: ArityType
1086 vanillaArityType = AT 0 ATop -- Totally uninformative
1088 incArity :: ArityType -> ArityType
1089 incArity (AT a r) = AT (a+1) r
1091 decArity :: ArityType -> ArityType
1092 decArity (AT 0 r) = AT 0 r
1093 decArity (AT a r) = AT (a-1) r
1095 andArityType :: ArityType -> ArityType -> ArityType -- Used for branches of a 'case'
1096 andArityType (AT a1 ATop) (AT a2 ATop) = AT (a1 `min` a2) ATop
1097 andArityType (AT _ ABot) (AT a2 ATop) = AT a2 ATop
1098 andArityType (AT a1 ATop) (AT _ ABot) = AT a1 ATop
1099 andArityType (AT a1 ABot) (AT a2 ABot) = AT (a1 `max` a2) ABot
1101 trimArity :: Bool -> ArityType -> ArityType
1102 -- We have something like (let x = E in b), where b has the given
1104 -- * If E is cheap we can push it inside as far as we like
1105 -- * If b eventually diverges, we allow ourselves to push inside
1106 -- arbitrarily, even though that is not quite right
1107 trimArity _cheap (AT a ABot) = AT a ABot
1108 trimArity True (AT a ATop) = AT a ATop
1109 trimArity False (AT _ ATop) = AT 0 ATop -- Bale out
1111 ---------------------------
1112 arityType :: Bool -> CoreExpr -> ArityType
1114 | Just strict_sig <- idNewStrictness_maybe v
1115 , (ds, res) <- splitStrictSig strict_sig
1117 = AT (length ds) ABot -- Function diverges
1119 = AT (idArity v) ATop
1121 -- Lambdas; increase arity
1122 arityType dicts_cheap (Lam x e)
1123 | isId x = incArity (arityType dicts_cheap e)
1124 | otherwise = arityType dicts_cheap e
1126 -- Applications; decrease arity
1127 arityType dicts_cheap (App fun (Type _))
1128 = arityType dicts_cheap fun
1129 arityType dicts_cheap (App fun arg )
1130 = trimArity (exprIsCheap arg) (decArity (arityType dicts_cheap fun))
1132 -- Case/Let; keep arity if either the expression is cheap
1133 -- or it's a 1-shot lambda
1134 -- The former is not really right for Haskell
1135 -- f x = case x of { (a,b) -> \y. e }
1137 -- f x y = case x of { (a,b) -> e }
1138 -- The difference is observable using 'seq'
1139 arityType dicts_cheap (Case scrut _ _ alts)
1140 = trimArity (exprIsCheap scrut)
1141 (foldr1 andArityType [arityType dicts_cheap rhs | (_,_,rhs) <- alts])
1143 arityType dicts_cheap (Let b e)
1144 = trimArity (cheap_bind b) (arityType dicts_cheap e)
1146 cheap_bind (NonRec b e) = is_cheap (b,e)
1147 cheap_bind (Rec prs) = all is_cheap prs
1148 is_cheap (b,e) = (dicts_cheap && isDictId b) || exprIsCheap e
1149 -- If the experimental -fdicts-cheap flag is on, we eta-expand through
1150 -- dictionary bindings. This improves arities. Thereby, it also
1151 -- means that full laziness is less prone to floating out the
1152 -- application of a function to its dictionary arguments, which
1153 -- can thereby lose opportunities for fusion. Example:
1154 -- foo :: Ord a => a -> ...
1155 -- foo = /\a \(d:Ord a). let d' = ...d... in \(x:a). ....
1156 -- -- So foo has arity 1
1158 -- f = \x. foo dInt $ bar x
1160 -- The (foo DInt) is floated out, and makes ineffective a RULE
1161 -- foo (bar x) = ...
1163 -- One could go further and make exprIsCheap reply True to any
1164 -- dictionary-typed expression, but that's more work.
1166 arityType dicts_cheap (Note _ e) = arityType dicts_cheap e
1167 arityType dicts_cheap (Cast e _) = arityType dicts_cheap e
1168 arityType _ _ = vanillaArityType
1173 -- | @etaExpand n us e ty@ returns an expression with
1174 -- the same meaning as @e@, but with arity @n@.
1178 -- > e' = etaExpand n us e ty
1180 -- We should have that:
1182 -- > ty = exprType e = exprType e'
1183 etaExpand :: Arity -- ^ Result should have this number of value args
1184 -> [Unique] -- ^ Uniques to assign to the new binders
1185 -> CoreExpr -- ^ Expression to expand
1186 -> Type -- ^ Type of expression to expand
1188 -- Note that SCCs are not treated specially. If we have
1189 -- etaExpand 2 (\x -> scc "foo" e)
1190 -- = (\xy -> (scc "foo" e) y)
1191 -- So the costs of evaluating 'e' (not 'e y') are attributed to "foo"
1193 etaExpand n us expr ty
1194 | manifestArity expr >= n = expr -- The no-op case
1195 | otherwise = eta_expand n us expr ty
1197 -- manifestArity sees how many leading value lambdas there are
1198 manifestArity :: CoreExpr -> Arity
1199 manifestArity (Lam v e) | isId v = 1 + manifestArity e
1200 | otherwise = manifestArity e
1201 manifestArity (Note _ e) = manifestArity e
1202 manifestArity (Cast e _) = manifestArity e
1205 -- etaExpand deals with for-alls. For example:
1207 -- where E :: forall a. a -> a
1209 -- (/\b. \y::a -> E b y)
1211 -- It deals with coerces too, though they are now rare
1212 -- so perhaps the extra code isn't worth it
1213 eta_expand :: Int -> [Unique] -> CoreExpr -> Type -> CoreExpr
1215 eta_expand n _ expr _
1216 | n == 0 -- Saturated, so nothing to do
1219 -- Short cut for the case where there already
1220 -- is a lambda; no point in gratuitously adding more
1221 eta_expand n us (Lam v body) ty
1223 = Lam v (eta_expand n us body (applyTy ty (mkTyVarTy v)))
1226 = Lam v (eta_expand (n-1) us body (funResultTy ty))
1228 -- We used to have a special case that stepped inside Coerces here,
1229 -- thus: eta_expand n us (Note note@(Coerce _ ty) e) _
1230 -- = Note note (eta_expand n us e ty)
1231 -- BUT this led to an infinite loop
1232 -- Example: newtype T = MkT (Int -> Int)
1233 -- eta_expand 1 (coerce (Int->Int) e)
1234 -- --> coerce (Int->Int) (eta_expand 1 T e)
1236 -- --> coerce (Int->Int) (coerce T
1237 -- (\x::Int -> eta_expand 1 (coerce (Int->Int) e)))
1238 -- by the splitNewType_maybe case below
1241 eta_expand n us expr ty
1242 = ASSERT2 (exprType expr `coreEqType` ty, ppr (exprType expr) $$ ppr ty)
1243 case splitForAllTy_maybe ty of {
1246 Lam lam_tv (eta_expand n us2 (App expr (Type (mkTyVarTy lam_tv))) (substTyWith [tv] [mkTyVarTy lam_tv] ty'))
1248 lam_tv = setVarName tv (mkSysTvName uniq (fsLit "etaT"))
1249 -- Using tv as a base retains its tyvar/covar-ness
1253 case splitFunTy_maybe ty of {
1254 Just (arg_ty, res_ty) -> Lam arg1 (eta_expand (n-1) us2 (App expr (Var arg1)) res_ty)
1256 arg1 = mkSysLocal (fsLit "eta") uniq arg_ty
1262 -- newtype T = MkT ([T] -> Int)
1263 -- Consider eta-expanding this
1266 -- coerce T (\x::[T] -> (coerce ([T]->Int) e) x)
1268 case splitNewTypeRepCo_maybe ty of {
1269 Just(ty1,co) -> mkCoerce (mkSymCoercion co)
1270 (eta_expand n us (mkCoerce co expr) ty1) ;
1273 -- We have an expression of arity > 0, but its type isn't a function
1274 -- This *can* legitmately happen: e.g. coerce Int (\x. x)
1275 -- Essentially the programmer is playing fast and loose with types
1276 -- (Happy does this a lot). So we simply decline to eta-expand.
1277 -- Otherwise we'd end up with an explicit lambda having a non-function type
1282 exprArity is a cheap-and-cheerful version of exprEtaExpandArity.
1283 It tells how many things the expression can be applied to before doing
1284 any work. It doesn't look inside cases, lets, etc. The idea is that
1285 exprEtaExpandArity will do the hard work, leaving something that's easy
1286 for exprArity to grapple with. In particular, Simplify uses exprArity to
1287 compute the ArityInfo for the Id.
1289 Originally I thought that it was enough just to look for top-level lambdas, but
1290 it isn't. I've seen this
1292 foo = PrelBase.timesInt
1294 We want foo to get arity 2 even though the eta-expander will leave it
1295 unchanged, in the expectation that it'll be inlined. But occasionally it
1296 isn't, because foo is blacklisted (used in a rule).
1298 Similarly, see the ok_note check in exprEtaExpandArity. So
1299 f = __inline_me (\x -> e)
1300 won't be eta-expanded.
1302 And in any case it seems more robust to have exprArity be a bit more intelligent.
1303 But note that (\x y z -> f x y z)
1304 should have arity 3, regardless of f's arity.
1306 Note [exprArity invariant]
1307 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1308 exprArity has the following invariant:
1309 (exprArity e) = n, then manifestArity (etaExpand e n) = n
1311 That is, if exprArity says "the arity is n" then etaExpand really can get
1312 "n" manifest lambdas to the top.
1314 Why is this important? Because
1315 - In TidyPgm we use exprArity to fix the *final arity* of
1316 each top-level Id, and in
1317 - In CorePrep we use etaExpand on each rhs, so that the visible lambdas
1318 actually match that arity, which in turn means
1319 that the StgRhs has the right number of lambdas
1321 An alternative would be to do the eta-expansion in TidyPgm, at least
1322 for top-level bindings, in which case we would not need the trim_arity
1323 in exprArity. That is a less local change, so I'm going to leave it for today!
1327 -- | An approximate, fast, version of 'exprEtaExpandArity'
1328 exprArity :: CoreExpr -> Arity
1331 go (Var v) = idArity v
1332 go (Lam x e) | isId x = go e + 1
1334 go (Note _ e) = go e
1335 go (Cast e co) = trim_arity (go e) 0 (snd (coercionKind co))
1336 go (App e (Type _)) = go e
1337 go (App f a) | exprIsCheap a = (go f - 1) `max` 0
1338 -- NB: exprIsCheap a!
1339 -- f (fac x) does not have arity 2,
1340 -- even if f has arity 3!
1341 -- NB: `max 0`! (\x y -> f x) has arity 2, even if f is
1342 -- unknown, hence arity 0
1345 -- Note [exprArity invariant]
1348 | Just (_, ty') <- splitForAllTy_maybe ty = trim_arity n a ty'
1349 | Just (_, ty') <- splitFunTy_maybe ty = trim_arity n (a+1) ty'
1350 | Just (ty',_) <- splitNewTypeRepCo_maybe ty = trim_arity n a ty'
1354 %************************************************************************
1356 \subsection{Equality}
1358 %************************************************************************
1361 -- | A cheap equality test which bales out fast!
1362 -- If it returns @True@ the arguments are definitely equal,
1363 -- otherwise, they may or may not be equal.
1365 -- See also 'exprIsBig'
1366 cheapEqExpr :: Expr b -> Expr b -> Bool
1368 cheapEqExpr (Var v1) (Var v2) = v1==v2
1369 cheapEqExpr (Lit lit1) (Lit lit2) = lit1 == lit2
1370 cheapEqExpr (Type t1) (Type t2) = t1 `coreEqType` t2
1372 cheapEqExpr (App f1 a1) (App f2 a2)
1373 = f1 `cheapEqExpr` f2 && a1 `cheapEqExpr` a2
1375 cheapEqExpr (Cast e1 t1) (Cast e2 t2)
1376 = e1 `cheapEqExpr` e2 && t1 `coreEqCoercion` t2
1378 cheapEqExpr _ _ = False
1380 exprIsBig :: Expr b -> Bool
1381 -- ^ Returns @True@ of expressions that are too big to be compared by 'cheapEqExpr'
1382 exprIsBig (Lit _) = False
1383 exprIsBig (Var _) = False
1384 exprIsBig (Type _) = False
1385 exprIsBig (Lam _ e) = exprIsBig e
1386 exprIsBig (App f a) = exprIsBig f || exprIsBig a
1387 exprIsBig (Cast e _) = exprIsBig e -- Hopefully coercions are not too big!
1393 tcEqExpr :: CoreExpr -> CoreExpr -> Bool
1394 -- ^ A kind of shallow equality used in rule matching, so does
1395 -- /not/ look through newtypes or predicate types
1397 tcEqExpr e1 e2 = tcEqExprX rn_env e1 e2
1399 rn_env = mkRnEnv2 (mkInScopeSet (exprFreeVars e1 `unionVarSet` exprFreeVars e2))
1401 tcEqExprX :: RnEnv2 -> CoreExpr -> CoreExpr -> Bool
1402 tcEqExprX env (Var v1) (Var v2) = rnOccL env v1 == rnOccR env v2
1403 tcEqExprX _ (Lit lit1) (Lit lit2) = lit1 == lit2
1404 tcEqExprX env (App f1 a1) (App f2 a2) = tcEqExprX env f1 f2 && tcEqExprX env a1 a2
1405 tcEqExprX env (Lam v1 e1) (Lam v2 e2) = tcEqExprX (rnBndr2 env v1 v2) e1 e2
1406 tcEqExprX env (Let (NonRec v1 r1) e1)
1407 (Let (NonRec v2 r2) e2) = tcEqExprX env r1 r2
1408 && tcEqExprX (rnBndr2 env v1 v2) e1 e2
1409 tcEqExprX env (Let (Rec ps1) e1)
1410 (Let (Rec ps2) e2) = equalLength ps1 ps2
1411 && and (zipWith eq_rhs ps1 ps2)
1412 && tcEqExprX env' e1 e2
1414 env' = foldl2 rn_bndr2 env ps2 ps2
1415 rn_bndr2 env (b1,_) (b2,_) = rnBndr2 env b1 b2
1416 eq_rhs (_,r1) (_,r2) = tcEqExprX env' r1 r2
1417 tcEqExprX env (Case e1 v1 t1 a1)
1418 (Case e2 v2 t2 a2) = tcEqExprX env e1 e2
1419 && tcEqTypeX env t1 t2
1420 && equalLength a1 a2
1421 && and (zipWith (eq_alt env') a1 a2)
1423 env' = rnBndr2 env v1 v2
1425 tcEqExprX env (Note n1 e1) (Note n2 e2) = eq_note env n1 n2 && tcEqExprX env e1 e2
1426 tcEqExprX env (Cast e1 co1) (Cast e2 co2) = tcEqTypeX env co1 co2 && tcEqExprX env e1 e2
1427 tcEqExprX env (Type t1) (Type t2) = tcEqTypeX env t1 t2
1428 tcEqExprX _ _ _ = False
1430 eq_alt :: RnEnv2 -> CoreAlt -> CoreAlt -> Bool
1431 eq_alt env (c1,vs1,r1) (c2,vs2,r2) = c1==c2 && tcEqExprX (rnBndrs2 env vs1 vs2) r1 r2
1433 eq_note :: RnEnv2 -> Note -> Note -> Bool
1434 eq_note _ (SCC cc1) (SCC cc2) = cc1 == cc2
1435 eq_note _ (CoreNote s1) (CoreNote s2) = s1 == s2
1436 eq_note _ _ _ = False
1440 %************************************************************************
1442 \subsection{The size of an expression}
1444 %************************************************************************
1447 coreBindsSize :: [CoreBind] -> Int
1448 coreBindsSize bs = foldr ((+) . bindSize) 0 bs
1450 exprSize :: CoreExpr -> Int
1451 -- ^ A measure of the size of the expressions, strictly greater than 0
1452 -- It also forces the expression pretty drastically as a side effect
1453 exprSize (Var v) = v `seq` 1
1454 exprSize (Lit lit) = lit `seq` 1
1455 exprSize (App f a) = exprSize f + exprSize a
1456 exprSize (Lam b e) = varSize b + exprSize e
1457 exprSize (Let b e) = bindSize b + exprSize e
1458 exprSize (Case e b t as) = seqType t `seq` exprSize e + varSize b + 1 + foldr ((+) . altSize) 0 as
1459 exprSize (Cast e co) = (seqType co `seq` 1) + exprSize e
1460 exprSize (Note n e) = noteSize n + exprSize e
1461 exprSize (Type t) = seqType t `seq` 1
1463 noteSize :: Note -> Int
1464 noteSize (SCC cc) = cc `seq` 1
1465 noteSize (CoreNote s) = s `seq` 1 -- hdaume: core annotations
1467 varSize :: Var -> Int
1468 varSize b | isTyVar b = 1
1469 | otherwise = seqType (idType b) `seq`
1470 megaSeqIdInfo (idInfo b) `seq`
1473 varsSize :: [Var] -> Int
1474 varsSize = sum . map varSize
1476 bindSize :: CoreBind -> Int
1477 bindSize (NonRec b e) = varSize b + exprSize e
1478 bindSize (Rec prs) = foldr ((+) . pairSize) 0 prs
1480 pairSize :: (Var, CoreExpr) -> Int
1481 pairSize (b,e) = varSize b + exprSize e
1483 altSize :: CoreAlt -> Int
1484 altSize (c,bs,e) = c `seq` varsSize bs + exprSize e
1488 %************************************************************************
1490 \subsection{Hashing}
1492 %************************************************************************
1495 hashExpr :: CoreExpr -> Int
1496 -- ^ Two expressions that hash to the same @Int@ may be equal (but may not be)
1497 -- Two expressions that hash to the different Ints are definitely unequal.
1499 -- The emphasis is on a crude, fast hash, rather than on high precision.
1501 -- But unequal here means \"not identical\"; two alpha-equivalent
1502 -- expressions may hash to the different Ints.
1504 -- We must be careful that @\\x.x@ and @\\y.y@ map to the same hash code,
1505 -- (at least if we want the above invariant to be true).
1507 hashExpr e = fromIntegral (hash_expr (1,emptyVarEnv) e .&. 0x7fffffff)
1508 -- UniqFM doesn't like negative Ints
1510 type HashEnv = (Int, VarEnv Int) -- Hash code for bound variables
1512 hash_expr :: HashEnv -> CoreExpr -> Word32
1513 -- Word32, because we're expecting overflows here, and overflowing
1514 -- signed types just isn't cool. In C it's even undefined.
1515 hash_expr env (Note _ e) = hash_expr env e
1516 hash_expr env (Cast e _) = hash_expr env e
1517 hash_expr env (Var v) = hashVar env v
1518 hash_expr _ (Lit lit) = fromIntegral (hashLiteral lit)
1519 hash_expr env (App f e) = hash_expr env f * fast_hash_expr env e
1520 hash_expr env (Let (NonRec b r) e) = hash_expr (extend_env env b) e * fast_hash_expr env r
1521 hash_expr env (Let (Rec ((b,_):_)) e) = hash_expr (extend_env env b) e
1522 hash_expr env (Case e _ _ _) = hash_expr env e
1523 hash_expr env (Lam b e) = hash_expr (extend_env env b) e
1524 hash_expr _ (Type _) = WARN(True, text "hash_expr: type") 1
1525 -- Shouldn't happen. Better to use WARN than trace, because trace
1526 -- prevents the CPR optimisation kicking in for hash_expr.
1528 fast_hash_expr :: HashEnv -> CoreExpr -> Word32
1529 fast_hash_expr env (Var v) = hashVar env v
1530 fast_hash_expr env (Type t) = fast_hash_type env t
1531 fast_hash_expr _ (Lit lit) = fromIntegral (hashLiteral lit)
1532 fast_hash_expr env (Cast e _) = fast_hash_expr env e
1533 fast_hash_expr env (Note _ e) = fast_hash_expr env e
1534 fast_hash_expr env (App _ a) = fast_hash_expr env a -- A bit idiosyncratic ('a' not 'f')!
1535 fast_hash_expr _ _ = 1
1537 fast_hash_type :: HashEnv -> Type -> Word32
1538 fast_hash_type env ty
1539 | Just tv <- getTyVar_maybe ty = hashVar env tv
1540 | Just (tc,tys) <- splitTyConApp_maybe ty = let hash_tc = fromIntegral (hashName (tyConName tc))
1541 in foldr (\t n -> fast_hash_type env t + n) hash_tc tys
1544 extend_env :: HashEnv -> Var -> (Int, VarEnv Int)
1545 extend_env (n,env) b = (n+1, extendVarEnv env b n)
1547 hashVar :: HashEnv -> Var -> Word32
1549 = fromIntegral (lookupVarEnv env v `orElse` hashName (idName v))
1552 %************************************************************************
1554 \subsection{Determining non-updatable right-hand-sides}
1556 %************************************************************************
1558 Top-level constructor applications can usually be allocated
1559 statically, but they can't if the constructor, or any of the
1560 arguments, come from another DLL (because we can't refer to static
1561 labels in other DLLs).
1563 If this happens we simply make the RHS into an updatable thunk,
1564 and 'execute' it rather than allocating it statically.
1567 -- | This function is called only on *top-level* right-hand sides.
1568 -- Returns @True@ if the RHS can be allocated statically in the output,
1569 -- with no thunks involved at all.
1570 rhsIsStatic :: PackageId -> CoreExpr -> Bool
1571 -- It's called (i) in TidyPgm.hasCafRefs to decide if the rhs is, or
1572 -- refers to, CAFs; (ii) in CoreToStg to decide whether to put an
1573 -- update flag on it and (iii) in DsExpr to decide how to expand
1576 -- The basic idea is that rhsIsStatic returns True only if the RHS is
1577 -- (a) a value lambda
1578 -- (b) a saturated constructor application with static args
1580 -- BUT watch out for
1581 -- (i) Any cross-DLL references kill static-ness completely
1582 -- because they must be 'executed' not statically allocated
1583 -- ("DLL" here really only refers to Windows DLLs, on other platforms,
1584 -- this is not necessary)
1586 -- (ii) We treat partial applications as redexes, because in fact we
1587 -- make a thunk for them that runs and builds a PAP
1588 -- at run-time. The only appliations that are treated as
1589 -- static are *saturated* applications of constructors.
1591 -- We used to try to be clever with nested structures like this:
1592 -- ys = (:) w ((:) w [])
1593 -- on the grounds that CorePrep will flatten ANF-ise it later.
1594 -- But supporting this special case made the function much more
1595 -- complicated, because the special case only applies if there are no
1596 -- enclosing type lambdas:
1597 -- ys = /\ a -> Foo (Baz ([] a))
1598 -- Here the nested (Baz []) won't float out to top level in CorePrep.
1600 -- But in fact, even without -O, nested structures at top level are
1601 -- flattened by the simplifier, so we don't need to be super-clever here.
1605 -- f = \x::Int. x+7 TRUE
1606 -- p = (True,False) TRUE
1608 -- d = (fst p, False) FALSE because there's a redex inside
1609 -- (this particular one doesn't happen but...)
1611 -- h = D# (1.0## /## 2.0##) FALSE (redex again)
1612 -- n = /\a. Nil a TRUE
1614 -- t = /\a. (:) (case w a of ...) (Nil a) FALSE (redex)
1617 -- This is a bit like CoreUtils.exprIsHNF, with the following differences:
1618 -- a) scc "foo" (\x -> ...) is updatable (so we catch the right SCC)
1620 -- b) (C x xs), where C is a contructor is updatable if the application is
1623 -- c) don't look through unfolding of f in (f x).
1625 rhsIsStatic _this_pkg rhs = is_static False rhs
1627 is_static :: Bool -- True <=> in a constructor argument; must be atomic
1630 is_static False (Lam b e) = isRuntimeVar b || is_static False e
1632 is_static _ (Note (SCC _) _) = False
1633 is_static in_arg (Note _ e) = is_static in_arg e
1634 is_static in_arg (Cast e _) = is_static in_arg e
1636 is_static _ (Lit lit)
1638 MachLabel _ _ -> False
1640 -- A MachLabel (foreign import "&foo") in an argument
1641 -- prevents a constructor application from being static. The
1642 -- reason is that it might give rise to unresolvable symbols
1643 -- in the object file: under Linux, references to "weak"
1644 -- symbols from the data segment give rise to "unresolvable
1645 -- relocation" errors at link time This might be due to a bug
1646 -- in the linker, but we'll work around it here anyway.
1649 is_static in_arg other_expr = go other_expr 0
1651 go (Var f) n_val_args
1652 #if mingw32_TARGET_OS
1653 | not (isDllName _this_pkg (idName f))
1655 = saturated_data_con f n_val_args
1656 || (in_arg && n_val_args == 0)
1657 -- A naked un-applied variable is *not* deemed a static RHS
1659 -- Reason: better to update so that the indirection gets shorted
1660 -- out, and the true value will be seen
1661 -- NB: if you change this, you'll break the invariant that THUNK_STATICs
1662 -- are always updatable. If you do so, make sure that non-updatable
1663 -- ones have enough space for their static link field!
1665 go (App f a) n_val_args
1666 | isTypeArg a = go f n_val_args
1667 | not in_arg && is_static True a = go f (n_val_args + 1)
1668 -- The (not in_arg) checks that we aren't in a constructor argument;
1669 -- if we are, we don't allow (value) applications of any sort
1671 -- NB. In case you wonder, args are sometimes not atomic. eg.
1672 -- x = D# (1.0## /## 2.0##)
1673 -- can't float because /## can fail.
1675 go (Note (SCC _) _) _ = False
1676 go (Note _ f) n_val_args = go f n_val_args
1677 go (Cast e _) n_val_args = go e n_val_args
1681 saturated_data_con f n_val_args
1682 = case isDataConWorkId_maybe f of
1683 Just dc -> n_val_args == dataConRepArity dc