Fix a bug in CorePrep that meant output invariants not satisfied
[ghc-hetmet.git] / compiler / coreSyn / CorePrep.lhs
1 %
2 % (c) The University of Glasgow, 1994-2006
3 %
4
5 Core pass to saturate constructors and PrimOps
6
7 \begin{code}
8 module CorePrep (
9       corePrepPgm, corePrepExpr
10   ) where
11
12 #include "HsVersions.h"
13
14 import PrelNames        ( lazyIdKey, hasKey )
15 import CoreUtils
16 import CoreArity
17 import CoreFVs
18 import CoreMonad        ( endPass, CoreToDo(..) )
19 import CoreSyn
20 import Type
21 import Coercion
22 import TyCon
23 import Demand
24 import Var
25 import VarSet
26 import VarEnv
27 import Id
28 import IdInfo
29 import DataCon
30 import PrimOp
31 import BasicTypes
32 import UniqSupply
33 import Maybes
34 import OrdList
35 import ErrUtils
36 import DynFlags
37 import Util
38 import Outputable
39 import MonadUtils
40 import FastString
41 import Control.Monad
42 \end{code}
43
44 -- ---------------------------------------------------------------------------
45 -- Overview
46 -- ---------------------------------------------------------------------------
47
48 The goal of this pass is to prepare for code generation.
49
50 1.  Saturate constructor and primop applications.
51
52 2.  Convert to A-normal form; that is, function arguments
53     are always variables.
54
55     * Use case for strict arguments:
56         f E ==> case E of x -> f x
57         (where f is strict)
58
59     * Use let for non-trivial lazy arguments
60         f E ==> let x = E in f x
61         (were f is lazy and x is non-trivial)
62
63 3.  Similarly, convert any unboxed lets into cases.
64     [I'm experimenting with leaving 'ok-for-speculation' 
65      rhss in let-form right up to this point.]
66
67 4.  Ensure that *value* lambdas only occur as the RHS of a binding
68     (The code generator can't deal with anything else.)
69     Type lambdas are ok, however, because the code gen discards them.
70
71 5.  [Not any more; nuked Jun 2002] Do the seq/par munging.
72
73 6.  Clone all local Ids.
74     This means that all such Ids are unique, rather than the 
75     weaker guarantee of no clashes which the simplifier provides.
76     And that is what the code generator needs.
77
78     We don't clone TyVars. The code gen doesn't need that, 
79     and doing so would be tiresome because then we'd need
80     to substitute in types.
81
82
83 7.  Give each dynamic CCall occurrence a fresh unique; this is
84     rather like the cloning step above.
85
86 8.  Inject bindings for the "implicit" Ids:
87         * Constructor wrappers
88         * Constructor workers
89     We want curried definitions for all of these in case they
90     aren't inlined by some caller.
91         
92 9.  Replace (lazy e) by e.  See Note [lazyId magic] in MkId.lhs
93
94 This is all done modulo type applications and abstractions, so that
95 when type erasure is done for conversion to STG, we don't end up with
96 any trivial or useless bindings.
97
98   
99 Invariants
100 ~~~~~~~~~~
101 Here is the syntax of the Core produced by CorePrep:
102
103     Trivial expressions 
104        triv ::= lit |  var  | triv ty  |  /\a. triv  |  triv |> co
105
106     Applications
107        app ::= lit  |  var  |  app triv  |  app ty  |  app |> co
108
109     Expressions
110        body ::= app  
111               | let(rec) x = rhs in body     -- Boxed only
112               | case body of pat -> body
113               | /\a. body
114               | body |> co
115
116     Right hand sides (only place where lambdas can occur)
117        rhs ::= /\a.rhs  |  \x.rhs  |  body
118
119 We define a synonym for each of these non-terminals.  Functions
120 with the corresponding name produce a result in that syntax.
121
122 \begin{code}
123 type CpeTriv = CoreExpr    -- Non-terminal 'triv'
124 type CpeApp  = CoreExpr    -- Non-terminal 'app'
125 type CpeBody = CoreExpr    -- Non-terminal 'body'
126 type CpeRhs  = CoreExpr    -- Non-terminal 'rhs'
127 \end{code}
128
129 %************************************************************************
130 %*                                                                      *
131                 Top level stuff
132 %*                                                                      *
133 %************************************************************************
134
135 \begin{code}
136 corePrepPgm :: DynFlags -> [CoreBind] -> [TyCon] -> IO [CoreBind]
137 corePrepPgm dflags binds data_tycons = do
138     showPass dflags "CorePrep"
139     us <- mkSplitUniqSupply 's'
140
141     let implicit_binds = mkDataConWorkers data_tycons
142             -- NB: we must feed mkImplicitBinds through corePrep too
143             -- so that they are suitably cloned and eta-expanded
144
145         binds_out = initUs_ us $ do
146                       floats1 <- corePrepTopBinds binds
147                       floats2 <- corePrepTopBinds implicit_binds
148                       return (deFloatTop (floats1 `appendFloats` floats2))
149
150     endPass dflags CorePrep binds_out []
151     return binds_out
152
153 corePrepExpr :: DynFlags -> CoreExpr -> IO CoreExpr
154 corePrepExpr dflags expr = do
155     showPass dflags "CorePrep"
156     us <- mkSplitUniqSupply 's'
157     let new_expr = initUs_ us (cpeBodyNF emptyCorePrepEnv expr)
158     dumpIfSet_dyn dflags Opt_D_dump_prep "CorePrep" (ppr new_expr)
159     return new_expr
160
161 corePrepTopBinds :: [CoreBind] -> UniqSM Floats
162 -- Note [Floating out of top level bindings]
163 corePrepTopBinds binds 
164   = go emptyCorePrepEnv binds
165   where
166     go _   []             = return emptyFloats
167     go env (bind : binds) = do (env', bind') <- cpeBind TopLevel env bind
168                                binds' <- go env' binds
169                                return (bind' `appendFloats` binds')
170
171 mkDataConWorkers :: [TyCon] -> [CoreBind]
172 -- See Note [Data constructor workers]
173 mkDataConWorkers data_tycons
174   = [ NonRec id (Var id)        -- The ice is thin here, but it works
175     | tycon <- data_tycons,     -- CorePrep will eta-expand it
176       data_con <- tyConDataCons tycon,
177       let id = dataConWorkId data_con ]
178 \end{code}
179
180 Note [Floating out of top level bindings]
181 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
182 NB: we do need to float out of top-level bindings
183 Consider        x = length [True,False]
184 We want to get
185                 s1 = False : []
186                 s2 = True  : s1
187                 x  = length s2
188
189 We return a *list* of bindings, because we may start with
190         x* = f (g y)
191 where x is demanded, in which case we want to finish with
192         a = g y
193         x* = f a
194 And then x will actually end up case-bound
195
196 Note [CafInfo and floating]
197 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
198 What happens to the CafInfo on the floated bindings?  By default, all
199 the CafInfos will be set to MayHaveCafRefs, which is safe.
200
201 This might be pessimistic, because the floated binding might not refer
202 to any CAFs and the GC will end up doing more traversal than is
203 necessary, but it's still better than not floating the bindings at
204 all, because then the GC would have to traverse the structure in the
205 heap instead.  Given this, we decided not to try to get the CafInfo on
206 the floated bindings correct, because it looks difficult.
207
208 But that means we can't float anything out of a NoCafRefs binding.
209 Consider       f = g (h x)
210 If f is NoCafRefs, we don't want to convert to
211                sat = h x
212                f = g sat
213 where sat conservatively says HasCafRefs, because now f's info
214 is wrong.  I don't think this is common, so we simply switch off
215 floating in this case.
216
217 Note [Data constructor workers]
218 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
219 Create any necessary "implicit" bindings for data con workers.  We
220 create the rather strange (non-recursive!) binding
221
222         $wC = \x y -> $wC x y
223
224 i.e. a curried constructor that allocates.  This means that we can
225 treat the worker for a constructor like any other function in the rest
226 of the compiler.  The point here is that CoreToStg will generate a
227 StgConApp for the RHS, rather than a call to the worker (which would
228 give a loop).  As Lennart says: the ice is thin here, but it works.
229
230 Hmm.  Should we create bindings for dictionary constructors?  They are
231 always fully applied, and the bindings are just there to support
232 partial applications. But it's easier to let them through.
233
234
235 %************************************************************************
236 %*                                                                      *
237                 The main code
238 %*                                                                      *
239 %************************************************************************
240
241 \begin{code}
242 cpeBind :: TopLevelFlag
243         -> CorePrepEnv -> CoreBind
244         -> UniqSM (CorePrepEnv, Floats)
245 cpeBind top_lvl env (NonRec bndr rhs)
246   = do { (_, bndr1) <- cloneBndr env bndr
247        ; let is_strict   = isStrictDmd (idDemandInfo bndr)
248              is_unlifted = isUnLiftedType (idType bndr)
249        ; (floats, bndr2, rhs2) <- cpePair top_lvl NonRecursive 
250                                           (is_strict || is_unlifted) 
251                                           env bndr1 rhs
252        ; let new_float = mkFloat is_strict is_unlifted bndr2 rhs2
253
254         -- We want bndr'' in the envt, because it records
255         -- the evaluated-ness of the binder
256        ; return (extendCorePrepEnv env bndr bndr2, 
257                  addFloat floats new_float) }
258
259 cpeBind top_lvl env (Rec pairs)
260   = do { let (bndrs,rhss) = unzip pairs
261        ; (env', bndrs1) <- cloneBndrs env (map fst pairs)
262        ; stuff <- zipWithM (cpePair top_lvl Recursive False env') bndrs1 rhss
263
264        ; let (floats_s, bndrs2, rhss2) = unzip3 stuff
265              all_pairs = foldrOL add_float (bndrs1 `zip` rhss2)
266                                            (concatFloats floats_s)
267        ; return (extendCorePrepEnvList env (bndrs `zip` bndrs2),
268                  unitFloat (FloatLet (Rec all_pairs))) }
269   where
270         -- Flatten all the floats, and the currrent
271         -- group into a single giant Rec
272     add_float (FloatLet (NonRec b r)) prs2 = (b,r) : prs2
273     add_float (FloatLet (Rec prs1))   prs2 = prs1 ++ prs2
274     add_float b                       _    = pprPanic "cpeBind" (ppr b)
275
276 ---------------
277 cpePair :: TopLevelFlag -> RecFlag -> RhsDemand
278         -> CorePrepEnv -> Id -> CoreExpr
279         -> UniqSM (Floats, Id, CpeRhs)
280 -- Used for all bindings
281 cpePair top_lvl is_rec is_strict_or_unlifted env bndr rhs
282   = do { (floats1, rhs1) <- cpeRhsE env rhs
283
284        ; (floats2, rhs2)
285             <- if manifestArity rhs1 <= arity 
286                then return (floats1, cpeEtaExpand arity rhs1)
287                else WARN(True, text "CorePrep: silly extra arguments:" <+> ppr bndr)
288                                -- Note [Silly extra arguments]
289                     (do { v <- newVar (idType bndr)
290                         ; let float = mkFloat False False v rhs1
291                         ; return (addFloat floats1 float, cpeEtaExpand arity (Var v)) })
292
293        ; (floats3, rhs')
294             <- if want_float floats2 rhs2 
295                then return (floats2, rhs2)
296                else -- Non-empty floats will wrap rhs1
297                     -- But: rhs1 might have lambdas, and we can't
298                     --      put them inside a wrapBinds
299                do { body2 <- rhsToBodyNF rhs2
300                   ; return (emptyFloats, wrapBinds floats2 body2) } 
301
302                 -- Record if the binder is evaluated
303        ; let bndr' | exprIsHNF rhs' = bndr `setIdUnfolding` evaldUnfolding
304                    | otherwise      = bndr
305
306        ; return (floats3, bndr', rhs') }
307   where
308     arity = idArity bndr        -- We must match this arity
309     want_float floats rhs 
310      | isTopLevel top_lvl = wantFloatTop bndr floats
311      | otherwise          = wantFloatNested is_rec is_strict_or_unlifted floats rhs
312
313 {- Note [Silly extra arguments]
314 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
315 Suppose we had this
316         f{arity=1} = \x\y. e
317 We *must* match the arity on the Id, so we have to generate
318         f' = \x\y. e
319         f  = \x. f' x
320
321 It's a bizarre case: why is the arity on the Id wrong?  Reason
322 (in the days of __inline_me__): 
323         f{arity=0} = __inline_me__ (let v = expensive in \xy. e)
324 When InlineMe notes go away this won't happen any more.  But
325 it seems good for CorePrep to be robust.
326 -}
327
328 -- ---------------------------------------------------------------------------
329 --              CpeRhs: produces a result satisfying CpeRhs
330 -- ---------------------------------------------------------------------------
331
332 cpeRhsE :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
333 -- If
334 --      e  ===>  (bs, e')
335 -- then 
336 --      e = let bs in e'        (semantically, that is!)
337 --
338 -- For example
339 --      f (g x)   ===>   ([v = g x], f v)
340
341 cpeRhsE _env expr@(Type _) = return (emptyFloats, expr)
342 cpeRhsE _env expr@(Lit _)  = return (emptyFloats, expr)
343 cpeRhsE env expr@(Var {})  = cpeApp env expr
344
345 cpeRhsE env (Var f `App` _ `App` arg)
346   | f `hasKey` lazyIdKey          -- Replace (lazy a) by a
347   = cpeRhsE env arg               -- See Note [lazyId magic] in MkId
348
349 cpeRhsE env expr@(App {}) = cpeApp env expr
350
351 cpeRhsE env (Let bind expr)
352   = do { (env', new_binds) <- cpeBind NotTopLevel env bind
353        ; (floats, body) <- cpeRhsE env' expr
354        ; return (new_binds `appendFloats` floats, body) }
355
356 cpeRhsE env (Note note expr)
357   | ignoreNote note
358   = cpeRhsE env expr
359   | otherwise         -- Just SCCs actually
360   = do { body <- cpeBodyNF env expr
361        ; return (emptyFloats, Note note body) }
362
363 cpeRhsE env (Cast expr co)
364    = do { (floats, expr') <- cpeRhsE env expr
365         ; return (floats, Cast expr' co) }
366
367 cpeRhsE env expr@(Lam {})
368    = do { let (bndrs,body) = collectBinders expr
369         ; (env', bndrs') <- cloneBndrs env bndrs
370         ; body' <- cpeBodyNF env' body
371         ; return (emptyFloats, mkLams bndrs' body') }
372
373 cpeRhsE env (Case (Var id) bndr ty [(DEFAULT,[],expr)])
374   | Just (TickBox {}) <- isTickBoxOp_maybe id
375   = do { body <- cpeBodyNF env expr
376        ; return (emptyFloats, Case (Var id) bndr ty [(DEFAULT,[],body)]) }
377
378 cpeRhsE env (Case scrut bndr ty alts)
379   = do { (floats, scrut') <- cpeBody env scrut
380        ; let bndr1 = bndr `setIdUnfolding` evaldUnfolding
381             -- Record that the case binder is evaluated in the alternatives
382        ; (env', bndr2) <- cloneBndr env bndr1
383        ; alts' <- mapM (sat_alt env') alts
384        ; return (floats, Case scrut' bndr2 ty alts') }
385   where
386     sat_alt env (con, bs, rhs)
387        = do { (env2, bs') <- cloneBndrs env bs
388             ; rhs' <- cpeBodyNF env2 rhs
389             ; return (con, bs', rhs') }
390
391 -- ---------------------------------------------------------------------------
392 --              CpeBody: produces a result satisfying CpeBody
393 -- ---------------------------------------------------------------------------
394
395 cpeBodyNF :: CorePrepEnv -> CoreExpr -> UniqSM CpeBody
396 cpeBodyNF env expr 
397   = do { (floats, body) <- cpeBody env expr
398        ; return (wrapBinds floats body) }
399
400 --------
401 cpeBody :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeBody)
402 cpeBody env expr
403   = do { (floats1, rhs) <- cpeRhsE env expr
404        ; (floats2, body) <- rhsToBody rhs
405        ; return (floats1 `appendFloats` floats2, body) }
406
407 --------
408 rhsToBodyNF :: CpeRhs -> UniqSM CpeBody
409 rhsToBodyNF rhs = do { (floats,body) <- rhsToBody rhs
410                      ; return (wrapBinds floats body) }
411
412 --------
413 rhsToBody :: CpeRhs -> UniqSM (Floats, CpeBody)
414 -- Remove top level lambdas by let-binding
415
416 rhsToBody (Note n expr)
417         -- You can get things like
418         --      case e of { p -> coerce t (\s -> ...) }
419   = do { (floats, expr') <- rhsToBody expr
420        ; return (floats, Note n expr') }
421
422 rhsToBody (Cast e co)
423   = do { (floats, e') <- rhsToBody e
424        ; return (floats, Cast e' co) }
425
426 rhsToBody expr@(Lam {})
427   | Just no_lam_result <- tryEtaReduce bndrs body
428   = return (emptyFloats, no_lam_result)
429   | all isTyVar bndrs           -- Type lambdas are ok
430   = return (emptyFloats, expr)
431   | otherwise                   -- Some value lambdas
432   = do { fn <- newVar (exprType expr)
433        ; let rhs   = cpeEtaExpand (exprArity expr) expr
434              float = FloatLet (NonRec fn rhs)
435        ; return (unitFloat float, Var fn) }
436   where
437     (bndrs,body) = collectBinders expr
438
439 rhsToBody expr = return (emptyFloats, expr)
440
441
442
443 -- ---------------------------------------------------------------------------
444 --              CpeApp: produces a result satisfying CpeApp
445 -- ---------------------------------------------------------------------------
446
447 cpeApp :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
448 -- May return a CpeRhs because of saturating primops
449 cpeApp env expr 
450   = do { (app, (head,depth), _, floats, ss) <- collect_args expr 0
451        ; MASSERT(null ss)       -- make sure we used all the strictness info
452
453         -- Now deal with the function
454        ; case head of
455            Var fn_id -> do { sat_app <- maybeSaturate fn_id app depth
456                            ; return (floats, sat_app) }
457            _other    -> return (floats, app) }
458
459   where
460     -- Deconstruct and rebuild the application, floating any non-atomic
461     -- arguments to the outside.  We collect the type of the expression,
462     -- the head of the application, and the number of actual value arguments,
463     -- all of which are used to possibly saturate this application if it
464     -- has a constructor or primop at the head.
465
466     collect_args
467         :: CoreExpr
468         -> Int                     -- Current app depth
469         -> UniqSM (CpeApp,         -- The rebuilt expression
470                    (CoreExpr,Int), -- The head of the application,
471                                    -- and no. of args it was applied to
472                    Type,           -- Type of the whole expr
473                    Floats,         -- Any floats we pulled out
474                    [Demand])       -- Remaining argument demands
475
476     collect_args (App fun arg@(Type arg_ty)) depth
477       = do { (fun',hd,fun_ty,floats,ss) <- collect_args fun depth
478            ; return (App fun' arg, hd, applyTy fun_ty arg_ty, floats, ss) }
479
480     collect_args (App fun arg) depth
481       = do { (fun',hd,fun_ty,floats,ss) <- collect_args fun (depth+1)
482            ; let
483               (ss1, ss_rest)   = case ss of
484                                    (ss1:ss_rest) -> (ss1,     ss_rest)
485                                    []            -> (lazyDmd, [])
486               (arg_ty, res_ty) = expectJust "cpeBody:collect_args" $
487                                  splitFunTy_maybe fun_ty
488
489            ; (fs, arg') <- cpeArg env (isStrictDmd ss1) arg arg_ty
490            ; return (App fun' arg', hd, res_ty, fs `appendFloats` floats, ss_rest) }
491
492     collect_args (Var v) depth 
493       = do { v1 <- fiddleCCall v
494            ; let v2 = lookupCorePrepEnv env v1
495            ; return (Var v2, (Var v2, depth), idType v2, emptyFloats, stricts) }
496         where
497           stricts = case idStrictness v of
498                         StrictSig (DmdType _ demands _)
499                             | listLengthCmp demands depth /= GT -> demands
500                                     -- length demands <= depth
501                             | otherwise                         -> []
502                 -- If depth < length demands, then we have too few args to 
503                 -- satisfy strictness  info so we have to  ignore all the 
504                 -- strictness info, e.g. + (error "urk")
505                 -- Here, we can't evaluate the arg strictly, because this 
506                 -- partial application might be seq'd
507
508     collect_args (Cast fun co) depth
509       = do { let (_ty1,ty2) = coercionKind co
510            ; (fun', hd, _, floats, ss) <- collect_args fun depth
511            ; return (Cast fun' co, hd, ty2, floats, ss) }
512           
513     collect_args (Note note fun) depth
514       | ignoreNote note         -- Drop these notes altogether
515       = collect_args fun depth  -- They aren't used by the code generator
516
517         -- N-variable fun, better let-bind it
518     collect_args fun depth
519       = do { (fun_floats, fun') <- cpeArg env True fun ty
520                           -- The True says that it's sure to be evaluated,
521                           -- so we'll end up case-binding it
522            ; return (fun', (fun', depth), ty, fun_floats, []) }
523         where
524           ty = exprType fun
525
526 -- ---------------------------------------------------------------------------
527 --      CpeArg: produces a result satisfying CpeArg
528 -- ---------------------------------------------------------------------------
529
530 -- This is where we arrange that a non-trivial argument is let-bound
531 cpeArg :: CorePrepEnv -> RhsDemand -> CoreArg -> Type
532        -> UniqSM (Floats, CpeTriv)
533 cpeArg env is_strict arg arg_ty
534   | cpe_ExprIsTrivial arg   -- Do not eta expand etc a trivial argument
535   = cpeBody env arg         -- Must still do substitution though
536   | otherwise
537   = do { (floats1, arg1) <- cpeRhsE env arg     -- arg1 can be a lambda
538        ; (floats2, arg2) <- if want_float floats1 arg1 
539                             then return (floats1, arg1)
540                             else do { body1 <- rhsToBodyNF arg1
541                                     ; return (emptyFloats, wrapBinds floats1 body1) } 
542                 -- Else case: arg1 might have lambdas, and we can't
543                 --            put them inside a wrapBinds
544
545        ; v <- newVar arg_ty
546        ; let arg3      = cpeEtaExpand (exprArity arg2) arg2
547              arg_float = mkFloat is_strict is_unlifted v arg3
548        ; return (addFloat floats2 arg_float, Var v) }
549   where
550     is_unlifted = isUnLiftedType arg_ty
551     want_float = wantFloatNested NonRecursive (is_strict || is_unlifted)
552 \end{code}
553
554 Note [Floating unlifted arguments]
555 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
556 Consider    C (let v* = expensive in v)
557
558 where the "*" indicates "will be demanded".  Usually v will have been
559 inlined by now, but let's suppose it hasn't (see Trac #2756).  Then we
560 do *not* want to get
561
562      let v* = expensive in C v
563
564 because that has different strictness.  Hence the use of 'allLazy'.
565 (NB: the let v* turns into a FloatCase, in mkLocalNonRec.)
566
567
568 ------------------------------------------------------------------------------
569 -- Building the saturated syntax
570 -- ---------------------------------------------------------------------------
571
572 maybeSaturate deals with saturating primops and constructors
573 The type is the type of the entire application
574
575 \begin{code}
576 maybeSaturate :: Id -> CpeApp -> Int -> UniqSM CpeRhs
577 maybeSaturate fn expr n_args
578   | Just DataToTagOp <- isPrimOpId_maybe fn     -- DataToTag must have an evaluated arg
579                                                 -- A gruesome special case
580   = saturateDataToTag sat_expr
581
582   | hasNoBinding fn        -- There's no binding
583   = return sat_expr
584
585   | otherwise 
586   = return expr
587   where
588     fn_arity     = idArity fn
589     excess_arity = fn_arity - n_args
590     sat_expr     = cpeEtaExpand excess_arity expr
591
592 -------------
593 saturateDataToTag :: CpeApp -> UniqSM CpeApp
594 -- Horrid: ensure that the arg of data2TagOp is evaluated
595 --   (data2tag x) -->  (case x of y -> data2tag y)
596 -- (yuk yuk) take into account the lambdas we've now introduced
597 saturateDataToTag sat_expr
598   = do { let (eta_bndrs, eta_body) = collectBinders sat_expr
599        ; eta_body' <- eval_data2tag_arg eta_body
600        ; return (mkLams eta_bndrs eta_body') }
601   where
602     eval_data2tag_arg :: CpeApp -> UniqSM CpeBody
603     eval_data2tag_arg app@(fun `App` arg)
604         | exprIsHNF arg         -- Includes nullary constructors
605         = return app            -- The arg is evaluated
606         | otherwise                     -- Arg not evaluated, so evaluate it
607         = do { arg_id <- newVar (exprType arg)
608              ; let arg_id1 = setIdUnfolding arg_id evaldUnfolding
609              ; return (Case arg arg_id1 (exprType app)
610                             [(DEFAULT, [], fun `App` Var arg_id1)]) }
611
612     eval_data2tag_arg (Note note app)   -- Scc notes can appear
613         = do { app' <- eval_data2tag_arg app
614              ; return (Note note app') }
615
616     eval_data2tag_arg other     -- Should not happen
617         = pprPanic "eval_data2tag" (ppr other)
618 \end{code}
619
620
621
622
623 %************************************************************************
624 %*                                                                      *
625                 Simple CoreSyn operations
626 %*                                                                      *
627 %************************************************************************
628
629 \begin{code}
630         -- We don't ignore SCCs, since they require some code generation
631 ignoreNote :: Note -> Bool
632 -- Tells which notes to drop altogether; they are ignored by code generation
633 -- Do not ignore SCCs!
634 -- It's important that we do drop InlineMe notes; for example
635 --    unzip = __inline_me__ (/\ab. foldr (..) (..))
636 -- Here unzip gets arity 1 so we'll eta-expand it. But we don't
637 -- want to get this:
638 --     unzip = /\ab \xs. (__inline_me__ ...) a b xs
639 ignoreNote (CoreNote _) = True 
640 ignoreNote _other       = False
641
642
643 cpe_ExprIsTrivial :: CoreExpr -> Bool
644 -- Version that doesn't consider an scc annotation to be trivial.
645 cpe_ExprIsTrivial (Var _)                  = True
646 cpe_ExprIsTrivial (Type _)                 = True
647 cpe_ExprIsTrivial (Lit _)                  = True
648 cpe_ExprIsTrivial (App e arg)              = isTypeArg arg && cpe_ExprIsTrivial e
649 cpe_ExprIsTrivial (Note (SCC _) _)         = False
650 cpe_ExprIsTrivial (Note _ e)               = cpe_ExprIsTrivial e
651 cpe_ExprIsTrivial (Cast e _)               = cpe_ExprIsTrivial e
652 cpe_ExprIsTrivial (Lam b body) | isTyVar b = cpe_ExprIsTrivial body
653 cpe_ExprIsTrivial _                        = False
654 \end{code}
655
656 -- -----------------------------------------------------------------------------
657 --      Eta reduction
658 -- -----------------------------------------------------------------------------
659
660 Note [Eta expansion]
661 ~~~~~~~~~~~~~~~~~~~~~
662 Eta expand to match the arity claimed by the binder Remember,
663 CorePrep must not change arity
664
665 Eta expansion might not have happened already, because it is done by
666 the simplifier only when there at least one lambda already.
667
668 NB1:we could refrain when the RHS is trivial (which can happen
669     for exported things).  This would reduce the amount of code
670     generated (a little) and make things a little words for
671     code compiled without -O.  The case in point is data constructor
672     wrappers.
673
674 NB2: we have to be careful that the result of etaExpand doesn't
675    invalidate any of the assumptions that CorePrep is attempting
676    to establish.  One possible cause is eta expanding inside of
677    an SCC note - we're now careful in etaExpand to make sure the
678    SCC is pushed inside any new lambdas that are generated.
679
680 Note [Eta expansion and the CorePrep invariants]
681 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
682 It turns out to be much much easier to do eta expansion
683 *after* the main CorePrep stuff.  But that places constraints
684 on the eta expander: given a CpeRhs, it must return a CpeRhs.
685
686 For example here is what we do not want:
687                 f = /\a -> g (h 3)      -- h has arity 2
688 After ANFing we get
689                 f = /\a -> let s = h 3 in g s
690 and now we do NOT want eta expansion to give
691                 f = /\a -> \ y -> (let s = h 3 in g s) y
692
693 Instead CoreArity.etaExpand gives
694                 f = /\a -> \y -> let s = h 3 in g s y
695
696 \begin{code}
697 cpeEtaExpand :: Arity -> CpeRhs -> CpeRhs
698 cpeEtaExpand arity expr
699   | arity == 0 = expr
700   | otherwise  = etaExpand arity expr
701 \end{code}
702
703 -- -----------------------------------------------------------------------------
704 --      Eta reduction
705 -- -----------------------------------------------------------------------------
706
707 Why try eta reduction?  Hasn't the simplifier already done eta?
708 But the simplifier only eta reduces if that leaves something
709 trivial (like f, or f Int).  But for deLam it would be enough to
710 get to a partial application:
711         case x of { p -> \xs. map f xs }
712     ==> case x of { p -> map f }
713
714 \begin{code}
715 tryEtaReduce :: [CoreBndr] -> CoreExpr -> Maybe CoreExpr
716 tryEtaReduce bndrs expr@(App _ _)
717   | ok_to_eta_reduce f &&
718     n_remaining >= 0 &&
719     and (zipWith ok bndrs last_args) &&
720     not (any (`elemVarSet` fvs_remaining) bndrs)
721   = Just remaining_expr
722   where
723     (f, args) = collectArgs expr
724     remaining_expr = mkApps f remaining_args
725     fvs_remaining = exprFreeVars remaining_expr
726     (remaining_args, last_args) = splitAt n_remaining args
727     n_remaining = length args - length bndrs
728
729     ok bndr (Var arg) = bndr == arg
730     ok _    _         = False
731
732           -- we can't eta reduce something which must be saturated.
733     ok_to_eta_reduce (Var f) = not (hasNoBinding f)
734     ok_to_eta_reduce _       = False --safe. ToDo: generalise
735
736 tryEtaReduce bndrs (Let bind@(NonRec _ r) body)
737   | not (any (`elemVarSet` fvs) bndrs)
738   = case tryEtaReduce bndrs body of
739         Just e -> Just (Let bind e)
740         Nothing -> Nothing
741   where
742     fvs = exprFreeVars r
743
744 tryEtaReduce _ _ = Nothing
745 \end{code}
746
747
748 -- -----------------------------------------------------------------------------
749 -- Demands
750 -- -----------------------------------------------------------------------------
751
752 \begin{code}
753 type RhsDemand = Bool  -- True => used strictly; hence not top-level, non-recursive
754 \end{code}
755
756 %************************************************************************
757 %*                                                                      *
758                 Floats
759 %*                                                                      *
760 %************************************************************************
761
762 \begin{code}
763 data FloatingBind 
764   = FloatLet CoreBind           -- Rhs of bindings are CpeRhss
765   | FloatCase Id CpeBody Bool   -- The bool indicates "ok-for-speculation"
766
767 data Floats = Floats OkToSpec (OrdList FloatingBind)
768
769 -- Can we float these binds out of the rhs of a let?  We cache this decision
770 -- to avoid having to recompute it in a non-linear way when there are
771 -- deeply nested lets.
772 data OkToSpec
773    = NotOkToSpec        -- definitely not
774    | OkToSpec           -- yes
775    | IfUnboxedOk        -- only if floating an unboxed binding is ok
776
777 mkFloat :: Bool -> Bool -> Id -> CpeRhs -> FloatingBind
778 mkFloat is_strict is_unlifted bndr rhs
779   | use_case  = FloatCase bndr rhs (exprOkForSpeculation rhs)
780   | otherwise = FloatLet (NonRec bndr rhs)
781   where
782     use_case = is_unlifted || is_strict && not (exprIsHNF rhs)
783                 -- Don't make a case for a value binding,
784                 -- even if it's strict.  Otherwise we get
785                 --      case (\x -> e) of ...!
786              
787 emptyFloats :: Floats
788 emptyFloats = Floats OkToSpec nilOL
789
790 isEmptyFloats :: Floats -> Bool
791 isEmptyFloats (Floats _ bs) = isNilOL bs
792
793 wrapBinds :: Floats -> CpeBody -> CpeBody
794 wrapBinds (Floats _ binds) body
795   = foldrOL mk_bind body binds
796   where
797     mk_bind (FloatCase bndr rhs _) body = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
798     mk_bind (FloatLet bind)        body = Let bind body
799
800 addFloat :: Floats -> FloatingBind -> Floats
801 addFloat (Floats ok_to_spec floats) new_float
802   = Floats (combine ok_to_spec (check new_float)) (floats `snocOL` new_float)
803   where
804     check (FloatLet _) = OkToSpec
805     check (FloatCase _ _ ok_for_spec) 
806         | ok_for_spec  =  IfUnboxedOk
807         | otherwise    =  NotOkToSpec
808         -- The ok-for-speculation flag says that it's safe to
809         -- float this Case out of a let, and thereby do it more eagerly
810         -- We need the top-level flag because it's never ok to float
811         -- an unboxed binding to the top level
812
813 unitFloat :: FloatingBind -> Floats
814 unitFloat = addFloat emptyFloats
815
816 appendFloats :: Floats -> Floats -> Floats
817 appendFloats (Floats spec1 floats1) (Floats spec2 floats2)
818   = Floats (combine spec1 spec2) (floats1 `appOL` floats2)
819
820 concatFloats :: [Floats] -> OrdList FloatingBind
821 concatFloats = foldr (\ (Floats _ bs1) bs2 -> appOL bs1 bs2) nilOL
822
823 combine :: OkToSpec -> OkToSpec -> OkToSpec
824 combine NotOkToSpec _ = NotOkToSpec
825 combine _ NotOkToSpec = NotOkToSpec
826 combine IfUnboxedOk _ = IfUnboxedOk
827 combine _ IfUnboxedOk = IfUnboxedOk
828 combine _ _           = OkToSpec
829     
830 instance Outputable FloatingBind where
831   ppr (FloatLet bind)        = text "FloatLet" <+> ppr bind
832   ppr (FloatCase b rhs spec) = text "FloatCase" <+> ppr b <+> ppr spec <+> equals <+> ppr rhs
833
834 deFloatTop :: Floats -> [CoreBind]
835 -- For top level only; we don't expect any FloatCases
836 deFloatTop (Floats _ floats)
837   = foldrOL get [] floats
838   where
839     get (FloatLet b) bs = b:bs
840     get b            _  = pprPanic "corePrepPgm" (ppr b)
841
842 -------------------------------------------
843 wantFloatTop :: Id -> Floats -> Bool
844        -- Note [CafInfo and floating]
845 wantFloatTop bndr floats = isEmptyFloats floats
846                          || (mayHaveCafRefs (idCafInfo bndr)
847                              && allLazyTop floats)
848
849 wantFloatNested :: RecFlag -> Bool -> Floats -> CpeRhs -> Bool
850 wantFloatNested is_rec strict_or_unlifted floats rhs
851   =  isEmptyFloats floats
852   || strict_or_unlifted
853   || (allLazyNested is_rec floats && exprIsHNF rhs)
854         -- Why the test for allLazyNested? 
855         --      v = f (x `divInt#` y)
856         -- we don't want to float the case, even if f has arity 2,
857         -- because floating the case would make it evaluated too early
858
859 allLazyTop :: Floats -> Bool
860 allLazyTop (Floats OkToSpec _) = True
861 allLazyTop _                   = False
862
863 allLazyNested :: RecFlag -> Floats -> Bool
864 allLazyNested _      (Floats OkToSpec    _) = True
865 allLazyNested _      (Floats NotOkToSpec _) = False
866 allLazyNested is_rec (Floats IfUnboxedOk _) = isNonRec is_rec
867 \end{code}
868
869
870 %************************************************************************
871 %*                                                                      *
872                 Cloning
873 %*                                                                      *
874 %************************************************************************
875
876 \begin{code}
877 -- ---------------------------------------------------------------------------
878 --                      The environment
879 -- ---------------------------------------------------------------------------
880
881 data CorePrepEnv = CPE (IdEnv Id)       -- Clone local Ids
882
883 emptyCorePrepEnv :: CorePrepEnv
884 emptyCorePrepEnv = CPE emptyVarEnv
885
886 extendCorePrepEnv :: CorePrepEnv -> Id -> Id -> CorePrepEnv
887 extendCorePrepEnv (CPE env) id id' = CPE (extendVarEnv env id id')
888
889 extendCorePrepEnvList :: CorePrepEnv -> [(Id,Id)] -> CorePrepEnv
890 extendCorePrepEnvList (CPE env) prs = CPE (extendVarEnvList env prs)
891
892 lookupCorePrepEnv :: CorePrepEnv -> Id -> Id
893 lookupCorePrepEnv (CPE env) id
894   = case lookupVarEnv env id of
895         Nothing  -> id
896         Just id' -> id'
897
898 ------------------------------------------------------------------------------
899 -- Cloning binders
900 -- ---------------------------------------------------------------------------
901
902 cloneBndrs :: CorePrepEnv -> [Var] -> UniqSM (CorePrepEnv, [Var])
903 cloneBndrs env bs = mapAccumLM cloneBndr env bs
904
905 cloneBndr  :: CorePrepEnv -> Var -> UniqSM (CorePrepEnv, Var)
906 cloneBndr env bndr
907   | isLocalId bndr
908   = do bndr' <- setVarUnique bndr <$> getUniqueM
909        return (extendCorePrepEnv env bndr bndr', bndr')
910
911   | otherwise   -- Top level things, which we don't want
912                 -- to clone, have become GlobalIds by now
913                 -- And we don't clone tyvars
914   = return (env, bndr)
915   
916
917 ------------------------------------------------------------------------------
918 -- Cloning ccall Ids; each must have a unique name,
919 -- to give the code generator a handle to hang it on
920 -- ---------------------------------------------------------------------------
921
922 fiddleCCall :: Id -> UniqSM Id
923 fiddleCCall id 
924   | isFCallId id = (id `setVarUnique`) <$> getUniqueM
925   | otherwise    = return id
926
927 ------------------------------------------------------------------------------
928 -- Generating new binders
929 -- ---------------------------------------------------------------------------
930
931 newVar :: Type -> UniqSM Id
932 newVar ty
933  = seqType ty `seq` do
934      uniq <- getUniqueM
935      return (mkSysLocal (fsLit "sat") uniq ty)
936 \end{code}