Simplify.lhs 81.5 KB
Newer Older
1
%
2
% (c) The AQUA Project, Glasgow University, 1993-1998
3 4 5 6
%
\section[Simplify]{The main module of the simplifier}

\begin{code}
7
module Simplify ( simplTopBinds, simplExpr ) where
8

9
#include "HsVersions.h"
10

simonpj@microsoft.com's avatar
Wibble  
simonpj@microsoft.com committed
11
import DynFlags
12
import SimplMonad
Ian Lynagh's avatar
Ian Lynagh committed
13 14
import Type hiding      ( substTy, extendTvSubst )
import SimplEnv
15 16
import SimplUtils
import Id
17
import Var
18 19
import IdInfo
import Coercion
Ian Lynagh's avatar
Ian Lynagh committed
20 21
import FamInstEnv       ( topNormaliseType )
import DataCon          ( dataConRepStrictness, dataConUnivTyVars )
22
import CoreSyn
Ian Lynagh's avatar
Ian Lynagh committed
23 24 25
import NewDemand        ( isStrictDmd )
import PprCore          ( pprParendExpr, pprCoreExpr )
import CoreUnfold       ( mkUnfolding, callSiteInline, CallCtxt(..) )
26
import CoreUtils
Ian Lynagh's avatar
Ian Lynagh committed
27 28 29 30 31 32 33 34 35
import Rules            ( lookupRule )
import BasicTypes       ( isMarkedStrict )
import CostCentre       ( currentCCS )
import TysPrim          ( realWorldStatePrimTy )
import PrelInfo         ( realWorldPrimId )
import BasicTypes       ( TopLevelFlag(..), isTopLevel,
                          RecFlag(..), isNonRuleLoopBreaker )
import Maybes           ( orElse )
import Data.List        ( mapAccumL )
36
import Outputable
37 38 39
\end{code}


40 41
The guts of the simplifier is in this module, but the driver loop for
the simplifier is in SimplCore.lhs.
42 43


44
-----------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
45
        *** IMPORTANT NOTE ***
46 47 48 49 50 51
-----------------------------------------
The simplifier used to guarantee that the output had no shadowing, but
it does not do so any more.   (Actually, it never did!)  The reason is
documented with simplifyArgs.


52
-----------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
53
        *** IMPORTANT NOTE ***
54 55 56 57 58 59 60 61 62 63
-----------------------------------------
Many parts of the simplifier return a bunch of "floats" as well as an
expression. This is wrapped as a datatype SimplUtils.FloatsWith.

All "floats" are let-binds, not case-binds, but some non-rec lets may
be unlifted (with RHS ok-for-speculation).



-----------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
64
        ORGANISATION OF FUNCTIONS
65 66 67 68 69 70
-----------------------------------------
simplTopBinds
  - simplify all top-level binders
  - for NonRec, call simplRecOrTopPair
  - for Rec,    call simplRecBind

Ian Lynagh's avatar
Ian Lynagh committed
71 72 73

        ------------------------------
simplExpr (applied lambda)      ==> simplNonRecBind
74 75 76
simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
simplExpr (Let (Rec ...)    ..) ==> simplify binders; simplRecBind

Ian Lynagh's avatar
Ian Lynagh committed
77 78
        ------------------------------
simplRecBind    [binders already simplfied]
79 80 81 82
  - use simplRecOrTopPair on each pair in turn

simplRecOrTopPair [binder already simplified]
  Used for: recursive bindings (top level and nested)
Ian Lynagh's avatar
Ian Lynagh committed
83 84
            top-level non-recursive bindings
  Returns:
85 86 87 88 89
  - check for PreInlineUnconditionally
  - simplLazyBind

simplNonRecBind
  Used for: non-top-level non-recursive bindings
Ian Lynagh's avatar
Ian Lynagh committed
90 91 92
            beta reductions (which amount to the same thing)
  Because it can deal with strict arts, it takes a
        "thing-inside" and returns an expression
93 94 95 96

  - check for PreInlineUnconditionally
  - simplify binder, including its IdInfo
  - if strict binding
Ian Lynagh's avatar
Ian Lynagh committed
97 98 99
        simplStrictArg
        mkAtomicArgs
        completeNonRecX
100
    else
Ian Lynagh's avatar
Ian Lynagh committed
101 102
        simplLazyBind
        addFloats
103

Ian Lynagh's avatar
Ian Lynagh committed
104
simplNonRecX:   [given a *simplified* RHS, but an *unsimplified* binder]
105 106 107 108
  Used for: binding case-binder and constr args in a known-constructor case
  - check for PreInLineUnconditionally
  - simplify binder
  - completeNonRecX
Ian Lynagh's avatar
Ian Lynagh committed
109 110 111

        ------------------------------
simplLazyBind:  [binder already simplified, RHS not]
112
  Used for: recursive bindings (top level and nested)
Ian Lynagh's avatar
Ian Lynagh committed
113 114 115
            top-level non-recursive bindings
            non-top-level, but *lazy* non-recursive bindings
        [must not be strict or unboxed]
116
  Returns floats + an augmented environment, not an expression
Ian Lynagh's avatar
Ian Lynagh committed
117 118
  - substituteIdInfo and add result to in-scope
        [so that rules are available in rec rhs]
119 120 121
  - simplify rhs
  - mkAtomicArgs
  - float if exposes constructor or PAP
122
  - completeBind
123 124


Ian Lynagh's avatar
Ian Lynagh committed
125
completeNonRecX:        [binder and rhs both simplified]
126
  - if the the thing needs case binding (unlifted and not ok-for-spec)
Ian Lynagh's avatar
Ian Lynagh committed
127
        build a Case
128
   else
Ian Lynagh's avatar
Ian Lynagh committed
129 130
        completeBind
        addFloats
131

Ian Lynagh's avatar
Ian Lynagh committed
132 133
completeBind:   [given a simplified RHS]
        [used for both rec and non-rec bindings, top level and not]
134 135 136 137 138 139 140 141
  - try PostInlineUnconditionally
  - add unfolding [this is the only place we add an unfolding]
  - add arity



