CoreUtils.lhs 72.8 KB
Newer Older
1
%
Simon Marlow's avatar
Simon Marlow committed
2
% (c) The University of Glasgow 2006
3
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
%
Simon Marlow's avatar
Simon Marlow committed
5 6

Utility functions on @Core@ syntax
7 8

\begin{code}
batterseapower's avatar
batterseapower committed
9
-- | Commonly useful utilites for manipulating the Core language
10
module CoreUtils (
11
        -- * Constructing expressions
12
        mkCast,
13
        mkTick, mkTickNoHNF, tickHNFArgs,
Simon Marlow's avatar
Simon Marlow committed
14
        bindNonRec, needsCaseBinding,
15
        mkAltExpr,
16

17
        -- * Taking expressions apart
18 19
        findDefault, findAlt, isDefaultAlt,
        mergeAlts, trimConArgs, filterAlts,
20

21
        -- * Properties of expressions
Simon Marlow's avatar
Simon Marlow committed
22
        exprType, coreAltType, coreAltsType,
23
        exprIsDupable, exprIsTrivial, getIdFromTrivialExpr, exprIsBottom,
24
        exprIsCheap, exprIsExpandable, exprIsCheap', CheapAppFun,
25
        exprIsHNF, exprOkForSpeculation, exprOkForSideEffects, exprIsWorkFree,
26 27
        exprIsBig, exprIsConLike,
        rhsIsStatic, isCheapApp, isExpandableApp,
28

29 30 31
        -- * Expression and bindings size
        coreBindsSize, exprSize,
        CoreStats(..), coreBindsStats,
32

33 34
        -- * Hashing
        hashExpr,
35

36 37
        -- * Equality
        cheapEqExpr, eqExpr, eqExprX,
38

39 40
        -- * Eta reduction
        tryEtaReduce,
41

42 43
        -- * Manipulating data constructors and types
        applyTypeToArgs, applyTypeToArg,
44
        dataConRepInstPat, dataConRepFSInstPat
45
    ) where
46

47
#include "HsVersions.h"
48

49
import CoreSyn
Simon Marlow's avatar
Simon Marlow committed
50 51 52
import PprCore
import Var
import SrcLoc
53
import VarEnv
54
import VarSet
Simon Marlow's avatar
Simon Marlow committed
55 56 57 58 59 60 61 62 63 64
import Name
import Literal
import DataCon
import PrimOp
import Id
import IdInfo
import Type
import Coercion
import TyCon
import Unique
65
import Outputable
Simon Marlow's avatar
Simon Marlow committed
66
import TysPrim
67
import DynFlags
Simon Marlow's avatar
Simon Marlow committed
68
import FastString
69
import Maybes
70
import Platform
Simon Marlow's avatar
Simon Marlow committed
71
import Util
72
import Pair
73 74
import Data.Word
import Data.Bits
75
import Data.List
76
\end{code}
77

78

79
%************************************************************************
80
%*                                                                      *
81
\subsection{Find the type of a Core atom/expression}
82
%*                                                                      *
83 84 85
%************************************************************************

\begin{code}
86
exprType :: CoreExpr -> Type
batterseapower's avatar
batterseapower committed
87 88 89
-- ^ Recover the type of a well-typed Core expression. Fails when
-- applied to the actual 'CoreSyn.Type' expression as it cannot
-- really be said to have a type
90 91 92 93
exprType (Var var)           = idType var
exprType (Lit lit)           = literalType lit
exprType (Coercion co)       = coercionType co
exprType (Let _ body)        = exprType body
94
exprType (Case _ _ ty _)     = ty
95
exprType (Cast _ co)         = pSnd (coercionKind co)
96
exprType (Tick _ e)          = exprType e
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
97
exprType (Lam binder expr)   = mkPiType binder (exprType expr)
98
exprType e@(App _ _)
99
  = case collectArgs e of
100
        (fun, args) -> applyTypeToArgs e (exprType fun) args
101

102
exprType other = pprTrace "exprType" (pprCoreExpr other) alphaTy
103

104
coreAltType :: CoreAlt -> Type
batterseapower's avatar
batterseapower committed
105
-- ^ Returns the type of the alternatives right hand side
106
coreAltType (_,bs,rhs)
107 108 109 110 111
  | any bad_binder bs = expandTypeSynonyms ty
  | otherwise         = ty    -- Note [Existential variables and silly type synonyms]
  where
    ty           = exprType rhs
    free_tvs     = tyVarsOfType ty
112
    bad_binder b = isTyVar b && b `elemVarSet` free_tvs
113 114

coreAltsType :: [CoreAlt] -> Type
batterseapower's avatar
batterseapower committed
115
-- ^ Returns the type of the first alternative, which should be the same as for all alternatives
116
coreAltsType (alt:_) = coreAltType alt
117
coreAltsType []      = panic "corAltsType"
118 119
\end{code}

