0f81ab3027b129ef350cedaadc62bbf9686fefaf
[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 ( isUsedOnce )
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.hs).
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 text "Id arity:" <+> ppr id_arity,
314 text "STG arity:" <+> ppr stg_arity]
315
316 mkTopStgRhs :: DynFlags -> Module -> FreeVarsInfo
317 -> SRT -> Id -> StgBinderInfo -> StgExpr
318 -> StgRhs
319
320 mkTopStgRhs dflags this_mod = mkStgRhs' con_updateable
321 -- Dynamic StgConApps are updatable
322 where con_updateable con args = isDllConApp dflags this_mod con args
323
324 -- ---------------------------------------------------------------------------
325 -- Expressions
326 -- ---------------------------------------------------------------------------
327
328 coreToStgExpr
329 :: CoreExpr
330 -> LneM (StgExpr, -- Decorated STG expr
331 FreeVarsInfo, -- Its free vars (NB free, not live)
332 EscVarsSet) -- Its escapees, a subset of its free vars;
333 -- also a subset of the domain of the envt
334 -- because we are only interested in the escapees
335 -- for vars which might be turned into
336 -- let-no-escaped ones.
337
338 -- The second and third components can be derived in a simple bottom up pass, not
339 -- dependent on any decisions about which variables will be let-no-escaped or
340 -- not. The first component, that is, the decorated expression, may then depend
341 -- on these components, but it in turn is not scrutinised as the basis for any
342 -- decisions. Hence no black holes.
343
344 -- No LitInteger's should be left by the time this is called. CorePrep
345 -- should have converted them all to a real core representation.
346 coreToStgExpr (Lit (LitInteger {})) = panic "coreToStgExpr: LitInteger"
347 coreToStgExpr (Lit l) = return (StgLit l, emptyFVInfo, emptyVarSet)
348 coreToStgExpr (Var v) = coreToStgApp Nothing v [] []
349 coreToStgExpr (Coercion _) = coreToStgApp Nothing coercionTokenId [] []
350
351 coreToStgExpr expr@(App _ _)
352 = coreToStgApp Nothing f args ticks
353 where
354 (f, args, ticks) = myCollectArgs expr
355
356 coreToStgExpr expr@(Lam _ _)
357 = let
358 (args, body) = myCollectBinders expr
359 args' = filterStgBinders args
360 in
361 extendVarEnvLne [ (a, LambdaBound) | a <- args' ] $ do
362 (body, body_fvs, body_escs) <- coreToStgExpr body
363 let
364 fvs = args' `minusFVBinders` body_fvs
365 escs = body_escs `delVarSetList` args'
366 result_expr | null args' = body
367 | otherwise = StgLam args' body
368
369 return (result_expr, fvs, escs)
370
371 coreToStgExpr (Tick tick expr)
372 = do case tick of
373 HpcTick{} -> return ()
374 ProfNote{} -> return ()
375 SourceNote{} -> return ()
376 Breakpoint{} -> panic "coreToStgExpr: breakpoint should not happen"
377 (expr2, fvs, escs) <- coreToStgExpr expr
378 return (StgTick tick expr2, fvs, escs)
379
380 coreToStgExpr (Cast expr _)
381 = coreToStgExpr expr
382
383 -- Cases require a little more real work.
384
385 coreToStgExpr (Case scrut _ _ [])
386 = coreToStgExpr scrut
387 -- See Note [Empty case alternatives] in CoreSyn If the case
388 -- alternatives are empty, the scrutinee must diverge or raise an
389 -- exception, so we can just dive into it.
390 --
391 -- Of course this may seg-fault if the scrutinee *does* return. A
392 -- belt-and-braces approach would be to move this case into the
393 -- code generator, and put a return point anyway that calls a
394 -- runtime system error function.
395
396
397 coreToStgExpr (Case scrut bndr _ alts) = do
398 (alts2, alts_fvs, alts_escs)
399 <- extendVarEnvLne [(bndr, LambdaBound)] $ do
400 (alts2, fvs_s, escs_s) <- mapAndUnzip3M vars_alt alts
401 return ( alts2,
402 unionFVInfos fvs_s,
403 unionVarSets escs_s )
404 let
405 -- Determine whether the default binder is dead or not
406 -- This helps the code generator to avoid generating an assignment
407 -- for the case binder (is extremely rare cases) ToDo: remove.
408 bndr' | bndr `elementOfFVInfo` alts_fvs = bndr
409 | otherwise = bndr `setIdOccInfo` IAmDead
410
411 -- Don't consider the default binder as being 'live in alts',
412 -- since this is from the point of view of the case expr, where
413 -- the default binder is not free.
414 alts_fvs_wo_bndr = bndr `minusFVBinder` alts_fvs
415 alts_escs_wo_bndr = alts_escs `delVarSet` bndr
416
417 alts_lv_info <- freeVarsToLiveVars alts_fvs_wo_bndr
418
419 -- We tell the scrutinee that everything
420 -- live in the alts is live in it, too.
421 (scrut2, scrut_fvs, _scrut_escs, scrut_lv_info)
422 <- setVarsLiveInCont alts_lv_info $ do
423 (scrut2, scrut_fvs, scrut_escs) <- coreToStgExpr scrut
424 scrut_lv_info <- freeVarsToLiveVars scrut_fvs
425 return (scrut2, scrut_fvs, scrut_escs, scrut_lv_info)
426
427 return (
428 StgCase scrut2 (getLiveVars scrut_lv_info)
429 (getLiveVars alts_lv_info)
430 bndr'
431 (mkSRT alts_lv_info)
432 (mkStgAltType bndr alts)
433 alts2,
434 scrut_fvs `unionFVInfo` alts_fvs_wo_bndr,
435 alts_escs_wo_bndr `unionVarSet` getFVSet scrut_fvs
436 -- You might think we should have scrut_escs, not
437 -- (getFVSet scrut_fvs), but actually we can't call, and
438 -- then return from, a let-no-escape thing.
439 )
440 where
441 vars_alt (con, binders, rhs)
442 | DataAlt c <- con, c == unboxedUnitDataCon
443 = -- This case is a bit smelly.
444 -- See Note [Nullary unboxed tuple] in Type.hs
445 -- where a nullary tuple is mapped to (State# World#)
446 ASSERT( null binders )
447 do { (rhs2, rhs_fvs, rhs_escs) <- coreToStgExpr rhs
448 ; return ((DEFAULT, [], [], rhs2), rhs_fvs, rhs_escs) }
449 | otherwise
450 = let -- Remove type variables
451 binders' = filterStgBinders binders
452 in
453 extendVarEnvLne [(b, LambdaBound) | b <- binders'] $ do
454 (rhs2, rhs_fvs, rhs_escs) <- coreToStgExpr rhs
455 let
456 -- Records whether each param is used in the RHS
457 good_use_mask = [ b `elementOfFVInfo` rhs_fvs | b <- binders' ]
458
459 return ( (con, binders', good_use_mask, rhs2),
460 binders' `minusFVBinders` rhs_fvs,
461 rhs_escs `delVarSetList` binders' )
462 -- ToDo: remove the delVarSet;
463 -- since escs won't include any of these binders
464
465 -- Lets not only take quite a bit of work, but this is where we convert
466 -- then to let-no-escapes, if we wish.
467 -- (Meanwhile, we don't expect to see let-no-escapes...)
468
469
470 coreToStgExpr (Let bind body) = do
471 (new_let, fvs, escs, _)
472 <- mfix (\ ~(_, _, _, no_binder_escapes) ->
473 coreToStgLet no_binder_escapes bind body
474 )
475
476 return (new_let, fvs, escs)
477
478 coreToStgExpr e = pprPanic "coreToStgExpr" (ppr e)
479
480 mkStgAltType :: Id -> [CoreAlt] -> AltType
481 mkStgAltType bndr alts = case repType (idType bndr) of
482 UnaryRep rep_ty -> case tyConAppTyCon_maybe rep_ty of
483 Just tc | isUnliftedTyCon tc -> PrimAlt tc
484 | isAbstractTyCon tc -> look_for_better_tycon
485 | isAlgTyCon tc -> AlgAlt tc
486 | otherwise -> ASSERT2( _is_poly_alt_tycon tc, ppr tc )
487 PolyAlt
488 Nothing -> PolyAlt
489 UbxTupleRep rep_tys -> UbxTupAlt (length rep_tys)
490 -- NB Nullary unboxed tuples have UnaryRep, and generate a PrimAlt
491 where
492 _is_poly_alt_tycon tc
493 = isFunTyCon tc
494 || isPrimTyCon tc -- "Any" is lifted but primitive
495 || isFamilyTyCon tc -- Type family; e.g. Any, or arising from strict
496 -- function application where argument has a
497 -- type-family type
498
499 -- Sometimes, the TyCon is a AbstractTyCon which may not have any
500 -- constructors inside it. Then we may get a better TyCon by
501 -- grabbing the one from a constructor alternative
502 -- if one exists.
503 look_for_better_tycon
504 | ((DataAlt con, _, _) : _) <- data_alts =
505 AlgAlt (dataConTyCon con)
506 | otherwise =
507 ASSERT(null data_alts)
508 PolyAlt
509 where
510 (data_alts, _deflt) = findDefault alts
511
512 -- ---------------------------------------------------------------------------
513 -- Applications
514 -- ---------------------------------------------------------------------------
515
516 coreToStgApp
517 :: Maybe UpdateFlag -- Just upd <=> this application is
518 -- the rhs of a thunk binding
519 -- x = [...] \upd [] -> the_app
520 -- with specified update flag
521 -> Id -- Function
522 -> [CoreArg] -- Arguments
523 -> [Tickish Id] -- Debug ticks
524 -> LneM (StgExpr, FreeVarsInfo, EscVarsSet)
525
526
527 coreToStgApp _ f args ticks = do
528 (args', args_fvs, ticks') <- coreToStgArgs args
529 how_bound <- lookupVarLne f
530
531 let
532 n_val_args = valArgCount args
533 not_letrec_bound = not (isLetBound how_bound)
534 fun_fvs = singletonFVInfo f how_bound fun_occ
535 -- e.g. (f :: a -> int) (x :: a)
536 -- Here the free variables are "f", "x" AND the type variable "a"
537 -- coreToStgArgs will deal with the arguments recursively
538
539 -- Mostly, the arity info of a function is in the fn's IdInfo
540 -- But new bindings introduced by CoreSat may not have no
541 -- arity info; it would do us no good anyway. For example:
542 -- let f = \ab -> e in f
543 -- No point in having correct arity info for f!
544 -- Hence the hasArity stuff below.
545 -- NB: f_arity is only consulted for LetBound things
546 f_arity = stgArity f how_bound
547 saturated = f_arity <= n_val_args
548
549 fun_occ
550 | not_letrec_bound = noBinderInfo -- Uninteresting variable
551 | f_arity > 0 && saturated = stgSatOcc -- Saturated or over-saturated function call
552 | otherwise = stgUnsatOcc -- Unsaturated function or thunk
553
554 fun_escs
555 | not_letrec_bound = emptyVarSet -- Only letrec-bound escapees are interesting
556 | f_arity == n_val_args = emptyVarSet -- A function *or thunk* with an exactly
557 -- saturated call doesn't escape
558 -- (let-no-escape applies to 'thunks' too)
559
560 | otherwise = unitVarSet f -- Inexact application; it does escape
561
562 -- At the moment of the call:
563
564 -- either the function is *not* let-no-escaped, in which case
565 -- nothing is live except live_in_cont
566 -- or the function *is* let-no-escaped in which case the
567 -- variables it uses are live, but still the function
568 -- itself is not. PS. In this case, the function's
569 -- live vars should already include those of the
570 -- continuation, but it does no harm to just union the
571 -- two regardless.
572
573 res_ty = exprType (mkApps (Var f) args)
574 app = case idDetails f of
575 DataConWorkId dc | saturated -> StgConApp dc args'
576
577 -- Some primitive operator that might be implemented as a library call.
578 PrimOpId op -> ASSERT( saturated )
579 StgOpApp (StgPrimOp op) args' res_ty
580
581 -- A call to some primitive Cmm function.
582 FCallId (CCall (CCallSpec (StaticTarget _ lbl (Just pkgId) True)
583 PrimCallConv _))
584 -> ASSERT( saturated )
585 StgOpApp (StgPrimCallOp (PrimCall lbl pkgId)) args' res_ty
586
587 -- A regular foreign call.
588 FCallId call -> ASSERT( saturated )
589 StgOpApp (StgFCallOp call (idUnique f)) args' res_ty
590
591 TickBoxOpId {} -> pprPanic "coreToStg TickBox" $ ppr (f,args')
592 _other -> StgApp f args'
593 fvs = fun_fvs `unionFVInfo` args_fvs
594 vars = fun_escs `unionVarSet` (getFVSet args_fvs)
595 -- All the free vars of the args are disqualified
596 -- from being let-no-escaped.
597
598 tapp = foldr StgTick app (ticks ++ ticks')
599
600 -- Forcing these fixes a leak in the code generator, noticed while
601 -- profiling for trac #4367
602 app `seq` fvs `seq` seqVarSet vars `seq` return (
603 tapp,
604 fvs,
605 vars
606 )
607
608
609
610 -- ---------------------------------------------------------------------------
611 -- Argument lists
612 -- This is the guy that turns applications into A-normal form
613 -- ---------------------------------------------------------------------------
614
615 coreToStgArgs :: [CoreArg] -> LneM ([StgArg], FreeVarsInfo, [Tickish Id])
616 coreToStgArgs []
617 = return ([], emptyFVInfo, [])
618
619 coreToStgArgs (Type _ : args) = do -- Type argument
620 (args', fvs, ts) <- coreToStgArgs args
621 return (args', fvs, ts)
622
623 coreToStgArgs (Coercion _ : args) -- Coercion argument; replace with place holder
624 = do { (args', fvs, ts) <- coreToStgArgs args
625 ; return (StgVarArg coercionTokenId : args', fvs, ts) }
626
627 coreToStgArgs (Tick t e : args)
628 = ASSERT( not (tickishIsCode t) )
629 do { (args', fvs, ts) <- coreToStgArgs (e : args)
630 ; return (args', fvs, t:ts) }
631
632 coreToStgArgs (arg : args) = do -- Non-type argument
633 (stg_args, args_fvs, ticks) <- coreToStgArgs args
634 (arg', arg_fvs, _escs) <- coreToStgExpr arg
635 let
636 fvs = args_fvs `unionFVInfo` arg_fvs
637
638 (aticks, arg'') = stripStgTicksTop tickishFloatable arg'
639 stg_arg = case arg'' of
640 StgApp v [] -> StgVarArg v
641 StgConApp con [] -> StgVarArg (dataConWorkId con)
642 StgLit lit -> StgLitArg lit
643 _ -> pprPanic "coreToStgArgs" (ppr arg)
644
645 -- WARNING: what if we have an argument like (v `cast` co)
646 -- where 'co' changes the representation type?
647 -- (This really only happens if co is unsafe.)
648 -- Then all the getArgAmode stuff in CgBindery will set the
649 -- cg_rep of the CgIdInfo based on the type of v, rather
650 -- than the type of 'co'.
651 -- This matters particularly when the function is a primop
652 -- or foreign call.
653 -- Wanted: a better solution than this hacky warning
654 let
655 arg_ty = exprType arg
656 stg_arg_ty = stgArgType stg_arg
657 bad_args = (isUnliftedType arg_ty && not (isUnliftedType stg_arg_ty))
658 || (map typePrimRep (flattenRepType (repType arg_ty))
659 /= map typePrimRep (flattenRepType (repType stg_arg_ty)))
660 -- In GHCi we coerce an argument of type BCO# (unlifted) to HValue (lifted),
661 -- and pass it to a function expecting an HValue (arg_ty). This is ok because
662 -- we can treat an unlifted value as lifted. But the other way round
663 -- we complain.
664 -- We also want to check if a pointer is cast to a non-ptr etc
665
666 WARN( bad_args, text "Dangerous-looking argument. Probable cause: bad unsafeCoerce#" $$ ppr arg )
667 return (stg_arg : stg_args, fvs, ticks ++ aticks)
668
669
670 -- ---------------------------------------------------------------------------
671 -- The magic for lets:
672 -- ---------------------------------------------------------------------------
673
674 coreToStgLet
675 :: Bool -- True <=> yes, we are let-no-escaping this let
676 -> CoreBind -- bindings
677 -> CoreExpr -- body
678 -> LneM (StgExpr, -- new let
679 FreeVarsInfo, -- variables free in the whole let
680 EscVarsSet, -- variables that escape from the whole let
681 Bool) -- True <=> none of the binders in the bindings
682 -- is among the escaping vars
683
684 coreToStgLet let_no_escape bind body = do
685 (bind2, bind_fvs, bind_escs, bind_lvs,
686 body2, body_fvs, body_escs, body_lvs)
687 <- mfix $ \ ~(_, _, _, _, _, rec_body_fvs, _, _) -> do
688
689 -- Do the bindings, setting live_in_cont to empty if
690 -- we ain't in a let-no-escape world
691 live_in_cont <- getVarsLiveInCont
692 ( bind2, bind_fvs, bind_escs, bind_lv_info, env_ext)
693 <- setVarsLiveInCont (if let_no_escape
694 then live_in_cont
695 else emptyLiveInfo)
696 (vars_bind rec_body_fvs bind)
697
698 -- Do the body
699 extendVarEnvLne env_ext $ do
700 (body2, body_fvs, body_escs) <- coreToStgExpr body
701 body_lv_info <- freeVarsToLiveVars body_fvs
702
703 return (bind2, bind_fvs, bind_escs, getLiveVars bind_lv_info,
704 body2, body_fvs, body_escs, getLiveVars body_lv_info)
705
706
707 -- Compute the new let-expression
708 let
709 new_let | let_no_escape = StgLetNoEscape live_in_whole_let bind_lvs bind2 body2
710 | otherwise = StgLet bind2 body2
711
712 free_in_whole_let
713 = binders `minusFVBinders` (bind_fvs `unionFVInfo` body_fvs)
714
715 live_in_whole_let
716 = bind_lvs `unionVarSet` (body_lvs `delVarSetList` binders)
717
718 real_bind_escs = if let_no_escape then
719 bind_escs
720 else
721 getFVSet bind_fvs
722 -- Everything escapes which is free in the bindings
723
724 let_escs = (real_bind_escs `unionVarSet` body_escs) `delVarSetList` binders
725
726 all_escs = bind_escs `unionVarSet` body_escs -- Still includes binders of
727 -- this let(rec)
728
729 no_binder_escapes = isEmptyVarSet (set_of_binders `intersectVarSet` all_escs)
730
731 -- Debugging code as requested by Andrew Kennedy
732 checked_no_binder_escapes
733 | debugIsOn && not no_binder_escapes && any is_join_var binders
734 = pprTrace "Interesting! A join var that isn't let-no-escaped" (ppr binders)
735 False
736 | otherwise = no_binder_escapes
737
738 -- Mustn't depend on the passed-in let_no_escape flag, since
739 -- no_binder_escapes is used by the caller to derive the flag!
740 return (
741 new_let,
742 free_in_whole_let,
743 let_escs,
744 checked_no_binder_escapes
745 )
746 where
747 set_of_binders = mkVarSet binders
748 binders = bindersOf bind
749
750 mk_binding bind_lv_info binder rhs
751 = (binder, LetBound (NestedLet live_vars) (manifestArity rhs))
752 where
753 live_vars | let_no_escape = addLiveVar bind_lv_info binder
754 | otherwise = unitLiveVar binder
755 -- c.f. the invariant on NestedLet
756
757 vars_bind :: FreeVarsInfo -- Free var info for body of binding
758 -> CoreBind
759 -> LneM (StgBinding,
760 FreeVarsInfo,
761 EscVarsSet, -- free vars; escapee vars
762 LiveInfo, -- Vars and CAFs live in binding
763 [(Id, HowBound)]) -- extension to environment
764
765
766 vars_bind body_fvs (NonRec binder rhs) = do
767 (rhs2, bind_fvs, bind_lv_info, escs) <- coreToStgRhs body_fvs [] (binder,rhs)
768 let
769 env_ext_item = mk_binding bind_lv_info binder rhs
770
771 return (StgNonRec binder rhs2,
772 bind_fvs, escs, bind_lv_info, [env_ext_item])
773
774
775 vars_bind body_fvs (Rec pairs)
776 = mfix $ \ ~(_, rec_rhs_fvs, _, bind_lv_info, _) ->
777 let
778 rec_scope_fvs = unionFVInfo body_fvs rec_rhs_fvs
779 binders = map fst pairs
780 env_ext = [ mk_binding bind_lv_info b rhs
781 | (b,rhs) <- pairs ]
782 in
783 extendVarEnvLne env_ext $ do
784 (rhss2, fvss, lv_infos, escss)
785 <- mapAndUnzip4M (coreToStgRhs rec_scope_fvs binders) pairs
786 let
787 bind_fvs = unionFVInfos fvss
788 bind_lv_info = foldr unionLiveInfo emptyLiveInfo lv_infos
789 escs = unionVarSets escss
790
791 return (StgRec (binders `zip` rhss2),
792 bind_fvs, escs, bind_lv_info, env_ext)
793
794
795 is_join_var :: Id -> Bool
796 -- A hack (used only for compiler debuggging) to tell if
797 -- a variable started life as a join point ($j)
798 is_join_var j = occNameString (getOccName j) == "$j"
799
800 coreToStgRhs :: FreeVarsInfo -- Free var info for the scope of the binding
801 -> [Id]
802 -> (Id,CoreExpr)
803 -> LneM (StgRhs, FreeVarsInfo, LiveInfo, EscVarsSet)
804
805 coreToStgRhs scope_fv_info binders (bndr, rhs) = do
806 (new_rhs, rhs_fvs, rhs_escs) <- coreToStgExpr rhs
807 lv_info <- freeVarsToLiveVars (binders `minusFVBinders` rhs_fvs)
808 return (mkStgRhs rhs_fvs (mkSRT lv_info) bndr bndr_info new_rhs,
809 rhs_fvs, lv_info, rhs_escs)
810 where
811 bndr_info = lookupFVInfo scope_fv_info bndr
812
813 mkStgRhs :: FreeVarsInfo -> SRT -> Id -> StgBinderInfo -> StgExpr -> StgRhs
814 mkStgRhs = mkStgRhs' con_updateable
815 where con_updateable _ _ = False
816
817 mkStgRhs' :: (DataCon -> [StgArg] -> Bool)
818 -> FreeVarsInfo -> SRT -> Id -> StgBinderInfo -> StgExpr -> StgRhs
819 mkStgRhs' con_updateable rhs_fvs srt bndr binder_info rhs
820 | StgLam bndrs body <- rhs
821 = StgRhsClosure noCCS binder_info
822 (getFVs rhs_fvs)
823 ReEntrant
824 srt bndrs body
825 | StgConApp con args <- unticked_rhs
826 , not (con_updateable con args)
827 = StgRhsCon noCCS con args
828 | otherwise
829 = StgRhsClosure noCCS binder_info
830 (getFVs rhs_fvs)
831 upd_flag srt [] rhs
832 where
833
834 (_, unticked_rhs) = stripStgTicksTop (not . tickishIsCode) rhs
835
836 upd_flag | isUsedOnce (idDemandInfo bndr) = SingleEntry
837 | otherwise = Updatable
838
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 = returnLne
994 (<*>) = ap
995
996 instance Monad LneM where
997 (>>=) = thenLne
998
999 instance MonadFix LneM where
1000 mfix expr = LneM $ \env lvs_cont ->
1001 let result = unLneM (expr result) env lvs_cont
1002 in result
1003
1004 -- Functions specific to this monad:
1005
1006 getVarsLiveInCont :: LneM LiveInfo
1007 getVarsLiveInCont = LneM $ \_env lvs_cont -> lvs_cont
1008
1009 setVarsLiveInCont :: LiveInfo -> LneM a -> LneM a
1010 setVarsLiveInCont new_lvs_cont expr
1011 = LneM $ \env _lvs_cont
1012 -> unLneM expr env new_lvs_cont
1013
1014 extendVarEnvLne :: [(Id, HowBound)] -> LneM a -> LneM a
1015 extendVarEnvLne ids_w_howbound expr
1016 = LneM $ \env lvs_cont
1017 -> unLneM expr (extendVarEnvList env ids_w_howbound) lvs_cont
1018
1019 lookupVarLne :: Id -> LneM HowBound
1020 lookupVarLne v = LneM $ \env _lvs_cont -> lookupBinding env v
1021
1022 lookupBinding :: IdEnv HowBound -> Id -> HowBound
1023 lookupBinding env v = case lookupVarEnv env v of
1024 Just xx -> xx
1025 Nothing -> ASSERT2( isGlobalId v, ppr v ) ImportBound
1026
1027
1028 -- The result of lookupLiveVarsForSet, a set of live variables, is
1029 -- only ever tacked onto a decorated expression. It is never used as
1030 -- the basis of a control decision, which might give a black hole.
1031
1032 freeVarsToLiveVars :: FreeVarsInfo -> LneM LiveInfo
1033 freeVarsToLiveVars fvs = LneM freeVarsToLiveVars'
1034 where
1035 freeVarsToLiveVars' _env live_in_cont = live_info
1036 where
1037 live_info = foldr unionLiveInfo live_in_cont lvs_from_fvs
1038 lvs_from_fvs = map do_one (allFreeIds fvs)
1039
1040 do_one (v, how_bound)
1041 = case how_bound of
1042 ImportBound -> unitLiveCaf v -- Only CAF imports are
1043 -- recorded in fvs
1044 LetBound TopLet _
1045 | mayHaveCafRefs (idCafInfo v) -> unitLiveCaf v
1046 | otherwise -> emptyLiveInfo
1047
1048 LetBound (NestedLet lvs) _ -> lvs -- lvs already contains v
1049 -- (see the invariant on NestedLet)
1050
1051 _lambda_or_case_binding -> unitLiveVar v -- Bound by lambda or case
1052
1053
1054 -- ---------------------------------------------------------------------------
1055 -- Free variable information
1056 -- ---------------------------------------------------------------------------
1057
1058 type FreeVarsInfo = VarEnv (Var, HowBound, StgBinderInfo)
1059 -- The Var is so we can gather up the free variables
1060 -- as a set.
1061 --
1062 -- The HowBound info just saves repeated lookups;
1063 -- we look up just once when we encounter the occurrence.
1064 -- INVARIANT: Any ImportBound Ids are HaveCafRef Ids
1065 -- Imported Ids without CAF refs are simply
1066 -- not put in the FreeVarsInfo for an expression.
1067 -- See singletonFVInfo and freeVarsToLiveVars
1068 --
1069 -- StgBinderInfo records how it occurs; notably, we
1070 -- are interested in whether it only occurs in saturated
1071 -- applications, because then we don't need to build a
1072 -- curried version.
1073 -- If f is mapped to noBinderInfo, that means
1074 -- that f *is* mentioned (else it wouldn't be in the
1075 -- IdEnv at all), but perhaps in an unsaturated applications.
1076 --
1077 -- All case/lambda-bound things are also mapped to
1078 -- noBinderInfo, since we aren't interested in their
1079 -- occurrence info.
1080 --
1081 -- For ILX we track free var info for type variables too;
1082 -- hence VarEnv not IdEnv
1083
1084 emptyFVInfo :: FreeVarsInfo
1085 emptyFVInfo = emptyVarEnv
1086
1087 singletonFVInfo :: Id -> HowBound -> StgBinderInfo -> FreeVarsInfo
1088 -- Don't record non-CAF imports at all, to keep free-var sets small
1089 singletonFVInfo id ImportBound info
1090 | mayHaveCafRefs (idCafInfo id) = unitVarEnv id (id, ImportBound, info)
1091 | otherwise = emptyVarEnv
1092 singletonFVInfo id how_bound info = unitVarEnv id (id, how_bound, info)
1093
1094 unionFVInfo :: FreeVarsInfo -> FreeVarsInfo -> FreeVarsInfo
1095 unionFVInfo fv1 fv2 = plusVarEnv_C plusFVInfo fv1 fv2
1096
1097 unionFVInfos :: [FreeVarsInfo] -> FreeVarsInfo
1098 unionFVInfos fvs = foldr unionFVInfo emptyFVInfo fvs
1099
1100 minusFVBinders :: [Id] -> FreeVarsInfo -> FreeVarsInfo
1101 minusFVBinders vs fv = foldr minusFVBinder fv vs
1102
1103 minusFVBinder :: Id -> FreeVarsInfo -> FreeVarsInfo
1104 minusFVBinder v fv = fv `delVarEnv` v
1105 -- When removing a binder, remember to add its type variables
1106 -- c.f. CoreFVs.delBinderFV
1107
1108 elementOfFVInfo :: Id -> FreeVarsInfo -> Bool
1109 elementOfFVInfo id fvs = isJust (lookupVarEnv fvs id)
1110
1111 lookupFVInfo :: FreeVarsInfo -> Id -> StgBinderInfo
1112 -- Find how the given Id is used.
1113 -- Externally visible things may be used any old how
1114 lookupFVInfo fvs id
1115 | isExternalName (idName id) = noBinderInfo
1116 | otherwise = case lookupVarEnv fvs id of
1117 Nothing -> noBinderInfo
1118 Just (_,_,info) -> info
1119
1120 allFreeIds :: FreeVarsInfo -> [(Id,HowBound)] -- Both top level and non-top-level Ids
1121 allFreeIds fvs = ASSERT( all (isId . fst) ids ) ids
1122 where
1123 ids = [(id,how_bound) | (id,how_bound,_) <- varEnvElts fvs]
1124
1125 -- Non-top-level things only, both type variables and ids
1126 getFVs :: FreeVarsInfo -> [Var]
1127 getFVs fvs = [id | (id, how_bound, _) <- varEnvElts fvs,
1128 not (topLevelBound how_bound) ]
1129
1130 getFVSet :: FreeVarsInfo -> VarSet
1131 getFVSet fvs = mkVarSet (getFVs fvs)
1132
1133 plusFVInfo :: (Var, HowBound, StgBinderInfo)
1134 -> (Var, HowBound, StgBinderInfo)
1135 -> (Var, HowBound, StgBinderInfo)
1136 plusFVInfo (id1,hb1,info1) (id2,hb2,info2)
1137 = ASSERT(id1 == id2 && hb1 `check_eq_how_bound` hb2)
1138 (id1, hb1, combineStgBinderInfo info1 info2)
1139
1140 -- The HowBound info for a variable in the FVInfo should be consistent
1141 check_eq_how_bound :: HowBound -> HowBound -> Bool
1142 check_eq_how_bound ImportBound ImportBound = True
1143 check_eq_how_bound LambdaBound LambdaBound = True
1144 check_eq_how_bound (LetBound li1 ar1) (LetBound li2 ar2) = ar1 == ar2 && check_eq_li li1 li2
1145 check_eq_how_bound _ _ = False
1146
1147 check_eq_li :: LetInfo -> LetInfo -> Bool
1148 check_eq_li (NestedLet _) (NestedLet _) = True
1149 check_eq_li TopLet TopLet = True
1150 check_eq_li _ _ = False
1151
1152 -- Misc.
1153
1154 filterStgBinders :: [Var] -> [Var]
1155 filterStgBinders bndrs = filter isId bndrs
1156
1157 myCollectBinders :: Expr Var -> ([Var], Expr Var)
1158 myCollectBinders expr
1159 = go [] expr
1160 where
1161 go bs (Lam b e) = go (b:bs) e
1162 go bs (Cast e _) = go bs e
1163 go bs e = (reverse bs, e)
1164
1165 myCollectArgs :: CoreExpr -> (Id, [CoreArg], [Tickish Id])
1166 -- We assume that we only have variables
1167 -- in the function position by now
1168 myCollectArgs expr
1169 = go expr [] []
1170 where
1171 go (Var v) as ts = (v, as, ts)
1172 go (App f a) as ts = go f (a:as) ts
1173 go (Tick t e) as ts = ASSERT( all isTypeArg as )
1174 go e as (t:ts) -- ticks can appear in type apps
1175 go (Cast e _) as ts = go e as ts
1176 go (Lam b e) as ts
1177 | isTyVar b = go e as ts -- Note [Collect args]
1178 go _ _ _ = pprPanic "CoreToStg.myCollectArgs" (ppr expr)
1179
1180 -- Note [Collect args]
1181 -- ~~~~~~~~~~~~~~~~~~~
1182 --
1183 -- This big-lambda case occurred following a rather obscure eta expansion.
1184 -- It all seems a bit yukky to me.
1185
1186 stgArity :: Id -> HowBound -> Arity
1187 stgArity _ (LetBound _ arity) = arity
1188 stgArity f ImportBound = idArity f
1189 stgArity _ LambdaBound = 0