compiler: de-lhs stgSyn/
[ghc.git] / compiler / stgSyn / CoreToStg.hs
1 {-# LANGUAGE CPP #-}
2
3 --
4 -- (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
5 --
6
7 --------------------------------------------------------------
8 -- Converting Core to STG Syntax
9 --------------------------------------------------------------
10
11 -- And, as we have the info in hand, we may convert some lets to
12 -- let-no-escapes.
13
14 module CoreToStg ( coreToStg, coreExprToStg ) where
15
16 #include "HsVersions.h"
17
18 import CoreSyn
19 import CoreUtils ( exprType, findDefault )
20 import CoreArity ( manifestArity )
21 import StgSyn
22
23 import Type
24 import TyCon
25 import MkId ( coercionTokenId )
26 import Id
27 import IdInfo
28 import DataCon
29 import CostCentre ( noCCS )
30 import VarSet
31 import VarEnv
32 import Module
33 import Name ( getOccName, isExternalName, nameOccName )
34 import OccName ( occNameString, occNameFS )
35 import BasicTypes ( Arity )
36 import TysWiredIn ( unboxedUnitDataCon )
37 import Literal
38 import Outputable
39 import MonadUtils
40 import FastString
41 import Util
42 import DynFlags
43 import ForeignCall
44 import Demand ( isSingleUsed )
45 import PrimOp ( PrimCall(..) )
46
47 import Data.Maybe (isJust)
48 import Control.Monad (liftM, ap)
49
50 -- Note [Live vs free]
51 -- ~~~~~~~~~~~~~~~~~~~
52 --
53 -- The actual Stg datatype is decorated with live variable information, as well
54 -- as free variable information. The two are not the same. Liveness is an
55 -- operational property rather than a semantic one. A variable is live at a
56 -- particular execution point if it can be referred to directly again. In
57 -- particular, a dead variable's stack slot (if it has one):
58 --
59 -- - should be stubbed to avoid space leaks, and
60 -- - may be reused for something else.
61 --
62 -- There ought to be a better way to say this. Here are some examples:
63 --
64 -- let v = [q] \[x] -> e
65 -- in
66 -- ...v... (but no q's)
67 --
68 -- Just after the `in', v is live, but q is dead. If the whole of that
69 -- let expression was enclosed in a case expression, thus:
70 --
71 -- case (let v = [q] \[x] -> e in ...v...) of
72 -- alts[...q...]
73 --
74 -- (ie `alts' mention `q'), then `q' is live even after the `in'; because
75 -- we'll return later to the `alts' and need it.
76 --
77 -- Let-no-escapes make this a bit more interesting:
78 --
79 -- let-no-escape v = [q] \ [x] -> e
80 -- in
81 -- ...v...
82 --
83 -- Here, `q' is still live at the `in', because `v' is represented not by
84 -- a closure but by the current stack state. In other words, if `v' is
85 -- live then so is `q'. Furthermore, if `e' mentions an enclosing
86 -- let-no-escaped variable, then its free variables are also live if `v' is.
87
88 -- Note [Collecting live CAF info]
89 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
90 --
91 -- In this pass we also collect information on which CAFs are live for
92 -- constructing SRTs (see SRT.lhs).
93 --
94 -- A top-level Id has CafInfo, which is
95 --
96 -- - MayHaveCafRefs, if it may refer indirectly to
97 -- one or more CAFs, or
98 -- - NoCafRefs if it definitely doesn't
99 --
100 -- The CafInfo has already been calculated during the CoreTidy pass.
101 --
102 -- During CoreToStg, we then pin onto each binding and case expression, a
103 -- list of Ids which represents the "live" CAFs at that point. The meaning
104 -- of "live" here is the same as for live variables, see above (which is
105 -- why it's convenient to collect CAF information here rather than elsewhere).
106 --
107 -- The later SRT pass takes these lists of Ids and uses them to construct
108 -- the actual nested SRTs, and replaces the lists of Ids with (offset,length)
109 -- pairs.
110
111
112 -- Note [Interaction of let-no-escape with SRTs]
113 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
114 -- Consider
115 --
116 -- let-no-escape x = ...caf1...caf2...
117 -- in
118 -- ...x...x...x...
119 --
120 -- where caf1,caf2 are CAFs. Since x doesn't have a closure, we
121 -- build SRTs just as if x's defn was inlined at each call site, and
122 -- that means that x's CAF refs get duplicated in the overall SRT.
123 --
124 -- This is unlike ordinary lets, in which the CAF refs are not duplicated.
125 --
126 -- We could fix this loss of (static) sharing by making a sort of pseudo-closure
127 -- for x, solely to put in the SRTs lower down.
128
129 -- Note [What is a non-escaping let]
130 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
131 --
132 -- Consider:
133 --
134 -- let x = fvs \ args -> e
135 -- in
136 -- if ... then x else
137 -- if ... then x else ...
138 --
139 -- `x' is used twice (so we probably can't unfold it), but when it is
140 -- entered, the stack is deeper than it was when the definition of `x'
141 -- happened. Specifically, if instead of allocating a closure for `x',
142 -- we saved all `x's fvs on the stack, and remembered the stack depth at
143 -- that moment, then whenever we enter `x' we can simply set the stack
144 -- pointer(s) to these remembered (compile-time-fixed) values, and jump
145 -- to the code for `x'.
146 --
147 -- All of this is provided x is:
148 -- 1. non-updatable - it must have at least one parameter (see Note
149 -- [Join point abstraction]);
150 -- 2. guaranteed to be entered before the stack retreats -- ie x is not
151 -- buried in a heap-allocated closure, or passed as an argument to
152 -- something;
153 -- 3. all the enters have exactly the right number of arguments,
154 -- no more no less;
155 -- 4. all the enters are tail calls; that is, they return to the
156 -- caller enclosing the definition of `x'.
157 --
158 -- Under these circumstances we say that `x' is non-escaping.
159 --
160 -- An example of when (4) does not hold:
161 --
162 -- let x = ...
163 -- in case x of ...alts...
164 --
165 -- Here, `x' is certainly entered only when the stack is deeper than when
166 -- `x' is defined, but here it must return to ...alts... So we can't just
167 -- adjust the stack down to `x''s recalled points, because that would lost
168 -- alts' context.
169 --
170 -- Things can get a little more complicated. Consider:
171 --
172 -- let y = ...
173 -- in let x = fvs \ args -> ...y...
174 -- in ...x...
175 --
176 -- Now, if `x' is used in a non-escaping way in ...x..., and `y' is used in a
177 -- non-escaping way in ...y..., then `y' is non-escaping.
178 --
179 -- `x' can even be recursive! Eg:
180 --
181 -- letrec x = [y] \ [v] -> if v then x True else ...
182 -- in
183 -- ...(x b)...
184
185 -- --------------------------------------------------------------
186 -- Setting variable info: top-level, binds, RHSs
187 -- --------------------------------------------------------------
188
189 coreToStg :: DynFlags -> Module -> CoreProgram -> IO [StgBinding]
190 coreToStg dflags this_mod pgm
191 = return pgm'
192 where (_, _, pgm') = coreTopBindsToStg dflags this_mod emptyVarEnv pgm
193
194 coreExprToStg :: CoreExpr -> StgExpr
195 coreExprToStg expr
196 = new_expr where (new_expr,_,_) = initLne emptyVarEnv (coreToStgExpr expr)
197
198
199 coreTopBindsToStg
200 :: DynFlags
201 -> Module
202 -> IdEnv HowBound -- environment for the bindings
203 -> CoreProgram
204 -> (IdEnv HowBound, FreeVarsInfo, [StgBinding])
205
206 coreTopBindsToStg _ _ env [] = (env, emptyFVInfo, [])
207 coreTopBindsToStg dflags this_mod env (b:bs)
208 = (env2, fvs2, b':bs')
209 where
210 -- Notice the mutually-recursive "knot" here:
211 -- env accumulates down the list of binds,
212 -- fvs accumulates upwards
213 (env1, fvs2, b' ) = coreTopBindToStg dflags this_mod env fvs1 b
214 (env2, fvs1, bs') = coreTopBindsToStg dflags this_mod env1 bs
215
216 coreTopBindToStg
217 :: DynFlags
218 -> Module
219 -> IdEnv HowBound
220 -> FreeVarsInfo -- Info about the body
221 -> CoreBind
222 -> (IdEnv HowBound, FreeVarsInfo, StgBinding)
223
224 coreTopBindToStg dflags this_mod env body_fvs (NonRec id rhs)
225 = let
226 env' = extendVarEnv env id how_bound
227 how_bound = LetBound TopLet $! manifestArity rhs
228
229 (stg_rhs, fvs') =
230 initLne env $ do
231 (stg_rhs, fvs') <- coreToTopStgRhs dflags this_mod body_fvs (id,rhs)
232 return (stg_rhs, fvs')
233
234 bind = StgNonRec id stg_rhs
235 in
236 ASSERT2(consistentCafInfo id bind, ppr id )
237 -- NB: previously the assertion printed 'rhs' and 'bind'
238 -- as well as 'id', but that led to a black hole
239 -- where printing the assertion error tripped the
240 -- assertion again!
241 (env', fvs' `unionFVInfo` body_fvs, bind)
242
243 coreTopBindToStg dflags this_mod env body_fvs (Rec pairs)
244 = ASSERT( not (null pairs) )
245 let
246 binders = map fst pairs
247
248 extra_env' = [ (b, LetBound TopLet $! manifestArity rhs)
249 | (b, rhs) <- pairs ]
250 env' = extendVarEnvList env extra_env'
251
252 (stg_rhss, fvs')
253 = initLne env' $ do
254 (stg_rhss, fvss') <- mapAndUnzipM (coreToTopStgRhs dflags this_mod body_fvs) pairs
255 let fvs' = unionFVInfos fvss'
256 return (stg_rhss, fvs')
257
258 bind = StgRec (zip binders stg_rhss)
259 in
260 ASSERT2(consistentCafInfo (head binders) bind, ppr binders)
261 (env', fvs' `unionFVInfo` body_fvs, bind)
262
263
264 -- Assertion helper: this checks that the CafInfo on the Id matches
265 -- what CoreToStg has figured out about the binding's SRT. The
266 -- CafInfo will be exact in all cases except when CorePrep has
267 -- floated out a binding, in which case it will be approximate.
268 consistentCafInfo :: Id -> GenStgBinding Var Id -> Bool
269 consistentCafInfo id bind
270 = WARN( not (exact || is_sat_thing) , ppr id <+> ppr id_marked_caffy <+> ppr binding_is_caffy )
271 safe
272 where
273 safe = id_marked_caffy || not binding_is_caffy
274 exact = id_marked_caffy == binding_is_caffy
275 id_marked_caffy = mayHaveCafRefs (idCafInfo id)
276 binding_is_caffy = stgBindHasCafRefs bind
277 is_sat_thing = occNameFS (nameOccName (idName id)) == fsLit "sat"
278
279 coreToTopStgRhs
280 :: DynFlags
281 -> Module
282 -> FreeVarsInfo -- Free var info for the scope of the binding
283 -> (Id,CoreExpr)
284 -> LneM (StgRhs, FreeVarsInfo)
285
286 coreToTopStgRhs dflags this_mod scope_fv_info (bndr, rhs)
287 = do { (new_rhs, rhs_fvs, _) <- coreToStgExpr rhs
288 ; lv_info <- freeVarsToLiveVars rhs_fvs
289
290 ; let stg_rhs = mkTopStgRhs dflags this_mod rhs_fvs (mkSRT lv_info) bndr bndr_info new_rhs
291 stg_arity = stgRhsArity stg_rhs
292 ; return (ASSERT2( arity_ok stg_arity, mk_arity_msg stg_arity) stg_rhs,
293 rhs_fvs) }
294 where
295 bndr_info = lookupFVInfo scope_fv_info bndr
296
297 -- It's vital that the arity on a top-level Id matches
298 -- the arity of the generated STG binding, else an importing
299 -- module will use the wrong calling convention
300 -- (Trac #2844 was an example where this happened)
301 -- NB1: we can't move the assertion further out without
302 -- blocking the "knot" tied in coreTopBindsToStg
303 -- NB2: the arity check is only needed for Ids with External
304 -- Names, because they are externally visible. The CorePrep
305 -- pass introduces "sat" things with Local Names and does
306 -- not bother to set their Arity info, so don't fail for those
307 arity_ok stg_arity
308 | isExternalName (idName bndr) = id_arity == stg_arity
309 | otherwise = True
310 id_arity = idArity bndr
311 mk_arity_msg stg_arity
312 = vcat [ppr bndr,
313 ptext (sLit "Id arity:") <+> ppr id_arity,
314 ptext (sLit "STG arity:") <+> ppr stg_arity]
315
316 mkTopStgRhs :: DynFlags -> Module -> FreeVarsInfo
317 -> SRT -> Id -> StgBinderInfo -> StgExpr
318 -> StgRhs
319
320 mkTopStgRhs _ _ rhs_fvs srt _ binder_info (StgLam bndrs body)
321 = StgRhsClosure noCCS binder_info
322 (getFVs rhs_fvs)
323 ReEntrant
324 srt
325 bndrs body
326
327 mkTopStgRhs dflags this_mod _ _ _ _ (StgConApp con args)
328 | not (isDllConApp dflags this_mod con args) -- Dynamic StgConApps are updatable
329 = StgRhsCon noCCS con args
330
331 mkTopStgRhs _ _ rhs_fvs srt bndr binder_info rhs
332 = StgRhsClosure noCCS binder_info
333 (getFVs rhs_fvs)
334 (getUpdateFlag bndr)
335 srt
336 [] rhs
337
338 getUpdateFlag :: Id -> UpdateFlag
339 getUpdateFlag bndr
340 = if isSingleUsed (idDemandInfo bndr)
341 then SingleEntry else Updatable
342
343 -- ---------------------------------------------------------------------------
344 -- Expressions
345 -- ---------------------------------------------------------------------------
346
347 coreToStgExpr
348 :: CoreExpr
349 -> LneM (StgExpr, -- Decorated STG expr
350 FreeVarsInfo, -- Its free vars (NB free, not live)
351 EscVarsSet) -- Its escapees, a subset of its free vars;
352 -- also a subset of the domain of the envt
353 -- because we are only interested in the escapees
354 -- for vars which might be turned into
355 -- let-no-escaped ones.
356
357 -- The second and third components can be derived in a simple bottom up pass, not
358 -- dependent on any decisions about which variables will be let-no-escaped or
359 -- not. The first component, that is, the decorated expression, may then depend
360 -- on these components, but it in turn is not scrutinised as the basis for any
361 -- decisions. Hence no black holes.
362
363 -- No LitInteger's should be left by the time this is called. CorePrep
364 -- should have converted them all to a real core representation.
365 coreToStgExpr (Lit (LitInteger {})) = panic "coreToStgExpr: LitInteger"
366 coreToStgExpr (Lit l) = return (StgLit l, emptyFVInfo, emptyVarSet)
367 coreToStgExpr (Var v) = coreToStgApp Nothing v []
368 coreToStgExpr (Coercion _) = coreToStgApp Nothing coercionTokenId []
369
370 coreToStgExpr expr@(App _ _)
371 = coreToStgApp Nothing f args
372 where
373 (f, args) = myCollectArgs expr
374
375 coreToStgExpr expr@(Lam _ _)
376 = let
377 (args, body) = myCollectBinders expr
378 args' = filterStgBinders args
379 in
380 extendVarEnvLne [ (a, LambdaBound) | a <- args' ] $ do
381 (body, body_fvs, body_escs) <- coreToStgExpr body
382 let
383 fvs = args' `minusFVBinders` body_fvs
384 escs = body_escs `delVarSetList` args'
385 result_expr | null args' = body
386 | otherwise = StgLam args' body
387
388 return (result_expr, fvs, escs)
389
390 coreToStgExpr (Tick (HpcTick m n) expr)
391 = do (expr2, fvs, escs) <- coreToStgExpr expr
392 return (StgTick m n expr2, fvs, escs)
393
394 coreToStgExpr (Tick (ProfNote cc tick push) expr)
395 = do (expr2, fvs, escs) <- coreToStgExpr expr
396 return (StgSCC cc tick push expr2, fvs, escs)
397
398 coreToStgExpr (Tick Breakpoint{} _expr)
399 = panic "coreToStgExpr: breakpoint should not happen"
400
401 coreToStgExpr (Cast expr _)
402 = coreToStgExpr expr
403
404 -- Cases require a little more real work.
405
406 coreToStgExpr (Case scrut _ _ [])
407 = coreToStgExpr scrut
408 -- See Note [Empty case alternatives] in CoreSyn If the case
409 -- alternatives are empty, the scrutinee must diverge or raise an
410 -- exception, so we can just dive into it.
411 --
412 -- Of course this may seg-fault if the scrutinee *does* return. A
413 -- belt-and-braces approach would be to move this case into the
414 -- code generator, and put a return point anyway that calls a
415 -- runtime system error function.
416
417
418 coreToStgExpr (Case scrut bndr _ alts) = do
419 (alts2, alts_fvs, alts_escs)
420 <- extendVarEnvLne [(bndr, LambdaBound)] $ do
421 (alts2, fvs_s, escs_s) <- mapAndUnzip3M vars_alt alts
422 return ( alts2,
423 unionFVInfos fvs_s,
424 unionVarSets escs_s )
425 let
426 -- Determine whether the default binder is dead or not
427 -- This helps the code generator to avoid generating an assignment
428 -- for the case binder (is extremely rare cases) ToDo: remove.
429 bndr' | bndr `elementOfFVInfo` alts_fvs = bndr
430 | otherwise = bndr `setIdOccInfo` IAmDead
431
432 -- Don't consider the default binder as being 'live in alts',
433 -- since this is from the point of view of the case expr, where
434 -- the default binder is not free.
435 alts_fvs_wo_bndr = bndr `minusFVBinder` alts_fvs
436 alts_escs_wo_bndr = alts_escs `delVarSet` bndr
437
438 alts_lv_info <- freeVarsToLiveVars alts_fvs_wo_bndr
439
440 -- We tell the scrutinee that everything
441 -- live in the alts is live in it, too.
442 (scrut2, scrut_fvs, _scrut_escs, scrut_lv_info)
443 <- setVarsLiveInCont alts_lv_info $ do
444 (scrut2, scrut_fvs, scrut_escs) <- coreToStgExpr scrut
445 scrut_lv_info <- freeVarsToLiveVars scrut_fvs
446 return (scrut2, scrut_fvs, scrut_escs, scrut_lv_info)
447
448 return (
449 StgCase scrut2 (getLiveVars scrut_lv_info)
450 (getLiveVars alts_lv_info)
451 bndr'
452 (mkSRT alts_lv_info)
453 (mkStgAltType bndr alts)
454 alts2,
455 scrut_fvs `unionFVInfo` alts_fvs_wo_bndr,
456 alts_escs_wo_bndr `unionVarSet` getFVSet scrut_fvs
457 -- You might think we should have scrut_escs, not
458 -- (getFVSet scrut_fvs), but actually we can't call, and
459 -- then return from, a let-no-escape thing.
460 )
461 where
462 vars_alt (con, binders, rhs)
463 | DataAlt c <- con, c == unboxedUnitDataCon
464 = -- This case is a bit smelly.
465 -- See Note [Nullary unboxed tuple] in Type.lhs
466 -- where a nullary tuple is mapped to (State# World#)
467 ASSERT( null binders )
468 do { (rhs2, rhs_fvs, rhs_escs) <- coreToStgExpr rhs
469 ; return ((DEFAULT, [], [], rhs2), rhs_fvs, rhs_escs) }
470 | otherwise
471 = let -- Remove type variables
472 binders' = filterStgBinders binders
473 in
474 extendVarEnvLne [(b, LambdaBound) | b <- binders'] $ do
475 (rhs2, rhs_fvs, rhs_escs) <- coreToStgExpr rhs
476 let
477 -- Records whether each param is used in the RHS
478 good_use_mask = [ b `elementOfFVInfo` rhs_fvs | b <- binders' ]
479
480 return ( (con, binders', good_use_mask, rhs2),
481 binders' `minusFVBinders` rhs_fvs,
482 rhs_escs `delVarSetList` binders' )
483 -- ToDo: remove the delVarSet;
484 -- since escs won't include any of these binders
485
486 -- Lets not only take quite a bit of work, but this is where we convert
487 -- then to let-no-escapes, if we wish.
488 -- (Meanwhile, we don't expect to see let-no-escapes...)
489
490
491 coreToStgExpr (Let bind body) = do
492 (new_let, fvs, escs, _)
493 <- mfix (\ ~(_, _, _, no_binder_escapes) ->
494 coreToStgLet no_binder_escapes bind body
495 )
496
497 return (new_let, fvs, escs)
498
499 coreToStgExpr e = pprPanic "coreToStgExpr" (ppr e)
500
501 mkStgAltType :: Id -> [CoreAlt] -> AltType
502 mkStgAltType bndr alts = case repType (idType bndr) of
503 UnaryRep rep_ty -> case tyConAppTyCon_maybe rep_ty of
504 Just tc | isUnLiftedTyCon tc -> PrimAlt tc
505 | isAbstractTyCon tc -> look_for_better_tycon
506 | isAlgTyCon tc -> AlgAlt tc
507 | otherwise -> ASSERT2( _is_poly_alt_tycon tc, ppr tc )
508 PolyAlt
509 Nothing -> PolyAlt
510 UbxTupleRep rep_tys -> UbxTupAlt (length rep_tys)
511 -- NB Nullary unboxed tuples have UnaryRep, and generate a PrimAlt
512 where
513 _is_poly_alt_tycon tc
514 = isFunTyCon tc
515 || isPrimTyCon tc -- "Any" is lifted but primitive
516 || isFamilyTyCon tc -- Type family; e.g. Any, or arising from strict
517 -- function application where argument has a
518 -- type-family type
519
520 -- Sometimes, the TyCon is a AbstractTyCon which may not have any
521 -- constructors inside it. Then we may get a better TyCon by
522 -- grabbing the one from a constructor alternative
523 -- if one exists.
524 look_for_better_tycon
525 | ((DataAlt con, _, _) : _) <- data_alts =
526 AlgAlt (dataConTyCon con)
527 | otherwise =
528 ASSERT(null data_alts)
529 PolyAlt
530 where
531 (data_alts, _deflt) = findDefault alts
532
533 -- ---------------------------------------------------------------------------
534 -- Applications
535 -- ---------------------------------------------------------------------------
536
537 coreToStgApp
538 :: Maybe UpdateFlag -- Just upd <=> this application is
539 -- the rhs of a thunk binding
540 -- x = [...] \upd [] -> the_app
541 -- with specified update flag
542 -> Id -- Function
543 -> [CoreArg] -- Arguments
544 -> LneM (StgExpr, FreeVarsInfo, EscVarsSet)
545
546
547 coreToStgApp _ f args = do
548 (args', args_fvs) <- coreToStgArgs args
549 how_bound <- lookupVarLne f
550
551 let
552 n_val_args = valArgCount args
553 not_letrec_bound = not (isLetBound how_bound)
554 fun_fvs = singletonFVInfo f how_bound fun_occ
555 -- e.g. (f :: a -> int) (x :: a)
556 -- Here the free variables are "f", "x" AND the type variable "a"
557 -- coreToStgArgs will deal with the arguments recursively
558
559 -- Mostly, the arity info of a function is in the fn's IdInfo
560 -- But new bindings introduced by CoreSat may not have no
561 -- arity info; it would do us no good anyway. For example:
562 -- let f = \ab -> e in f
563 -- No point in having correct arity info for f!
564 -- Hence the hasArity stuff below.
565 -- NB: f_arity is only consulted for LetBound things
566 f_arity = stgArity f how_bound
567 saturated = f_arity <= n_val_args
568
569 fun_occ
570 | not_letrec_bound = noBinderInfo -- Uninteresting variable
571 | f_arity > 0 && saturated = stgSatOcc -- Saturated or over-saturated function call
572 | otherwise = stgUnsatOcc -- Unsaturated function or thunk
573
574 fun_escs
575 | not_letrec_bound = emptyVarSet -- Only letrec-bound escapees are interesting
576 | f_arity == n_val_args = emptyVarSet -- A function *or thunk* with an exactly
577 -- saturated call doesn't escape
578 -- (let-no-escape applies to 'thunks' too)
579
580 | otherwise = unitVarSet f -- Inexact application; it does escape
581
582 -- At the moment of the call:
583
584 -- either the function is *not* let-no-escaped, in which case
585 -- nothing is live except live_in_cont
586 -- or the function *is* let-no-escaped in which case the
587 -- variables it uses are live, but still the function
588 -- itself is not. PS. In this case, the function's
589 -- live vars should already include those of the
590 -- continuation, but it does no harm to just union the
591 -- two regardless.
592
593 res_ty = exprType (mkApps (Var f) args)
594 app = case idDetails f of
595 DataConWorkId dc | saturated -> StgConApp dc args'
596
597 -- Some primitive operator that might be implemented as a library call.
598 PrimOpId op -> ASSERT( saturated )
599 StgOpApp (StgPrimOp op) args' res_ty
600
601 -- A call to some primitive Cmm function.
602 FCallId (CCall (CCallSpec (StaticTarget lbl (Just pkgId) True) PrimCallConv _))
603 -> ASSERT( saturated )
604 StgOpApp (StgPrimCallOp (PrimCall lbl pkgId)) args' res_ty
605
606 -- A regular foreign call.
607 FCallId call -> ASSERT( saturated )
608 StgOpApp (StgFCallOp call (idUnique f)) args' res_ty
609
610 TickBoxOpId {} -> pprPanic "coreToStg TickBox" $ ppr (f,args')
611 _other -> StgApp f args'
612 fvs = fun_fvs `unionFVInfo` args_fvs
613 vars = fun_escs `unionVarSet` (getFVSet args_fvs)
614 -- All the free vars of the args are disqualified
615 -- from being let-no-escaped.
616
617 -- Forcing these fixes a leak in the code generator, noticed while
618 -- profiling for trac #4367
619 app `seq` fvs `seq` seqVarSet vars `seq` return (
620 app,
621 fvs,
622 vars
623 )
624
625
626
627 -- ---------------------------------------------------------------------------
628 -- Argument lists
629 -- This is the guy that turns applications into A-normal form
630 -- ---------------------------------------------------------------------------
631
632 coreToStgArgs :: [CoreArg] -> LneM ([StgArg], FreeVarsInfo)
633 coreToStgArgs []
634 = return ([], emptyFVInfo)
635
636 coreToStgArgs (Type _ : args) = do -- Type argument
637 (args', fvs) <- coreToStgArgs args
638 return (args', fvs)
639
640 coreToStgArgs (Coercion _ : args) -- Coercion argument; replace with place holder
641 = do { (args', fvs) <- coreToStgArgs args
642 ; return (StgVarArg coercionTokenId : args', fvs) }
643
644 coreToStgArgs (arg : args) = do -- Non-type argument
645 (stg_args, args_fvs) <- coreToStgArgs args
646 (arg', arg_fvs, _escs) <- coreToStgExpr arg
647 let
648 fvs = args_fvs `unionFVInfo` arg_fvs
649 stg_arg = case arg' of
650 StgApp v [] -> StgVarArg v
651 StgConApp con [] -> StgVarArg (dataConWorkId con)
652 StgLit lit -> StgLitArg lit
653 _ -> pprPanic "coreToStgArgs" (ppr arg)
654
655 -- WARNING: what if we have an argument like (v `cast` co)
656 -- where 'co' changes the representation type?
657 -- (This really only happens if co is unsafe.)
658 -- Then all the getArgAmode stuff in CgBindery will set the
659 -- cg_rep of the CgIdInfo based on the type of v, rather
660 -- than the type of 'co'.
661 -- This matters particularly when the function is a primop
662 -- or foreign call.
663 -- Wanted: a better solution than this hacky warning
664 let
665 arg_ty = exprType arg
666 stg_arg_ty = stgArgType stg_arg
667 bad_args = (isUnLiftedType arg_ty && not (isUnLiftedType stg_arg_ty))
668 || (map typePrimRep (flattenRepType (repType arg_ty))
669 /= map typePrimRep (flattenRepType (repType stg_arg_ty)))
670 -- In GHCi we coerce an argument of type BCO# (unlifted) to HValue (lifted),
671 -- and pass it to a function expecting an HValue (arg_ty). This is ok because
672 -- we can treat an unlifted value as lifted. But the other way round
673 -- we complain.
674 -- We also want to check if a pointer is cast to a non-ptr etc
675
676 WARN( bad_args, ptext (sLit "Dangerous-looking argument. Probable cause: bad unsafeCoerce#") $$ ppr arg )
677 return (stg_arg : stg_args, fvs)
678
679
680 -- ---------------------------------------------------------------------------
681 -- The magic for lets:
682 -- ---------------------------------------------------------------------------
683
684 coreToStgLet
685 :: Bool -- True <=> yes, we are let-no-escaping this let
686 -> CoreBind -- bindings
687 -> CoreExpr -- body
688 -> LneM (StgExpr, -- new let
689 FreeVarsInfo, -- variables free in the whole let
690 EscVarsSet, -- variables that escape from the whole let
691 Bool) -- True <=> none of the binders in the bindings
692 -- is among the escaping vars
693
694 coreToStgLet let_no_escape bind body = do
695 (bind2, bind_fvs, bind_escs, bind_lvs,
696 body2, body_fvs, body_escs, body_lvs)
697 <- mfix $ \ ~(_, _, _, _, _, rec_body_fvs, _, _) -> do
698
699 -- Do the bindings, setting live_in_cont to empty if
700 -- we ain't in a let-no-escape world
701 live_in_cont <- getVarsLiveInCont
702 ( bind2, bind_fvs, bind_escs, bind_lv_info, env_ext)
703 <- setVarsLiveInCont (if let_no_escape
704 then live_in_cont
705 else emptyLiveInfo)
706 (vars_bind rec_body_fvs bind)
707
708 -- Do the body
709 extendVarEnvLne env_ext $ do
710 (body2, body_fvs, body_escs) <- coreToStgExpr body
711 body_lv_info <- freeVarsToLiveVars body_fvs
712
713 return (bind2, bind_fvs, bind_escs, getLiveVars bind_lv_info,
714 body2, body_fvs, body_escs, getLiveVars body_lv_info)
715
716
717 -- Compute the new let-expression
718 let
719 new_let | let_no_escape = StgLetNoEscape live_in_whole_let bind_lvs bind2 body2
720 | otherwise = StgLet bind2 body2
721
722 free_in_whole_let
723 = binders `minusFVBinders` (bind_fvs `unionFVInfo` body_fvs)
724
725 live_in_whole_let
726 = bind_lvs `unionVarSet` (body_lvs `delVarSetList` binders)
727
728 real_bind_escs = if let_no_escape then
729 bind_escs
730 else
731 getFVSet bind_fvs
732 -- Everything escapes which is free in the bindings
733
734 let_escs = (real_bind_escs `unionVarSet` body_escs) `delVarSetList` binders
735
736 all_escs = bind_escs `unionVarSet` body_escs -- Still includes binders of
737 -- this let(rec)
738
739 no_binder_escapes = isEmptyVarSet (set_of_binders `intersectVarSet` all_escs)
740
741 -- Debugging code as requested by Andrew Kennedy
742 checked_no_binder_escapes
743 | debugIsOn && not no_binder_escapes && any is_join_var binders
744 = pprTrace "Interesting! A join var that isn't let-no-escaped" (ppr binders)
745 False
746 | otherwise = no_binder_escapes
747
748 -- Mustn't depend on the passed-in let_no_escape flag, since
749 -- no_binder_escapes is used by the caller to derive the flag!
750 return (
751 new_let,
752 free_in_whole_let,
753 let_escs,
754 checked_no_binder_escapes
755 )
756 where
757 set_of_binders = mkVarSet binders
758 binders = bindersOf bind
759
760 mk_binding bind_lv_info binder rhs
761 = (binder, LetBound (NestedLet live_vars) (manifestArity rhs))
762 where
763 live_vars | let_no_escape = addLiveVar bind_lv_info binder
764 | otherwise = unitLiveVar binder
765 -- c.f. the invariant on NestedLet
766
767 vars_bind :: FreeVarsInfo -- Free var info for body of binding
768 -> CoreBind
769 -> LneM (StgBinding,
770 FreeVarsInfo,
771 EscVarsSet, -- free vars; escapee vars
772 LiveInfo, -- Vars and CAFs live in binding
773 [(Id, HowBound)]) -- extension to environment
774
775
776 vars_bind body_fvs (NonRec binder rhs) = do
777 (rhs2, bind_fvs, bind_lv_info, escs) <- coreToStgRhs body_fvs [] (binder,rhs)
778 let
779 env_ext_item = mk_binding bind_lv_info binder rhs
780
781 return (StgNonRec binder rhs2,
782 bind_fvs, escs, bind_lv_info, [env_ext_item])
783
784
785 vars_bind body_fvs (Rec pairs)
786 = mfix $ \ ~(_, rec_rhs_fvs, _, bind_lv_info, _) ->
787 let
788 rec_scope_fvs = unionFVInfo body_fvs rec_rhs_fvs
789 binders = map fst pairs
790 env_ext = [ mk_binding bind_lv_info b rhs
791 | (b,rhs) <- pairs ]
792 in
793 extendVarEnvLne env_ext $ do
794 (rhss2, fvss, lv_infos, escss)
795 <- mapAndUnzip4M (coreToStgRhs rec_scope_fvs binders) pairs
796 let
797 bind_fvs = unionFVInfos fvss
798 bind_lv_info = foldr unionLiveInfo emptyLiveInfo lv_infos
799 escs = unionVarSets escss
800
801 return (StgRec (binders `zip` rhss2),
802 bind_fvs, escs, bind_lv_info, env_ext)
803
804
805 is_join_var :: Id -> Bool
806 -- A hack (used only for compiler debuggging) to tell if
807 -- a variable started life as a join point ($j)
808 is_join_var j = occNameString (getOccName j) == "$j"
809
810 coreToStgRhs :: FreeVarsInfo -- Free var info for the scope of the binding
811 -> [Id]
812 -> (Id,CoreExpr)
813 -> LneM (StgRhs, FreeVarsInfo, LiveInfo, EscVarsSet)
814
815 coreToStgRhs scope_fv_info binders (bndr, rhs) = do
816 (new_rhs, rhs_fvs, rhs_escs) <- coreToStgExpr rhs
817 lv_info <- freeVarsToLiveVars (binders `minusFVBinders` rhs_fvs)
818 return (mkStgRhs rhs_fvs (mkSRT lv_info) bndr bndr_info new_rhs,
819 rhs_fvs, lv_info, rhs_escs)
820 where
821 bndr_info = lookupFVInfo scope_fv_info bndr
822
823 mkStgRhs :: FreeVarsInfo -> SRT -> Id -> StgBinderInfo -> StgExpr -> StgRhs
824
825 mkStgRhs _ _ _ _ (StgConApp con args) = StgRhsCon noCCS con args
826
827 mkStgRhs rhs_fvs srt _ binder_info (StgLam bndrs body)
828 = StgRhsClosure noCCS binder_info
829 (getFVs rhs_fvs)
830 ReEntrant
831 srt bndrs body
832
833 mkStgRhs rhs_fvs srt bndr binder_info rhs
834 = StgRhsClosure noCCS binder_info
835 (getFVs rhs_fvs)
836 upd_flag srt [] rhs
837 where
838 upd_flag = getUpdateFlag bndr
839 {-
840 SDM: disabled. Eval/Apply can't handle functions with arity zero very
841 well; and making these into simple non-updatable thunks breaks other
842 assumptions (namely that they will be entered only once).
843
844 upd_flag | isPAP env rhs = ReEntrant
845 | otherwise = Updatable
846
847 -- Detect thunks which will reduce immediately to PAPs, and make them
848 -- non-updatable. This has several advantages:
849 --
850 -- - the non-updatable thunk behaves exactly like the PAP,
851 --
852 -- - the thunk is more efficient to enter, because it is
853 -- specialised to the task.
854 --
855 -- - we save one update frame, one stg_update_PAP, one update
856 -- and lots of PAP_enters.
857 --
858 -- - in the case where the thunk is top-level, we save building
859 -- a black hole and futhermore the thunk isn't considered to
860 -- be a CAF any more, so it doesn't appear in any SRTs.
861 --
862 -- We do it here, because the arity information is accurate, and we need
863 -- to do it before the SRT pass to save the SRT entries associated with
864 -- any top-level PAPs.
865
866 isPAP env (StgApp f args) = listLengthCmp args arity == LT -- idArity f > length args
867 where
868 arity = stgArity f (lookupBinding env f)
869 isPAP env _ = False
870
871 -}
872
873 {- ToDo:
874 upd = if isOnceDem dem
875 then (if isNotTop toplev
876 then SingleEntry -- HA! Paydirt for "dem"
877 else
878 (if debugIsOn then trace "WARNING: SE CAFs unsupported, forcing UPD instead" else id) $
879 Updatable)
880 else Updatable
881 -- For now we forbid SingleEntry CAFs; they tickle the
882 -- ASSERT in rts/Storage.c line 215 at newCAF() re mut_link,
883 -- and I don't understand why. There's only one SE_CAF (well,
884 -- only one that tickled a great gaping bug in an earlier attempt
885 -- at ClosureInfo.getEntryConvention) in the whole of nofib,
886 -- specifically Main.lvl6 in spectral/cryptarithm2.
887 -- So no great loss. KSW 2000-07.
888 -}
889
890 -- ---------------------------------------------------------------------------
891 -- A little monad for this let-no-escaping pass
892 -- ---------------------------------------------------------------------------
893
894 -- There's a lot of stuff to pass around, so we use this LneM monad to
895 -- help. All the stuff here is only passed *down*.
896
897 newtype LneM a = LneM
898 { unLneM :: IdEnv HowBound
899 -> LiveInfo -- Vars and CAFs live in continuation
900 -> a
901 }
902
903 type LiveInfo = (StgLiveVars, -- Dynamic live variables;
904 -- i.e. ones with a nested (non-top-level) binding
905 CafSet) -- Static live variables;
906 -- i.e. top-level variables that are CAFs or refer to them
907
908 type EscVarsSet = IdSet
909 type CafSet = IdSet
910
911 data HowBound
912 = ImportBound -- Used only as a response to lookupBinding; never
913 -- exists in the range of the (IdEnv HowBound)
914
915 | LetBound -- A let(rec) in this module
916 LetInfo -- Whether top level or nested
917 Arity -- Its arity (local Ids don't have arity info at this point)
918
919 | LambdaBound -- Used for both lambda and case
920
921 data LetInfo
922 = TopLet -- top level things
923 | NestedLet LiveInfo -- For nested things, what is live if this
924 -- thing is live? Invariant: the binder
925 -- itself is always a member of
926 -- the dynamic set of its own LiveInfo
927
928 isLetBound :: HowBound -> Bool
929 isLetBound (LetBound _ _) = True
930 isLetBound _ = False
931
932 topLevelBound :: HowBound -> Bool
933 topLevelBound ImportBound = True
934 topLevelBound (LetBound TopLet _) = True
935 topLevelBound _ = False
936
937 -- For a let(rec)-bound variable, x, we record LiveInfo, the set of
938 -- variables that are live if x is live. This LiveInfo comprises
939 -- (a) dynamic live variables (ones with a non-top-level binding)
940 -- (b) static live variabes (CAFs or things that refer to CAFs)
941 --
942 -- For "normal" variables (a) is just x alone. If x is a let-no-escaped
943 -- variable then x is represented by a code pointer and a stack pointer
944 -- (well, one for each stack). So all of the variables needed in the
945 -- execution of x are live if x is, and are therefore recorded in the
946 -- LetBound constructor; x itself *is* included.
947 --
948 -- The set of dynamic live variables is guaranteed ot have no further
949 -- let-no-escaped variables in it.
950
951 emptyLiveInfo :: LiveInfo
952 emptyLiveInfo = (emptyVarSet,emptyVarSet)
953
954 unitLiveVar :: Id -> LiveInfo
955 unitLiveVar lv = (unitVarSet lv, emptyVarSet)
956
957 unitLiveCaf :: Id -> LiveInfo
958 unitLiveCaf caf = (emptyVarSet, unitVarSet caf)
959
960 addLiveVar :: LiveInfo -> Id -> LiveInfo
961 addLiveVar (lvs, cafs) id = (lvs `extendVarSet` id, cafs)
962
963 unionLiveInfo :: LiveInfo -> LiveInfo -> LiveInfo
964 unionLiveInfo (lv1,caf1) (lv2,caf2) = (lv1 `unionVarSet` lv2, caf1 `unionVarSet` caf2)
965
966 mkSRT :: LiveInfo -> SRT
967 mkSRT (_, cafs) = SRTEntries cafs
968
969 getLiveVars :: LiveInfo -> StgLiveVars
970 getLiveVars (lvs, _) = lvs
971
972 -- The std monad functions:
973
974 initLne :: IdEnv HowBound -> LneM a -> a
975 initLne env m = unLneM m env emptyLiveInfo
976
977
978
979 {-# INLINE thenLne #-}
980 {-# INLINE returnLne #-}
981
982 returnLne :: a -> LneM a
983 returnLne e = LneM $ \_ _ -> e
984
985 thenLne :: LneM a -> (a -> LneM b) -> LneM b
986 thenLne m k = LneM $ \env lvs_cont
987 -> unLneM (k (unLneM m env lvs_cont)) env lvs_cont
988
989 instance Functor LneM where
990 fmap = liftM
991
992 instance Applicative LneM where
993 pure = return
994 (<*>) = ap
995
996 instance Monad LneM where
997 return = returnLne
998 (>>=) = thenLne
999
1000 instance MonadFix LneM where
1001 mfix expr = LneM $ \env lvs_cont ->
1002 let result = unLneM (expr result) env lvs_cont
1003 in result
1004
1005 -- Functions specific to this monad:
1006
1007 getVarsLiveInCont :: LneM LiveInfo
1008 getVarsLiveInCont = LneM $ \_env lvs_cont -> lvs_cont
1009
1010 setVarsLiveInCont :: LiveInfo -> LneM a -> LneM a
1011 setVarsLiveInCont new_lvs_cont expr
1012 = LneM $ \env _lvs_cont
1013 -> unLneM expr env new_lvs_cont
1014
1015 extendVarEnvLne :: [(Id, HowBound)] -> LneM a -> LneM a
1016 extendVarEnvLne ids_w_howbound expr
1017 = LneM $ \env lvs_cont
1018 -> unLneM expr (extendVarEnvList env ids_w_howbound) lvs_cont
1019
1020 lookupVarLne :: Id -> LneM HowBound
1021 lookupVarLne v = LneM $ \env _lvs_cont -> lookupBinding env v
1022
1023 lookupBinding :: IdEnv HowBound -> Id -> HowBound
1024 lookupBinding env v = case lookupVarEnv env v of
1025 Just xx -> xx
1026 Nothing -> ASSERT2( isGlobalId v, ppr v ) ImportBound
1027
1028
1029 -- The result of lookupLiveVarsForSet, a set of live variables, is
1030 -- only ever tacked onto a decorated expression. It is never used as
1031 -- the basis of a control decision, which might give a black hole.
1032
1033 freeVarsToLiveVars :: FreeVarsInfo -> LneM LiveInfo
1034 freeVarsToLiveVars fvs = LneM freeVarsToLiveVars'
1035 where
1036 freeVarsToLiveVars' _env live_in_cont = live_info
1037 where
1038 live_info = foldr unionLiveInfo live_in_cont lvs_from_fvs
1039 lvs_from_fvs = map do_one (allFreeIds fvs)
1040
1041 do_one (v, how_bound)
1042 = case how_bound of
1043 ImportBound -> unitLiveCaf v -- Only CAF imports are
1044 -- recorded in fvs
1045 LetBound TopLet _
1046 | mayHaveCafRefs (idCafInfo v) -> unitLiveCaf v
1047 | otherwise -> emptyLiveInfo
1048
1049 LetBound (NestedLet lvs) _ -> lvs -- lvs already contains v
1050 -- (see the invariant on NestedLet)
1051
1052 _lambda_or_case_binding -> unitLiveVar v -- Bound by lambda or case
1053
1054
1055 -- ---------------------------------------------------------------------------
1056 -- Free variable information
1057 -- ---------------------------------------------------------------------------
1058
1059 type FreeVarsInfo = VarEnv (Var, HowBound, StgBinderInfo)
1060 -- The Var is so we can gather up the free variables
1061 -- as a set.
1062 --
1063 -- The HowBound info just saves repeated lookups;
1064 -- we look up just once when we encounter the occurrence.
1065 -- INVARIANT: Any ImportBound Ids are HaveCafRef Ids
1066 -- Imported Ids without CAF refs are simply
1067 -- not put in the FreeVarsInfo for an expression.
1068 -- See singletonFVInfo and freeVarsToLiveVars
1069 --
1070 -- StgBinderInfo records how it occurs; notably, we
1071 -- are interested in whether it only occurs in saturated
1072 -- applications, because then we don't need to build a
1073 -- curried version.
1074 -- If f is mapped to noBinderInfo, that means
1075 -- that f *is* mentioned (else it wouldn't be in the
1076 -- IdEnv at all), but perhaps in an unsaturated applications.
1077 --
1078 -- All case/lambda-bound things are also mapped to
1079 -- noBinderInfo, since we aren't interested in their
1080 -- occurrence info.
1081 --
1082 -- For ILX we track free var info for type variables too;
1083 -- hence VarEnv not IdEnv
1084
1085 emptyFVInfo :: FreeVarsInfo
1086 emptyFVInfo = emptyVarEnv
1087
1088 singletonFVInfo :: Id -> HowBound -> StgBinderInfo -> FreeVarsInfo
1089 -- Don't record non-CAF imports at all, to keep free-var sets small
1090 singletonFVInfo id ImportBound info
1091 | mayHaveCafRefs (idCafInfo id) = unitVarEnv id (id, ImportBound, info)
1092 | otherwise = emptyVarEnv
1093 singletonFVInfo id how_bound info = unitVarEnv id (id, how_bound, info)
1094
1095 unionFVInfo :: FreeVarsInfo -> FreeVarsInfo -> FreeVarsInfo
1096 unionFVInfo fv1 fv2 = plusVarEnv_C plusFVInfo fv1 fv2
1097
1098 unionFVInfos :: [FreeVarsInfo] -> FreeVarsInfo
1099 unionFVInfos fvs = foldr unionFVInfo emptyFVInfo fvs
1100
1101 minusFVBinders :: [Id] -> FreeVarsInfo -> FreeVarsInfo
1102 minusFVBinders vs fv = foldr minusFVBinder fv vs
1103
1104 minusFVBinder :: Id -> FreeVarsInfo -> FreeVarsInfo
1105 minusFVBinder v fv = fv `delVarEnv` v
1106 -- When removing a binder, remember to add its type variables
1107 -- c.f. CoreFVs.delBinderFV
1108
1109 elementOfFVInfo :: Id -> FreeVarsInfo -> Bool
1110 elementOfFVInfo id fvs = isJust (lookupVarEnv fvs id)
1111
1112 lookupFVInfo :: FreeVarsInfo -> Id -> StgBinderInfo
1113 -- Find how the given Id is used.
1114 -- Externally visible things may be used any old how
1115 lookupFVInfo fvs id
1116 | isExternalName (idName id) = noBinderInfo
1117 | otherwise = case lookupVarEnv fvs id of
1118 Nothing -> noBinderInfo
1119 Just (_,_,info) -> info
1120
1121 allFreeIds :: FreeVarsInfo -> [(Id,HowBound)] -- Both top level and non-top-level Ids
1122 allFreeIds fvs = ASSERT( all (isId . fst) ids ) ids
1123 where
1124 ids = [(id,how_bound) | (id,how_bound,_) <- varEnvElts fvs]
1125
1126 -- Non-top-level things only, both type variables and ids
1127 getFVs :: FreeVarsInfo -> [Var]
1128 getFVs fvs = [id | (id, how_bound, _) <- varEnvElts fvs,
1129 not (topLevelBound how_bound) ]
1130
1131 getFVSet :: FreeVarsInfo -> VarSet
1132 getFVSet fvs = mkVarSet (getFVs fvs)
1133
1134 plusFVInfo :: (Var, HowBound, StgBinderInfo)
1135 -> (Var, HowBound, StgBinderInfo)
1136 -> (Var, HowBound, StgBinderInfo)
1137 plusFVInfo (id1,hb1,info1) (id2,hb2,info2)
1138 = ASSERT(id1 == id2 && hb1 `check_eq_how_bound` hb2)
1139 (id1, hb1, combineStgBinderInfo info1 info2)
1140
1141 -- The HowBound info for a variable in the FVInfo should be consistent
1142 check_eq_how_bound :: HowBound -> HowBound -> Bool
1143 check_eq_how_bound ImportBound ImportBound = True
1144 check_eq_how_bound LambdaBound LambdaBound = True
1145 check_eq_how_bound (LetBound li1 ar1) (LetBound li2 ar2) = ar1 == ar2 && check_eq_li li1 li2
1146 check_eq_how_bound _ _ = False
1147
1148 check_eq_li :: LetInfo -> LetInfo -> Bool
1149 check_eq_li (NestedLet _) (NestedLet _) = True
1150 check_eq_li TopLet TopLet = True
1151 check_eq_li _ _ = False
1152
1153 -- Misc.
1154
1155 filterStgBinders :: [Var] -> [Var]
1156 filterStgBinders bndrs = filter isId bndrs
1157
1158 myCollectBinders :: Expr Var -> ([Var], Expr Var)
1159 myCollectBinders expr
1160 = go [] expr
1161 where
1162 go bs (Lam b e) = go (b:bs) e
1163 go bs e@(Tick t e')
1164 | tickishIsCode t = (reverse bs, e)
1165 | otherwise = go bs e'
1166 -- Ignore only non-code source annotations
1167 go bs (Cast e _) = go bs e
1168 go bs e = (reverse bs, e)
1169
1170 myCollectArgs :: CoreExpr -> (Id, [CoreArg])
1171 -- We assume that we only have variables
1172 -- in the function position by now
1173 myCollectArgs expr
1174 = go expr []
1175 where
1176 go (Var v) as = (v, as)
1177 go (App f a) as = go f (a:as)
1178 go (Tick _ _) _ = pprPanic "CoreToStg.myCollectArgs" (ppr expr)
1179 go (Cast e _) as = go e as
1180 go (Lam b e) as
1181 | isTyVar b = go e as -- Note [Collect args]
1182 go _ _ = pprPanic "CoreToStg.myCollectArgs" (ppr expr)
1183
1184 -- Note [Collect args]
1185 -- ~~~~~~~~~~~~~~~~~~~
1186 --
1187 -- This big-lambda case occurred following a rather obscure eta expansion.
1188 -- It all seems a bit yukky to me.
1189
1190 stgArity :: Id -> HowBound -> Arity
1191 stgArity _ (LetBound _ arity) = arity
1192 stgArity f ImportBound = idArity f
1193 stgArity _ LambdaBound = 0