120 121 122
Note [Existential variables and silly type synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
123 124 125 126
        data T = forall a. T (Funny a)
        type Funny a = Bool
        f :: T -> Bool
        f (T x) = x
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

Now, the type of 'x' is (Funny a), where 'a' is existentially quantified.
That means that 'exprType' and 'coreAltsType' may give a result that *appears*
to mention an out-of-scope type variable.  See Trac #3409 for a more real-world
example.

Various possibilities suggest themselves:

 - Ignore the problem, and make Lint not complain about such variables

 - Expand all type synonyms (or at least all those that discard arguments)
      This is tricky, because at least for top-level things we want to
      retain the type the user originally specified.

 - Expand synonyms on the fly, when the problem arises. That is what
   we are doing here.  It's not too expensive, I think.

144
\begin{code}
145
applyTypeToArg :: Type -> CoreExpr -> Type
batterseapower's avatar
batterseapower committed
146
-- ^ Determines the type resulting from applying an expression to a function with the given type
147
applyTypeToArg fun_ty (Type arg_ty) = applyTy fun_ty arg_ty
148
applyTypeToArg fun_ty _             = funResultTy fun_ty
149

150
applyTypeToArgs :: CoreExpr -> Type -> [CoreExpr] -> Type
batterseapower's avatar
batterseapower committed
151 152
-- ^ A more efficient version of 'applyTypeToArg' when we have several arguments.
-- The first argument is just for debugging, and gives some context
153
applyTypeToArgs _ op_ty [] = op_ty
154

155
applyTypeToArgs e op_ty (Type ty : args)
156
  =     -- Accumulate type arguments so we can instantiate all at once
157
    go [ty] args
158
  where
159
    go rev_tys (Type ty : args) = go (ty:rev_tys) args
160
    go rev_tys rest_args         = applyTypeToArgs e op_ty' rest_args
161 162 163 164
                                 where
                                   op_ty' = applyTysD msg op_ty (reverse rev_tys)
                                   msg = ptext (sLit "applyTypeToArgs") <+>
                                         panic_msg e op_ty
165

166
applyTypeToArgs e op_ty (_ : args)
167
  = case (splitFunTy_maybe op_ty) of
168 169
        Just (_, res_ty) -> applyTypeToArgs e res_ty args
        Nothing -> pprPanic "applyTypeToArgs" (panic_msg e op_ty)
170 171 172

panic_msg :: CoreExpr -> Type -> SDoc
panic_msg e op_ty = pprCoreExpr e $$ ppr op_ty
173 174
\end{code}

175
%************************************************************************
176
%*                                                                      *
177
\subsection{Attaching notes}
178
%*                                                                      *
179 180 181
%************************************************************************

\begin{code}
182 183
-- | Wrap the given expression in the coercion safely, dropping
-- identity coercions and coalescing nested coercions
184 185 186 187
mkCast :: CoreExpr -> Coercion -> CoreExpr
mkCast e co | isReflCo co = e

mkCast (Coercion e_co) co 
188 189 190 191
  | isCoVarType (pSnd (coercionKind co))
       -- The guard here checks that g has a (~#) on both sides,
       -- otherwise decomposeCo fails.  Can in principle happen
       -- with unsafeCoerce
192
  = Coercion (mkCoCast e_co co)
193 194

mkCast (Cast expr co2) co
195
  = ASSERT(let { Pair  from_ty  _to_ty  = coercionKind co;
196 197
                 Pair _from_ty2  to_ty2 = coercionKind co2} in
           from_ty `eqType` to_ty2 )
198
    mkCast expr (mkTransCo co2 co)
199

200
mkCast expr co
201 202
  = let Pair from_ty _to_ty = coercionKind co in
--    if to_ty `eqType` from_ty
203
--    then expr
204
--    else
205
        WARN(not (from_ty `eqType` exprType expr), text "Trying to coerce" <+> text "(" <> ppr expr $$ text "::" <+> ppr (exprType expr) <> text ")" $$ ppr co $$ pprEqPred (coercionKind co))
206
         (Cast expr co)
207 208 209
\end{code}

\begin{code}
210 211 212 213
-- | Wraps the given expression in the source annotation, dropping the
-- annotation if possible.
mkTick :: Tickish Id -> CoreExpr -> CoreExpr

214 215 216 217 218 219 220 221 222
mkTick t (Var x)
  | isFunTy (idType x) = Tick t (Var x)
  | otherwise
  = if tickishCounts t
       then if tickishScoped t && tickishCanSplit t
               then Tick (mkNoScope t) (Var x)
               else Tick t (Var x)
       else Var x

223 224 225
mkTick t (Cast e co)
  = Cast (mkTick t e) co -- Move tick inside cast

Simon Marlow's avatar
Simon Marlow committed
226
mkTick _ (Coercion co) = Coercion co
227

228 229
mkTick t (Lit l)
  | not (tickishCounts t) = Lit l
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

mkTick t expr@(App f arg)
  | not (isRuntimeArg arg) = App (mkTick t f) arg
  | isSaturatedConApp expr
    = if not (tickishCounts t)
         then tickHNFArgs t expr
         else if tickishScoped t && tickishCanSplit t
                 then Tick (mkNoScope t) (tickHNFArgs (mkNoTick t) expr)
                 else Tick t expr

mkTick t (Lam x e)
     -- if this is a type lambda, or the tick does not count entries,
     -- then we can push the tick inside:
  | not (isRuntimeVar x) || not (tickishCounts t) = Lam x (mkTick t e)
     -- if it is both counting and scoped, we split the tick into its
     -- two components, keep the counting tick on the outside of the lambda
     -- and push the scoped tick inside.  The point of this is that the
     -- counting tick can probably be floated, and the lambda may then be
     -- in a position to be beta-reduced.
  | tickishScoped t && tickishCanSplit t
         = Tick (mkNoScope t) (Lam x (mkTick (mkNoTick t) e))
     -- just a counting tick: leave it on the outside
  | otherwise        = Tick t (Lam x e)

mkTick t other = Tick t other

isSaturatedConApp :: CoreExpr -> Bool
isSaturatedConApp e = go e []
  where go (App f a) as = go f (a:as)
        go (Var fun) args
           = isConLikeId fun && idArity fun == valArgCount args
        go (Cast f _) as = go f as
        go _ _ = False

mkTickNoHNF :: Tickish Id -> CoreExpr -> CoreExpr
mkTickNoHNF t e
  | exprIsHNF e = tickHNFArgs t e
  | otherwise   = mkTick t e

-- push a tick into the arguments of a HNF (call or constructor app)
tickHNFArgs :: Tickish Id -> CoreExpr -> CoreExpr
tickHNFArgs t e = push t e
 where
  push t (App f (Type u)) = App (push t f) (Type u)
  push t (App f arg) = App (push t f) (mkTick t arg)
  push _t e = e
276 277
\end{code}

278
%************************************************************************
279
%*                                                                      *
280
\subsection{Other expression construction}
281
%*                                                                      *
282 283 284 285
%************************************************************************

\begin{code}
bindNonRec :: Id -> CoreExpr -> CoreExpr -> CoreExpr
batterseapower's avatar
batterseapower committed
286 287 288 289 290 291 292
-- ^ @bindNonRec x r b@ produces either:
--
-- > let x = r in b
--
-- or:
--
-- > case r of x { _DEFAULT_ -> b }
293
--
batterseapower's avatar
batterseapower committed
294 295
-- depending on whether we have to use a @case@ or @let@
-- binding for the expression (see 'needsCaseBinding').
296
-- It's used by the desugarer to avoid building bindings
batterseapower's avatar
batterseapower committed
297 298 299
-- that give Core Lint a heart attack, although actually
-- the simplifier deals with them perfectly well. See
-- also 'MkCore.mkCoreLet'
300
bindNonRec bndr rhs body
batterseapower's avatar
batterseapower committed
301
  | needsCaseBinding (idType bndr) rhs = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
302
  | otherwise                          = Let (NonRec bndr rhs) body
303

batterseapower's avatar
batterseapower committed
304 305
-- | Tests whether we have to use a @case@ rather than @let@ binding for this expression
-- as per the invariants of 'CoreExpr': see "CoreSyn#let_app_invariant"
306
needsCaseBinding :: Type -> CoreExpr -> Bool
307
needsCaseBinding ty rhs = isUnLiftedType ty && not (exprOkForSpeculation rhs)
308 309 310
        -- Make a case expression instead of a let
        -- These can arise either from the desugarer,
        -- or from beta reductions: (\x.e) (x +# y)
311 312 313
\end{code}

\begin{code}
batterseapower's avatar
batterseapower committed
314 315 316 317 318 319
mkAltExpr :: AltCon     -- ^ Case alternative constructor
          -> [CoreBndr] -- ^ Things bound by the pattern match
          -> [Type]     -- ^ The type arguments to the case alternative
          -> CoreExpr
-- ^ This guy constructs the value that the scrutinee must have
-- given that you are in one particular branch of a case
320
mkAltExpr (DataAlt con) args inst_tys
321
  = mkConApp con (map Type inst_tys ++ varsToCoreExprs args)
322 323
mkAltExpr (LitAlt lit) [] []
  = Lit lit
324 325
mkAltExpr (LitAlt _) _ _ = panic "mkAltExpr LitAlt"
mkAltExpr DEFAULT _ _ = panic "mkAltExpr DEFAULT"
326 327
\end{code}

328 329

%************************************************************************
330
%*                                                                      *
331
\subsection{Taking expressions apart}
332
%*                                                                      *
333 334
%************************************************************************

335 336
The default alternative must be first, if it exists at all.
This makes it easy to find, though it makes matching marginally harder.
337 338

\begin{code}
batterseapower's avatar
batterseapower committed
339
-- | Extract the default case alternative
340
findDefault :: [(AltCon, [a], b)] -> ([(AltCon, [a], b)], Maybe b)
341
findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null args ) (alts, Just rhs)
342
findDefault alts                        =                     (alts, Nothing)
343

344
isDefaultAlt :: (AltCon, a, b) -> Bool
345 346 347 348
isDefaultAlt (DEFAULT, _, _) = True
isDefaultAlt _               = False


349
-- | Find the case alternative corresponding to a particular
batterseapower's avatar
batterseapower committed
350
-- constructor: panics if no such constructor exists
351
findAlt :: AltCon -> [(AltCon, a, b)] -> Maybe (AltCon, a, b)
352 353
    -- A "Nothing" result *is* legitmiate
    -- See Note [Unreachable code]
354
findAlt con alts
355
  = case alts of
356
        (deflt@(DEFAULT,_,_):alts) -> go alts (Just deflt)
357
        _                          -> go alts Nothing
358
  where
359
    go []                     deflt = deflt
360
    go (alt@(con1,_,_) : alts) deflt
361 362 363 364
      = case con `cmpAltCon` con1 of
          LT -> deflt   -- Missed it already; the alts are in increasing order
          EQ -> Just alt
          GT -> ASSERT( not (con1 == DEFAULT) ) go alts deflt
365

366
---------------------------------
367
mergeAlts :: [(AltCon, a, b)] -> [(AltCon, a, b)] -> [(AltCon, a, b)]
batterseapower's avatar
batterseapower committed
368 369
-- ^ Merge alternatives preserving order; alternatives in
-- the first argument shadow ones in the second
370 371 372 373
mergeAlts [] as2 = as2
mergeAlts as1 [] = as1
mergeAlts (a1:as1) (a2:as2)
  = case a1 `cmpAlt` a2 of
374 375 376
        LT -> a1 : mergeAlts as1      (a2:as2)
        EQ -> a1 : mergeAlts as1      as2       -- Discard a2
        GT -> a2 : mergeAlts (a1:as1) as2
377 378 379 380


---------------------------------
trimConArgs :: AltCon -> [CoreArg] -> [CoreArg]
batterseapower's avatar
batterseapower committed
381 382 383 384 385 386
-- ^ Given:
--
-- > case (C a b x y) of
-- >        C b x y -> ...
--
-- We want to drop the leading type argument of the scrutinee
387 388 389
-- leaving the arguments to match agains the pattern

trimConArgs DEFAULT      args = ASSERT( null args ) []
390
trimConArgs (LitAlt _)   args = ASSERT( null args ) []
391
trimConArgs (DataAlt dc) args = dropList (dataConUnivTyVars dc) args
392 393
\end{code}

394 395 396
\begin{code}
filterAlts :: [Unique]             -- ^ Supply of uniques used in case we have to manufacture a new AltCon
           -> Type                 -- ^ Type of scrutinee (used to prune possibilities)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
397
           -> [AltCon]             -- ^ 'imposs_cons': constructors known to be impossible due to the form of the scrutinee
398 399 400
           -> [(AltCon, [Var], a)] -- ^ Alternatives
           -> ([AltCon], Bool, [(AltCon, [Var], a)])
             -- Returns:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
401 402 403 404 405 406 407 408
             --  1. Constructors that will never be encountered by the 
             --     *default* case (if any).  A superset of imposs_cons
             --  2. Whether we managed to refine the default alternative into a specific constructor (for statistics only)
             --  3. The new alternatives, trimmed by
             --        a) remove imposs_cons
             --        b) remove constructors which can't match because of GADTs
             --      and with the DEFAULT expanded to a DataAlt if there is exactly
             --      remaining constructor that can match
