Propagate scalar variables and tycons for vectorisation through 'HscTypes.VectInfo'.
[ghc-hetmet.git] / compiler / specialise / Specialise.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[Specialise]{Stamping out overloading, and (optionally) polymorphism}
5
6 \begin{code}
7 module Specialise ( specProgram ) where
8
9 #include "HsVersions.h"
10
11 import Id
12 import TcType
13 import CoreMonad
14 import CoreSubst 
15 import CoreUnfold
16 import VarSet
17 import VarEnv
18 import CoreSyn
19 import Rules
20 import CoreUtils        ( exprIsTrivial, applyTypeToArgs, mkPiTypes )
21 import CoreFVs          ( exprFreeVars, exprsFreeVars, idFreeVars )
22 import UniqSupply       ( UniqSM, initUs_, MonadUnique(..) )
23 import Name
24 import MkId             ( voidArgId, realWorldPrimId )
25 import Maybes           ( catMaybes, isJust )
26 import BasicTypes       
27 import HscTypes
28 import Bag
29 import Util
30 import Outputable
31 import FastString
32
33 import Data.Map (Map)
34 import qualified Data.Map as Map
35 import qualified FiniteMap as Map
36 \end{code}
37
38 %************************************************************************
39 %*                                                                      *
40 \subsection[notes-Specialise]{Implementation notes [SLPJ, Aug 18 1993]}
41 %*                                                                      *
42 %************************************************************************
43
44 These notes describe how we implement specialisation to eliminate
45 overloading.
46
47 The specialisation pass works on Core
48 syntax, complete with all the explicit dictionary application,
49 abstraction and construction as added by the type checker.  The
50 existing type checker remains largely as it is.
51
52 One important thought: the {\em types} passed to an overloaded
53 function, and the {\em dictionaries} passed are mutually redundant.
54 If the same function is applied to the same type(s) then it is sure to
55 be applied to the same dictionary(s)---or rather to the same {\em
56 values}.  (The arguments might look different but they will evaluate
57 to the same value.)
58
59 Second important thought: we know that we can make progress by
60 treating dictionary arguments as static and worth specialising on.  So
61 we can do without binding-time analysis, and instead specialise on
62 dictionary arguments and no others.
63
64 The basic idea
65 ~~~~~~~~~~~~~~
66 Suppose we have
67
68         let f = <f_rhs>
69         in <body>
70
71 and suppose f is overloaded.
72
73 STEP 1: CALL-INSTANCE COLLECTION
74
75 We traverse <body>, accumulating all applications of f to types and
76 dictionaries.
77
78 (Might there be partial applications, to just some of its types and
79 dictionaries?  In principle yes, but in practice the type checker only
80 builds applications of f to all its types and dictionaries, so partial
81 applications could only arise as a result of transformation, and even
82 then I think it's unlikely.  In any case, we simply don't accumulate such
83 partial applications.)
84
85
86 STEP 2: EQUIVALENCES
87
88 So now we have a collection of calls to f:
89         f t1 t2 d1 d2
90         f t3 t4 d3 d4
91         ...
92 Notice that f may take several type arguments.  To avoid ambiguity, we
93 say that f is called at type t1/t2 and t3/t4.
94
95 We take equivalence classes using equality of the *types* (ignoring
96 the dictionary args, which as mentioned previously are redundant).
97
98 STEP 3: SPECIALISATION
99
100 For each equivalence class, choose a representative (f t1 t2 d1 d2),
101 and create a local instance of f, defined thus:
102
103         f@t1/t2 = <f_rhs> t1 t2 d1 d2
104
105 f_rhs presumably has some big lambdas and dictionary lambdas, so lots
106 of simplification will now result.  However we don't actually *do* that
107 simplification.  Rather, we leave it for the simplifier to do.  If we
108 *did* do it, though, we'd get more call instances from the specialised
109 RHS.  We can work out what they are by instantiating the call-instance
110 set from f's RHS with the types t1, t2.
111
112 Add this new id to f's IdInfo, to record that f has a specialised version.
113
114 Before doing any of this, check that f's IdInfo doesn't already
115 tell us about an existing instance of f at the required type/s.
116 (This might happen if specialisation was applied more than once, or
117 it might arise from user SPECIALIZE pragmas.)
118
119 Recursion
120 ~~~~~~~~~
121 Wait a minute!  What if f is recursive?  Then we can't just plug in
122 its right-hand side, can we?
123
124 But it's ok.  The type checker *always* creates non-recursive definitions
125 for overloaded recursive functions.  For example:
126
127         f x = f (x+x)           -- Yes I know its silly
128
129 becomes
130
131         f a (d::Num a) = let p = +.sel a d
132                          in
133                          letrec fl (y::a) = fl (p y y)
134                          in
135                          fl
136
137 We still have recusion for non-overloaded functions which we
138 speciailise, but the recursive call should get specialised to the
139 same recursive version.
140
141
142 Polymorphism 1
143 ~~~~~~~~~~~~~~
144
145 All this is crystal clear when the function is applied to *constant
146 types*; that is, types which have no type variables inside.  But what if
147 it is applied to non-constant types?  Suppose we find a call of f at type
148 t1/t2.  There are two possibilities:
149
150 (a) The free type variables of t1, t2 are in scope at the definition point
151 of f.  In this case there's no problem, we proceed just as before.  A common
152 example is as follows.  Here's the Haskell:
153
154         g y = let f x = x+x
155               in f y + f y
156
157 After typechecking we have
158
159         g a (d::Num a) (y::a) = let f b (d'::Num b) (x::b) = +.sel b d' x x
160                                 in +.sel a d (f a d y) (f a d y)
161
162 Notice that the call to f is at type type "a"; a non-constant type.
163 Both calls to f are at the same type, so we can specialise to give:
164
165         g a (d::Num a) (y::a) = let f@a (x::a) = +.sel a d x x
166                                 in +.sel a d (f@a y) (f@a y)
167
168
169 (b) The other case is when the type variables in the instance types
170 are *not* in scope at the definition point of f.  The example we are
171 working with above is a good case.  There are two instances of (+.sel a d),
172 but "a" is not in scope at the definition of +.sel.  Can we do anything?
173 Yes, we can "common them up", a sort of limited common sub-expression deal.
174 This would give:
175
176         g a (d::Num a) (y::a) = let +.sel@a = +.sel a d
177                                     f@a (x::a) = +.sel@a x x
178                                 in +.sel@a (f@a y) (f@a y)
179
180 This can save work, and can't be spotted by the type checker, because
181 the two instances of +.sel weren't originally at the same type.
182
183 Further notes on (b)
184
185 * There are quite a few variations here.  For example, the defn of
186   +.sel could be floated ouside the \y, to attempt to gain laziness.
187   It certainly mustn't be floated outside the \d because the d has to
188   be in scope too.
189
190 * We don't want to inline f_rhs in this case, because
191 that will duplicate code.  Just commoning up the call is the point.
192
193 * Nothing gets added to +.sel's IdInfo.
194
195 * Don't bother unless the equivalence class has more than one item!
196
197 Not clear whether this is all worth it.  It is of course OK to
198 simply discard call-instances when passing a big lambda.
199
200 Polymorphism 2 -- Overloading
201 ~~~~~~~~~~~~~~
202 Consider a function whose most general type is
203
204         f :: forall a b. Ord a => [a] -> b -> b
205
206 There is really no point in making a version of g at Int/Int and another
207 at Int/Bool, because it's only instancing the type variable "a" which
208 buys us any efficiency. Since g is completely polymorphic in b there
209 ain't much point in making separate versions of g for the different
210 b types.
211
212 That suggests that we should identify which of g's type variables
213 are constrained (like "a") and which are unconstrained (like "b").
214 Then when taking equivalence classes in STEP 2, we ignore the type args
215 corresponding to unconstrained type variable.  In STEP 3 we make
216 polymorphic versions.  Thus:
217
218         f@t1/ = /\b -> <f_rhs> t1 b d1 d2
219
220 We do this.
221
222
223 Dictionary floating
224 ~~~~~~~~~~~~~~~~~~~
225 Consider this
226
227         f a (d::Num a) = let g = ...
228                          in
229                          ...(let d1::Ord a = Num.Ord.sel a d in g a d1)...
230
231 Here, g is only called at one type, but the dictionary isn't in scope at the
232 definition point for g.  Usually the type checker would build a
233 definition for d1 which enclosed g, but the transformation system
234 might have moved d1's defn inward.  Solution: float dictionary bindings
235 outwards along with call instances.
236
237 Consider
238
239         f x = let g p q = p==q
240                   h r s = (r+s, g r s)
241               in
242               h x x
243
244
245 Before specialisation, leaving out type abstractions we have
246
247         f df x = let g :: Eq a => a -> a -> Bool
248                      g dg p q = == dg p q
249                      h :: Num a => a -> a -> (a, Bool)
250                      h dh r s = let deq = eqFromNum dh
251                                 in (+ dh r s, g deq r s)
252               in
253               h df x x
254
255 After specialising h we get a specialised version of h, like this:
256
257                     h' r s = let deq = eqFromNum df
258                              in (+ df r s, g deq r s)
259
260 But we can't naively make an instance for g from this, because deq is not in scope
261 at the defn of g.  Instead, we have to float out the (new) defn of deq
262 to widen its scope.  Notice that this floating can't be done in advance -- it only
263 shows up when specialisation is done.
264
265 User SPECIALIZE pragmas
266 ~~~~~~~~~~~~~~~~~~~~~~~
267 Specialisation pragmas can be digested by the type checker, and implemented
268 by adding extra definitions along with that of f, in the same way as before
269
270         f@t1/t2 = <f_rhs> t1 t2 d1 d2
271
272 Indeed the pragmas *have* to be dealt with by the type checker, because
273 only it knows how to build the dictionaries d1 and d2!  For example
274
275         g :: Ord a => [a] -> [a]
276         {-# SPECIALIZE f :: [Tree Int] -> [Tree Int] #-}
277
278 Here, the specialised version of g is an application of g's rhs to the
279 Ord dictionary for (Tree Int), which only the type checker can conjure
280 up.  There might not even *be* one, if (Tree Int) is not an instance of
281 Ord!  (All the other specialision has suitable dictionaries to hand
282 from actual calls.)
283
284 Problem.  The type checker doesn't have to hand a convenient <f_rhs>, because
285 it is buried in a complex (as-yet-un-desugared) binding group.
286 Maybe we should say
287
288         f@t1/t2 = f* t1 t2 d1 d2
289
290 where f* is the Id f with an IdInfo which says "inline me regardless!".
291 Indeed all the specialisation could be done in this way.
292 That in turn means that the simplifier has to be prepared to inline absolutely
293 any in-scope let-bound thing.
294
295
296 Again, the pragma should permit polymorphism in unconstrained variables:
297
298         h :: Ord a => [a] -> b -> b
299         {-# SPECIALIZE h :: [Int] -> b -> b #-}
300
301 We *insist* that all overloaded type variables are specialised to ground types,
302 (and hence there can be no context inside a SPECIALIZE pragma).
303 We *permit* unconstrained type variables to be specialised to
304         - a ground type
305         - or left as a polymorphic type variable
306 but nothing in between.  So
307
308         {-# SPECIALIZE h :: [Int] -> [c] -> [c] #-}
309
310 is *illegal*.  (It can be handled, but it adds complication, and gains the
311 programmer nothing.)
312
313
314 SPECIALISING INSTANCE DECLARATIONS
315 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
316 Consider
317
318         instance Foo a => Foo [a] where
319                 ...
320         {-# SPECIALIZE instance Foo [Int] #-}
321
322 The original instance decl creates a dictionary-function
323 definition:
324
325         dfun.Foo.List :: forall a. Foo a -> Foo [a]
326
327 The SPECIALIZE pragma just makes a specialised copy, just as for
328 ordinary function definitions:
329
330         dfun.Foo.List@Int :: Foo [Int]
331         dfun.Foo.List@Int = dfun.Foo.List Int dFooInt
332
333 The information about what instance of the dfun exist gets added to
334 the dfun's IdInfo in the same way as a user-defined function too.
335
336
337 Automatic instance decl specialisation?
338 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
339 Can instance decls be specialised automatically?  It's tricky.
340 We could collect call-instance information for each dfun, but
341 then when we specialised their bodies we'd get new call-instances
342 for ordinary functions; and when we specialised their bodies, we might get
343 new call-instances of the dfuns, and so on.  This all arises because of
344 the unrestricted mutual recursion between instance decls and value decls.
345
346 Still, there's no actual problem; it just means that we may not do all
347 the specialisation we could theoretically do.
348
349 Furthermore, instance decls are usually exported and used non-locally,
350 so we'll want to compile enough to get those specialisations done.
351
352 Lastly, there's no such thing as a local instance decl, so we can
353 survive solely by spitting out *usage* information, and then reading that
354 back in as a pragma when next compiling the file.  So for now,
355 we only specialise instance decls in response to pragmas.
356
357
358 SPITTING OUT USAGE INFORMATION
359 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
360
361 To spit out usage information we need to traverse the code collecting
362 call-instance information for all imported (non-prelude?) functions
363 and data types. Then we equivalence-class it and spit it out.
364
365 This is done at the top-level when all the call instances which escape
366 must be for imported functions and data types.
367
368 *** Not currently done ***
369
370
371 Partial specialisation by pragmas
372 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
373 What about partial specialisation:
374
375         k :: (Ord a, Eq b) => [a] -> b -> b -> [a]
376         {-# SPECIALIZE k :: Eq b => [Int] -> b -> b -> [a] #-}
377
378 or even
379
380         {-# SPECIALIZE k :: Eq b => [Int] -> [b] -> [b] -> [a] #-}
381
382 Seems quite reasonable.  Similar things could be done with instance decls:
383
384         instance (Foo a, Foo b) => Foo (a,b) where
385                 ...
386         {-# SPECIALIZE instance Foo a => Foo (a,Int) #-}
387         {-# SPECIALIZE instance Foo b => Foo (Int,b) #-}
388
389 Ho hum.  Things are complex enough without this.  I pass.
390
391
392 Requirements for the simplifer
393 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
394 The simplifier has to be able to take advantage of the specialisation.
395
396 * When the simplifier finds an application of a polymorphic f, it looks in
397 f's IdInfo in case there is a suitable instance to call instead.  This converts
398
399         f t1 t2 d1 d2   ===>   f_t1_t2
400
401 Note that the dictionaries get eaten up too!
402
403 * Dictionary selection operations on constant dictionaries must be
404   short-circuited:
405
406         +.sel Int d     ===>  +Int
407
408 The obvious way to do this is in the same way as other specialised
409 calls: +.sel has inside it some IdInfo which tells that if it's applied
410 to the type Int then it should eat a dictionary and transform to +Int.
411
412 In short, dictionary selectors need IdInfo inside them for constant
413 methods.
414
415 * Exactly the same applies if a superclass dictionary is being
416   extracted:
417
418         Eq.sel Int d   ===>   dEqInt
419
420 * Something similar applies to dictionary construction too.  Suppose
421 dfun.Eq.List is the function taking a dictionary for (Eq a) to
422 one for (Eq [a]).  Then we want
423
424         dfun.Eq.List Int d      ===> dEq.List_Int
425
426 Where does the Eq [Int] dictionary come from?  It is built in
427 response to a SPECIALIZE pragma on the Eq [a] instance decl.
428
429 In short, dfun Ids need IdInfo with a specialisation for each
430 constant instance of their instance declaration.
431
432 All this uses a single mechanism: the SpecEnv inside an Id
433
434
435 What does the specialisation IdInfo look like?
436 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
437
438 The SpecEnv of an Id maps a list of types (the template) to an expression
439
440         [Type]  |->  Expr
441
442 For example, if f has this SpecInfo:
443
444         [Int, a]  ->  \d:Ord Int. f' a
445
446 it means that we can replace the call
447
448         f Int t  ===>  (\d. f' t)
449
450 This chucks one dictionary away and proceeds with the
451 specialised version of f, namely f'.
452
453
454 What can't be done this way?
455 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
456 There is no way, post-typechecker, to get a dictionary for (say)
457 Eq a from a dictionary for Eq [a].  So if we find
458
459         ==.sel [t] d
460
461 we can't transform to
462
463         eqList (==.sel t d')
464
465 where
466         eqList :: (a->a->Bool) -> [a] -> [a] -> Bool
467
468 Of course, we currently have no way to automatically derive
469 eqList, nor to connect it to the Eq [a] instance decl, but you
470 can imagine that it might somehow be possible.  Taking advantage
471 of this is permanently ruled out.
472
473 Still, this is no great hardship, because we intend to eliminate
474 overloading altogether anyway!
475
476 A note about non-tyvar dictionaries
477 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
478 Some Ids have types like
479
480         forall a,b,c. Eq a -> Ord [a] -> tau
481
482 This seems curious at first, because we usually only have dictionary
483 args whose types are of the form (C a) where a is a type variable.
484 But this doesn't hold for the functions arising from instance decls,
485 which sometimes get arguements with types of form (C (T a)) for some
486 type constructor T.
487
488 Should we specialise wrt this compound-type dictionary?  We used to say
489 "no", saying:
490         "This is a heuristic judgement, as indeed is the fact that we 
491         specialise wrt only dictionaries.  We choose *not* to specialise
492         wrt compound dictionaries because at the moment the only place
493         they show up is in instance decls, where they are simply plugged
494         into a returned dictionary.  So nothing is gained by specialising
495         wrt them."
496
497 But it is simpler and more uniform to specialise wrt these dicts too;
498 and in future GHC is likely to support full fledged type signatures 
499 like
500         f :: Eq [(a,b)] => ...
501
502
503 %************************************************************************
504 %*                                                                      *
505 \subsubsection{The new specialiser}
506 %*                                                                      *
507 %************************************************************************
508
509 Our basic game plan is this.  For let(rec) bound function
510         f :: (C a, D c) => (a,b,c,d) -> Bool
511
512 * Find any specialised calls of f, (f ts ds), where 
513   ts are the type arguments t1 .. t4, and
514   ds are the dictionary arguments d1 .. d2.
515
516 * Add a new definition for f1 (say):
517
518         f1 = /\ b d -> (..body of f..) t1 b t3 d d1 d2
519
520   Note that we abstract over the unconstrained type arguments.
521
522 * Add the mapping
523
524         [t1,b,t3,d]  |->  \d1 d2 -> f1 b d
525
526   to the specialisations of f.  This will be used by the
527   simplifier to replace calls 
528                 (f t1 t2 t3 t4) da db
529   by
530                 (\d1 d1 -> f1 t2 t4) da db
531
532   All the stuff about how many dictionaries to discard, and what types
533   to apply the specialised function to, are handled by the fact that the
534   SpecEnv contains a template for the result of the specialisation.
535
536 We don't build *partial* specialisations for f.  For example:
537
538   f :: Eq a => a -> a -> Bool
539   {-# SPECIALISE f :: (Eq b, Eq c) => (b,c) -> (b,c) -> Bool #-}
540
541 Here, little is gained by making a specialised copy of f.
542 There's a distinct danger that the specialised version would
543 first build a dictionary for (Eq b, Eq c), and then select the (==) 
544 method from it!  Even if it didn't, not a great deal is saved.
545
546 We do, however, generate polymorphic, but not overloaded, specialisations:
547
548   f :: Eq a => [a] -> b -> b -> b
549   {#- SPECIALISE f :: [Int] -> b -> b -> b #-}
550
551 Hence, the invariant is this: 
552
553         *** no specialised version is overloaded ***
554
555
556 %************************************************************************
557 %*                                                                      *
558 \subsubsection{The exported function}
559 %*                                                                      *
560 %************************************************************************
561
562 \begin{code}
563 specProgram :: ModGuts -> CoreM ModGuts
564 specProgram guts 
565   = do { hpt_rules <- getRuleBase
566        ; let local_rules = mg_rules guts
567              rule_base = extendRuleBaseList hpt_rules (mg_rules guts)
568
569              -- Specialise the bindings of this module
570        ; (binds', uds) <- runSpecM (go (mg_binds guts))
571
572              -- Specialise imported functions 
573        ; (new_rules, spec_binds) <- specImports emptyVarSet rule_base uds
574
575        ; let final_binds | null spec_binds = binds'
576                          | otherwise       = Rec (flattenBinds spec_binds) : binds'
577                    -- Note [Glom the bindings if imported functions are specialised]
578
579        ; return (guts { mg_binds = final_binds
580                       , mg_rules = new_rules ++ local_rules }) }
581   where
582         -- We need to start with a Subst that knows all the things
583         -- that are in scope, so that the substitution engine doesn't
584         -- accidentally re-use a unique that's already in use
585         -- Easiest thing is to do it all at once, as if all the top-level
586         -- decls were mutually recursive
587     top_subst = mkEmptySubst $ mkInScopeSet $ mkVarSet $ 
588                 bindersOfBinds $ mg_binds guts
589
590     go []           = return ([], emptyUDs)
591     go (bind:binds) = do (binds', uds) <- go binds
592                          (bind', uds') <- specBind top_subst bind uds
593                          return (bind' ++ binds', uds')
594
595 specImports :: VarSet           -- Don't specialise these ones
596                                 -- See Note [Avoiding recursive specialisation]
597             -> RuleBase         -- Rules from this module and the home package
598                                 -- (but not external packages, which can change)
599             -> UsageDetails     -- Calls for imported things, and floating bindings
600             -> CoreM ( [CoreRule]   -- New rules
601                      , [CoreBind] ) -- Specialised bindings and floating bindings
602 -- See Note [Specialise imported INLINABLE things]
603 specImports done rb uds
604   = do { let import_calls = varEnvElts (ud_calls uds)
605        ; (rules, spec_binds) <- go rb import_calls
606        ; return (rules, wrapDictBinds (ud_binds uds) spec_binds) }
607   where
608     go _ [] = return ([], [])
609     go rb (CIS fn calls_for_fn : other_calls)
610       = do { (rules1, spec_binds1) <- specImport done rb fn (Map.toList calls_for_fn)
611            ; (rules2, spec_binds2) <- go (extendRuleBaseList rb rules1) other_calls
612            ; return (rules1 ++ rules2, spec_binds1 ++ spec_binds2) }
613
614 specImport :: VarSet                -- Don't specialise these
615                                     -- See Note [Avoiding recursive specialisation]
616            -> RuleBase              -- Rules from this module
617            -> Id -> [CallInfo]      -- Imported function and calls for it
618            -> CoreM ( [CoreRule]    -- New rules
619                     , [CoreBind] )  -- Specialised bindings
620 specImport done rb fn calls_for_fn
621   | fn `elemVarSet` done
622   = return ([], [])     -- No warning.  This actually happens all the time
623                         -- when specialising a recursive function, becuase
624                         -- the RHS of the specialised function contains a recursive
625                         -- call to the original function
626
627   | isInlinablePragma (idInlinePragma fn)
628   , Just rhs <- maybeUnfoldingTemplate (realIdUnfolding fn)
629   = do {     -- Get rules from the external package state
630              -- We keep doing this in case we "page-fault in" 
631              -- more rules as we go along
632        ; hsc_env <- getHscEnv
633        ; eps <- liftIO $ hscEPS hsc_env 
634        ; let full_rb = unionRuleBase rb (eps_rule_base eps)
635              rules_for_fn = getRules full_rb fn 
636
637        ; (rules1, spec_pairs, uds) <- runSpecM $
638               specCalls emptySubst rules_for_fn calls_for_fn fn rhs
639        ; let spec_binds1 = [NonRec b r | (b,r) <- spec_pairs]
640              -- After the rules kick in we may get recursion, but 
641              -- we rely on a global GlomBinds to sort that out later
642              -- See Note [Glom the bindings if imported functions are specialised]
643        
644               -- Now specialise any cascaded calls
645        ; (rules2, spec_binds2) <- specImports (extendVarSet done fn) 
646                                               (extendRuleBaseList rb rules1)
647                                               uds
648
649        ; return (rules2 ++ rules1, spec_binds2 ++ spec_binds1) }
650
651   | otherwise
652   = WARN( True, ptext (sLit "specImport discard") <+> ppr fn <+> ppr calls_for_fn )
653     return ([], [])    
654 \end{code}
655
656 Note [Specialise imported INLINABLE things]
657 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
658 We specialise INLINABLE things but not INLINE things.  The latter
659 should be inlined bodily, so not much point in specialising them.
660 Moreover, we risk lots of orphan modules from vigorous specialisation.
661
662 Note [Glom the bindings if imported functions are specialised]
663 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
664 Suppose we have an imported, *recursive*, INLINABLE function 
665    f :: Eq a => a -> a
666    f = /\a \d x. ...(f a d)...
667 In the module being compiled we have
668    g x = f (x::Int)
669 Now we'll make a specialised function
670    f_spec :: Int -> Int
671    f_spec = \x -> ...(f Int dInt)...
672    {-# RULE  f Int _ = f_spec #-}
673    g = \x. f Int dInt x
674 Note that f_spec doesn't look recursive
675 After rewriting with the RULE, we get
676    f_spec = \x -> ...(f_spec)...
677 BUT since f_spec was non-recursive before it'll *stay* non-recursive.
678 The occurrence analyser never turns a NonRec into a Rec.  So we must
679 make sure that f_spec is recursive.  Easiest thing is to make all
680 the specialisations for imported bindings recursive.
681
682
683 Note [Avoiding recursive specialisation]
684 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
685 When we specialise 'f' we may find new overloaded calls to 'g', 'h' in
686 'f's RHS.  So we want to specialise g,h.  But we don't want to
687 specialise f any more!  It's possible that f's RHS might have a
688 recursive yet-more-specialised call, so we'd diverge in that case.
689 And if the call is to the same type, one specialisation is enough.
690 Avoiding this recursive specialisation loop is the reason for the 
691 'done' VarSet passed to specImports and specImport.
692
693 %************************************************************************
694 %*                                                                      *
695 \subsubsection{@specExpr@: the main function}
696 %*                                                                      *
697 %************************************************************************
698
699 \begin{code}
700 specVar :: Subst -> Id -> CoreExpr
701 specVar subst v = lookupIdSubst (text "specVar") subst v
702
703 specExpr :: Subst -> CoreExpr -> SpecM (CoreExpr, UsageDetails)
704 -- We carry a substitution down:
705 --      a) we must clone any binding that might float outwards,
706 --         to avoid name clashes
707 --      b) we carry a type substitution to use when analysing
708 --         the RHS of specialised bindings (no type-let!)
709
710 ---------------- First the easy cases --------------------
711 specExpr subst (Type ty) = return (Type (CoreSubst.substTy subst ty), emptyUDs)
712 specExpr subst (Coercion co) = return (Coercion (CoreSubst.substCo subst co), emptyUDs)
713 specExpr subst (Var v)   = return (specVar subst v,         emptyUDs)
714 specExpr _     (Lit lit) = return (Lit lit,                 emptyUDs)
715 specExpr subst (Cast e co) = do
716     (e', uds) <- specExpr subst e
717     return ((Cast e' (CoreSubst.substCo subst co)), uds)
718 specExpr subst (Note note body) = do
719     (body', uds) <- specExpr subst body
720     return (Note (specNote subst note) body', uds)
721
722
723 ---------------- Applications might generate a call instance --------------------
724 specExpr subst expr@(App {})
725   = go expr []
726   where
727     go (App fun arg) args = do (arg', uds_arg) <- specExpr subst arg
728                                (fun', uds_app) <- go fun (arg':args)
729                                return (App fun' arg', uds_arg `plusUDs` uds_app)
730
731     go (Var f)       args = case specVar subst f of
732                                 Var f' -> return (Var f', mkCallUDs f' args)
733                                 e'     -> return (e', emptyUDs) -- I don't expect this!
734     go other         _    = specExpr subst other
735
736 ---------------- Lambda/case require dumping of usage details --------------------
737 specExpr subst e@(Lam _ _) = do
738     (body', uds) <- specExpr subst' body
739     let (free_uds, dumped_dbs) = dumpUDs bndrs' uds 
740     return (mkLams bndrs' (wrapDictBindsE dumped_dbs body'), free_uds)
741   where
742     (bndrs, body) = collectBinders e
743     (subst', bndrs') = substBndrs subst bndrs
744         -- More efficient to collect a group of binders together all at once
745         -- and we don't want to split a lambda group with dumped bindings
746
747 specExpr subst (Case scrut case_bndr ty alts) 
748   = do { (scrut', scrut_uds) <- specExpr subst scrut
749        ; (scrut'', case_bndr', alts', alts_uds) 
750              <- specCase subst scrut' case_bndr alts 
751        ; return (Case scrut'' case_bndr' (CoreSubst.substTy subst ty) alts'
752                 , scrut_uds `plusUDs` alts_uds) }
753
754 ---------------- Finally, let is the interesting case --------------------
755 specExpr subst (Let bind body) = do
756         -- Clone binders
757     (rhs_subst, body_subst, bind') <- cloneBindSM subst bind
758
759         -- Deal with the body
760     (body', body_uds) <- specExpr body_subst body
761
762         -- Deal with the bindings
763     (binds', uds) <- specBind rhs_subst bind' body_uds
764
765         -- All done
766     return (foldr Let body' binds', uds)
767
768 -- Must apply the type substitution to coerceions
769 specNote :: Subst -> Note -> Note
770 specNote _ note = note
771
772
773 specCase :: Subst 
774          -> CoreExpr            -- Scrutinee, already done
775          -> Id -> [CoreAlt]
776          -> SpecM ( CoreExpr    -- New scrutinee
777                   , Id
778                   , [CoreAlt]
779                   , UsageDetails)
780 specCase subst scrut' case_bndr [(con, args, rhs)]
781   | isDictId case_bndr           -- See Note [Floating dictionaries out of cases]
782   , interestingDict scrut'
783   , not (isDeadBinder case_bndr && null sc_args')
784   = do { (case_bndr_flt : sc_args_flt) <- mapM clone_me (case_bndr' : sc_args')
785
786        ; let sc_rhss = [ Case (Var case_bndr_flt) case_bndr' (idType sc_arg')
787                               [(con, args', Var sc_arg')]
788                        | sc_arg' <- sc_args' ]
789
790              -- Extend the substitution for RHS to map the *original* binders
791              -- to their floated verions.  Attach an unfolding to these floated
792              -- binders so they look interesting to interestingDict
793              mb_sc_flts :: [Maybe DictId]
794              mb_sc_flts = map (lookupVarEnv clone_env) args'
795              clone_env  = zipVarEnv sc_args' (zipWith add_unf sc_args_flt sc_rhss)
796              subst_prs  = (case_bndr, Var (add_unf case_bndr_flt scrut'))
797                         : [ (arg, Var sc_flt) 
798                           | (arg, Just sc_flt) <- args `zip` mb_sc_flts ]
799              subst_rhs' = extendIdSubstList subst_rhs subst_prs
800                                                       
801        ; (rhs',   rhs_uds)   <- specExpr subst_rhs' rhs
802        ; let scrut_bind    = mkDB (NonRec case_bndr_flt scrut')
803              case_bndr_set = unitVarSet case_bndr_flt
804              sc_binds      = [(NonRec sc_arg_flt sc_rhs, case_bndr_set)
805                              | (sc_arg_flt, sc_rhs) <- sc_args_flt `zip` sc_rhss ]
806              flt_binds     = scrut_bind : sc_binds
807              (free_uds, dumped_dbs) = dumpUDs (case_bndr':args') rhs_uds
808              all_uds = flt_binds `addDictBinds` free_uds
809              alt'    = (con, args', wrapDictBindsE dumped_dbs rhs')
810        ; return (Var case_bndr_flt, case_bndr', [alt'], all_uds) }
811   where
812     (subst_rhs, (case_bndr':args')) = substBndrs subst (case_bndr:args)
813     sc_args' = filter is_flt_sc_arg args'
814              
815     clone_me bndr = do { uniq <- getUniqueM
816                        ; return (mkUserLocal occ uniq ty loc) }
817        where
818          name = idName bndr
819          ty   = idType bndr
820          occ  = nameOccName name
821          loc  = getSrcSpan name
822
823     add_unf sc_flt sc_rhs  -- Sole purpose: make sc_flt respond True to interestingDictId
824       = setIdUnfolding sc_flt (mkSimpleUnfolding sc_rhs)
825
826     arg_set = mkVarSet args'
827     is_flt_sc_arg var =  isId var
828                       && not (isDeadBinder var)
829                       && isDictTy var_ty
830                       && not (tyVarsOfType var_ty `intersectsVarSet` arg_set)
831        where
832          var_ty = idType var
833
834
835 specCase subst scrut case_bndr alts
836   = do { (alts', uds_alts) <- mapAndCombineSM spec_alt alts
837        ; return (scrut, case_bndr', alts', uds_alts) }
838   where
839     (subst_alt, case_bndr') = substBndr subst case_bndr
840     spec_alt (con, args, rhs) = do
841           (rhs', uds) <- specExpr subst_rhs rhs
842           let (free_uds, dumped_dbs) = dumpUDs (case_bndr' : args') uds
843           return ((con, args', wrapDictBindsE dumped_dbs rhs'), free_uds)
844         where
845           (subst_rhs, args') = substBndrs subst_alt args
846 \end{code}
847
848 Note [Floating dictionaries out of cases]
849 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
850 Consider
851    g = \d. case d of { MkD sc ... -> ...(f sc)... }
852 Naively we can't float d2's binding out of the case expression,
853 because 'sc' is bound by the case, and that in turn means we can't
854 specialise f, which seems a pity.  
855
856 So we invert the case, by floating out a binding 
857 for 'sc_flt' thus:
858     sc_flt = case d of { MkD sc ... -> sc }
859 Now we can float the call instance for 'f'.  Indeed this is just
860 what'll happen if 'sc' was originally bound with a let binding,
861 but case is more efficient, and necessary with equalities. So it's
862 good to work with both.
863
864 You might think that this won't make any difference, because the
865 call instance will only get nuked by the \d.  BUT if 'g' itself is 
866 specialised, then transitively we should be able to specialise f.
867
868 In general, given
869    case e of cb { MkD sc ... -> ...(f sc)... }
870 we transform to
871    let cb_flt = e
872        sc_flt = case cb_flt of { MkD sc ... -> sc }
873    in
874    case cb_flt of bg { MkD sc ... -> ....(f sc_flt)... }
875
876 The "_flt" things are the floated binds; we use the current substitution
877 to substitute sc -> sc_flt in the RHS
878
879 %************************************************************************
880 %*                                                                      *
881                      Dealing with a binding
882 %*                                                                      *
883 %************************************************************************
884
885 \begin{code}
886 specBind :: Subst                       -- Use this for RHSs
887          -> CoreBind
888          -> UsageDetails                -- Info on how the scope of the binding
889          -> SpecM ([CoreBind],          -- New bindings
890                    UsageDetails)        -- And info to pass upstream
891
892 -- Returned UsageDetails:
893 --    No calls for binders of this bind
894 specBind rhs_subst (NonRec fn rhs) body_uds
895   = do { (rhs', rhs_uds) <- specExpr rhs_subst rhs
896        ; (fn', spec_defns, body_uds1) <- specDefn rhs_subst body_uds fn rhs
897
898        ; let pairs = spec_defns ++ [(fn', rhs')]
899                         -- fn' mentions the spec_defns in its rules, 
900                         -- so put the latter first
901
902              combined_uds = body_uds1 `plusUDs` rhs_uds
903                 -- This way round a call in rhs_uds of a function f
904                 -- at type T will override a call of f at T in body_uds1; and
905                 -- that is good because it'll tend to keep "earlier" calls
906                 -- See Note [Specialisation of dictionary functions]
907
908              (free_uds, dump_dbs, float_all) = dumpBindUDs [fn] combined_uds
909                 -- See Note [From non-recursive to recursive]
910
911              final_binds | isEmptyBag dump_dbs = [NonRec b r | (b,r) <- pairs]
912                          | otherwise = [Rec (flattenDictBinds dump_dbs pairs)]
913
914          ; if float_all then
915              -- Rather than discard the calls mentioning the bound variables
916              -- we float this binding along with the others
917               return ([], free_uds `snocDictBinds` final_binds)
918            else
919              -- No call in final_uds mentions bound variables, 
920              -- so we can just leave the binding here
921               return (final_binds, free_uds) }
922
923
924 specBind rhs_subst (Rec pairs) body_uds
925        -- Note [Specialising a recursive group]
926   = do { let (bndrs,rhss) = unzip pairs
927        ; (rhss', rhs_uds) <- mapAndCombineSM (specExpr rhs_subst) rhss
928        ; let scope_uds = body_uds `plusUDs` rhs_uds
929                        -- Includes binds and calls arising from rhss
930
931        ; (bndrs1, spec_defns1, uds1) <- specDefns rhs_subst scope_uds pairs
932
933        ; (bndrs3, spec_defns3, uds3)
934              <- if null spec_defns1  -- Common case: no specialisation
935                 then return (bndrs1, [], uds1)
936                 else do {            -- Specialisation occurred; do it again
937                           (bndrs2, spec_defns2, uds2)
938                               <- specDefns rhs_subst uds1 (bndrs1 `zip` rhss)
939                         ; return (bndrs2, spec_defns2 ++ spec_defns1, uds2) }
940
941        ; let (final_uds, dumped_dbs, float_all) = dumpBindUDs bndrs uds3
942              bind = Rec (flattenDictBinds dumped_dbs $
943                          spec_defns3 ++ zip bndrs3 rhss')
944              
945        ; if float_all then
946               return ([], final_uds `snocDictBind` bind)
947            else
948               return ([bind], final_uds) }
949
950
951 ---------------------------
952 specDefns :: Subst
953           -> UsageDetails               -- Info on how it is used in its scope
954           -> [(Id,CoreExpr)]            -- The things being bound and their un-processed RHS
955           -> SpecM ([Id],               -- Original Ids with RULES added
956                     [(Id,CoreExpr)],    -- Extra, specialised bindings
957                     UsageDetails)       -- Stuff to fling upwards from the specialised versions
958
959 -- Specialise a list of bindings (the contents of a Rec), but flowing usages
960 -- upwards binding by binding.  Example: { f = ...g ...; g = ...f .... }
961 -- Then if the input CallDetails has a specialised call for 'g', whose specialisation
962 -- in turn generates a specialised call for 'f', we catch that in this one sweep.
963 -- But not vice versa (it's a fixpoint problem).
964
965 specDefns _subst uds []
966   = return ([], [], uds)
967 specDefns subst uds ((bndr,rhs):pairs)
968   = do { (bndrs1, spec_defns1, uds1) <- specDefns subst uds pairs
969        ; (bndr1, spec_defns2, uds2)  <- specDefn subst uds1 bndr rhs
970        ; return (bndr1 : bndrs1, spec_defns1 ++ spec_defns2, uds2) }
971
972 ---------------------------
973 specDefn :: Subst
974          -> UsageDetails                -- Info on how it is used in its scope
975          -> Id -> CoreExpr              -- The thing being bound and its un-processed RHS
976          -> SpecM (Id,                  -- Original Id with added RULES
977                    [(Id,CoreExpr)],     -- Extra, specialised bindings
978                    UsageDetails)        -- Stuff to fling upwards from the specialised versions
979
980 specDefn subst body_uds fn rhs
981   = do { let (body_uds_without_me, calls_for_me) = callsForMe fn body_uds
982              rules_for_me = idCoreRules fn
983        ; (rules, spec_defns, spec_uds) <- specCalls subst rules_for_me 
984                                                     calls_for_me fn rhs
985        ; return ( fn `addIdSpecialisations` rules
986                 , spec_defns
987                 , body_uds_without_me `plusUDs` spec_uds) }
988                 -- It's important that the `plusUDs` is this way
989                 -- round, because body_uds_without_me may bind
990                 -- dictionaries that are used in calls_for_me passed
991                 -- to specDefn.  So the dictionary bindings in
992                 -- spec_uds may mention dictionaries bound in
993                 -- body_uds_without_me
994
995 ---------------------------
996 specCalls :: Subst
997           -> [CoreRule]                 -- Existing RULES for the fn
998           -> [CallInfo] 
999           -> Id -> CoreExpr
1000           -> SpecM ([CoreRule],         -- New RULES for the fn
1001                     [(Id,CoreExpr)],    -- Extra, specialised bindings
1002                     UsageDetails)       -- New usage details from the specialised RHSs
1003
1004 -- This function checks existing rules, and does not create
1005 -- duplicate ones. So the caller does not need to do this filtering.
1006 -- See 'already_covered'
1007
1008 specCalls subst rules_for_me calls_for_me fn rhs
1009         -- The first case is the interesting one
1010   |  rhs_tyvars `lengthIs`     n_tyvars -- Rhs of fn's defn has right number of big lambdas
1011   && rhs_ids    `lengthAtLeast` n_dicts -- and enough dict args
1012   && notNull calls_for_me               -- And there are some calls to specialise
1013   && not (isNeverActive (idInlineActivation fn))
1014         -- Don't specialise NOINLINE things
1015         -- See Note [Auto-specialisation and RULES]
1016
1017 --   && not (certainlyWillInline (idUnfolding fn))      -- And it's not small
1018 --      See Note [Inline specialisation] for why we do not 
1019 --      switch off specialisation for inline functions
1020
1021   = -- pprTrace "specDefn: some" (ppr fn $$ ppr calls_for_me $$ ppr rules_for_me) $
1022     do { stuff <- mapM spec_call calls_for_me
1023        ; let (spec_defns, spec_uds, spec_rules) = unzip3 (catMaybes stuff)
1024        ; return (spec_rules, spec_defns, plusUDList spec_uds) }
1025
1026   | otherwise   -- No calls or RHS doesn't fit our preconceptions
1027   = WARN( notNull calls_for_me, ptext (sLit "Missed specialisation opportunity for") 
1028                                  <+> ppr fn $$ _trace_doc )
1029           -- Note [Specialisation shape]
1030     -- pprTrace "specDefn: none" (ppr fn $$ ppr calls_for_me) $
1031     return ([], [], emptyUDs)
1032   where
1033     _trace_doc = vcat [ ppr rhs_tyvars, ppr n_tyvars
1034                       , ppr rhs_ids, ppr n_dicts
1035                       , ppr (idInlineActivation fn) ]
1036
1037     fn_type            = idType fn
1038     fn_arity           = idArity fn
1039     fn_unf             = realIdUnfolding fn     -- Ignore loop-breaker-ness here
1040     (tyvars, theta, _) = tcSplitSigmaTy fn_type
1041     n_tyvars           = length tyvars
1042     n_dicts            = length theta
1043     inl_prag           = idInlinePragma fn
1044     inl_act            = inlinePragmaActivation inl_prag
1045     is_local           = isLocalId fn
1046
1047         -- Figure out whether the function has an INLINE pragma
1048         -- See Note [Inline specialisations]
1049
1050     spec_arity = unfoldingArity fn_unf - n_dicts  -- Arity of the *specialised* inline rule
1051
1052     (rhs_tyvars, rhs_ids, rhs_body) = collectTyAndValBinders rhs
1053
1054     rhs_dict_ids = take n_dicts rhs_ids
1055     body         = mkLams (drop n_dicts rhs_ids) rhs_body
1056                 -- Glue back on the non-dict lambdas
1057
1058     already_covered :: [CoreExpr] -> Bool
1059     already_covered args          -- Note [Specialisations already covered]
1060        = isJust (lookupRule (const True) realIdUnfolding 
1061                             (substInScope subst) 
1062                             fn args rules_for_me)
1063
1064     mk_ty_args :: [Maybe Type] -> [CoreExpr]
1065     mk_ty_args call_ts = zipWithEqual "spec_call" mk_ty_arg rhs_tyvars call_ts
1066                where
1067                   mk_ty_arg rhs_tyvar Nothing   = Type (mkTyVarTy rhs_tyvar)
1068                   mk_ty_arg _         (Just ty) = Type ty
1069
1070     ----------------------------------------------------------
1071         -- Specialise to one particular call pattern
1072     spec_call :: CallInfo                         -- Call instance
1073               -> SpecM (Maybe ((Id,CoreExpr),     -- Specialised definition
1074                                UsageDetails,      -- Usage details from specialised body
1075                                CoreRule))         -- Info for the Id's SpecEnv
1076     spec_call (CallKey call_ts, (call_ds, _))
1077       = ASSERT( call_ts `lengthIs` n_tyvars  && call_ds `lengthIs` n_dicts )
1078         
1079         -- Suppose f's defn is  f = /\ a b c -> \ d1 d2 -> rhs  
1080         -- Supppose the call is for f [Just t1, Nothing, Just t3] [dx1, dx2]
1081
1082         -- Construct the new binding
1083         --      f1 = SUBST[a->t1,c->t3, d1->d1', d2->d2'] (/\ b -> rhs)
1084         -- PLUS the usage-details
1085         --      { d1' = dx1; d2' = dx2 }
1086         -- where d1', d2' are cloned versions of d1,d2, with the type substitution
1087         -- applied.  These auxiliary bindings just avoid duplication of dx1, dx2
1088         --
1089         -- Note that the substitution is applied to the whole thing.
1090         -- This is convenient, but just slightly fragile.  Notably:
1091         --      * There had better be no name clashes in a/b/c
1092         do { let
1093                 -- poly_tyvars = [b] in the example above
1094                 -- spec_tyvars = [a,c] 
1095                 -- ty_args     = [t1,b,t3]
1096                 poly_tyvars   = [tv | (tv, Nothing) <- rhs_tyvars `zip` call_ts]
1097                 spec_tv_binds = [(tv,ty) | (tv, Just ty) <- rhs_tyvars `zip` call_ts]
1098                 spec_ty_args  = map snd spec_tv_binds
1099                 ty_args       = mk_ty_args call_ts
1100                 rhs_subst     = CoreSubst.extendTvSubstList subst spec_tv_binds
1101
1102            ; (rhs_subst1, inst_dict_ids) <- newDictBndrs rhs_subst rhs_dict_ids
1103                           -- Clone rhs_dicts, including instantiating their types
1104
1105            ; let (rhs_subst2, dx_binds) = bindAuxiliaryDicts rhs_subst1 $
1106                                           (my_zipEqual rhs_dict_ids inst_dict_ids call_ds)
1107                  inst_args = ty_args ++ map Var inst_dict_ids
1108
1109            ; if already_covered inst_args then
1110                 return Nothing
1111              else do
1112            {    -- Figure out the type of the specialised function
1113              let body_ty = applyTypeToArgs rhs fn_type inst_args
1114                  (lam_args, app_args)           -- Add a dummy argument if body_ty is unlifted
1115                    | isUnLiftedType body_ty     -- C.f. WwLib.mkWorkerArgs
1116                    = (poly_tyvars ++ [voidArgId], poly_tyvars ++ [realWorldPrimId])
1117                    | otherwise = (poly_tyvars, poly_tyvars)
1118                  spec_id_ty = mkPiTypes lam_args body_ty
1119         
1120            ; spec_f <- newSpecIdSM fn spec_id_ty
1121            ; (spec_rhs, rhs_uds) <- specExpr rhs_subst2 (mkLams lam_args body)
1122            ; let
1123                 -- The rule to put in the function's specialisation is:
1124                 --      forall b, d1',d2'.  f t1 b t3 d1' d2' = f1 b  
1125                 rule_name = mkFastString ("SPEC " ++ showSDoc (ppr fn <+> ppr spec_ty_args))
1126                 spec_env_rule = mkRule True {- Auto generated -} is_local
1127                                   rule_name
1128                                   inl_act       -- Note [Auto-specialisation and RULES]
1129                                   (idName fn)
1130                                   (poly_tyvars ++ inst_dict_ids)
1131                                   inst_args 
1132                                   (mkVarApps (Var spec_f) app_args)
1133
1134                 -- Add the { d1' = dx1; d2' = dx2 } usage stuff
1135                 final_uds = foldr consDictBind rhs_uds dx_binds
1136
1137                 --------------------------------------
1138                 -- Add a suitable unfolding if the spec_inl_prag says so
1139                 -- See Note [Inline specialisations]
1140                 spec_inl_prag 
1141                   = case inl_prag of
1142                        InlinePragma { inl_inline = Inlinable } 
1143                           -> inl_prag { inl_inline = EmptyInlineSpec }
1144                        _  -> inl_prag
1145
1146                 spec_unf
1147                   = case inlinePragmaSpec spec_inl_prag of
1148                       Inline    -> mkInlineUnfolding (Just spec_arity) spec_rhs
1149                       Inlinable -> mkInlinableUnfolding spec_rhs
1150                       _         -> NoUnfolding
1151
1152                 --------------------------------------
1153                 -- Adding arity information just propagates it a bit faster
1154                 --      See Note [Arity decrease] in Simplify
1155                 -- Copy InlinePragma information from the parent Id.
1156                 -- So if f has INLINE[1] so does spec_f
1157                 spec_f_w_arity = spec_f `setIdArity`      max 0 (fn_arity - n_dicts)
1158                                         `setInlinePragma` spec_inl_prag
1159                                         `setIdUnfolding`  spec_unf
1160
1161            ; return (Just ((spec_f_w_arity, spec_rhs), final_uds, spec_env_rule)) } }
1162       where
1163         my_zipEqual xs ys zs
1164          | debugIsOn && not (equalLength xs ys && equalLength ys zs)
1165              = pprPanic "my_zipEqual" (vcat [ ppr xs, ppr ys
1166                                             , ppr fn <+> ppr call_ts
1167                                             , ppr (idType fn), ppr theta
1168                                             , ppr n_dicts, ppr rhs_dict_ids 
1169                                             , ppr rhs])
1170          | otherwise = zip3 xs ys zs
1171
1172 bindAuxiliaryDicts
1173         :: Subst
1174         -> [(DictId,DictId,CoreExpr)]   -- (orig_dict, inst_dict, dx)
1175         -> (Subst,                      -- Substitute for all orig_dicts
1176             [CoreBind])                 -- Auxiliary bindings
1177 -- Bind any dictionary arguments to fresh names, to preserve sharing
1178 -- Substitution already substitutes orig_dict -> inst_dict
1179 bindAuxiliaryDicts subst triples = go subst [] triples
1180   where
1181     go subst binds []    = (subst, binds)
1182     go subst binds ((d, dx_id, dx) : pairs)
1183       | exprIsTrivial dx = go (extendIdSubst subst d dx) binds pairs
1184              -- No auxiliary binding necessary
1185              -- Note that we bind the *original* dict in the substitution,
1186              -- overriding any d->dx_id binding put there by substBndrs
1187
1188       | otherwise        = go subst_w_unf (NonRec dx_id dx : binds) pairs
1189       where
1190         dx_id1 = dx_id `setIdUnfolding` mkSimpleUnfolding dx
1191         subst_w_unf = extendIdSubst subst d (Var dx_id1)
1192              -- Important!  We're going to substitute dx_id1 for d
1193              -- and we want it to look "interesting", else we won't gather *any*
1194              -- consequential calls. E.g.
1195              --     f d = ...g d....
1196              -- If we specialise f for a call (f (dfun dNumInt)), we'll get 
1197              -- a consequent call (g d') with an auxiliary definition
1198              --     d' = df dNumInt
1199              -- We want that consequent call to look interesting
1200              --
1201              -- Again, note that we bind the *original* dict in the substitution,
1202              -- overriding any d->dx_id binding put there by substBndrs
1203 \end{code}
1204
1205 Note [From non-recursive to recursive]
1206 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1207 Even in the non-recursive case, if any dict-binds depend on 'fn' we might 
1208 have built a recursive knot
1209
1210       f a d x = <blah>
1211       MkUD { ud_binds = d7 = MkD ..f..
1212            , ud_calls = ...(f T d7)... }
1213
1214 The we generate
1215
1216       Rec { fs x = <blah>[T/a, d7/d]
1217             f a d x = <blah>
1218                RULE f T _ = fs
1219             d7 = ...f... }
1220
1221 Here the recursion is only through the RULE.
1222
1223  
1224 Note [Specialisation of dictionary functions]
1225 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1226 Here is a nasty example that bit us badly: see Trac #3591
1227
1228      class Eq a => C a
1229      instance Eq [a] => C [a]
1230
1231 ---------------
1232      dfun :: Eq [a] -> C [a]
1233      dfun a d = MkD a d (meth d)
1234
1235      d4 :: Eq [T] = <blah>
1236      d2 ::  C [T] = dfun T d4
1237      d1 :: Eq [T] = $p1 d2
1238      d3 ::  C [T] = dfun T d1
1239
1240 None of these definitions is recursive. What happened was that we 
1241 generated a specialisation:
1242
1243      RULE forall d. dfun T d = dT  :: C [T]
1244      dT = (MkD a d (meth d)) [T/a, d1/d]
1245         = MkD T d1 (meth d1)
1246
1247 But now we use the RULE on the RHS of d2, to get
1248
1249     d2 = dT = MkD d1 (meth d1)
1250     d1 = $p1 d2
1251
1252 and now d1 is bottom!  The problem is that when specialising 'dfun' we
1253 should first dump "below" the binding all floated dictionary bindings
1254 that mention 'dfun' itself.  So d2 and d3 (and hence d1) must be
1255 placed below 'dfun', and thus unavailable to it when specialising
1256 'dfun'.  That in turn means that the call (dfun T d1) must be
1257 discarded.  On the other hand, the call (dfun T d4) is fine, assuming
1258 d4 doesn't mention dfun.
1259
1260 But look at this:
1261
1262   class C a where { foo,bar :: [a] -> [a] }
1263
1264   instance C Int where 
1265      foo x = r_bar x    
1266      bar xs = reverse xs
1267
1268   r_bar :: C a => [a] -> [a]
1269   r_bar xs = bar (xs ++ xs)
1270
1271 That translates to:
1272
1273     r_bar a (c::C a) (xs::[a]) = bar a d (xs ++ xs)
1274
1275     Rec { $fCInt :: C Int = MkC foo_help reverse
1276           foo_help (xs::[Int]) = r_bar Int $fCInt xs }
1277
1278 The call (r_bar $fCInt) mentions $fCInt, 
1279                         which mentions foo_help, 
1280                         which mentions r_bar
1281 But we DO want to specialise r_bar at Int:
1282
1283     Rec { $fCInt :: C Int = MkC foo_help reverse
1284           foo_help (xs::[Int]) = r_bar Int $fCInt xs
1285
1286           r_bar a (c::C a) (xs::[a]) = bar a d (xs ++ xs)
1287             RULE r_bar Int _ = r_bar_Int
1288
1289           r_bar_Int xs = bar Int $fCInt (xs ++ xs)
1290            }
1291    
1292 Note that, because of its RULE, r_bar joins the recursive
1293 group.  (In this case it'll unravel a short moment later.)
1294
1295
1296 Conclusion: we catch the nasty case using filter_dfuns in
1297 callsForMe. To be honest I'm not 100% certain that this is 100%
1298 right, but it works.  Sigh.
1299
1300
1301 Note [Specialising a recursive group]
1302 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1303 Consider
1304     let rec { f x = ...g x'...
1305             ; g y = ...f y'.... }
1306     in f 'a'
1307 Here we specialise 'f' at Char; but that is very likely to lead to 
1308 a specialisation of 'g' at Char.  We must do the latter, else the
1309 whole point of specialisation is lost.
1310
1311 But we do not want to keep iterating to a fixpoint, because in the
1312 presence of polymorphic recursion we might generate an infinite number
1313 of specialisations.
1314
1315 So we use the following heuristic:
1316   * Arrange the rec block in dependency order, so far as possible
1317     (the occurrence analyser already does this)
1318
1319   * Specialise it much like a sequence of lets
1320
1321   * Then go through the block a second time, feeding call-info from
1322     the RHSs back in the bottom, as it were
1323
1324 In effect, the ordering maxmimises the effectiveness of each sweep,
1325 and we do just two sweeps.   This should catch almost every case of 
1326 monomorphic recursion -- the exception could be a very knotted-up
1327 recursion with multiple cycles tied up together.
1328
1329 This plan is implemented in the Rec case of specBindItself.
1330  
1331 Note [Specialisations already covered]
1332 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1333 We obviously don't want to generate two specialisations for the same
1334 argument pattern.  There are two wrinkles
1335
1336 1. We do the already-covered test in specDefn, not when we generate
1337 the CallInfo in mkCallUDs.  We used to test in the latter place, but
1338 we now iterate the specialiser somewhat, and the Id at the call site
1339 might therefore not have all the RULES that we can see in specDefn
1340
1341 2. What about two specialisations where the second is an *instance*
1342 of the first?  If the more specific one shows up first, we'll generate
1343 specialisations for both.  If the *less* specific one shows up first,
1344 we *don't* currently generate a specialisation for the more specific
1345 one.  (See the call to lookupRule in already_covered.)  Reasons:
1346   (a) lookupRule doesn't say which matches are exact (bad reason)
1347   (b) if the earlier specialisation is user-provided, it's
1348       far from clear that we should auto-specialise further
1349
1350 Note [Auto-specialisation and RULES]
1351 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1352 Consider:
1353    g :: Num a => a -> a
1354    g = ...
1355
1356    f :: (Int -> Int) -> Int
1357    f w = ...
1358    {-# RULE f g = 0 #-}
1359
1360 Suppose that auto-specialisation makes a specialised version of
1361 g::Int->Int That version won't appear in the LHS of the RULE for f.
1362 So if the specialisation rule fires too early, the rule for f may
1363 never fire. 
1364
1365 It might be possible to add new rules, to "complete" the rewrite system.
1366 Thus when adding
1367         RULE forall d. g Int d = g_spec
1368 also add
1369         RULE f g_spec = 0
1370
1371 But that's a bit complicated.  For now we ask the programmer's help,
1372 by *copying the INLINE activation pragma* to the auto-specialised
1373 rule.  So if g says {-# NOINLINE[2] g #-}, then the auto-spec rule
1374 will also not be active until phase 2.  And that's what programmers
1375 should jolly well do anyway, even aside from specialisation, to ensure
1376 that g doesn't inline too early.
1377
1378 This in turn means that the RULE would never fire for a NOINLINE
1379 thing so not much point in generating a specialisation at all.
1380
1381 Note [Specialisation shape]
1382 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1383 We only specialise a function if it has visible top-level lambdas
1384 corresponding to its overloading.  E.g. if
1385         f :: forall a. Eq a => ....
1386 then its body must look like
1387         f = /\a. \d. ...
1388
1389 Reason: when specialising the body for a call (f ty dexp), we want to
1390 substitute dexp for d, and pick up specialised calls in the body of f.
1391
1392 This doesn't always work.  One example I came across was this:
1393         newtype Gen a = MkGen{ unGen :: Int -> a }
1394
1395         choose :: Eq a => a -> Gen a
1396         choose n = MkGen (\r -> n)
1397
1398         oneof = choose (1::Int)
1399
1400 It's a silly exapmle, but we get
1401         choose = /\a. g `cast` co
1402 where choose doesn't have any dict arguments.  Thus far I have not
1403 tried to fix this (wait till there's a real example).
1404
1405 Note [Inline specialisations]
1406 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1407 Here is what we do with the InlinePragma of the original function
1408   * Activation/RuleMatchInfo: both transferred to the
1409                               specialised function
1410   * InlineSpec:
1411        (a) An INLINE pragma is transferred
1412        (b) An INLINABLE pragma is *not* transferred
1413
1414 Why (a)? Previously the idea is that the point of INLINE was
1415 precisely to specialise the function at its call site, and that's not
1416 so important for the specialised copies.  But *pragma-directed*
1417 specialisation now takes place in the typechecker/desugarer, with
1418 manually specified INLINEs.  The specialiation here is automatic.
1419 It'd be very odd if a function marked INLINE was specialised (because
1420 of some local use), and then forever after (including importing
1421 modules) the specialised version wasn't INLINEd.  After all, the
1422 programmer said INLINE!
1423
1424 You might wonder why we don't just not-specialise INLINE functions.
1425 It's because even INLINE functions are sometimes not inlined, when 
1426 they aren't applied to interesting arguments.  But perhaps the type
1427 arguments alone are enough to specialise (even though the args are too
1428 boring to trigger inlining), and it's certainly better to call the 
1429 specialised version.
1430
1431 Why (b)? See Trac #4874 for persuasive examples.  Suppose we have
1432     {-# INLINABLE f #-}
1433     f :: Ord a => [a] -> Int
1434     f xs = letrec f' = ...f'... in f'
1435 Then, when f is specialised and optimised we might get
1436     wgo :: [Int] -> Int#
1437     wgo = ...wgo...
1438     f_spec :: [Int] -> Int
1439     f_spec xs = case wgo xs of { r -> I# r }
1440 and we clearly want to inline f_spec at call sites.  But if we still
1441 have the big, un-optimised of f (albeit specialised) captured in an
1442 INLINABLE pragma for f_spec, we won't get that optimisation.
1443
1444 So we simply drop INLINABLE pragmas when specialising. It's not really
1445 a complete solution; ignoring specalisation for now, INLINABLE functions
1446 don't get properly strictness analysed, for example. But it works well
1447 for examples involving specialisation, which is the dominant use of
1448 INLINABLE.  See Trac #4874.
1449
1450
1451 %************************************************************************
1452 %*                                                                      *
1453 \subsubsection{UsageDetails and suchlike}
1454 %*                                                                      *
1455 %************************************************************************
1456
1457 \begin{code}
1458 data UsageDetails 
1459   = MkUD {
1460         ud_binds :: !(Bag DictBind),
1461                         -- Floated dictionary bindings
1462                         -- The order is important; 
1463                         -- in ds1 `union` ds2, bindings in ds2 can depend on those in ds1
1464                         -- (Remember, Bags preserve order in GHC.)
1465
1466         ud_calls :: !CallDetails  
1467
1468         -- INVARIANT: suppose bs = bindersOf ud_binds
1469         -- Then 'calls' may *mention* 'bs', 
1470         -- but there should be no calls *for* bs
1471     }
1472
1473 instance Outputable UsageDetails where
1474   ppr (MkUD { ud_binds = dbs, ud_calls = calls })
1475         = ptext (sLit "MkUD") <+> braces (sep (punctuate comma 
1476                 [ptext (sLit "binds") <+> equals <+> ppr dbs,
1477                  ptext (sLit "calls") <+> equals <+> ppr calls]))
1478
1479 type DictBind = (CoreBind, VarSet)
1480         -- The set is the free vars of the binding
1481         -- both tyvars and dicts
1482
1483 type DictExpr = CoreExpr
1484
1485 emptyUDs :: UsageDetails
1486 emptyUDs = MkUD { ud_binds = emptyBag, ud_calls = emptyVarEnv }
1487
1488 ------------------------------------------------------------                    
1489 type CallDetails  = IdEnv CallInfoSet
1490 newtype CallKey   = CallKey [Maybe Type]                        -- Nothing => unconstrained type argument
1491
1492 -- CallInfo uses a Map, thereby ensuring that
1493 -- we record only one call instance for any key
1494 --
1495 -- The list of types and dictionaries is guaranteed to
1496 -- match the type of f
1497 data CallInfoSet = CIS Id (Map CallKey ([DictExpr], VarSet))
1498                         -- Range is dict args and the vars of the whole
1499                         -- call (including tyvars)
1500                         -- [*not* include the main id itself, of course]
1501
1502 type CallInfo = (CallKey, ([DictExpr], VarSet))
1503
1504 instance Outputable CallInfoSet where
1505   ppr (CIS fn map) = hang (ptext (sLit "CIS") <+> ppr fn)
1506                         2 (ppr map)
1507
1508 instance Outputable CallKey where
1509   ppr (CallKey ts) = ppr ts
1510
1511 -- Type isn't an instance of Ord, so that we can control which
1512 -- instance we use.  That's tiresome here.  Oh well
1513 instance Eq CallKey where
1514   k1 == k2 = case k1 `compare` k2 of { EQ -> True; _ -> False }
1515
1516 instance Ord CallKey where
1517   compare (CallKey k1) (CallKey k2) = cmpList cmp k1 k2
1518                 where
1519                   cmp Nothing   Nothing   = EQ
1520                   cmp Nothing   (Just _)  = LT
1521                   cmp (Just _)  Nothing   = GT
1522                   cmp (Just t1) (Just t2) = cmpType t1 t2
1523
1524 unionCalls :: CallDetails -> CallDetails -> CallDetails
1525 unionCalls c1 c2 = plusVarEnv_C unionCallInfoSet c1 c2
1526
1527 unionCallInfoSet :: CallInfoSet -> CallInfoSet -> CallInfoSet
1528 unionCallInfoSet (CIS f calls1) (CIS _ calls2) = CIS f (calls1 `Map.union` calls2)
1529
1530 callDetailsFVs :: CallDetails -> VarSet
1531 callDetailsFVs calls = foldVarEnv (unionVarSet . callInfoFVs) emptyVarSet calls
1532
1533 callInfoFVs :: CallInfoSet -> VarSet
1534 callInfoFVs (CIS _ call_info) = Map.foldRight (\(_,fv) vs -> unionVarSet fv vs) emptyVarSet call_info
1535
1536 ------------------------------------------------------------                    
1537 singleCall :: Id -> [Maybe Type] -> [DictExpr] -> UsageDetails
1538 singleCall id tys dicts 
1539   = MkUD {ud_binds = emptyBag, 
1540           ud_calls = unitVarEnv id $ CIS id $ 
1541                      Map.singleton (CallKey tys) (dicts, call_fvs) }
1542   where
1543     call_fvs = exprsFreeVars dicts `unionVarSet` tys_fvs
1544     tys_fvs  = tyVarsOfTypes (catMaybes tys)
1545         -- The type args (tys) are guaranteed to be part of the dictionary
1546         -- types, because they are just the constrained types,
1547         -- and the dictionary is therefore sure to be bound
1548         -- inside the binding for any type variables free in the type;
1549         -- hence it's safe to neglect tyvars free in tys when making
1550         -- the free-var set for this call
1551         -- BUT I don't trust this reasoning; play safe and include tys_fvs
1552         --
1553         -- We don't include the 'id' itself.
1554
1555 mkCallUDs :: Id -> [CoreExpr] -> UsageDetails
1556 mkCallUDs f args 
1557   | not (want_calls_for f)  -- Imported from elsewhere
1558   || null theta             -- Not overloaded
1559   || not (all isClassPred theta)        
1560         -- Only specialise if all overloading is on class params. 
1561         -- In ptic, with implicit params, the type args
1562         --  *don't* say what the value of the implicit param is!
1563   || not (spec_tys `lengthIs` n_tyvars)
1564   || not ( dicts   `lengthIs` n_dicts)
1565   || not (any interestingDict dicts)    -- Note [Interesting dictionary arguments]
1566   -- See also Note [Specialisations already covered]
1567   = -- pprTrace "mkCallUDs: discarding" _trace_doc
1568     emptyUDs    -- Not overloaded, or no specialisation wanted
1569
1570   | otherwise
1571   = -- pprTrace "mkCallUDs: keeping" _trace_doc
1572     singleCall f spec_tys dicts
1573   where
1574     _trace_doc = vcat [ppr f, ppr args, ppr n_tyvars, ppr n_dicts
1575                       , ppr (map interestingDict dicts)]
1576     (tyvars, theta, _) = tcSplitSigmaTy (idType f)
1577     constrained_tyvars = tyVarsOfTheta theta 
1578     n_tyvars           = length tyvars
1579     n_dicts            = length theta
1580
1581     spec_tys = [mk_spec_ty tv ty | (tv, Type ty) <- tyvars `zip` args]
1582     dicts    = [dict_expr | (_, dict_expr) <- theta `zip` (drop n_tyvars args)]
1583     
1584     mk_spec_ty tyvar ty 
1585         | tyvar `elemVarSet` constrained_tyvars = Just ty
1586         | otherwise                             = Nothing
1587
1588     want_calls_for f = isLocalId f || isInlinablePragma (idInlinePragma f)
1589 \end{code}
1590
1591 Note [Interesting dictionary arguments]
1592 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1593 Consider this
1594          \a.\d:Eq a.  let f = ... in ...(f d)...
1595 There really is not much point in specialising f wrt the dictionary d,
1596 because the code for the specialised f is not improved at all, because
1597 d is lambda-bound.  We simply get junk specialisations.
1598
1599 What is "interesting"?  Just that it has *some* structure.  
1600
1601 \begin{code}
1602 interestingDict :: CoreExpr -> Bool
1603 -- A dictionary argument is interesting if it has *some* structure
1604 interestingDict (Var v) =  hasSomeUnfolding (idUnfolding v)
1605                         || isDataConWorkId v
1606 interestingDict (Type _)          = False
1607 interestingDict (Coercion _)      = False
1608 interestingDict (App fn (Type _)) = interestingDict fn
1609 interestingDict (App fn (Coercion _)) = interestingDict fn
1610 interestingDict (Note _ a)        = interestingDict a
1611 interestingDict (Cast e _)        = interestingDict e
1612 interestingDict _                 = True
1613 \end{code}
1614
1615 \begin{code}
1616 plusUDs :: UsageDetails -> UsageDetails -> UsageDetails
1617 plusUDs (MkUD {ud_binds = db1, ud_calls = calls1})
1618         (MkUD {ud_binds = db2, ud_calls = calls2})
1619   = MkUD { ud_binds = db1    `unionBags`   db2 
1620          , ud_calls = calls1 `unionCalls`  calls2 }
1621
1622 plusUDList :: [UsageDetails] -> UsageDetails
1623 plusUDList = foldr plusUDs emptyUDs
1624
1625 -----------------------------
1626 _dictBindBndrs :: Bag DictBind -> [Id]
1627 _dictBindBndrs dbs = foldrBag ((++) . bindersOf . fst) [] dbs
1628
1629 mkDB :: CoreBind -> DictBind
1630 mkDB bind = (bind, bind_fvs bind)
1631
1632 bind_fvs :: CoreBind -> VarSet
1633 bind_fvs (NonRec bndr rhs) = pair_fvs (bndr,rhs)
1634 bind_fvs (Rec prs)         = foldl delVarSet rhs_fvs bndrs
1635                            where
1636                              bndrs = map fst prs
1637                              rhs_fvs = unionVarSets (map pair_fvs prs)
1638
1639 pair_fvs :: (Id, CoreExpr) -> VarSet
1640 pair_fvs (bndr, rhs) = exprFreeVars rhs `unionVarSet` idFreeVars bndr
1641         -- Don't forget variables mentioned in the
1642         -- rules of the bndr.  C.f. OccAnal.addRuleUsage
1643         -- Also tyvars mentioned in its type; they may not appear in the RHS
1644         --      type T a = Int
1645         --      x :: T a = 3
1646
1647 flattenDictBinds :: Bag DictBind -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
1648 flattenDictBinds dbs pairs
1649   = foldrBag add pairs dbs
1650   where
1651     add (NonRec b r,_) pairs = (b,r) : pairs
1652     add (Rec prs1, _)  pairs = prs1 ++ pairs
1653
1654 snocDictBinds :: UsageDetails -> [CoreBind] -> UsageDetails
1655 -- Add ud_binds to the tail end of the bindings in uds
1656 snocDictBinds uds dbs
1657   = uds { ud_binds = ud_binds uds `unionBags` 
1658                      foldr (consBag . mkDB) emptyBag dbs }
1659
1660 consDictBind :: CoreBind -> UsageDetails -> UsageDetails
1661 consDictBind bind uds = uds { ud_binds = mkDB bind `consBag` ud_binds uds }
1662
1663 addDictBinds :: [DictBind] -> UsageDetails -> UsageDetails
1664 addDictBinds binds uds = uds { ud_binds = listToBag binds `unionBags` ud_binds uds }
1665
1666 snocDictBind :: UsageDetails -> CoreBind -> UsageDetails
1667 snocDictBind uds bind = uds { ud_binds = ud_binds uds `snocBag` mkDB bind }
1668
1669 wrapDictBinds :: Bag DictBind -> [CoreBind] -> [CoreBind]
1670 wrapDictBinds dbs binds
1671   = foldrBag add binds dbs
1672   where
1673     add (bind,_) binds = bind : binds
1674
1675 wrapDictBindsE :: Bag DictBind -> CoreExpr -> CoreExpr
1676 wrapDictBindsE dbs expr
1677   = foldrBag add expr dbs
1678   where
1679     add (bind,_) expr = Let bind expr
1680
1681 ----------------------
1682 dumpUDs :: [CoreBndr] -> UsageDetails -> (UsageDetails, Bag DictBind)
1683 -- Used at a lambda or case binder; just dump anything mentioning the binder
1684 dumpUDs bndrs uds@(MkUD { ud_binds = orig_dbs, ud_calls = orig_calls })
1685   | null bndrs = (uds, emptyBag)  -- Common in case alternatives
1686   | otherwise  = -- pprTrace "dumpUDs" (ppr bndrs $$ ppr free_uds $$ ppr dump_dbs) $
1687                  (free_uds, dump_dbs)
1688   where
1689     free_uds = MkUD { ud_binds = free_dbs, ud_calls = free_calls }
1690     bndr_set = mkVarSet bndrs
1691     (free_dbs, dump_dbs, dump_set) = splitDictBinds orig_dbs bndr_set
1692     free_calls = deleteCallsMentioning dump_set $   -- Drop calls mentioning bndr_set on the floor
1693                  deleteCallsFor bndrs orig_calls    -- Discard calls for bndr_set; there should be 
1694                                                     -- no calls for any of the dicts in dump_dbs
1695
1696 dumpBindUDs :: [CoreBndr] -> UsageDetails -> (UsageDetails, Bag DictBind, Bool)
1697 -- Used at a lambda or case binder; just dump anything mentioning the binder
1698 dumpBindUDs bndrs (MkUD { ud_binds = orig_dbs, ud_calls = orig_calls })
1699   = -- pprTrace "dumpBindUDs" (ppr bndrs $$ ppr free_uds $$ ppr dump_dbs) $
1700     (free_uds, dump_dbs, float_all)
1701   where
1702     free_uds = MkUD { ud_binds = free_dbs, ud_calls = free_calls }
1703     bndr_set = mkVarSet bndrs
1704     (free_dbs, dump_dbs, dump_set) = splitDictBinds orig_dbs bndr_set
1705     free_calls = deleteCallsFor bndrs orig_calls
1706     float_all = dump_set `intersectsVarSet` callDetailsFVs free_calls
1707
1708 callsForMe :: Id -> UsageDetails -> (UsageDetails, [CallInfo])
1709 callsForMe fn (MkUD { ud_binds = orig_dbs, ud_calls = orig_calls })
1710   = -- pprTrace ("callsForMe")
1711     --         (vcat [ppr fn, 
1712     --                text "Orig dbs ="     <+> ppr (_dictBindBndrs orig_dbs), 
1713     --                text "Orig calls ="   <+> ppr orig_calls,
1714     --                text "Dep set ="      <+> ppr dep_set, 
1715     --                text "Calls for me =" <+> ppr calls_for_me]) $
1716     (uds_without_me, calls_for_me)
1717   where
1718     uds_without_me = MkUD { ud_binds = orig_dbs, ud_calls = delVarEnv orig_calls fn }
1719     calls_for_me = case lookupVarEnv orig_calls fn of
1720                         Nothing -> []
1721                         Just (CIS _ calls) -> filter_dfuns (Map.toList calls)
1722
1723     dep_set = foldlBag go (unitVarSet fn) orig_dbs
1724     go dep_set (db,fvs) | fvs `intersectsVarSet` dep_set
1725                         = extendVarSetList dep_set (bindersOf db)
1726                         | otherwise = dep_set
1727
1728         -- Note [Specialisation of dictionary functions]
1729     filter_dfuns | isDFunId fn = filter ok_call
1730                  | otherwise   = \cs -> cs
1731
1732     ok_call (_, (_,fvs)) = not (fvs `intersectsVarSet` dep_set)
1733
1734 ----------------------
1735 splitDictBinds :: Bag DictBind -> IdSet -> (Bag DictBind, Bag DictBind, IdSet)
1736 -- Returns (free_dbs, dump_dbs, dump_set)
1737 splitDictBinds dbs bndr_set
1738    = foldlBag split_db (emptyBag, emptyBag, bndr_set) dbs
1739                 -- Important that it's foldl not foldr;
1740                 -- we're accumulating the set of dumped ids in dump_set
1741    where
1742     split_db (free_dbs, dump_dbs, dump_idset) db@(bind, fvs)
1743         | dump_idset `intersectsVarSet` fvs     -- Dump it
1744         = (free_dbs, dump_dbs `snocBag` db,
1745            extendVarSetList dump_idset (bindersOf bind))
1746
1747         | otherwise     -- Don't dump it
1748         = (free_dbs `snocBag` db, dump_dbs, dump_idset)
1749
1750
1751 ----------------------
1752 deleteCallsMentioning :: VarSet -> CallDetails -> CallDetails
1753 -- Remove calls *mentioning* bs 
1754 deleteCallsMentioning bs calls
1755   = mapVarEnv filter_calls calls
1756   where
1757     filter_calls :: CallInfoSet -> CallInfoSet
1758     filter_calls (CIS f calls) = CIS f (Map.filter keep_call calls)
1759     keep_call (_, fvs) = not (fvs `intersectsVarSet` bs)
1760
1761 deleteCallsFor :: [Id] -> CallDetails -> CallDetails
1762 -- Remove calls *for* bs
1763 deleteCallsFor bs calls = delVarEnvList calls bs
1764 \end{code}
1765
1766
1767 %************************************************************************
1768 %*                                                                      *
1769 \subsubsection{Boring helper functions}
1770 %*                                                                      *
1771 %************************************************************************
1772
1773 \begin{code}
1774 type SpecM a = UniqSM a
1775
1776 runSpecM:: SpecM a -> CoreM a
1777 runSpecM spec = do { us <- getUniqueSupplyM
1778                    ; return (initUs_ us spec) }
1779
1780 mapAndCombineSM :: (a -> SpecM (b, UsageDetails)) -> [a] -> SpecM ([b], UsageDetails)
1781 mapAndCombineSM _ []     = return ([], emptyUDs)
1782 mapAndCombineSM f (x:xs) = do (y, uds1) <- f x
1783                               (ys, uds2) <- mapAndCombineSM f xs
1784                               return (y:ys, uds1 `plusUDs` uds2)
1785
1786 cloneBindSM :: Subst -> CoreBind -> SpecM (Subst, Subst, CoreBind)
1787 -- Clone the binders of the bind; return new bind with the cloned binders
1788 -- Return the substitution to use for RHSs, and the one to use for the body
1789 cloneBindSM subst (NonRec bndr rhs) = do
1790     us <- getUniqueSupplyM
1791     let (subst', bndr') = cloneIdBndr subst us bndr
1792     return (subst, subst', NonRec bndr' rhs)
1793
1794 cloneBindSM subst (Rec pairs) = do
1795     us <- getUniqueSupplyM
1796     let (subst', bndrs') = cloneRecIdBndrs subst us (map fst pairs)
1797     return (subst', subst', Rec (bndrs' `zip` map snd pairs))
1798
1799 newDictBndrs :: Subst -> [CoreBndr] -> SpecM (Subst, [CoreBndr])
1800 -- Make up completely fresh binders for the dictionaries
1801 -- Their bindings are going to float outwards
1802 newDictBndrs subst bndrs 
1803   = do { bndrs' <- mapM new bndrs
1804        ; let subst' = extendIdSubstList subst 
1805                         [(d, Var d') | (d,d') <- bndrs `zip` bndrs']
1806        ; return (subst', bndrs' ) }
1807   where
1808     new b = do { uniq <- getUniqueM
1809                ; let n   = idName b
1810                      ty' = CoreSubst.substTy subst (idType b)
1811                ; return (mkUserLocal (nameOccName n) uniq ty' (getSrcSpan n)) }
1812
1813 newSpecIdSM :: Id -> Type -> SpecM Id
1814     -- Give the new Id a similar occurrence name to the old one
1815 newSpecIdSM old_id new_ty
1816   = do  { uniq <- getUniqueM
1817         ; let name    = idName old_id
1818               new_occ = mkSpecOcc (nameOccName name)
1819               new_id  = mkUserLocal new_occ uniq new_ty (getSrcSpan name)
1820         ; return new_id }
1821 \end{code}
1822
1823
1824                 Old (but interesting) stuff about unboxed bindings
1825                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1826
1827 What should we do when a value is specialised to a *strict* unboxed value?
1828
1829         map_*_* f (x:xs) = let h = f x
1830                                t = map f xs
1831                            in h:t
1832
1833 Could convert let to case:
1834
1835         map_*_Int# f (x:xs) = case f x of h# ->
1836                               let t = map f xs
1837                               in h#:t
1838
1839 This may be undesirable since it forces evaluation here, but the value
1840 may not be used in all branches of the body. In the general case this
1841 transformation is impossible since the mutual recursion in a letrec
1842 cannot be expressed as a case.
1843
1844 There is also a problem with top-level unboxed values, since our
1845 implementation cannot handle unboxed values at the top level.
1846
1847 Solution: Lift the binding of the unboxed value and extract it when it
1848 is used:
1849
1850         map_*_Int# f (x:xs) = let h = case (f x) of h# -> _Lift h#
1851                                   t = map f xs
1852                               in case h of
1853                                  _Lift h# -> h#:t
1854
1855 Now give it to the simplifier and the _Lifting will be optimised away.
1856
1857 The benfit is that we have given the specialised "unboxed" values a
1858 very simplep lifted semantics and then leave it up to the simplifier to
1859 optimise it --- knowing that the overheads will be removed in nearly
1860 all cases.
1861
1862 In particular, the value will only be evaluted in the branches of the
1863 program which use it, rather than being forced at the point where the
1864 value is bound. For example:
1865
1866         filtermap_*_* p f (x:xs)
1867           = let h = f x
1868                 t = ...
1869             in case p x of
1870                 True  -> h:t
1871                 False -> t
1872    ==>
1873         filtermap_*_Int# p f (x:xs)
1874           = let h = case (f x) of h# -> _Lift h#
1875                 t = ...
1876             in case p x of
1877                 True  -> case h of _Lift h#
1878                            -> h#:t
1879                 False -> t
1880
1881 The binding for h can still be inlined in the one branch and the
1882 _Lifting eliminated.
1883
1884
1885 Question: When won't the _Lifting be eliminated?
1886
1887 Answer: When they at the top-level (where it is necessary) or when
1888 inlining would duplicate work (or possibly code depending on
1889 options). However, the _Lifting will still be eliminated if the
1890 strictness analyser deems the lifted binding strict.
1891