Right hand sides and arguments
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Ian Lynagh's avatar
Ian Lynagh committed
142 143 144
In many ways we want to treat
        (a) the right hand side of a let(rec), and
        (b) a function argument
145 146 147
in the same way.  But not always!  In particular, we would
like to leave these arguments exactly as they are, so they
will match a RULE more easily.
Ian Lynagh's avatar
Ian Lynagh committed
148 149 150

        f (g x, h x)
        g (+ x)
151 152 153 154

It's harder to make the rule match if we ANF-ise the constructor,
or eta-expand the PAP:

Ian Lynagh's avatar
Ian Lynagh committed
155 156
        f (let { a = g x; b = h x } in (a,b))
        g (\y. + x y)
157 158 159

On the other hand if we see the let-defns

Ian Lynagh's avatar
Ian Lynagh committed
160 161
        p = (g x, h x)
        q = + x
162 163

then we *do* want to ANF-ise and eta-expand, so that p and q
Ian Lynagh's avatar
Ian Lynagh committed
164
can be safely inlined.
165 166 167 168 169

Even floating lets out is a bit dubious.  For let RHS's we float lets
out if that exposes a value, so that the value can be inlined more vigorously.
For example

Ian Lynagh's avatar
Ian Lynagh committed
170
        r = let x = e in (x,x)
171 172 173 174 175 176 177 178 179 180 181 182 183 184

Here, if we float the let out we'll expose a nice constructor. We did experiments
that showed this to be a generally good thing.  But it was a bad thing to float
lets out unconditionally, because that meant they got allocated more often.

For function arguments, there's less reason to expose a constructor (it won't
get inlined).  Just possibly it might make a rule match, but I'm pretty skeptical.
So for the moment we don't float lets out of function arguments either.


Eta expansion
~~~~~~~~~~~~~~
For eta expansion, we want to catch things like

Ian Lynagh's avatar
Ian Lynagh committed
185
        case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
186 187 188 189 190

If the \x was on the RHS of a let, we'd eta expand to bring the two
lambdas together.  And in general that's a good thing to do.  Perhaps
we should eta expand wherever we find a (value) lambda?  Then the eta
expansion at a let RHS can concentrate solely on the PAP case.
191 192


193
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
194
%*                                                                      *
195
\subsection{Bindings}
Ian Lynagh's avatar
Ian Lynagh committed
196
%*                                                                      *
197 198 199
%************************************************************************

\begin{code}
200
simplTopBinds :: SimplEnv -> [InBind] -> SimplM [OutBind]
201

Ian Lynagh's avatar
Ian Lynagh committed
202
simplTopBinds env0 binds0
Ian Lynagh's avatar
Ian Lynagh committed
203 204 205 206
  = do  {       -- Put all the top-level binders into scope at the start
                -- so that if a transformation rule has unexpectedly brought
                -- anything into scope, then we don't get a complaint about that.
                -- It's rather as if the top-level binders were imported.
Ian Lynagh's avatar
Ian Lynagh committed
207
        ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
Ian Lynagh's avatar
Ian Lynagh committed
208 209 210
        ; dflags <- getDOptsSmpl
        ; let dump_flag = dopt Opt_D_dump_inlinings dflags ||
                          dopt Opt_D_dump_rule_firings dflags
Ian Lynagh's avatar
Ian Lynagh committed
211
        ; env2 <- simpl_binds dump_flag env1 binds0
Ian Lynagh's avatar
Ian Lynagh committed
212
        ; freeTick SimplifierDone
Ian Lynagh's avatar
Ian Lynagh committed
213
        ; return (getFloats env2) }
214
  where
Ian Lynagh's avatar
Ian Lynagh committed
215 216 217 218 219 220
        -- We need to track the zapped top-level binders, because
        -- they should have their fragile IdInfo zapped (notably occurrence info)
        -- That's why we run down binds and bndrs' simultaneously.
        --
        -- The dump-flag emits a trace for each top-level binding, which
        -- helps to locate the tracing for inlining and rule firing
221
    simpl_binds :: Bool -> SimplEnv -> [InBind] -> SimplM SimplEnv
Ian Lynagh's avatar
Ian Lynagh committed
222 223
    simpl_binds _    env []           = return env
    simpl_binds dump env (bind:binds) = do { env' <- trace_bind dump bind $
Ian Lynagh's avatar
Ian Lynagh committed
224 225
                                                     simpl_bind env bind
                                           ; simpl_binds dump env' binds }
226

Ian Lynagh's avatar
Ian Lynagh committed
227 228
    trace_bind True  bind = pprTrace "SimplBind" (ppr (bindersOf bind))
    trace_bind False _    = \x -> x
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
229

230 231
    simpl_bind env (Rec pairs)  = simplRecBind      env  TopLevel pairs
    simpl_bind env (NonRec b r) = simplRecOrTopPair env' TopLevel b b' r
Ian Lynagh's avatar
Ian Lynagh committed
232 233
        where
          (env', b') = addBndrRules env b (lookupRecBndr env b)
234 235 236 237
\end{code}


%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
238
%*                                                                      *
239
\subsection{Lazy bindings}
Ian Lynagh's avatar
Ian Lynagh committed
240
%*                                                                      *
241 242 243
%************************************************************************

simplRecBind is used for
Ian Lynagh's avatar
Ian Lynagh committed
244
        * recursive bindings only
245 246 247

\begin{code}
simplRecBind :: SimplEnv -> TopLevelFlag
Ian Lynagh's avatar
Ian Lynagh committed
248 249
             -> [(InId, InExpr)]
             -> SimplM SimplEnv
Ian Lynagh's avatar
Ian Lynagh committed
250 251 252 253 254 255
simplRecBind env0 top_lvl pairs0
  = do  { let (env_with_info, triples) = mapAccumL add_rules env0 pairs0
        ; env1 <- go (zapFloats env_with_info) triples
        ; return (env0 `addRecFloats` env1) }
        -- addFloats adds the floats from env1,
        -- *and* updates env0 with the in-scope set from env1
256
  where
257
    add_rules :: SimplEnv -> (InBndr,InExpr) -> (SimplEnv, (InBndr, OutBndr, InExpr))
Ian Lynagh's avatar
Ian Lynagh committed
258
        -- Add the (substituted) rules to the binder
259
    add_rules env (bndr, rhs) = (env', (bndr, bndr', rhs))