409 410 411
             --
             -- NB: the final list of alternatives may be empty:
             -- This is a tricky corner case.  If the data type has no constructors,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
412 413
             -- which GHC allows, or if the imposs_cons covers all constructors (after taking 
             -- account of GADTs), then no alternatives can match.
414 415 416 417
             --
             -- If callers need to preserve the invariant that there is always at least one branch
             -- in a "case" statement then they will need to manually add a dummy case branch that just
             -- calls "error" or similar.
418 419 420 421 422
filterAlts us ty imposs_cons alts 
  | Just (tycon, inst_tys) <- splitTyConApp_maybe ty
  = filter_alts tycon inst_tys
  | otherwise
  = (imposs_cons, False, alts)
423 424 425
  where
    (alts_wo_default, maybe_deflt) = findDefault alts
    alt_cons = [con | (con,_,_) <- alts_wo_default]
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

    filter_alts tycon inst_tys 
      = (imposs_deflt_cons, refined_deflt, merged_alts)
     where
       trimmed_alts = filterOut (impossible_alt inst_tys) alts_wo_default

       imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
         -- "imposs_deflt_cons" are handled 
         --   EITHER by the context, 
         --   OR by a non-DEFAULT branch in this case expression.

       merged_alts  = mergeAlts trimmed_alts (maybeToList maybe_deflt')
         -- We need the mergeAlts in case the new default_alt 
         -- has turned into a constructor alternative.
         -- The merge keeps the inner DEFAULT at the front, if there is one
         -- and interleaves the alternatives in the right order

       (refined_deflt, maybe_deflt') = case maybe_deflt of
          Nothing -> (False, Nothing)
          Just deflt_rhs 
             | isAlgTyCon tycon            -- It's a data type, tuple, or unboxed tuples.  
             , not (isNewTyCon tycon)      -- We can have a newtype, if we are just doing an eval:
                                           --      case x of { DEFAULT -> e }
                                           -- and we don't want to fill in a default for them!
             , Just all_cons <- tyConDataCons_maybe tycon
             , let imposs_data_cons = [con | DataAlt con <- imposs_deflt_cons]   -- We now know it's a data type 
                   impossible con   = con `elem` imposs_data_cons || dataConCannotMatch inst_tys con
             -> case filterOut impossible all_cons of
                  -- Eliminate the default alternative
                  -- altogether if it can't match:
                  []    -> (False, Nothing)
                  -- It matches exactly one constructor, so fill it in:
                  [con] -> (True, Just (DataAlt con, ex_tvs ++ arg_ids, deflt_rhs))
                    where (ex_tvs, arg_ids) = dataConRepInstPat us con inst_tys
                  _     -> (False, Just (DEFAULT, [], deflt_rhs))

             | debugIsOn, isAlgTyCon tycon
             , null (tyConDataCons tycon)
             , not (isFamilyTyCon tycon || isAbstractTyCon tycon)
                   -- Check for no data constructors
                   -- This can legitimately happen for abstract types and type families,
                   -- so don't report that
             -> pprTrace "prepareDefault" (ppr tycon)
                (False, Just (DEFAULT, [], deflt_rhs))

             | otherwise -> (False, Just (DEFAULT, [], deflt_rhs))

    impossible_alt :: [Type] -> (AltCon, a, b) -> Bool
    impossible_alt _ (con, _, _) | con `elem` imposs_cons = True
    impossible_alt inst_tys (DataAlt con, _, _) = dataConCannotMatch inst_tys con
    impossible_alt _  _                         = False
477 478
\end{code}

479 480 481
Note [Unreachable code]
~~~~~~~~~~~~~~~~~~~~~~~
It is possible (although unusual) for GHC to find a case expression
482
that cannot match.  For example:
483 484 485

     data Col = Red | Green | Blue
     x = Red
486
     f v = case x of
487
              Red -> ...
488
              _ -> ...(case x of { Green -> e1; Blue -> e2 })...
489 490 491 492 493 494 495 496

Suppose that for some silly reason, x isn't substituted in the case
expression.  (Perhaps there's a NOINLINE on it, or profiling SCC stuff
gets in the way; cf Trac #3118.)  Then the full-lazines pass might produce
this

     x = Red
     lvl = case x of { Green -> e1; Blue -> e2 })
497
     f v = case x of
498
             Red -> ...
499
             _ -> ...lvl...
500 501 502 503 504 505 506 507 508

Now if x gets inlined, we won't be able to find a matching alternative
for 'Red'.  That's because 'lvl' is unreachable.  So rather than crashing
we generate (error "Inaccessible alternative").

Similar things can happen (augmented by GADTs) when the Simplifier
filters down the matching alternatives in Simplify.rebuildCase.


509
%************************************************************************
510
%*                                                                      *
511
             exprIsTrivial
512
%*                                                                      *
513 514
%************************************************************************

515 516
Note [exprIsTrivial]
~~~~~~~~~~~~~~~~~~~~
517
@exprIsTrivial@ is true of expressions we are unconditionally happy to
518 519 520
                duplicate; simple variables and constants, and type
                applications.  Note that primop Ids aren't considered
                trivial unless
521

522 523
Note [Variable are trivial]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
524 525
There used to be a gruesome test for (hasNoBinding v) in the
Var case:
526
        exprIsTrivial (Var v) | hasNoBinding v = idArity v == 0
batterseapower's avatar
batterseapower committed
527
The idea here is that a constructor worker, like \$wJust, is
Gabor Greif's avatar
typos  
Gabor Greif committed
528
really short for (\x -> \$wJust x), because \$wJust has no binding.
529 530 531 532 533 534
So it should be treated like a lambda.  Ditto unsaturated primops.
But now constructor workers are not "have-no-binding" Ids.  And
completely un-applied primops and foreign-call Ids are sufficiently
rare that I plan to allow them to be duplicated and put up with
saturating them.

535 536 537 538 539
Note [Tick trivial]
~~~~~~~~~~~~~~~~~~~
Ticks are not trivial.  If we treat "tick<n> x" as trivial, it will be
inlined inside lambdas and the entry count will be skewed, for
example.  Furthermore "scc<n> x" will turn into just "x" in mkTick.
540

541
\begin{code}
542
exprIsTrivial :: CoreExpr -> Bool
543
exprIsTrivial (Var _)          = True        -- See Note [Variables are trivial]
544 545
exprIsTrivial (Type _)        = True
exprIsTrivial (Coercion _)     = True
546 547
exprIsTrivial (Lit lit)        = litIsTrivial lit
exprIsTrivial (App e arg)      = not (isRuntimeArg arg) && exprIsTrivial e
548
exprIsTrivial (Tick _ _)       = False  -- See Note [Tick trivial]
549 550 551
exprIsTrivial (Cast e _)       = exprIsTrivial e
exprIsTrivial (Lam b body)     = not (isRuntimeVar b) && exprIsTrivial body
exprIsTrivial _                = False
552 553
\end{code}

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
When substituting in a breakpoint we need to strip away the type cruft
from a trivial expression and get back to the Id.  The invariant is
that the expression we're substituting was originally trivial
according to exprIsTrivial.

\begin{code}
getIdFromTrivialExpr :: CoreExpr -> Id
getIdFromTrivialExpr e = go e
  where go (Var v) = v
        go (App f t) | not (isRuntimeArg t) = go f
        go (Cast e _) = go e
        go (Lam b e) | not (isRuntimeVar b) = go e
        go e = pprPanic "getIdFromTrivialExpr" (ppr e)
\end{code}

569 570
exprIsBottom is a very cheap and cheerful function; it may return
False for bottoming expressions, but it never costs much to ask.
571
See also CoreArity.exprBotStrictness_maybe, but that's a bit more
572 573 574 575
expensive.

\begin{code}
exprIsBottom :: CoreExpr -> Bool
576
exprIsBottom e
577 578
  = go 0 e
  where
579 580 581
    go n (Var v) = isBottomingId v &&  n >= idArity v
    go n (App e a) | isTypeArg a = go n e
                   | otherwise   = go (n+1) e
582
    go n (Tick _ e)              = go n e
583 584 585
    go n (Cast e _)              = go n e
    go n (Let _ e)               = go n e
    go _ _                       = False
586 587
\end{code}

588

589
%************************************************************************
590
%*                                                                      *
591
             exprIsDupable
592
%*                                                                      *
593 594 595 596
%************************************************************************

Note [exprIsDupable]
~~~~~~~~~~~~~~~~~~~~
597 598 599
@exprIsDupable@ is true of expressions that can be duplicated at a modest
                cost in code size.  This will only happen in different case
                branches, so there's no issue about duplicating work.
600

601 602
                That is, exprIsDupable returns True of (f x) even if
                f is very very expensive to call.
603

604 605
                Its only purpose is to avoid fruitless let-binding
                and then inlining of case join points
606 607


608
\begin{code}
609 610
exprIsDupable :: DynFlags -> CoreExpr -> Bool
exprIsDupable dflags e
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
611
  = isJust (go dupAppSize e)
612
  where
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
613
    go :: Int -> CoreExpr -> Maybe Int
614 615 616
    go n (Type {})     = Just n
    go n (Coercion {}) = Just n
    go n (Var {})      = decrement n
617
    go n (Tick _ e)    = go n e
618
    go n (Cast e _)    = go n e
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
619
    go n (App f a) | Just n' <- go n a = go n' f
620
    go n (Lit lit) | litIsDupable dflags lit = decrement n
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
621 622 623 624 625
    go _ _ = Nothing

    decrement :: Int -> Maybe Int
    decrement 0 = Nothing
    decrement n = Just (n-1)
626 627

dupAppSize :: Int
628 629 630 631
dupAppSize = 8   -- Size of term we are prepared to duplicate
                 -- This is *just* big enough to make test MethSharing
                 -- inline enough join points.  Really it should be
                 -- smaller, and could be if we fixed Trac #4960.
632
\end{code}
633

634
%************************************************************************
635
%*                                                                      *
636
             exprIsCheap, exprIsExpandable
637
%*                                                                      *
638 639
%************************************************************************

640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
Note [exprIsWorkFree]
~~~~~~~~~~~~~~~~~~~~~
exprIsWorkFree is used when deciding whether to inline something; we
don't inline it if doing so might duplicate work, by peeling off a
complete copy of the expression.  Here we do not want even to
duplicate a primop (Trac #5623):
   eg   let x = a #+ b in x +# x
   we do not want to inline/duplicate x

Previously we were a bit more liberal, which led to the primop-duplicating
problem.  However, being more conservative did lead to a big regression in
one nofib benchmark, wheel-sieve1.  The situation looks like this:

   let noFactor_sZ3 :: GHC.Types.Int -> GHC.Types.Bool
       noFactor_sZ3 = case s_adJ of _ { GHC.Types.I# x_aRs ->
         case GHC.Prim.<=# x_aRs 2 of _ {
           GHC.Types.False -> notDivBy ps_adM qs_adN;
           GHC.Types.True -> lvl_r2Eb }}
       go = \x. ...(noFactor (I# y))....(go x')...

The function 'noFactor' is heap-allocated and then called.  Turns out
that 'notDivBy' is strict in its THIRD arg, but that is invisible to
the caller of noFactor, which therefore cannot do w/w and
heap-allocates noFactor's argument.  At the moment (May 12) we are just
going to put up with this, because the previous more aggressive inlining 
(which treated 'noFactor' as work-free) was duplicating primops, which 
in turn was making inner loops of array calculations runs slow (#5623)

\begin{code}
exprIsWorkFree :: CoreExpr -> Bool
-- See Note [exprIsWorkFree]
exprIsWorkFree e = go 0 e
  where    -- n is the number of value arguments
    go _ (Lit {})                     = True
    go _ (Type {})                    = True
    go _ (Coercion {})                = True
    go n (Cast e _)                   = go n e
    go n (Case scrut _ _ alts)        = foldl (&&) (exprIsWorkFree scrut) 
                                              [ go n rhs | (_,_,rhs) <- alts ]
         -- See Note [Case expressions are work-free]
    go _ (Let {})                     = False
681
    go n (Var v)                      = isCheapApp v n
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
    go n (Tick t e) | tickishCounts t = False
                    | otherwise       = go n e
    go n (Lam x e)  | isRuntimeVar x = n==0 || go (n-1) e
                    | otherwise      = go n e
    go n (App f e)  | isRuntimeArg e = exprIsWorkFree e && go (n+1) f
                    | otherwise      = go n f
\end{code}

Note [Case expressions are work-free]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Are case-expressions work-free?  Consider
    let v = case x of (p,q) -> p
        go = \y -> ...case v of ...
Should we inline 'v' at its use site inside the loop?  At the moment
we do.  I experimented with saying that case are *not* work-free, but
that increased allocation slightly.  It's a fairly small effect, and at
the moment we go for the slightly more aggressive version which treats
(case x of ....) as work-free if the alterantives are.


702 703
Note [exprIsCheap]   See also Note [Interaction of exprIsCheap and lone variables]
~~~~~~~~~~~~~~~~~~   in CoreUnfold.lhs
704 705 706 707
@exprIsCheap@ looks at a Core expression and returns \tr{True} if
it is obviously in weak head normal form, or is cheap to get to WHNF.
[Note that that's not the same as exprIsDupable; an expression might be
big, and hence not dupable, but still cheap.]
708 709

By ``cheap'' we mean a computation we're willing to:
710 711
        push inside a lambda, or
        inline at more than one place
712 713 714
That might mean it gets evaluated more than once, instead of being
shared.  The main examples of things which aren't WHNF but are
``cheap'' are:
715

716 717 718
  *     case e of
          pi -> ei
        (where e, and all the ei are cheap)
719

720 721
  *     let x = e in b
        (where e and b are cheap)
722

723 724
  *     op x1 ... xn
        (where op is a cheap primitive operator)
725

726 727
  *     error "foo"
        (because we are happy to substitute it inside a lambda)
728

729 730 731
Notice that a variable is considered 'cheap': we can push it inside a lambda,
because sharing will make sure it is only evaluated once.

732 733 734
Note [exprIsCheap and exprIsHNF]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Note that exprIsHNF does not imply exprIsCheap.  Eg
735
        let x = fac 20 in Just x
736 737 738
This responds True to exprIsHNF (you can discard a seq), but
False to exprIsCheap.

739
\begin{code}
740
exprIsCheap :: CoreExpr -> Bool
741
exprIsCheap = exprIsCheap' isCheapApp
742 743

exprIsExpandable :: CoreExpr -> Bool
744
exprIsExpandable = exprIsCheap' isExpandableApp -- See Note [CONLIKE pragma] in BasicTypes
745

746
exprIsCheap' :: CheapAppFun -> CoreExpr -> Bool
747
exprIsCheap' _        (Lit _)      = True
748
exprIsCheap' _        (Type _)    = True
749 750 751 752 753
exprIsCheap' _        (Coercion _) = True
exprIsCheap' _        (Var _)      = True
exprIsCheap' good_app (Cast e _)   = exprIsCheap' good_app e
exprIsCheap' good_app (Lam x e)    = isRuntimeVar x
                                  || exprIsCheap' good_app e
754

755 756 757 758 759 760
exprIsCheap' good_app (Case e _ _ alts) = exprIsCheap' good_app e &&
                                          and [exprIsCheap' good_app rhs | (_,_,rhs) <- alts]
        -- Experimentally, treat (case x of ...) as cheap
        -- (and case __coerce x etc.)
        -- This improves arities of overloaded functions where
        -- there is only dictionary selection (no construction) involved
761

762 763 764 765 766 767
exprIsCheap' good_app (Tick t e)
  | tickishCounts t = False
  | otherwise       = exprIsCheap' good_app e
     -- never duplicate ticks.  If we get this wrong, then HPC's entry
     -- counts will be off (check test in libraries/hpc/tests/raytrace)

768
exprIsCheap' good_app (Let (NonRec x _) e)
769
  | isUnLiftedType (idType x) = exprIsCheap' good_app e
770 771 772 773 774
  | otherwise                 = False
        -- Strict lets always have cheap right hand sides,
        -- and do no allocation, so just look at the body
        -- Non-strict lets do allocation so we don't treat them as cheap
        -- See also
775

776
exprIsCheap' good_app other_expr        -- Applications and variables
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
777
  = go other_expr []
778
  where
779
        -- Accumulate value arguments, then decide
780
    go (Cast e _) val_args                 = go e val_args
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
781
    go (App f a) val_args | isRuntimeArg a = go f (a:val_args)
782
                          | otherwise      = go f val_args
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
783

784 785 786 787 788 789 790 791 792
    go (Var _) [] = True        
         -- Just a type application of a variable
         -- (f t1 t2 t3) counts as WHNF
         -- This case is probably handeld by the good_app case
         -- below, which should have a case for n=0, but putting
         -- it here too is belt and braces; and it's such a common
         -- case that checking for null directly seems like a 
         -- good plan

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
793
    go (Var f) args
794 795 796 797
       | good_app f (length args) 
       = go_pap args

       | otherwise
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
798
        = case idDetails f of
799 800 801 802 803
                RecSelId {}         -> go_sel args
                ClassOpId {}        -> go_sel args
                PrimOpId op         -> go_primop op args
                _ | isBottomingId f -> True
                  | otherwise       -> False
804 805 806 807
                        -- Application of a function which
                        -- always gives bottom; we treat this as cheap
                        -- because it certainly doesn't need to be shared!

808
    go _ _ = False
809

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
810
    --------------
811 812 813
    go_pap args = all (exprIsCheap' good_app) args
        -- Used to be "all exprIsTrivial args" due to concerns about
        -- duplicating nested constructor applications, but see #4978.
814 815
        -- The principle here is that
        --    let x = a +# b in c *# x
Simon Peyton Jones's avatar
Simon Peyton Jones committed
816 817
        -- should behave equivalently to
        --    c *# (a +# b)
818
        -- Since lets with cheap RHSs are accepted,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
819
        -- so should paps with cheap arguments
820

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
821
    --------------
822
    go_primop op args = primOpIsCheap op && all (exprIsCheap' good_app) args
823 824 825 826 827
        -- In principle we should worry about primops
        -- that return a type variable, since the result
        -- might be applied to something, but I'm not going
        -- to bother to check the number of args

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
828
    --------------
829 830 831 832 833
    go_sel [arg] = exprIsCheap' good_app arg    -- I'm experimenting with making record selection
    go_sel _     = False                -- look cheap, so we will substitute it inside a
                                        -- lambda.  Particularly for dictionary field selection.
                -- BUT: Take care with (sel d x)!  The (sel d) might be cheap, but
                --      there's no guarantee that (sel d x) will be too.  Hence (n_val_args == 1)
834

835 836 837 838 839 840 841
-------------------------------------
type CheapAppFun = Id -> Int -> Bool  
  -- Is an application of this function to n *value* args 
  -- always cheap, assuming the arguments are cheap?  
  -- Mainly true of partial applications, data constructors,
  -- and of course true if the number of args is zero

842 843
isCheapApp :: CheapAppFun
isCheapApp fn n_val_args
844 845
  =  isDataConWorkId fn 
  || n_val_args == 0 
846 847 848 849 850 851 852 853 854 855
  || n_val_args < idArity fn

isExpandableApp :: CheapAppFun
isExpandableApp fn n_val_args
  =  isConLikeId fn
  || n_val_args < idArity fn
  || go n_val_args (idType fn)
  where
  -- See if all the arguments are PredTys (implicit params or classes)
  -- If so we'll regard it as expandable; see Note [Expandable overloadings]
856
  -- This incidentally picks up the (n_val_args = 0) case
857 858 859 860 861 862
     go 0 _ = True
     go n_val_args ty
       | Just (_, ty) <- splitForAllTy_maybe ty   = go n_val_args ty
       | Just (arg, ty) <- splitFunTy_maybe ty
       , isPredTy arg                             = go (n_val_args-1) ty
       | otherwise                                = False
863 864
\end{code}

865 866 867 868 869 870 871 872 873 874 875 876
Note [Expandable overloadings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose the user wrote this
   {-# RULE  forall x. foo (negate x) = h x #-}
   f x = ....(foo (negate x))....
He'd expect the rule to fire. But since negate is overloaded, we might
get this:
    f = \d -> let n = negate d in \x -> ...foo (n x)...
So we treat the application of a function (negate in this case) to a
*dictionary* as expandable.  In effect, every function is CONLIKE when
it's applied only to dictionaries.

877

878
%************************************************************************
879
%*                                                                      *
880
             exprOkForSpeculation
881
%*                                                                      *
882 883
%************************************************************************

884
\begin{code}
885
-----------------------------
batterseapower's avatar
batterseapower committed
886 887
-- | 'exprOkForSpeculation' returns True of an expression that is:
--
888
--  * Safe to evaluate even if normal order eval might not
batterseapower's avatar
batterseapower committed
889 890 891 892
--    evaluate the expression at all, or
--
--  * Safe /not/ to evaluate even if normal order would do so
--
893 894
-- It is usually called on arguments of unlifted type, but not always
-- In particular, Simplify.rebuildCase calls it on lifted types
895
-- when a 'case' is a plain 'seq'. See the example in
896 897
-- Note [exprOkForSpeculation: case expressions] below
--
batterseapower's avatar
batterseapower committed
898 899
-- Precisely, it returns @True@ iff:
--
900 901
--  * The expression guarantees to terminate,
--  * soon,
batterseapower's avatar
batterseapower committed
902 903 904 905 906 907 908 909 910 911 912
--  * without raising an exception,
--  * without causing a side effect (e.g. writing a mutable variable)
--
-- Note that if @exprIsHNF e@, then @exprOkForSpecuation e@.
-- As an example of the considerations in this test, consider:
--
-- > let x = case y# +# 1# of { r# -> I# r# }
-- > in E
--
-- being translated to:
--
913
-- > case y# +# 1# of { r# ->
batterseapower's avatar
batterseapower committed
914
-- >    let x = I# r#
915
-- >    in E
batterseapower's avatar
batterseapower committed
916
-- > }
917
--
batterseapower's avatar
batterseapower committed
918 919
-- We can only do this if the @y + 1@ is ok for speculation: it has no
-- side effects, and can't diverge or raise an exception.
920 921 922
exprOkForSpeculation, exprOkForSideEffects :: Expr b -> Bool
exprOkForSpeculation = expr_ok primOpOkForSpeculation
exprOkForSideEffects = expr_ok primOpOkForSideEffects
923 924
  -- Polymorphic in binder type
  -- There is one call at a non-Id binder type, in SetLevels
925 926 927 928 929 930 931

expr_ok :: (PrimOp -> Bool) -> Expr b -> Bool
expr_ok _ (Lit _)      = True
expr_ok _ (Type _)     = True
expr_ok _ (Coercion _) = True
expr_ok primop_ok (Var v)      = app_ok primop_ok v []
expr_ok primop_ok (Cast e _)   = expr_ok primop_ok e
932 933 934 935

-- Tick annotations that *tick* cannot be speculated, because these
-- are meant to identify whether or not (and how often) the particular
-- source expression was evaluated at runtime.
936
expr_ok primop_ok (Tick tickish e)
937
   | tickishCounts tickish = False
938
   | otherwise             = expr_ok primop_ok e
939

940 941 942 943
expr_ok primop_ok (Case e _ _ alts)
  =  expr_ok primop_ok e  -- Note [exprOkForSpeculation: case expressions]
  && all (\(_,_,rhs) -> expr_ok primop_ok rhs) alts
  && altsAreExhaustive alts     -- Note [Exhaustive alts]
944

945
expr_ok primop_ok other_expr
946
  = case collectArgs other_expr of
947
        (Var f, args) -> app_ok primop_ok f args
948
        _             -> False
949

950
-----------------------------
951 952
app_ok :: (PrimOp -> Bool) -> Id -> [Expr b] -> Bool
app_ok primop_ok fun args
953
  = case idDetails fun of
954
      DFunId _ new_type ->  not new_type
955 956 957 958 959
         -- DFuns terminate, unless the dict is implemented 
         -- with a newtype in which case they may not

      DataConWorkId {} -> True
                -- The strictness of the constructor has already
960 961
                -- been expressed by its "wrapper", so we don't need
                -- to take the arguments into account
simonpj's avatar