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