Ian Lynagh's avatar
Ian Lynagh committed
260 261
        where
          (env', bndr') = addBndrRules env bndr (lookupRecBndr env bndr)
262

263
    go env [] = return env
Ian Lynagh's avatar
Ian Lynagh committed
264

265
    go env ((old_bndr, new_bndr, rhs) : pairs)
Ian Lynagh's avatar
Ian Lynagh committed
266 267
        = do { env' <- simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
             ; go env' pairs }
268 269
\end{code}

270
simplOrTopPair is used for
Ian Lynagh's avatar
Ian Lynagh committed
271 272
        * recursive bindings (whether top level or not)
        * top-level non-recursive bindings
273 274 275 276 277

It assumes the binder has already been simplified, but not its IdInfo.

\begin{code}
simplRecOrTopPair :: SimplEnv
Ian Lynagh's avatar
Ian Lynagh committed
278 279 280
                  -> TopLevelFlag
                  -> InId -> OutBndr -> InExpr  -- Binder and rhs
                  -> SimplM SimplEnv    -- Returns an env that includes the binding
281

282
simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
Ian Lynagh's avatar
Ian Lynagh committed
283 284 285
  | preInlineUnconditionally env top_lvl old_bndr rhs   -- Check for unconditional inline
  = do  { tick (PreInlineUnconditionally old_bndr)
        ; return (extendIdSubst env old_bndr (mkContEx env rhs)) }
286 287

  | otherwise
Ian Lynagh's avatar
Ian Lynagh committed
288 289
  = simplLazyBind env top_lvl Recursive old_bndr new_bndr rhs env
        -- May not actually be recursive, but it doesn't matter
290 291 292 293
\end{code}


simplLazyBind is used for
294 295
  * [simplRecOrTopPair] recursive bindings (whether top level or not)
  * [simplRecOrTopPair] top-level non-recursive bindings
Ian Lynagh's avatar
Ian Lynagh committed
296
  * [simplNonRecE]      non-top-level *lazy* non-recursive bindings
297 298

Nota bene:
Ian Lynagh's avatar
Ian Lynagh committed
299
    1. It assumes that the binder is *already* simplified,
300
       and is in scope, and its IdInfo too, except unfolding
301 302 303 304 305 306 307 308

    2. It assumes that the binder type is lifted.

    3. It does not check for pre-inline-unconditionallly;
       that should have been done already.

\begin{code}
simplLazyBind :: SimplEnv
Ian Lynagh's avatar
Ian Lynagh committed
309 310 311 312 313
              -> TopLevelFlag -> RecFlag
              -> InId -> OutId          -- Binder, both pre-and post simpl
                                        -- The OutId has IdInfo, except arity, unfolding
              -> InExpr -> SimplEnv     -- The RHS and its environment
              -> SimplM SimplEnv
314

315
simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
Ian Lynagh's avatar
Ian Lynagh committed
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
  = do  { let   rhs_env     = rhs_se `setInScope` env
                (tvs, body) = collectTyBinders rhs
        ; (body_env, tvs') <- simplBinders rhs_env tvs
                -- See Note [Floating and type abstraction]
                -- in SimplUtils

        -- Simplify the RHS; note the mkRhsStop, which tells
        -- the simplifier that this is the RHS of a let.
        ; let rhs_cont = mkRhsStop (applyTys (idType bndr1) (mkTyVarTys tvs'))
        ; (body_env1, body1) <- simplExprF body_env body rhs_cont

        -- ANF-ise a constructor or PAP rhs
        ; (body_env2, body2) <- prepareRhs body_env1 body1

        ; (env', rhs')
            <-  if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
                then                            -- No floating, just wrap up!
                     do { rhs' <- mkLam tvs' (wrapFloats body_env2 body2)
                        ; return (env, rhs') }

                else if null tvs then           -- Simple floating
                     do { tick LetFloatFromLet
                        ; return (addFloats env body_env2, body2) }

                else                            -- Do type-abstraction first
                     do { tick LetFloatFromLet
                        ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
                        ; rhs' <- mkLam tvs' body3
                        ; return (extendFloats env poly_binds, rhs') }

        ; completeBind env' top_lvl bndr bndr1 rhs' }
347
\end{code}
348

Ian Lynagh's avatar
Ian Lynagh committed
349
A specialised variant of simplNonRec used when the RHS is already simplified,
350 351 352 353
notably in knownCon.  It uses case-binding where necessary.

\begin{code}
simplNonRecX :: SimplEnv
Ian Lynagh's avatar
Ian Lynagh committed
354 355 356
             -> InId            -- Old binder
             -> OutExpr         -- Simplified RHS
             -> SimplM SimplEnv
357 358

simplNonRecX env bndr new_rhs
Ian Lynagh's avatar
Ian Lynagh committed
359 360
  = do  { (env', bndr') <- simplBinder env bndr
        ; completeNonRecX env' NotTopLevel NonRecursive
Ian Lynagh's avatar
Ian Lynagh committed
361
                          (isStrictId bndr) bndr bndr' new_rhs }
362 363

completeNonRecX :: SimplEnv
Ian Lynagh's avatar
Ian Lynagh committed
364 365 366 367 368
                -> TopLevelFlag -> RecFlag -> Bool
                -> InId                 -- Old binder
                -> OutId                -- New binder
                -> OutExpr              -- Simplified RHS
                -> SimplM SimplEnv
369 370

completeNonRecX env top_lvl is_rec is_strict old_bndr new_bndr new_rhs
Ian Lynagh's avatar
Ian Lynagh committed
371 372 373 374 375 376 377
  = do  { (env1, rhs1) <- prepareRhs (zapFloats env) new_rhs
        ; (env2, rhs2) <-
                if doFloatFromRhs top_lvl is_rec is_strict rhs1 env1
                then do { tick LetFloatFromLet
                        ; return (addFloats env env1, rhs1) }   -- Add the floats to the main env
                else return (env, wrapFloats env1 rhs1)         -- Wrap the floats around the RHS
        ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
378 379 380 381
\end{code}

{- No, no, no!  Do not try preInlineUnconditionally in completeNonRecX
   Doing so risks exponential behaviour, because new_rhs has been simplified once already
Ian Lynagh's avatar
Ian Lynagh committed
382
   In the cases described by the folowing commment, postInlineUnconditionally will
383
   catch many of the relevant cases.
Ian Lynagh's avatar
Ian Lynagh committed
384 385 386 387 388 389 390 391
        -- This happens; for example, the case_bndr during case of
        -- known constructor:  case (a,b) of x { (p,q) -> ... }
        -- Here x isn't mentioned in the RHS, so we don't want to
        -- create the (dead) let-binding  let x = (a,b) in ...
        --
        -- Similarly, single occurrences can be inlined vigourously
        -- e.g.  case (f x, g y) of (a,b) -> ....
        -- If a,b occur once we can avoid constructing the let binding for them.
392

393
   Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
Ian Lynagh's avatar
Ian Lynagh committed
394 395 396 397 398 399
        -- Consider     case I# (quotInt# x y) of
        --                I# v -> let w = J# v in ...
        -- If we gaily inline (quotInt# x y) for v, we end up building an
        -- extra thunk:
        --                let w = J# (quotInt# x y) in ...
        -- because quotInt# can fail.
400

401 402 403 404
  | preInlineUnconditionally env NotTopLevel bndr new_rhs
  = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
-}

405
----------------------------------
406
prepareRhs takes a putative RHS, checks whether it's a PAP or
Ian Lynagh's avatar
Ian Lynagh committed
407
constructor application and, if so, converts it to ANF, so that the
408
resulting thing can be inlined more easily.  Thus
Ian Lynagh's avatar
Ian Lynagh committed
409
        x = (f a, g b)
410
becomes
Ian Lynagh's avatar
Ian Lynagh committed
411 412 413
        t1 = f a
        t2 = g b
        x = (t1,t2)
414

415
We also want to deal well cases like this
Ian Lynagh's avatar
Ian Lynagh committed
416
        v = (f e1 `cast` co) e2
417
Here we want to make e1,e2 trivial and get
Ian Lynagh's avatar
Ian Lynagh committed
418
        x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
419 420
That's what the 'go' loop in prepareRhs does

421 422 423
\begin{code}
prepareRhs :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
-- Adds new floats to the env iff that allows us to return a good RHS
Ian Lynagh's avatar
Ian Lynagh committed
424
prepareRhs env (Cast rhs co)    -- Note [Float coercions]
Ian Lynagh's avatar
Ian Lynagh committed
425
  | (ty1, _ty2) <- coercionKind co       -- Do *not* do this if rhs has an unlifted type
Ian Lynagh's avatar
Ian Lynagh committed
426 427 428
  , not (isUnLiftedType ty1)            -- see Note [Float coercions (unlifted)]
  = do  { (env', rhs') <- makeTrivial env rhs
        ; return (env', Cast rhs' co) }
429

Ian Lynagh's avatar
Ian Lynagh committed
430 431 432
prepareRhs env0 rhs0
  = do  { (_is_val, env1, rhs1) <- go 0 env0 rhs0
        ; return (env1, rhs1) }
433
  where
434
    go n_val_args env (Cast rhs co)
Ian Lynagh's avatar
Ian Lynagh committed
435 436
        = do { (is_val, env', rhs') <- go n_val_args env rhs
             ; return (is_val, env', Cast rhs' co) }
437
    go n_val_args env (App fun (Type ty))
Ian Lynagh's avatar
Ian Lynagh committed
438 439
        = do { (is_val, env', rhs') <- go n_val_args env fun
             ; return (is_val, env', App rhs' (Type ty)) }
440
    go n_val_args env (App fun arg)
Ian Lynagh's avatar
Ian Lynagh committed
441 442 443 444 445
        = do { (is_val, env', fun') <- go (n_val_args+1) env fun
             ; case is_val of
                True -> do { (env'', arg') <- makeTrivial env' arg
                           ; return (True, env'', App fun' arg') }
                False -> return (False, env, App fun arg) }
446
    go n_val_args env (Var fun)
Ian Lynagh's avatar
Ian Lynagh committed
447 448 449 450 451
        = return (is_val, env, Var fun)
        where
          is_val = n_val_args > 0       -- There is at least one arg
                                        -- ...and the fun a constructor or PAP
                 && (isDataConWorkId fun || n_val_args < idArity fun)
Ian Lynagh's avatar
Ian Lynagh committed
452
    go _ env other
Ian Lynagh's avatar
Ian Lynagh committed
453
        = return (False, env, other)
454 455
\end{code}

456

457 458 459
Note [Float coercions]
~~~~~~~~~~~~~~~~~~~~~~
When we find the binding
Ian Lynagh's avatar
Ian Lynagh committed
460
        x = e `cast` co
461
we'd like to transform it to
Ian Lynagh's avatar
Ian Lynagh committed
462 463
        x' = e
        x = x `cast` co         -- A trivial binding
464 465 466 467 468 469 470 471 472 473 474 475 476
There's a chance that e will be a constructor application or function, or something
like that, so moving the coerion to the usage site may well cancel the coersions
and lead to further optimisation.  Example:

     data family T a :: *
     data instance T Int = T Int

     foo :: Int -> Int -> Int
     foo m n = ...
        where
          x = T m
          go 0 = 0
          go n = case x of { T m -> go (n-m) }
Ian Lynagh's avatar
Ian Lynagh committed
477
                -- This case should optimise
478

479 480
Note [Float coercions (unlifted)]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Ian Lynagh's avatar
Ian Lynagh committed
481
BUT don't do [Float coercions] if 'e' has an unlifted type.
482 483
This *can* happen:

Ian Lynagh's avatar
Ian Lynagh committed
484 485
     foo :: Int = (error (# Int,Int #) "urk")
                  `cast` CoUnsafe (# Int,Int #) Int
486 487 488

If do the makeTrivial thing to the error call, we'll get
    foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
Ian Lynagh's avatar
Ian Lynagh committed
489
But 'v' isn't in scope!
490 491

These strange casts can happen as a result of case-of-case
Ian Lynagh's avatar
Ian Lynagh committed
492 493
        bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
                (# p,q #) -> p+q
494

495 496 497 498 499 500 501

\begin{code}
makeTrivial :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
-- Binds the expression to a variable, if it's not trivial, returning the variable
makeTrivial env expr
  | exprIsTrivial expr
  = return (env, expr)
Ian Lynagh's avatar
Ian Lynagh committed
502 503
  | otherwise           -- See Note [Take care] below
  = do  { var <- newId FSLIT("a") (exprType expr)
Ian Lynagh's avatar
Ian Lynagh committed
504 505 506
        ; env' <- completeNonRecX env NotTopLevel NonRecursive
                                  False var var expr
        ; return (env', substExpr env' (Var var)) }
507
\end{code}
508 509


510
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
511
%*                                                                      *
512
\subsection{Completing a lazy binding}
Ian Lynagh's avatar
Ian Lynagh committed
513
%*                                                                      *
514 515
%************************************************************************

516 517 518 519 520
completeBind
  * deals only with Ids, not TyVars
  * takes an already-simplified binder and RHS
  * is used for both recursive and non-recursive bindings
  * is used for both top-level and non-top-level bindings
521 522 523 524 525 526 527 528

It does the following:
  - tries discarding a dead binding
  - tries PostInlineUnconditionally
  - add unfolding [this is the only place we add an unfolding]
  - add arity

It does *not* attempt to do let-to-case.  Why?  Because it is used for
Ian Lynagh's avatar
Ian Lynagh committed
529
  - top-level bindings (when let-to-case is impossible)
530
  - many situations where the "rhs" is known to be a WHNF
Ian Lynagh's avatar
Ian Lynagh committed
531
                (so let-to-case is inappropriate).
532

533 534
Nor does it do the atomic-argument thing

535
\begin{code}
536
completeBind :: SimplEnv
Ian Lynagh's avatar
Ian Lynagh committed
537 538 539 540 541 542 543
             -> TopLevelFlag            -- Flag stuck into unfolding
             -> InId                    -- Old binder
             -> OutId -> OutExpr        -- New binder and RHS
             -> SimplM SimplEnv
-- completeBind may choose to do its work
--      * by extending the substitution (e.g. let x = y in ...)
--      * or by adding to the floats in the envt
544 545

completeBind env top_lvl old_bndr new_bndr new_rhs
546
  | postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs unfolding
Ian Lynagh's avatar
Ian Lynagh committed
547 548 549 550 551 552
                -- Inline and discard the binding
  = do  { tick (PostInlineUnconditionally old_bndr)
        ; -- pprTrace "postInlineUnconditionally" (ppr old_bndr <+> ppr new_bndr <+> ppr new_rhs) $
          return (extendIdSubst env old_bndr (DoneEx new_rhs)) }
        -- Use the substitution to make quite, quite sure that the
        -- substitution will happen, since we are going to discard the binding
553 554 555

  |  otherwise
  = let
Ian Lynagh's avatar
Ian Lynagh committed
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
        --      Arity info
        new_bndr_info = idInfo new_bndr `setArityInfo` exprArity new_rhs

        --      Unfolding info
        -- Add the unfolding *only* for non-loop-breakers
        -- Making loop breakers not have an unfolding at all
        -- means that we can avoid tests in exprIsConApp, for example.
        -- This is important: if exprIsConApp says 'yes' for a recursive
        -- thing, then we can get into an infinite loop

        --      Demand info
        -- If the unfolding is a value, the demand info may
        -- go pear-shaped, so we nuke it.  Example:
        --      let x = (a,b) in
        --      case x of (p,q) -> h p q x
        -- Here x is certainly demanded. But after we've nuked
        -- the case, we'll get just
        --      let x = (a,b) in h a b x
        -- and now x is not demanded (I'm assuming h is lazy)
        -- This really happens.  Similarly
        --      let f = \x -> e in ...f..f...
        -- After inlining f at some of its call sites the original binding may
        -- (for example) be no longer strictly demanded.
        -- The solution here is a bit ad hoc...
        info_w_unf = new_bndr_info `setUnfoldingInfo` unfolding
                                   `setWorkerInfo`    worker_info

        final_info | loop_breaker               = new_bndr_info
                   | isEvaldUnfolding unfolding = zapDemandInfo info_w_unf `orElse` info_w_unf
                   | otherwise                  = info_w_unf

        final_id = new_bndr `setIdInfo` final_info
588
    in
Ian Lynagh's avatar
Ian Lynagh committed
589 590 591
                -- These seqs forces the Id, and hence its IdInfo,
                -- and hence any inner substitutions
    final_id                                    `seq`
592
    -- pprTrace "Binding" (ppr final_id <+> ppr unfolding) $
593
    return (addNonRec env final_id new_rhs)
Ian Lynagh's avatar
Ian Lynagh committed
594
  where
595
    unfolding    = mkUnfolding (isTopLevel top_lvl) new_rhs
596
    worker_info  = substWorker env (workerInfo old_info)
597
    loop_breaker = isNonRuleLoopBreaker occ_info
598 599
    old_info     = idInfo old_bndr
    occ_info     = occInfo old_info
SamB's avatar
SamB committed
600
\end{code}
601 602 603



604
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
605
%*                                                                      *
606
\subsection[Simplify-simplExpr]{The main function: simplExpr}
Ian Lynagh's avatar
Ian Lynagh committed
607
%*                                                                      *
608 609
%************************************************************************

610 611 612 613 614 615
The reason for this OutExprStuff stuff is that we want to float *after*
simplifying a RHS, not before.  If we do so naively we get quadratic
behaviour as things float out.

To see why it's important to do it after, consider this (real) example:

Ian Lynagh's avatar
Ian Lynagh committed
616 617
        let t = f x
        in fst t
618
==>
Ian Lynagh's avatar
Ian Lynagh committed
619 620 621 622
        let t = let a = e1
                    b = e2
                in (a,b)
        in fst t
623
==>
Ian Lynagh's avatar
Ian Lynagh committed
624 625 626 627 628
        let a = e1
            b = e2
            t = (a,b)
        in
        a       -- Can't inline a this round, cos it appears twice
629
==>
Ian Lynagh's avatar
Ian Lynagh committed
630
        e1
631 632 633 634

Each of the ==> steps is a round of simplification.  We'd save a
whole round if we float first.  This can cascade.  Consider

Ian Lynagh's avatar
Ian Lynagh committed
635 636
        let f = g d
        in \x -> ...f...
637
==>
Ian Lynagh's avatar
Ian Lynagh committed
638 639
        let f = let d1 = ..d.. in \y -> e
        in \x -> ...f...
640
==>
Ian Lynagh's avatar
Ian Lynagh committed
641 642
        let d1 = ..d..
        in \x -> ...(\y ->e)...
643

Ian Lynagh's avatar
Ian Lynagh committed
644
Only in this second round can the \y be applied, and it
645 646 647
might do the same again.


648
\begin{code}
649
simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
650
simplExpr env expr = simplExprC env expr (mkBoringStop expr_ty')
Ian Lynagh's avatar
Ian Lynagh committed
651 652 653 654 655 656
                   where
                     expr_ty' = substTy env (exprType expr)
        -- The type in the Stop continuation, expr_ty', is usually not used
        -- It's only needed when discarding continuations after finding
        -- a function that returns bottom.
        -- Hence the lazy substitution
657

658

659
simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
Ian Lynagh's avatar
Ian Lynagh committed
660 661
        -- Simplify an expression, given a continuation
simplExprC env expr cont
662
  = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
Ian Lynagh's avatar
Ian Lynagh committed
663 664 665 666
    do  { (env', expr') <- simplExprF (zapFloats env) expr cont
        ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
          -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
          -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
667 668 669 670
          return (wrapFloats env' expr') }

--------------------------------------------------
simplExprF :: SimplEnv -> InExpr -> SimplCont
Ian Lynagh's avatar
Ian Lynagh committed
671
           -> SimplM (SimplEnv, OutExpr)
672

Ian Lynagh's avatar
Ian Lynagh committed
673
simplExprF env e cont
674 675
  = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
    simplExprF' env e cont
Ian Lynagh's avatar
Ian Lynagh committed
676

Ian Lynagh's avatar
Ian Lynagh committed
677 678
simplExprF' :: SimplEnv -> InExpr -> SimplCont
            -> SimplM (SimplEnv, OutExpr)
Ian Lynagh's avatar
Ian Lynagh committed
679
simplExprF' env (Var v)        cont = simplVar env v cont
680 681 682 683
simplExprF' env (Lit lit)      cont = rebuild env (Lit lit) cont
simplExprF' env (Note n expr)  cont = simplNote env n expr cont
simplExprF' env (Cast body co) cont = simplCast env body co cont
simplExprF' env (App fun arg)  cont = simplExprF env fun $
Ian Lynagh's avatar
Ian Lynagh committed
684
                                      ApplyTo NoDup arg env cont
685

Ian Lynagh's avatar
Ian Lynagh committed
686
simplExprF' env expr@(Lam _ _) cont
687
  = simplLam env (map zap bndrs) body cont
Ian Lynagh's avatar
Ian Lynagh committed
688 689 690 691 692 693
        -- The main issue here is under-saturated lambdas
        --   (\x1. \x2. e) arg1
        -- Here x1 might have "occurs-once" occ-info, because occ-info
        -- is computed assuming that a group of lambdas is applied
        -- all at once.  If there are too few args, we must zap the
        -- occ-info.
694 695 696 697
  where
    n_args   = countArgs cont
    n_params = length bndrs
    (bndrs, body) = collectBinders expr
Ian Lynagh's avatar
Ian Lynagh committed
698 699 700 701 702
    zap | n_args >= n_params = \b -> b
        | otherwise          = \b -> if isTyVar b then b
                                     else zapLamIdInfo b
        -- NB: we count all the args incl type args
        -- so we must count all the binders (incl type lambdas)
703

704
simplExprF' env (Type ty) cont
705
  = ASSERT( contIsRhsOrArg cont )
Ian Lynagh's avatar
Ian Lynagh committed
706 707
    do  { ty' <- simplType env ty
        ; rebuild env (Type ty') cont }
708

709
simplExprF' env (Case scrut bndr case_ty alts) cont
710
  | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
Ian Lynagh's avatar
Ian Lynagh committed
711
  =     -- Simplify the scrutinee with a Select continuation
712
    simplExprF env scrut (Select NoDup bndr alts env cont)
713

714
  | otherwise
Ian Lynagh's avatar
Ian Lynagh committed
715 716 717 718
  =     -- If case-of-case is off, simply simplify the case expression
        -- in a vanilla Stop context, and rebuild the result around it
    do  { case_expr' <- simplExprC env scrut case_cont
        ; rebuild env case_expr' cont }
719
  where
720
    case_cont = Select NoDup bndr alts env (mkBoringStop case_ty')
Ian Lynagh's avatar
Ian Lynagh committed
721
    case_ty'  = substTy env case_ty     -- c.f. defn of simplExpr
722

723
simplExprF' env (Let (Rec pairs) body) cont
Ian Lynagh's avatar
Ian Lynagh committed
724
  = do  { env' <- simplRecBndrs env (map fst pairs)
Ian Lynagh's avatar
Ian Lynagh committed
725 726
                -- NB: bndrs' don't have unfoldings or rules
                -- We add them as we go down
727

Ian Lynagh's avatar
Ian Lynagh committed
728 729
        ; env'' <- simplRecBind env' NotTopLevel pairs
        ; simplExprF env'' body cont }
730

731 732
simplExprF' env (Let (NonRec bndr rhs) body) cont
  = simplNonRecE env bndr (rhs, env) ([], body) cont
733 734

---------------------------------
735
simplType :: SimplEnv -> InType -> SimplM OutType
Ian Lynagh's avatar
Ian Lynagh committed
736
        -- Kept monadic just so we can do the seqType
737
simplType env ty
738
  = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
739
    seqType new_ty   `seq`   return new_ty
740
  where
741
    new_ty = substTy env ty
742 743 744
\end{code}


745
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
746
%*                                                                      *
747
\subsection{The main rebuilder}
Ian Lynagh's avatar
Ian Lynagh committed
748
%*                                                                      *
749 750 751 752 753 754
%************************************************************************

\begin{code}
rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
-- At this point the substitution in the SimplEnv should be irrelevant
-- only the in-scope set and floats should matter
Ian Lynagh's avatar
Ian Lynagh committed
755 756 757
rebuild env expr cont0
  = -- pprTrace "rebuild" (ppr expr $$ ppr cont0 $$ ppr (seFloats env)) $
    case cont0 of
Ian Lynagh's avatar
Ian Lynagh committed
758 759
      Stop {}                      -> return (env, expr)
      CoerceIt co cont             -> rebuild env (mkCoerce co expr) cont
760
      Select _ bndr alts se cont   -> rebuildCase (se `setFloats` env) expr bndr alts cont
761
      StrictArg fun ty _ info cont -> rebuildCall env (fun `App` expr) (funResultTy ty) info cont
762
      StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
Ian Lynagh's avatar
Ian Lynagh committed
763 764 765
                                         ; simplLam env' bs body cont }
      ApplyTo _ arg se cont        -> do { arg' <- simplExpr (se `setInScope` env) arg
                                         ; rebuild env (App expr arg') cont }
766 767 768
\end{code}


769
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
770
%*                                                                      *
771
\subsection{Lambdas}
Ian Lynagh's avatar
Ian Lynagh committed
772
%*                                                                      *
773 774 775
%************************************************************************

\begin{code}
776
simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
Ian Lynagh's avatar
Ian Lynagh committed
777
          -> SimplM (SimplEnv, OutExpr)
Ian Lynagh's avatar
Ian Lynagh committed
778 779 780
simplCast env body co0 cont0
  = do  { co1 <- simplType env co0
        ; simplExprF env body (addCoerce co1 cont0) }
781
  where
782 783
       addCoerce co cont = add_coerce co (coercionKind co) cont

Ian Lynagh's avatar
Ian Lynagh committed
784
       add_coerce _co (s1, k1) cont     -- co :: ty~ty
Ian Lynagh's avatar
Ian Lynagh committed
785
         | s1 `coreEqType` k1 = cont    -- is a no-op
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
786

Ian Lynagh's avatar
Ian Lynagh committed
787 788
       add_coerce co1 (s1, _k2) (CoerceIt co2 cont)
         | (_l1, t1) <- coercionKind co2
Ian Lynagh's avatar
Ian Lynagh committed
789 790 791 792 793 794 795 796 797 798
                --      coerce T1 S1 (coerce S1 K1 e)
                -- ==>
                --      e,                      if T1=K1
                --      coerce T1 K1 e,         otherwise
                --
                -- For example, in the initial form of a worker
                -- we may find  (coerce T (coerce S (\x.e))) y
                -- and we'd like it to simplify to e[y/x] in one round
                -- of simplification
         , s1 `coreEqType` t1  = cont            -- The coerces cancel out
799
         | otherwise           = CoerceIt (mkTransCoercion co1 co2) cont
Ian Lynagh's avatar
Ian Lynagh committed
800

Ian Lynagh's avatar
Ian Lynagh committed
801
       add_coerce co (s1s2, _t1t2) (ApplyTo dup (Type arg_ty) arg_se cont)
Ian Lynagh's avatar
Ian Lynagh committed
802 803 804 805 806 807 808
                -- (f `cast` g) ty  --->   (f ty) `cast` (g @ ty)
                -- This implements the PushT rule from the paper
         | Just (tyvar,_) <- splitForAllTy_maybe s1s2
         , not (isCoVar tyvar)
         = ApplyTo dup (Type ty') (zapSubstEnv env) (addCoerce (mkInstCoercion co ty') cont)
         where
           ty' = substTy arg_se arg_ty
809

Ian Lynagh's avatar
Ian Lynagh committed
810
        -- ToDo: the PushC rule is not implemented at all
811

Ian Lynagh's avatar
Ian Lynagh committed
812
       add_coerce co (s1s2, _t1t2) (ApplyTo dup arg arg_se cont)
813
         | not (isTypeArg arg)  -- This implements the Push rule from the paper
Ian Lynagh's avatar
Ian Lynagh committed
814
         , isFunTy s1s2   -- t1t2 must be a function type, becuase it's applied
815
                -- co : s1s2 :=: t1t2
Ian Lynagh's avatar
Ian Lynagh committed
816 817 818 819 820 821 822 823 824 825 826 827 828
                --      (coerce (T1->T2) (S1->S2) F) E
                -- ===>
                --      coerce T2 S2 (F (coerce S1 T1 E))
                --
                -- t1t2 must be a function type, T1->T2, because it's applied
                -- to something but s1s2 might conceivably not be
                --
                -- When we build the ApplyTo we can't mix the out-types
                -- with the InExpr in the argument, so we simply substitute
                -- to make it all consistent.  It's a bit messy.
                -- But it isn't a common case.
                --
                -- Example of use: Trac #995
829
         = ApplyTo dup new_arg (zapSubstEnv env) (addCoerce co2 cont)
830
         where
Ian Lynagh's avatar
Ian Lynagh committed
831 832
           -- we split coercion t1->t2 :=: s1->s2 into t1 :=: s1 and
           -- t2 :=: s2 with left and right on the curried form:
833 834
           --    (->) t1 t2 :=: (->) s1 s2
           [co1, co2] = decomposeCo 2 co
835
           new_arg    = mkCoerce (mkSymCoercion co1) arg'
Ian Lynagh's avatar
Ian Lynagh committed
836
           arg'       = substExpr arg_se arg
837

838
       add_coerce co _ cont = CoerceIt co cont
839 840
\end{code}

841

842
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
843
%*                                                                      *
844
\subsection{Lambdas}
Ian Lynagh's avatar
Ian Lynagh committed
845
%*                                                                      *
846
%************************************************************************
847 848

\begin{code}
849
simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
Ian Lynagh's avatar
Ian Lynagh committed
850
         -> SimplM (SimplEnv, OutExpr)
851 852

simplLam env [] body cont = simplExprF env body cont
853

Ian Lynagh's avatar
Ian Lynagh committed
854
        -- Type-beta reduction
855 856
simplLam env (bndr:bndrs) body (ApplyTo _ (Type ty_arg) arg_se cont)
  = ASSERT( isTyVar bndr )
Ian Lynagh's avatar
Ian Lynagh committed
857 858 859
    do  { tick (BetaReduction bndr)
        ; ty_arg' <- simplType (arg_se `setInScope` env) ty_arg
        ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
860

Ian Lynagh's avatar
Ian Lynagh committed
861
        -- Ordinary beta reduction
862
simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
Ian Lynagh's avatar
Ian Lynagh committed
863 864
  = do  { tick (BetaReduction bndr)
        ; simplNonRecE env bndr (arg, arg_se) (bndrs, body) cont }
865

Ian Lynagh's avatar
Ian Lynagh committed
866
        -- Not enough args, so there are real lambdas left to put in the result
867
simplLam env bndrs body cont
Ian Lynagh's avatar
Ian Lynagh committed
868 869
  = do  { (env', bndrs') <- simplLamBndrs env bndrs
        ; body' <- simplExpr env' body
Ian Lynagh's avatar
Ian Lynagh committed
870
        ; new_lam <- mkLam bndrs' body'
Ian Lynagh's avatar
Ian Lynagh committed
871
        ; rebuild env' new_lam cont }
872 873

------------------
Ian Lynagh's avatar
Ian Lynagh committed
874 875 876 877 878 879 880
simplNonRecE :: SimplEnv
             -> InId                    -- The binder
             -> (InExpr, SimplEnv)      -- Rhs of binding (or arg of lambda)
             -> ([InId], InExpr)        -- Body of the let/lambda
                                        --      \xs.e
             -> SimplCont
             -> SimplM (SimplEnv, OutExpr)
881 882 883 884 885 886 887 888 889 890

-- simplNonRecE is used for
--  * non-top-level non-recursive lets in expressions
--  * beta reduction
--
-- It deals with strict bindings, via the StrictBind continuation,
-- which may abort the whole process
--
-- The "body" of the binding comes as a pair of ([InId],InExpr)
-- representing a lambda; so we recurse back to simplLam
Ian Lynagh's avatar
Ian Lynagh committed
891 892
-- Why?  Because of the binder-occ-info-zapping done before
--       the call to simplLam in simplExprF (Lam ...)
893 894 895

simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
  | preInlineUnconditionally env NotTopLevel bndr rhs
Ian Lynagh's avatar
Ian Lynagh committed
896 897
  = do  { tick (PreInlineUnconditionally bndr)
        ; simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
898

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
899
  | isStrictId bndr
Ian Lynagh's avatar
Ian Lynagh committed
900 901
  = do  { simplExprF (rhs_se `setFloats` env) rhs
                     (StrictBind bndr bndrs body env cont) }
902 903

  | otherwise
Ian Lynagh's avatar
Ian Lynagh committed
904 905 906 907
  = do  { (env1, bndr1) <- simplNonRecBndr env bndr
        ; let (env2, bndr2) = addBndrRules env1 bndr bndr1
        ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
        ; simplLam env3 bndrs body cont }
908 909
\end{code}

910

911
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
912
%*                                                                      *
913
\subsection{Notes}
Ian Lynagh's avatar
Ian Lynagh committed
914
%*                                                                      *
915 916
%************************************************************************

sof's avatar
sof committed
917
\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
918
-- Hack alert: we only distinguish subsumed cost centre stacks for the
919
-- purposes of inlining.  All other CCCSs are mapped to currentCCS.
Ian Lynagh's avatar
Ian Lynagh committed
920 921
simplNote :: SimplEnv -> Note -> CoreExpr -> SimplCont
          -> SimplM (SimplEnv, OutExpr)
922
simplNote env (SCC cc) e cont
Ian Lynagh's avatar
Ian Lynagh committed
923 924
  = do  { e' <- simplExpr (setEnclosingCC env currentCCS) e
        ; rebuild env (mkSCC cc e') cont }
925 926 927

-- See notes with SimplMonad.inlineMode
simplNote env InlineMe e cont
928
  | Just (inside, outside) <- splitInlineCont cont  -- Boring boring continuation; see notes above
Ian Lynagh's avatar
Ian Lynagh committed
929 930 931
  = do  {                       -- Don't inline inside an INLINE expression
          e' <- simplExprC (setMode inlineMode env) e inside
        ; rebuild env (mkInlineMe e') outside }
932

Ian Lynagh's avatar
Ian Lynagh committed
933 934 935
  | otherwise   -- Dissolve the InlineMe note if there's
                -- an interesting context of any kind to combine with
                -- (even a type application -- anything except Stop)
936
  = simplExprF env e cont
937

938 939
simplNote env (CoreNote s) e cont = do
    e' <- simplExpr env e
940
    rebuild env (Note (CoreNote s) e') cont
941 942 943
\end{code}


944
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
945
%*                                                                      *
946
\subsection{Dealing with calls}
Ian Lynagh's avatar
Ian Lynagh committed
947
%*                                                                      *
948
%************************************************************************
949

950
\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
951
simplVar :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
952
simplVar env var cont
953
  = case substId env var of
Ian Lynagh's avatar
Ian Lynagh committed
954 955 956 957 958 959 960 961 962 963 964 965
        DoneEx e         -> simplExprF (zapSubstEnv env) e cont
        ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
        DoneId var1      -> completeCall (zapSubstEnv env) var1 cont
                -- Note [zapSubstEnv]
                -- The template is already simplified, so don't re-substitute.
                -- This is VITAL.  Consider
                --      let x = e in
                --      let y = \z -> ...x... in
                --      \ x -> ...y...
                -- We'll clone the inner \x, adding x->x' in the id_subst
                -- Then when we inline y, we must *not* replace x by x' in
                -- the inlined copy!!
966

967
---------------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
968
--      Dealing with a call site
969