[project @ 1998-04-14 12:26:11 by simonpj]
[ghc-hetmet.git] / ghc / compiler / specialise / Specialise.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1996
3 %
4 \section[Specialise]{Stamping out overloading, and (optionally) polymorphism}
5
6 \begin{code}
7 module Specialise (
8         specProgram, 
9         idSpecVars
10     ) where
11
12 #include "HsVersions.h"
13
14 import MkId             ( mkUserLocal )
15 import Id               ( Id, DictVar, idType, mkTemplateLocals,
16
17                           getIdSpecialisation, setIdSpecialisation, isSpecPragmaId,
18
19                           IdSet, mkIdSet, addOneToIdSet, intersectIdSets, isEmptyIdSet, 
20                                  emptyIdSet, unionIdSets, minusIdSet, unitIdSet, elementOfIdSet,
21
22                           IdEnv, mkIdEnv, lookupIdEnv, addOneToIdEnv, delOneFromIdEnv
23                         )
24
25 import Type             ( Type, mkTyVarTy, splitSigmaTy, instantiateTy, isDictTy,
26                           tyVarsOfType, tyVarsOfTypes, applyTys, mkForAllTys
27                         )
28 import TyCon            ( TyCon )
29 import TyVar            ( TyVar, mkTyVar,
30                           TyVarSet, mkTyVarSet, isEmptyTyVarSet, intersectTyVarSets,
31                                     elementOfTyVarSet, unionTyVarSets, emptyTyVarSet,
32                                     minusTyVarSet,
33                           TyVarEnv, mkTyVarEnv, delFromTyVarEnv
34                         )
35 import Kind             ( mkBoxedTypeKind )
36 import CoreSyn
37 import PprCore          ()      -- Instances 
38 import Name             ( NamedThing(..), getSrcLoc, mkSysLocalName )
39 import SrcLoc           ( noSrcLoc )
40 import SpecEnv          ( addToSpecEnv, lookupSpecEnv, specEnvValues )
41
42 import UniqSupply       ( UniqSupply,
43                           UniqSM, initUs, thenUs, returnUs, getUnique, mapUs
44                         )
45 import Unique           ( mkAlphaTyVarUnique )
46 import FiniteMap
47 import Maybes           ( MaybeErr(..), maybeToBool )
48 import Bag
49 import List             ( partition )
50 import Util             ( zipEqual )
51 import Outputable
52
53
54 infixr 9 `thenSM`
55 \end{code}
56
57 %************************************************************************
58 %*                                                                      *
59 \subsection[notes-Specialise]{Implementation notes [SLPJ, Aug 18 1993]}
60 %*                                                                      *
61 %************************************************************************
62
63 These notes describe how we implement specialisation to eliminate
64 overloading.
65
66 The specialisation pass works on Core
67 syntax, complete with all the explicit dictionary application,
68 abstraction and construction as added by the type checker.  The
69 existing type checker remains largely as it is.
70
71 One important thought: the {\em types} passed to an overloaded
72 function, and the {\em dictionaries} passed are mutually redundant.
73 If the same function is applied to the same type(s) then it is sure to
74 be applied to the same dictionary(s)---or rather to the same {\em
75 values}.  (The arguments might look different but they will evaluate
76 to the same value.)
77
78 Second important thought: we know that we can make progress by
79 treating dictionary arguments as static and worth specialising on.  So
80 we can do without binding-time analysis, and instead specialise on
81 dictionary arguments and no others.
82
83 The basic idea
84 ~~~~~~~~~~~~~~
85 Suppose we have
86
87         let f = <f_rhs>
88         in <body>
89
90 and suppose f is overloaded.
91
92 STEP 1: CALL-INSTANCE COLLECTION
93
94 We traverse <body>, accumulating all applications of f to types and
95 dictionaries.
96
97 (Might there be partial applications, to just some of its types and
98 dictionaries?  In principle yes, but in practice the type checker only
99 builds applications of f to all its types and dictionaries, so partial
100 applications could only arise as a result of transformation, and even
101 then I think it's unlikely.  In any case, we simply don't accumulate such
102 partial applications.)
103
104 There's a choice of whether to collect details of all *polymorphic* functions
105 or simply all *overloaded* ones.  How to sort this out?
106   Pass in a predicate on the function to say if it is "interesting"?
107   This is dependent on the user flags: SpecialiseOverloaded
108                                        SpecialiseUnboxed
109                                        SpecialiseAll
110
111 STEP 2: EQUIVALENCES
112
113 So now we have a collection of calls to f:
114         f t1 t2 d1 d2
115         f t3 t4 d3 d4
116         ...
117 Notice that f may take several type arguments.  To avoid ambiguity, we
118 say that f is called at type t1/t2 and t3/t4.
119
120 We take equivalence classes using equality of the *types* (ignoring
121 the dictionary args, which as mentioned previously are redundant).
122
123 STEP 3: SPECIALISATION
124
125 For each equivalence class, choose a representative (f t1 t2 d1 d2),
126 and create a local instance of f, defined thus:
127
128         f@t1/t2 = <f_rhs> t1 t2 d1 d2
129
130 f_rhs presumably has some big lambdas and dictionary lambdas, so lots
131 of simplification will now result.  However we don't actually *do* that
132 simplification.  Rather, we leave it for the simplifier to do.  If we
133 *did* do it, though, we'd get more call instances from the specialised
134 RHS.  We can work out what they are by instantiating the call-instance
135 set from f's RHS with the types t1, t2.
136
137 Add this new id to f's IdInfo, to record that f has a specialised version.
138
139 Before doing any of this, check that f's IdInfo doesn't already
140 tell us about an existing instance of f at the required type/s.
141 (This might happen if specialisation was applied more than once, or
142 it might arise from user SPECIALIZE pragmas.)
143
144 Recursion
145 ~~~~~~~~~
146 Wait a minute!  What if f is recursive?  Then we can't just plug in
147 its right-hand side, can we?
148
149 But it's ok.  The type checker *always* creates non-recursive definitions
150 for overloaded recursive functions.  For example:
151
152         f x = f (x+x)           -- Yes I know its silly
153
154 becomes
155
156         f a (d::Num a) = let p = +.sel a d
157                          in
158                          letrec fl (y::a) = fl (p y y)
159                          in
160                          fl
161
162 We still have recusion for non-overloaded functions which we
163 speciailise, but the recursive call should get specialised to the
164 same recursive version.
165
166
167 Polymorphism 1
168 ~~~~~~~~~~~~~~
169
170 All this is crystal clear when the function is applied to *constant
171 types*; that is, types which have no type variables inside.  But what if
172 it is applied to non-constant types?  Suppose we find a call of f at type
173 t1/t2.  There are two possibilities:
174
175 (a) The free type variables of t1, t2 are in scope at the definition point
176 of f.  In this case there's no problem, we proceed just as before.  A common
177 example is as follows.  Here's the Haskell:
178
179         g y = let f x = x+x
180               in f y + f y
181
182 After typechecking we have
183
184         g a (d::Num a) (y::a) = let f b (d'::Num b) (x::b) = +.sel b d' x x
185                                 in +.sel a d (f a d y) (f a d y)
186
187 Notice that the call to f is at type type "a"; a non-constant type.
188 Both calls to f are at the same type, so we can specialise to give:
189
190         g a (d::Num a) (y::a) = let f@a (x::a) = +.sel a d x x
191                                 in +.sel a d (f@a y) (f@a y)
192
193
194 (b) The other case is when the type variables in the instance types
195 are *not* in scope at the definition point of f.  The example we are
196 working with above is a good case.  There are two instances of (+.sel a d),
197 but "a" is not in scope at the definition of +.sel.  Can we do anything?
198 Yes, we can "common them up", a sort of limited common sub-expression deal.
199 This would give:
200
201         g a (d::Num a) (y::a) = let +.sel@a = +.sel a d
202                                     f@a (x::a) = +.sel@a x x
203                                 in +.sel@a (f@a y) (f@a y)
204
205 This can save work, and can't be spotted by the type checker, because
206 the two instances of +.sel weren't originally at the same type.
207
208 Further notes on (b)
209
210 * There are quite a few variations here.  For example, the defn of
211   +.sel could be floated ouside the \y, to attempt to gain laziness.
212   It certainly mustn't be floated outside the \d because the d has to
213   be in scope too.
214
215 * We don't want to inline f_rhs in this case, because
216 that will duplicate code.  Just commoning up the call is the point.
217
218 * Nothing gets added to +.sel's IdInfo.
219
220 * Don't bother unless the equivalence class has more than one item!
221
222 Not clear whether this is all worth it.  It is of course OK to
223 simply discard call-instances when passing a big lambda.
224
225 Polymorphism 2 -- Overloading
226 ~~~~~~~~~~~~~~
227 Consider a function whose most general type is
228
229         f :: forall a b. Ord a => [a] -> b -> b
230
231 There is really no point in making a version of g at Int/Int and another
232 at Int/Bool, because it's only instancing the type variable "a" which
233 buys us any efficiency. Since g is completely polymorphic in b there
234 ain't much point in making separate versions of g for the different
235 b types.
236
237 That suggests that we should identify which of g's type variables
238 are constrained (like "a") and which are unconstrained (like "b").
239 Then when taking equivalence classes in STEP 2, we ignore the type args
240 corresponding to unconstrained type variable.  In STEP 3 we make
241 polymorphic versions.  Thus:
242
243         f@t1/ = /\b -> <f_rhs> t1 b d1 d2
244
245 We do this.
246
247
248 Dictionary floating
249 ~~~~~~~~~~~~~~~~~~~
250 Consider this
251
252         f a (d::Num a) = let g = ...
253                          in
254                          ...(let d1::Ord a = Num.Ord.sel a d in g a d1)...
255
256 Here, g is only called at one type, but the dictionary isn't in scope at the
257 definition point for g.  Usually the type checker would build a
258 definition for d1 which enclosed g, but the transformation system
259 might have moved d1's defn inward.  Solution: float dictionary bindings
260 outwards along with call instances.
261
262 Consider
263
264         f x = let g p q = p==q
265                   h r s = (r+s, g r s)
266               in
267               h x x
268
269
270 Before specialisation, leaving out type abstractions we have
271
272         f df x = let g :: Eq a => a -> a -> Bool
273                      g dg p q = == dg p q
274                      h :: Num a => a -> a -> (a, Bool)
275                      h dh r s = let deq = eqFromNum dh
276                                 in (+ dh r s, g deq r s)
277               in
278               h df x x
279
280 After specialising h we get a specialised version of h, like this:
281
282                     h' r s = let deq = eqFromNum df
283                              in (+ df r s, g deq r s)
284
285 But we can't naively make an instance for g from this, because deq is not in scope
286 at the defn of g.  Instead, we have to float out the (new) defn of deq
287 to widen its scope.  Notice that this floating can't be done in advance -- it only
288 shows up when specialisation is done.
289
290 User SPECIALIZE pragmas
291 ~~~~~~~~~~~~~~~~~~~~~~~
292 Specialisation pragmas can be digested by the type checker, and implemented
293 by adding extra definitions along with that of f, in the same way as before
294
295         f@t1/t2 = <f_rhs> t1 t2 d1 d2
296
297 Indeed the pragmas *have* to be dealt with by the type checker, because
298 only it knows how to build the dictionaries d1 and d2!  For example
299
300         g :: Ord a => [a] -> [a]
301         {-# SPECIALIZE f :: [Tree Int] -> [Tree Int] #-}
302
303 Here, the specialised version of g is an application of g's rhs to the
304 Ord dictionary for (Tree Int), which only the type checker can conjure
305 up.  There might not even *be* one, if (Tree Int) is not an instance of
306 Ord!  (All the other specialision has suitable dictionaries to hand
307 from actual calls.)
308
309 Problem.  The type checker doesn't have to hand a convenient <f_rhs>, because
310 it is buried in a complex (as-yet-un-desugared) binding group.
311 Maybe we should say
312
313         f@t1/t2 = f* t1 t2 d1 d2
314
315 where f* is the Id f with an IdInfo which says "inline me regardless!".
316 Indeed all the specialisation could be done in this way.
317 That in turn means that the simplifier has to be prepared to inline absolutely
318 any in-scope let-bound thing.
319
320
321 Again, the pragma should permit polymorphism in unconstrained variables:
322
323         h :: Ord a => [a] -> b -> b
324         {-# SPECIALIZE h :: [Int] -> b -> b #-}
325
326 We *insist* that all overloaded type variables are specialised to ground types,
327 (and hence there can be no context inside a SPECIALIZE pragma).
328 We *permit* unconstrained type variables to be specialised to
329         - a ground type
330         - or left as a polymorphic type variable
331 but nothing in between.  So
332
333         {-# SPECIALIZE h :: [Int] -> [c] -> [c] #-}
334
335 is *illegal*.  (It can be handled, but it adds complication, and gains the
336 programmer nothing.)
337
338
339 SPECIALISING INSTANCE DECLARATIONS
340 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
341 Consider
342
343         instance Foo a => Foo [a] where
344                 ...
345         {-# SPECIALIZE instance Foo [Int] #-}
346
347 The original instance decl creates a dictionary-function
348 definition:
349
350         dfun.Foo.List :: forall a. Foo a -> Foo [a]
351
352 The SPECIALIZE pragma just makes a specialised copy, just as for
353 ordinary function definitions:
354
355         dfun.Foo.List@Int :: Foo [Int]
356         dfun.Foo.List@Int = dfun.Foo.List Int dFooInt
357
358 The information about what instance of the dfun exist gets added to
359 the dfun's IdInfo in the same way as a user-defined function too.
360
361
362 Automatic instance decl specialisation?
363 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
364 Can instance decls be specialised automatically?  It's tricky.
365 We could collect call-instance information for each dfun, but
366 then when we specialised their bodies we'd get new call-instances
367 for ordinary functions; and when we specialised their bodies, we might get
368 new call-instances of the dfuns, and so on.  This all arises because of
369 the unrestricted mutual recursion between instance decls and value decls.
370
371 Still, there's no actual problem; it just means that we may not do all
372 the specialisation we could theoretically do.
373
374 Furthermore, instance decls are usually exported and used non-locally,
375 so we'll want to compile enough to get those specialisations done.
376
377 Lastly, there's no such thing as a local instance decl, so we can
378 survive solely by spitting out *usage* information, and then reading that
379 back in as a pragma when next compiling the file.  So for now,
380 we only specialise instance decls in response to pragmas.
381
382
383 SPITTING OUT USAGE INFORMATION
384 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
385
386 To spit out usage information we need to traverse the code collecting
387 call-instance information for all imported (non-prelude?) functions
388 and data types. Then we equivalence-class it and spit it out.
389
390 This is done at the top-level when all the call instances which escape
391 must be for imported functions and data types.
392
393 *** Not currently done ***
394
395
396 Partial specialisation by pragmas
397 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
398 What about partial specialisation:
399
400         k :: (Ord a, Eq b) => [a] -> b -> b -> [a]
401         {-# SPECIALIZE k :: Eq b => [Int] -> b -> b -> [a] #-}
402
403 or even
404
405         {-# SPECIALIZE k :: Eq b => [Int] -> [b] -> [b] -> [a] #-}
406
407 Seems quite reasonable.  Similar things could be done with instance decls:
408
409         instance (Foo a, Foo b) => Foo (a,b) where
410                 ...
411         {-# SPECIALIZE instance Foo a => Foo (a,Int) #-}
412         {-# SPECIALIZE instance Foo b => Foo (Int,b) #-}
413
414 Ho hum.  Things are complex enough without this.  I pass.
415
416
417 Requirements for the simplifer
418 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
419 The simplifier has to be able to take advantage of the specialisation.
420
421 * When the simplifier finds an application of a polymorphic f, it looks in
422 f's IdInfo in case there is a suitable instance to call instead.  This converts
423
424         f t1 t2 d1 d2   ===>   f_t1_t2
425
426 Note that the dictionaries get eaten up too!
427
428 * Dictionary selection operations on constant dictionaries must be
429   short-circuited:
430
431         +.sel Int d     ===>  +Int
432
433 The obvious way to do this is in the same way as other specialised
434 calls: +.sel has inside it some IdInfo which tells that if it's applied
435 to the type Int then it should eat a dictionary and transform to +Int.
436
437 In short, dictionary selectors need IdInfo inside them for constant
438 methods.
439
440 * Exactly the same applies if a superclass dictionary is being
441   extracted:
442
443         Eq.sel Int d   ===>   dEqInt
444
445 * Something similar applies to dictionary construction too.  Suppose
446 dfun.Eq.List is the function taking a dictionary for (Eq a) to
447 one for (Eq [a]).  Then we want
448
449         dfun.Eq.List Int d      ===> dEq.List_Int
450
451 Where does the Eq [Int] dictionary come from?  It is built in
452 response to a SPECIALIZE pragma on the Eq [a] instance decl.
453
454 In short, dfun Ids need IdInfo with a specialisation for each
455 constant instance of their instance declaration.
456
457 All this uses a single mechanism: the SpecEnv inside an Id
458
459
460 What does the specialisation IdInfo look like?
461 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
462
463 The SpecEnv of an Id maps a list of types (the template) to an expression
464
465         [Type]  |->  Expr
466
467 For example, if f has this SpecInfo:
468
469         [Int, a]  ->  \d:Ord Int. f' a
470
471 it means that we can replace the call
472
473         f Int t  ===>  (\d. f' t)
474
475 This chucks one dictionary away and proceeds with the
476 specialised version of f, namely f'.
477
478
479 What can't be done this way?
480 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
481 There is no way, post-typechecker, to get a dictionary for (say)
482 Eq a from a dictionary for Eq [a].  So if we find
483
484         ==.sel [t] d
485
486 we can't transform to
487
488         eqList (==.sel t d')
489
490 where
491         eqList :: (a->a->Bool) -> [a] -> [a] -> Bool
492
493 Of course, we currently have no way to automatically derive
494 eqList, nor to connect it to the Eq [a] instance decl, but you
495 can imagine that it might somehow be possible.  Taking advantage
496 of this is permanently ruled out.
497
498 Still, this is no great hardship, because we intend to eliminate
499 overloading altogether anyway!
500
501
502
503 A note about non-tyvar dictionaries
504 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
505 Some Ids have types like
506
507         forall a,b,c. Eq a -> Ord [a] -> tau
508
509 This seems curious at first, because we usually only have dictionary
510 args whose types are of the form (C a) where a is a type variable.
511 But this doesn't hold for the functions arising from instance decls,
512 which sometimes get arguements with types of form (C (T a)) for some
513 type constructor T.
514
515 Should we specialise wrt this compound-type dictionary?  We used to say
516 "no", saying:
517         "This is a heuristic judgement, as indeed is the fact that we 
518         specialise wrt only dictionaries.  We choose *not* to specialise
519         wrt compound dictionaries because at the moment the only place
520         they show up is in instance decls, where they are simply plugged
521         into a returned dictionary.  So nothing is gained by specialising
522         wrt them."
523
524 But it is simpler and more uniform to specialise wrt these dicts too;
525 and in future GHC is likely to support full fledged type signatures 
526 like
527         f ;: Eq [(a,b)] => ...
528
529
530 %************************************************************************
531 %*                                                                      *
532 \subsubsection{The new specialiser}
533 %*                                                                      *
534 %************************************************************************
535
536 Our basic game plan is this.  For let(rec) bound function
537         f :: (C a, D c) => (a,b,c,d) -> Bool
538
539 * Find any specialised calls of f, (f ts ds), where 
540   ts are the type arguments t1 .. t4, and
541   ds are the dictionary arguments d1 .. d2.
542
543 * Add a new definition for f1 (say):
544
545         f1 = /\ b d -> (..body of f..) t1 b t3 d d1 d2
546
547   Note that we abstract over the unconstrained type arguments.
548
549 * Add the mapping
550
551         [t1,b,t3,d]  |->  \d1 d2 -> f1 b d
552
553   to the specialisations of f.  This will be used by the
554   simplifier to replace calls 
555                 (f t1 t2 t3 t4) da db
556   by
557                 (\d1 d1 -> f1 t2 t4) da db
558
559   All the stuff about how many dictionaries to discard, and what types
560   to apply the specialised function to, are handled by the fact that the
561   SpecEnv contains a template for the result of the specialisation.
562
563 We don't build *partial* specialisations for f.  For example:
564
565   f :: Eq a => a -> a -> Bool
566   {-# SPECIALISE f :: (Eq b, Eq c) => (b,c) -> (b,c) -> Bool #-}
567
568 Here, little is gained by making a specialised copy of f.
569 There's a distinct danger that the specialised version would
570 first build a dictionary for (Eq b, Eq c), and then select the (==) 
571 method from it!  Even if it didn't, not a great deal is saved.
572
573 We do, however, generate polymorphic, but not overloaded, specialisations:
574
575   f :: Eq a => [a] -> b -> b -> b
576   {#- SPECIALISE f :: [Int] -> b -> b -> b #-}
577
578 Hence, the invariant is this: 
579
580         *** no specialised version is overloaded ***
581
582
583 %************************************************************************
584 %*                                                                      *
585 \subsubsection{The exported function}
586 %*                                                                      *
587 %************************************************************************
588
589 \begin{code}
590 specProgram :: UniqSupply -> [CoreBinding] -> [CoreBinding]
591 specProgram us binds
592   = initSM us (go binds         `thenSM` \ (binds', uds') ->
593                returnSM (dumpAllDictBinds uds' binds')
594               )
595   where
596     go []           = returnSM ([], emptyUDs)
597     go (bind:binds) = go binds          `thenSM` \ (binds', uds) ->
598                       specBind bind uds `thenSM` \ (bind', uds') ->
599                       returnSM (bind' ++ binds', uds')
600 \end{code}
601
602 %************************************************************************
603 %*                                                                      *
604 \subsubsection{@specExpr@: the main function}
605 %*                                                                      *
606 %************************************************************************
607
608 \begin{code}
609 specExpr :: CoreExpr -> SpecM (CoreExpr, UsageDetails)
610
611 ---------------- First the easy cases --------------------
612 specExpr e@(Var _)    = returnSM (e, emptyUDs)
613 specExpr e@(Lit _)    = returnSM (e, emptyUDs)
614 specExpr e@(Con _ _)  = returnSM (e, emptyUDs)
615 specExpr e@(Prim _ _) = returnSM (e, emptyUDs)
616
617 specExpr (Note note body)
618   = specExpr body       `thenSM` \ (body', uds) ->
619     returnSM (Note note body', uds)
620
621
622 ---------------- Applications might generate a call instance --------------------
623 specExpr e@(App fun arg)
624   = go fun [arg]
625   where
626     go (App fun arg) args = go fun (arg:args)
627     go (Var f)       args = returnSM (e, mkCallUDs f args)
628     go other         args = specExpr other      `thenSM` \ (e', uds) ->
629                             returnSM (foldl App e' args, uds)
630
631 ---------------- Lambda/case require dumping of usage details --------------------
632 specExpr e@(Lam _ _)
633   = specExpr body       `thenSM` \ (body', uds) ->
634     let
635         (filtered_uds, body'') = dumpUDs bndrs uds body'
636     in
637     returnSM (foldr Lam body'' bndrs, filtered_uds)
638   where
639     (bndrs, body) = go [] e
640
641         -- More efficient to collect a group of binders together all at once
642     go bndrs (Lam bndr e) = go (bndr:bndrs) e
643     go bndrs e            = (reverse bndrs, e)
644
645
646 specExpr (Case scrut alts)
647   = specExpr scrut      `thenSM` \ (scrut', uds_scrut) ->
648     spec_alts alts      `thenSM` \ (alts', uds_alts) ->
649     returnSM (Case scrut' alts', uds_scrut `plusUDs` uds_alts)
650   where
651     spec_alts (AlgAlts alts deflt)
652         = mapAndCombineSM spec_alg_alt alts     `thenSM` \ (alts', uds1) ->
653           spec_deflt deflt                      `thenSM` \ (deflt', uds2) ->
654           returnSM (AlgAlts alts' deflt', uds1 `plusUDs` uds2)
655
656     spec_alts (PrimAlts alts deflt)
657         = mapAndCombineSM spec_prim_alt alts    `thenSM` \ (alts', uds1) ->
658           spec_deflt deflt                      `thenSM` \ (deflt', uds2) ->
659           returnSM (PrimAlts alts' deflt', uds1 `plusUDs` uds2)
660
661     spec_alg_alt (con, args, rhs)
662         = specExpr rhs          `thenSM` \ (rhs', uds) ->
663           let
664              (uds', rhs'') = dumpUDs (map ValBinder args) uds rhs'
665           in
666           returnSM ((con, args, rhs''), uds')
667
668     spec_prim_alt (lit, rhs)
669         = specExpr rhs          `thenSM` \ (rhs', uds) ->
670           returnSM ((lit, rhs'), uds)
671
672     spec_deflt NoDefault = returnSM (NoDefault, emptyUDs)
673     spec_deflt (BindDefault arg rhs)
674         = specExpr rhs          `thenSM` \ (rhs', uds) ->
675           let
676              (uds', rhs'') = dumpUDs [ValBinder arg] uds rhs'
677           in
678           returnSM (BindDefault arg rhs'', uds')
679
680 ---------------- Finally, let is the interesting case --------------------
681 specExpr (Let bind body)
682   =     -- Deal with the body
683     specExpr body                               `thenSM` \ (body', body_uds) ->
684
685         -- Deal with the bindings
686     specBind bind body_uds                      `thenSM` \ (binds', uds) ->
687
688         -- All done
689     returnSM (foldr Let body' binds', uds)
690 \end{code}
691
692 %************************************************************************
693 %*                                                                      *
694 \subsubsection{Dealing with a binding}
695 %*                                                                      *
696 %************************************************************************
697
698 \begin{code}
699 specBind :: CoreBinding
700          -> UsageDetails                -- Info on how the scope of the binding
701          -> SpecM ([CoreBinding],       -- New bindings
702                    UsageDetails)        -- And info to pass upstream
703
704 specBind (NonRec bndr rhs) body_uds
705   | isDictTy (idType bndr)
706   =     -- It's a dictionary binding
707         -- Pick it up and float it outwards.
708     specExpr rhs                                `thenSM` \ (rhs', rhs_uds) ->
709     let
710         all_uds = rhs_uds `plusUDs` addDictBind body_uds bndr rhs'
711     in
712     returnSM ([], all_uds)
713
714   | isSpecPragmaId bndr
715   = specExpr rhs                                `thenSM` \ (rhs', rhs_uds) ->
716     returnSM ([], rhs_uds `plusUDs` body_uds)
717
718   | otherwise
719   =   -- Deal with the RHS, specialising it according
720       -- to the calls found in the body
721     specDefn (calls body_uds) (bndr,rhs)        `thenSM` \ ((bndr',rhs'), spec_defns, spec_uds) ->
722     let
723         (all_uds, (dict_binds, dump_calls)) 
724                 = splitUDs [ValBinder bndr]
725                            (body_uds `plusUDs` spec_uds)
726                         -- It's important that the `plusUDs` is this way round,
727                         -- because body_uds may bind dictionaries that are
728                         -- used in the calls passed to specDefn.  So the
729                         -- dictionary bindings in spec_uds may mention 
730                         -- dictionaries bound in body_uds.
731
732         -- If we make specialisations then we Rec the whole lot together
733         -- If not, leave it as a NonRec
734         new_bind | null spec_defns = NonRec bndr' rhs'
735                  | otherwise       = Rec ((bndr',rhs'):spec_defns)
736     in
737     returnSM ( new_bind : mkDictBinds dict_binds, all_uds )
738
739 specBind (Rec pairs) body_uds
740   = mapSM (specDefn (calls body_uds)) pairs     `thenSM` \ stuff ->
741     let
742         (pairs', spec_defns_s, spec_uds_s) = unzip3 stuff
743         spec_defns = concat spec_defns_s
744         spec_uds   = plusUDList spec_uds_s
745
746         (all_uds, (dict_binds, dump_calls)) 
747                 = splitUDs (map (ValBinder . fst) pairs)
748                            (body_uds `plusUDs` spec_uds)
749                         -- See notes for non-rec case
750
751         new_bind = Rec (spec_defns ++ pairs')
752     in
753     returnSM (  new_bind : mkDictBinds dict_binds, all_uds )
754     
755 specDefn :: CallDetails                 -- Info on how it is used in its scope
756          -> (Id, CoreExpr)              -- The thing being bound and its un-processed RHS
757          -> SpecM ((Id, CoreExpr),      -- The thing and its processed RHS
758                                         --      the Id may now have specialisations attached
759                    [(Id,CoreExpr)],     -- Extra, specialised bindings
760                    UsageDetails         -- Stuff to fling upwards from the RHS and its
761             )                           --      specialised versions
762
763 specDefn calls (fn, rhs)
764         -- The first case is the interesting one
765   |  n_tyvars == length rhs_tyvars      -- Rhs of fn's defn has right number of big lambdas
766   && n_dicts  <= length rhs_bndrs       -- and enough dict args
767   && not (null calls_for_me)            -- And there are some calls to specialise
768   =   -- Specialise the body of the function
769     specExpr body                                       `thenSM` \ (body', body_uds) ->
770     let
771         (float_uds, bound_uds@(dict_binds,_)) = splitUDs rhs_bndrs body_uds
772     in
773
774       -- Make a specialised version for each call in calls_for_me
775     mapSM (spec_call bound_uds) calls_for_me            `thenSM` \ stuff ->
776     let
777         (spec_defns, spec_uds, spec_env_stuff) = unzip3 stuff
778
779         fn'  = addIdSpecialisations fn spec_env_stuff
780         rhs' = foldr Lam (mkDictLets dict_binds body') rhs_bndrs 
781     in
782     returnSM ((fn',rhs'), 
783               spec_defns, 
784               float_uds `plusUDs` plusUDList spec_uds)
785
786   | otherwise   -- No calls or RHS doesn't fit our preconceptions
787   = specExpr rhs                        `thenSM` \ (rhs', rhs_uds) ->
788     returnSM ((fn, rhs'), [], rhs_uds)
789   
790   where
791     fn_type              = idType fn
792     (tyvars, theta, tau) = splitSigmaTy fn_type
793     n_tyvars             = length tyvars
794     n_dicts              = length theta
795     mk_spec_tys call_ts  = zipWith mk_spec_ty call_ts tyVarTemplates
796                          where
797                            mk_spec_ty (Just ty) _     = ty
798                            mk_spec_ty Nothing   tyvar = mkTyVarTy tyvar
799
800     (rhs_tyvars, rhs_ids, rhs_body) = collectBinders rhs
801     rhs_dicts = take n_dicts rhs_ids
802     rhs_bndrs = map TyBinder rhs_tyvars ++ map ValBinder rhs_dicts
803     body      = mkValLam (drop n_dicts rhs_ids) rhs_body
804                 -- Glue back on the non-dict lambdas
805
806     calls_for_me = case lookupFM calls fn of
807                         Nothing -> []
808                         Just cs -> fmToList cs
809
810     ----------------------------------------------------------
811         -- Specialise to one particular call pattern
812     spec_call :: ProtoUsageDetails          -- From the original body, captured by
813                                             -- the dictionary lambdas
814               -> ([Maybe Type], [DictVar])  -- Call instance
815               -> SpecM ((Id,CoreExpr),            -- Specialised definition
816                         UsageDetails,             -- Usage details from specialised body
817                         ([TyVar], [Type], CoreExpr))       -- Info for the Id's SpecEnv
818     spec_call bound_uds (call_ts, call_ds)
819       = ASSERT( length call_ts == n_tyvars && length call_ds == n_dicts )
820                 -- Calls are only recorded for properly-saturated applications
821         
822         -- Supppose the call is for f [Just t1, Nothing, Just t3, Nothing] [d1, d2]
823
824                 -- Construct the new binding
825                 --      f1 = /\ b d -> (..rhs of f..) t1 b t3 d d1 d2
826                 -- and the type of this binder
827         let
828            spec_tyvars = [tyvar | (tyvar, Nothing) <- tyVarTemplates `zip` call_ts]
829            spec_tys    = mk_spec_tys call_ts
830            spec_rhs    = mkTyLam spec_tyvars $
831                          mkGenApp rhs (map TyArg spec_tys ++ map VarArg call_ds)
832            spec_id_ty  = mkForAllTys spec_tyvars (instantiateTy ty_env tau)
833            ty_env      = mkTyVarEnv (zipEqual "spec_call" tyvars spec_tys)
834         in
835
836         newIdSM fn spec_id_ty           `thenSM` \ spec_f ->
837
838
839                 -- Construct the stuff for f's spec env
840                 --      [b,d] [t1,b,t3,d]  |->  \d1 d2 -> f1 b d
841                 -- The only awkward bit is that d1,d2 might well be global
842                 -- dictionaries, so it's tidier to make new local variables
843                 -- for the lambdas in the RHS, rather than lambda-bind the
844                 -- dictionaries themselves.
845                 --
846                 -- In fact we use the standard template locals, so that the
847                 -- they don't need to be "tidied" before putting in interface files
848         let
849            arg_ds        = mkTemplateLocals (map idType call_ds)
850            spec_env_rhs  = mkValLam arg_ds $
851                            mkTyApp (Var spec_f) $
852                            map mkTyVarTy spec_tyvars
853            spec_env_info = (spec_tyvars, spec_tys, spec_env_rhs)
854         in
855
856                 -- Specialise the UDs from f's RHS
857         let
858                 -- Only the overloaded tyvars should be free in the uds
859            ty_env   = [ (rhs_tyvar,ty) 
860                       | (rhs_tyvar, Just ty) <- zipEqual "specUDs1" rhs_tyvars call_ts
861                       ]
862            dict_env = zipEqual "specUDs2" rhs_dicts call_ds
863         in
864         specUDs ty_env dict_env bound_uds                       `thenSM` \ spec_uds ->
865
866         returnSM ((spec_f, spec_rhs),
867                   spec_uds,
868                   spec_env_info
869         )
870 \end{code}
871
872 %************************************************************************
873 %*                                                                      *
874 \subsubsection{UsageDetails and suchlike}
875 %*                                                                      *
876 %************************************************************************
877
878 \begin{code}
879 type FreeDicts = IdSet
880
881 data UsageDetails 
882   = MkUD {
883         dict_binds :: !(Bag DictBind),
884                         -- Floated dictionary bindings
885                         -- The order is important; 
886                         -- in ds1 `union` ds2, bindings in ds2 can depend on those in ds1
887                         -- (Remember, Bags preserve order in GHC.)
888                         -- The FreeDicts is the free vars of the RHS
889
890         calls     :: !CallDetails
891     }
892
893 type DictBind = (DictVar, CoreExpr, TyVarSet, FreeDicts)
894                         -- The FreeDicts are the free dictionaries (only)
895                         -- of the RHS of the dictionary bindings
896                         -- Similarly the TyVarSet
897
898 emptyUDs = MkUD { dict_binds = emptyBag, calls = emptyFM }
899
900 type ProtoUsageDetails = ([DictBind],
901                           [(Id, [Maybe Type], [DictVar])]
902                          )
903
904 ------------------------------------------------------------                    
905 type CallDetails  = FiniteMap Id CallInfo
906 type CallInfo     = FiniteMap [Maybe Type]      -- Nothing => unconstrained type argument
907                               [DictVar]         -- Dict args
908         -- The finite maps eliminate duplicates
909         -- The list of types and dictionaries is guaranteed to
910         -- match the type of f
911
912 callDetailsToList calls = [ (id,tys,dicts)
913                           | (id,fm) <- fmToList calls,
914                             (tys,dicts) <- fmToList fm
915                           ]
916
917 listToCallDetails calls  = foldr (unionCalls . singleCall) emptyFM calls
918
919 unionCalls :: CallDetails -> CallDetails -> CallDetails
920 unionCalls c1 c2 = plusFM_C plusFM c1 c2
921
922 singleCall (id, tys, dicts) = unitFM id (unitFM tys dicts)
923
924 mkCallUDs f args 
925   | null theta
926   || length spec_tys /= n_tyvars
927   || length dicts    /= n_dicts
928   = emptyUDs    -- Not overloaded
929
930   | otherwise
931   = MkUD {dict_binds = emptyBag, 
932           calls = singleCall (f, spec_tys, dicts)
933     }
934   where
935     (tyvars, theta, tau) = splitSigmaTy (idType f)
936     constrained_tyvars   = foldr (unionTyVarSets . tyVarsOfTypes . snd) emptyTyVarSet theta 
937     n_tyvars             = length tyvars
938     n_dicts              = length theta
939
940     spec_tys = [mk_spec_ty tv ty | (tv, TyArg ty) <- tyvars `zip` args]
941     dicts    = [d | (_, VarArg d) <- theta `zip` (drop n_tyvars args)]
942     
943     mk_spec_ty tyvar ty | tyvar `elementOfTyVarSet` constrained_tyvars
944                         = Just ty
945                         | otherwise
946                         = Nothing
947
948 ------------------------------------------------------------                    
949 plusUDs :: UsageDetails -> UsageDetails -> UsageDetails
950 plusUDs (MkUD {dict_binds = db1, calls = calls1})
951         (MkUD {dict_binds = db2, calls = calls2})
952   = MkUD {dict_binds, calls}
953   where
954     dict_binds = db1    `unionBags`   db2 
955     calls      = calls1 `unionCalls`  calls2
956
957 plusUDList = foldr plusUDs emptyUDs
958
959 mkDB dict rhs = (dict, rhs, db_ftvs, db_fvs)
960               where
961                 db_ftvs = tyVarsOfType (idType dict)    -- Superset of RHS fvs
962                 db_fvs  = dictRhsFVs rhs
963
964 addDictBind uds dict rhs = uds { dict_binds = mkDB dict rhs `consBag` dict_binds uds }
965
966 dumpAllDictBinds (MkUD {dict_binds = dbs}) binds
967   = foldrBag add binds dbs
968   where
969     add (dict,rhs,_,_) binds = NonRec dict rhs : binds
970
971 mkDictBinds :: [DictBind] -> [CoreBinding]
972 mkDictBinds = map (\(d,r,_,_) -> NonRec d r)
973
974 mkDictLets :: [DictBind] -> CoreExpr -> CoreExpr
975 mkDictLets dbs body = foldr mk body dbs
976                     where
977                       mk (d,r,_,_) e = Let (NonRec d r) e 
978
979 dumpUDs :: [CoreBinder]
980         -> UsageDetails -> CoreExpr
981         -> (UsageDetails, CoreExpr)
982 dumpUDs bndrs uds body
983   = (free_uds, mkDictLets dict_binds body)
984   where
985     (free_uds, (dict_binds, _)) = splitUDs bndrs uds
986
987 splitUDs :: [CoreBinder]
988          -> UsageDetails
989          -> (UsageDetails,              -- These don't mention the binders
990              ProtoUsageDetails)         -- These do
991              
992 splitUDs bndrs uds@(MkUD {dict_binds = orig_dbs, 
993                           calls      = orig_calls})
994
995   = if isEmptyBag dump_dbs && null dump_calls then
996         -- Common case: binder doesn't affect floats
997         (uds, ([],[]))  
998
999     else
1000         -- Binders bind some of the fvs of the floats
1001         (MkUD {dict_binds = free_dbs, 
1002                calls      = listToCallDetails free_calls},
1003          (bagToList dump_dbs, dump_calls)
1004         )
1005
1006   where
1007     tyvar_set    = mkTyVarSet [tv | TyBinder tv <- bndrs]
1008     id_set       = mkIdSet    [id | ValBinder id <- bndrs]
1009
1010     (free_dbs, dump_dbs, dump_idset) 
1011           = foldlBag dump_db (emptyBag, emptyBag, id_set) orig_dbs
1012                 -- Important that it's foldl not foldr;
1013                 -- we're accumulating the set of dumped ids in dump_set
1014
1015         -- Filter out any calls that mention things that are being dumped
1016         -- Don't need to worry about the tyvars because the dicts will
1017         -- spot the captured ones; any fully polymorphic arguments will
1018         -- be Nothings in the call details
1019     orig_call_list = callDetailsToList orig_calls
1020     (dump_calls, free_calls) = partition captured orig_call_list
1021     captured (id,tys,dicts)  = any (`elementOfIdSet` dump_idset) (id:dicts)
1022
1023     dump_db (free_dbs, dump_dbs, dump_idset) db@(dict, rhs, ftvs, fvs)
1024         |  isEmptyIdSet    (dump_idset `intersectIdSets`    fvs)
1025         && isEmptyTyVarSet (tyvar_set  `intersectTyVarSets` ftvs)
1026         = (free_dbs `snocBag` db, dump_dbs, dump_idset)
1027
1028         | otherwise     -- Dump it
1029         = (free_dbs, dump_dbs `snocBag` db,
1030            dump_idset `addOneToIdSet` dict)
1031 \end{code}
1032
1033 Given a type and value substitution, specUDs creates a specialised copy of
1034 the given UDs
1035
1036 \begin{code}
1037 specUDs :: [(TyVar,Type)] -> [(DictVar,DictVar)] -> ProtoUsageDetails -> SpecM UsageDetails
1038 specUDs tv_env_list dict_env_list (dbs, calls)
1039   = specDBs dict_env_list dbs           `thenSM` \ (dict_env_list', dbs') ->
1040     let
1041         dict_env = mkIdEnv dict_env_list'
1042     in
1043     returnSM (MkUD { dict_binds = dbs',
1044                      calls      = listToCallDetails (map (inst_call dict_env) calls)
1045     })
1046   where
1047     bound_tyvars = mkTyVarSet (map fst tv_env_list)
1048     tv_env   = mkTyVarEnv tv_env_list   -- Doesn't change
1049
1050     inst_call dict_env (id, tys, dicts) = (id, map inst_maybe_ty tys, 
1051                                                map (lookupId dict_env) dicts)
1052
1053     inst_maybe_ty Nothing   = Nothing
1054     inst_maybe_ty (Just ty) = Just (instantiateTy tv_env ty)
1055
1056     specDBs dict_env []
1057         = returnSM (dict_env, emptyBag)
1058     specDBs dict_env ((dict, rhs, ftvs, fvs) : dbs)
1059         = newIdSM dict (instantiateTy tv_env (idType dict))     `thenSM` \ dict' ->
1060           let
1061             rhs'      = foldl App (foldr Lam rhs (t_bndrs ++ d_bndrs)) (t_args ++ d_args)
1062             (t_bndrs, t_args) = unzip [(TyBinder tv, TyArg ty)  | (tv,ty) <- tv_env_list,
1063                                                                    tv `elementOfTyVarSet` ftvs]
1064             (d_bndrs, d_args) = unzip [(ValBinder d, VarArg d') | (d,d')  <- dict_env,
1065                                                                    d `elementOfIdSet` fvs]
1066             dict_env' = (dict,dict') : dict_env
1067             ftvs' = tyVarsOfTypes [ty | TyArg ty <- t_args] `unionTyVarSets`
1068                     (ftvs `minusTyVarSet` bound_tyvars)
1069             fvs'  = mkIdSet [d | VarArg d <- d_args] `unionIdSets`
1070                     (fvs `minusIdSet` mkIdSet [d | ValBinder d <- d_bndrs])
1071           in
1072           specDBs dict_env' dbs         `thenSM` \ (dict_env'', dbs') ->
1073           returnSM ( dict_env'', (dict', rhs', ftvs', fvs') `consBag` dbs' )
1074 \end{code}
1075
1076 %************************************************************************
1077 %*                                                                      *
1078 \subsubsection{Boring helper functions}
1079 %*                                                                      *
1080 %************************************************************************
1081
1082 \begin{code}
1083 tyVarTemplates :: [TyVar]
1084 tyVarTemplates = map mk [1..]
1085   where
1086     mk i = mkTyVar (mkSysLocalName uniq occ noSrcLoc) mkBoxedTypeKind
1087          where
1088            uniq = mkAlphaTyVarUnique i
1089            occ  = _PK_ ("$t" ++ show i)
1090 \end{code}
1091
1092 \begin{code}
1093 lookupId:: IdEnv Id -> Id -> Id
1094 lookupId env id = case lookupIdEnv env id of
1095                         Nothing  -> id
1096                         Just id' -> id'
1097
1098 dictRhsFVs :: CoreExpr -> IdSet
1099         -- Cheapo function for simple RHSs
1100 dictRhsFVs e
1101   = go e
1102   where
1103     go (App e1 (VarArg a)) = go e1 `addOneToIdSet` a
1104     go (App e1 (LitArg l)) = go e1
1105     go (App e1 (TyArg t))  = go e1
1106     go (Var v)             = unitIdSet v
1107     go (Lit l)             = emptyIdSet
1108     go (Con _ args)        = mkIdSet [id | VarArg id <- args]
1109     go (Note _ e)          = go e
1110
1111     go (Case e _)          = go e       -- Claim: no free dictionaries in the alternatives
1112                                         -- These case expressions are of the form
1113                                         --   case d of { D a b c -> b }
1114
1115     go (Lam _ _)           = emptyIdSet -- This can happen for a Functor "dict",
1116                                         -- which is represented by the function
1117                                         -- itself; but it won't have any further
1118                                         -- dicts inside it.  I hope.
1119
1120     go other               = pprPanic "dictRhsFVs" (ppr e)
1121
1122
1123 addIdSpecialisations id spec_stuff
1124   = (if not (null errs) then
1125         pprTrace "Duplicate specialisations" (vcat (map ppr errs))
1126      else \x -> x
1127     )
1128     setIdSpecialisation id new_spec_env
1129   where
1130     (new_spec_env, errs) = foldr add (getIdSpecialisation id, []) spec_stuff
1131
1132     add (tyvars, tys, template) (spec_env, errs)
1133         = case addToSpecEnv True spec_env tyvars tys template of
1134                 Succeeded spec_env' -> (spec_env', errs)
1135                 Failed err          -> (spec_env, err:errs)
1136
1137 -- Given an Id, isSpecVars returns all its specialisations.
1138 -- We extract these from its SpecEnv.
1139 -- This is used by the occurrence analyser and free-var finder;
1140 -- we regard an Id's specialisations as free in the Id's definition.
1141
1142 idSpecVars :: Id -> [Id]
1143 idSpecVars id 
1144   = map get_spec (specEnvValues (getIdSpecialisation id))
1145   where
1146     -- get_spec is another cheapo function like dictRhsFVs
1147     -- It knows what these specialisation temlates look like,
1148     -- and just goes for the jugular
1149     get_spec (App f _) = get_spec f
1150     get_spec (Lam _ b) = get_spec b
1151     get_spec (Var v)   = v
1152
1153 ----------------------------------------
1154 type SpecM a = UniqSM a
1155
1156 thenSM    = thenUs
1157 returnSM  = returnUs
1158 getUniqSM = getUnique
1159 mapSM     = mapUs
1160 initSM    = initUs
1161
1162 mapAndCombineSM f []     = returnSM ([], emptyUDs)
1163 mapAndCombineSM f (x:xs) = f x  `thenSM` \ (y, uds1) ->
1164                            mapAndCombineSM f xs `thenSM` \ (ys, uds2) ->
1165                            returnSM (y:ys, uds1 `plusUDs` uds2)
1166
1167 newIdSM old_id new_ty
1168   = getUnique           `thenSM` \ uniq ->
1169     returnSM (mkUserLocal (getOccName old_id) 
1170                           uniq
1171                           new_ty
1172                           (getSrcLoc old_id)
1173     )
1174 \end{code}
1175
1176
1177                 Old (but interesting) stuff about unboxed bindings
1178                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1179
1180 What should we do when a value is specialised to a *strict* unboxed value?
1181
1182         map_*_* f (x:xs) = let h = f x
1183                                t = map f xs
1184                            in h:t
1185
1186 Could convert let to case:
1187
1188         map_*_Int# f (x:xs) = case f x of h# ->
1189                               let t = map f xs
1190                               in h#:t
1191
1192 This may be undesirable since it forces evaluation here, but the value
1193 may not be used in all branches of the body. In the general case this
1194 transformation is impossible since the mutual recursion in a letrec
1195 cannot be expressed as a case.
1196
1197 There is also a problem with top-level unboxed values, since our
1198 implementation cannot handle unboxed values at the top level.
1199
1200 Solution: Lift the binding of the unboxed value and extract it when it
1201 is used:
1202
1203         map_*_Int# f (x:xs) = let h = case (f x) of h# -> _Lift h#
1204                                   t = map f xs
1205                               in case h of
1206                                  _Lift h# -> h#:t
1207
1208 Now give it to the simplifier and the _Lifting will be optimised away.
1209
1210 The benfit is that we have given the specialised "unboxed" values a
1211 very simplep lifted semantics and then leave it up to the simplifier to
1212 optimise it --- knowing that the overheads will be removed in nearly
1213 all cases.
1214
1215 In particular, the value will only be evaluted in the branches of the
1216 program which use it, rather than being forced at the point where the
1217 value is bound. For example:
1218
1219         filtermap_*_* p f (x:xs)
1220           = let h = f x
1221                 t = ...
1222             in case p x of
1223                 True  -> h:t
1224                 False -> t
1225    ==>
1226         filtermap_*_Int# p f (x:xs)
1227           = let h = case (f x) of h# -> _Lift h#
1228                 t = ...
1229             in case p x of
1230                 True  -> case h of _Lift h#
1231                            -> h#:t
1232                 False -> t
1233
1234 The binding for h can still be inlined in the one branch and the
1235 _Lifting eliminated.
1236
1237
1238 Question: When won't the _Lifting be eliminated?
1239
1240 Answer: When they at the top-level (where it is necessary) or when
1241 inlining would duplicate work (or possibly code depending on
1242 options). However, the _Lifting will still be eliminated if the
1243 strictness analyser deems the lifted binding strict.
1244