Define SpecConstrAnnotation in GHC.Exts, and import it from there
[ghc-hetmet.git] / compiler / specialise / SpecConstr.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[SpecConstr]{Specialise over constructors}
5
6 \begin{code}
7 -- The above warning supression flag is a temporary kludge.
8 -- While working on this module you are encouraged to remove it and fix
9 -- any warnings in the module. See
10 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
11 -- for details
12
13 module SpecConstr(
14         specConstrProgram
15 #ifdef GHCI
16         , SpecConstrAnnotation(..)
17 #endif
18     ) where
19
20 #include "HsVersions.h"
21
22 import CoreSyn
23 import CoreSubst
24 import CoreUtils
25 import CoreUnfold       ( couldBeSmallEnoughToInline )
26 import CoreFVs          ( exprsFreeVars )
27 import CoreMonad
28 import HscTypes         ( ModGuts(..) )
29 import WwLib            ( mkWorkerArgs )
30 import DataCon
31 import Coercion 
32 import Rules
33 import Type             hiding( substTy )
34 import Id
35 import MkCore           ( mkImpossibleExpr )
36 import Var
37 import VarEnv
38 import VarSet
39 import Name
40 import BasicTypes
41 import DynFlags         ( DynFlags(..) )
42 import StaticFlags      ( opt_PprStyle_Debug )
43 import Maybes           ( orElse, catMaybes, isJust, isNothing )
44 import Demand
45 import DmdAnal          ( both )
46 import Serialized       ( deserializeWithData )
47 import Util
48 import UniqSupply
49 import Outputable
50 import FastString
51 import UniqFM
52 import MonadUtils
53 import Control.Monad    ( zipWithM )
54 import Data.List
55
56
57 -- See Note [SpecConstrAnnotation]
58 #ifndef GHCI
59 type SpecConstrAnnotation = ()
60 #else
61 import Literal          ( literalType )
62 import TyCon            ( TyCon )
63 import GHC.Exts( SpecConstrAnnotation(..) )
64 #endif
65 \end{code}
66
67 -----------------------------------------------------
68                         Game plan
69 -----------------------------------------------------
70
71 Consider
72         drop n []     = []
73         drop 0 xs     = []
74         drop n (x:xs) = drop (n-1) xs
75
76 After the first time round, we could pass n unboxed.  This happens in
77 numerical code too.  Here's what it looks like in Core:
78
79         drop n xs = case xs of
80                       []     -> []
81                       (y:ys) -> case n of 
82                                   I# n# -> case n# of
83                                              0 -> []
84                                              _ -> drop (I# (n# -# 1#)) xs
85
86 Notice that the recursive call has an explicit constructor as argument.
87 Noticing this, we can make a specialised version of drop
88         
89         RULE: drop (I# n#) xs ==> drop' n# xs
90
91         drop' n# xs = let n = I# n# in ...orig RHS...
92
93 Now the simplifier will apply the specialisation in the rhs of drop', giving
94
95         drop' n# xs = case xs of
96                       []     -> []
97                       (y:ys) -> case n# of
98                                   0 -> []
99                                   _ -> drop (n# -# 1#) xs
100
101 Much better!  
102
103 We'd also like to catch cases where a parameter is carried along unchanged,
104 but evaluated each time round the loop:
105
106         f i n = if i>0 || i>n then i else f (i*2) n
107
108 Here f isn't strict in n, but we'd like to avoid evaluating it each iteration.
109 In Core, by the time we've w/wd (f is strict in i) we get
110
111         f i# n = case i# ># 0 of
112                    False -> I# i#
113                    True  -> case n of n' { I# n# ->
114                             case i# ># n# of
115                                 False -> I# i#
116                                 True  -> f (i# *# 2#) n'
117
118 At the call to f, we see that the argument, n is know to be (I# n#),
119 and n is evaluated elsewhere in the body of f, so we can play the same
120 trick as above.  
121
122
123 Note [Reboxing]
124 ~~~~~~~~~~~~~~~
125 We must be careful not to allocate the same constructor twice.  Consider
126         f p = (...(case p of (a,b) -> e)...p...,
127                ...let t = (r,s) in ...t...(f t)...)
128 At the recursive call to f, we can see that t is a pair.  But we do NOT want
129 to make a specialised copy:
130         f' a b = let p = (a,b) in (..., ...)
131 because now t is allocated by the caller, then r and s are passed to the
132 recursive call, which allocates the (r,s) pair again.
133
134 This happens if
135   (a) the argument p is used in other than a case-scrutinsation way.
136   (b) the argument to the call is not a 'fresh' tuple; you have to
137         look into its unfolding to see that it's a tuple
138
139 Hence the "OR" part of Note [Good arguments] below.
140
141 ALTERNATIVE 2: pass both boxed and unboxed versions.  This no longer saves
142 allocation, but does perhaps save evals. In the RULE we'd have
143 something like
144
145   f (I# x#) = f' (I# x#) x#
146
147 If at the call site the (I# x) was an unfolding, then we'd have to
148 rely on CSE to eliminate the duplicate allocation.... This alternative
149 doesn't look attractive enough to pursue.
150
151 ALTERNATIVE 3: ignore the reboxing problem.  The trouble is that 
152 the conservative reboxing story prevents many useful functions from being
153 specialised.  Example:
154         foo :: Maybe Int -> Int -> Int
155         foo   (Just m) 0 = 0
156         foo x@(Just m) n = foo x (n-m)
157 Here the use of 'x' will clearly not require boxing in the specialised function.
158
159 The strictness analyser has the same problem, in fact.  Example:
160         f p@(a,b) = ...
161 If we pass just 'a' and 'b' to the worker, it might need to rebox the
162 pair to create (a,b).  A more sophisticated analysis might figure out
163 precisely the cases in which this could happen, but the strictness
164 analyser does no such analysis; it just passes 'a' and 'b', and hopes
165 for the best.
166
167 So my current choice is to make SpecConstr similarly aggressive, and
168 ignore the bad potential of reboxing.
169
170
171 Note [Good arguments]
172 ~~~~~~~~~~~~~~~~~~~~~
173 So we look for
174
175 * A self-recursive function.  Ignore mutual recursion for now, 
176   because it's less common, and the code is simpler for self-recursion.
177
178 * EITHER
179
180    a) At a recursive call, one or more parameters is an explicit 
181       constructor application
182         AND
183       That same parameter is scrutinised by a case somewhere in 
184       the RHS of the function
185
186   OR
187
188     b) At a recursive call, one or more parameters has an unfolding
189        that is an explicit constructor application
190         AND
191       That same parameter is scrutinised by a case somewhere in 
192       the RHS of the function
193         AND
194       Those are the only uses of the parameter (see Note [Reboxing])
195
196
197 What to abstract over
198 ~~~~~~~~~~~~~~~~~~~~~
199 There's a bit of a complication with type arguments.  If the call
200 site looks like
201
202         f p = ...f ((:) [a] x xs)...
203
204 then our specialised function look like
205
206         f_spec x xs = let p = (:) [a] x xs in ....as before....
207
208 This only makes sense if either
209   a) the type variable 'a' is in scope at the top of f, or
210   b) the type variable 'a' is an argument to f (and hence fs)
211
212 Actually, (a) may hold for value arguments too, in which case
213 we may not want to pass them.  Supose 'x' is in scope at f's
214 defn, but xs is not.  Then we'd like
215
216         f_spec xs = let p = (:) [a] x xs in ....as before....
217
218 Similarly (b) may hold too.  If x is already an argument at the
219 call, no need to pass it again.
220
221 Finally, if 'a' is not in scope at the call site, we could abstract
222 it as we do the term variables:
223
224         f_spec a x xs = let p = (:) [a] x xs in ...as before...
225
226 So the grand plan is:
227
228         * abstract the call site to a constructor-only pattern
229           e.g.  C x (D (f p) (g q))  ==>  C s1 (D s2 s3)
230
231         * Find the free variables of the abstracted pattern
232
233         * Pass these variables, less any that are in scope at
234           the fn defn.  But see Note [Shadowing] below.
235
236
237 NOTICE that we only abstract over variables that are not in scope,
238 so we're in no danger of shadowing variables used in "higher up"
239 in f_spec's RHS.
240
241
242 Note [Shadowing]
243 ~~~~~~~~~~~~~~~~
244 In this pass we gather up usage information that may mention variables
245 that are bound between the usage site and the definition site; or (more
246 seriously) may be bound to something different at the definition site.
247 For example:
248
249         f x = letrec g y v = let x = ... 
250                              in ...(g (a,b) x)...
251
252 Since 'x' is in scope at the call site, we may make a rewrite rule that 
253 looks like
254         RULE forall a,b. g (a,b) x = ...
255 But this rule will never match, because it's really a different 'x' at 
256 the call site -- and that difference will be manifest by the time the
257 simplifier gets to it.  [A worry: the simplifier doesn't *guarantee*
258 no-shadowing, so perhaps it may not be distinct?]
259
260 Anyway, the rule isn't actually wrong, it's just not useful.  One possibility
261 is to run deShadowBinds before running SpecConstr, but instead we run the
262 simplifier.  That gives the simplest possible program for SpecConstr to
263 chew on; and it virtually guarantees no shadowing.
264
265 Note [Specialising for constant parameters]
266 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
267 This one is about specialising on a *constant* (but not necessarily
268 constructor) argument
269
270     foo :: Int -> (Int -> Int) -> Int
271     foo 0 f = 0
272     foo m f = foo (f m) (+1)
273
274 It produces
275
276     lvl_rmV :: GHC.Base.Int -> GHC.Base.Int
277     lvl_rmV =
278       \ (ds_dlk :: GHC.Base.Int) ->
279         case ds_dlk of wild_alH { GHC.Base.I# x_alG ->
280         GHC.Base.I# (GHC.Prim.+# x_alG 1)
281
282     T.$wfoo :: GHC.Prim.Int# -> (GHC.Base.Int -> GHC.Base.Int) ->
283     GHC.Prim.Int#
284     T.$wfoo =
285       \ (ww_sme :: GHC.Prim.Int#) (w_smg :: GHC.Base.Int -> GHC.Base.Int) ->
286         case ww_sme of ds_Xlw {
287           __DEFAULT ->
288         case w_smg (GHC.Base.I# ds_Xlw) of w1_Xmo { GHC.Base.I# ww1_Xmz ->
289         T.$wfoo ww1_Xmz lvl_rmV
290         };
291           0 -> 0
292         }
293
294 The recursive call has lvl_rmV as its argument, so we could create a specialised copy
295 with that argument baked in; that is, not passed at all.   Now it can perhaps be inlined.
296
297 When is this worth it?  Call the constant 'lvl'
298 - If 'lvl' has an unfolding that is a constructor, see if the corresponding
299   parameter is scrutinised anywhere in the body.
300
301 - If 'lvl' has an unfolding that is a inlinable function, see if the corresponding
302   parameter is applied (...to enough arguments...?)
303
304   Also do this is if the function has RULES?
305
306 Also    
307
308 Note [Specialising for lambda parameters]
309 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
310     foo :: Int -> (Int -> Int) -> Int
311     foo 0 f = 0
312     foo m f = foo (f m) (\n -> n-m)
313
314 This is subtly different from the previous one in that we get an
315 explicit lambda as the argument:
316
317     T.$wfoo :: GHC.Prim.Int# -> (GHC.Base.Int -> GHC.Base.Int) ->
318     GHC.Prim.Int#
319     T.$wfoo =
320       \ (ww_sm8 :: GHC.Prim.Int#) (w_sma :: GHC.Base.Int -> GHC.Base.Int) ->
321         case ww_sm8 of ds_Xlr {
322           __DEFAULT ->
323         case w_sma (GHC.Base.I# ds_Xlr) of w1_Xmf { GHC.Base.I# ww1_Xmq ->
324         T.$wfoo
325           ww1_Xmq
326           (\ (n_ad3 :: GHC.Base.Int) ->
327              case n_ad3 of wild_alB { GHC.Base.I# x_alA ->
328              GHC.Base.I# (GHC.Prim.-# x_alA ds_Xlr)
329              })
330         };
331           0 -> 0
332         }
333
334 I wonder if SpecConstr couldn't be extended to handle this? After all,
335 lambda is a sort of constructor for functions and perhaps it already
336 has most of the necessary machinery?
337
338 Furthermore, there's an immediate win, because you don't need to allocate the lamda
339 at the call site; and if perchance it's called in the recursive call, then you
340 may avoid allocating it altogether.  Just like for constructors.
341
342 Looks cool, but probably rare...but it might be easy to implement.
343
344
345 Note [SpecConstr for casts]
346 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
347 Consider 
348     data family T a :: *
349     data instance T Int = T Int
350
351     foo n = ...
352        where
353          go (T 0) = 0
354          go (T n) = go (T (n-1))
355
356 The recursive call ends up looking like 
357         go (T (I# ...) `cast` g)
358 So we want to spot the construtor application inside the cast.
359 That's why we have the Cast case in argToPat
360
361 Note [Local recursive groups]
362 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
363 For a *local* recursive group, we can see all the calls to the
364 function, so we seed the specialisation loop from the calls in the
365 body, not from the calls in the RHS.  Consider:
366
367   bar m n = foo n (n,n) (n,n) (n,n) (n,n)
368    where
369      foo n p q r s
370        | n == 0    = m
371        | n > 3000  = case p of { (p1,p2) -> foo (n-1) (p2,p1) q r s }
372        | n > 2000  = case q of { (q1,q2) -> foo (n-1) p (q2,q1) r s }
373        | n > 1000  = case r of { (r1,r2) -> foo (n-1) p q (r2,r1) s }
374        | otherwise = case s of { (s1,s2) -> foo (n-1) p q r (s2,s1) }
375
376 If we start with the RHSs of 'foo', we get lots and lots of specialisations,
377 most of which are not needed.  But if we start with the (single) call
378 in the rhs of 'bar' we get exactly one fully-specialised copy, and all
379 the recursive calls go to this fully-specialised copy. Indeed, the original
380 function is later collected as dead code.  This is very important in 
381 specialising the loops arising from stream fusion, for example in NDP where
382 we were getting literally hundreds of (mostly unused) specialisations of
383 a local function.
384
385 Note [Do not specialise diverging functions]
386 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
387 Specialising a function that just diverges is a waste of code.
388 Furthermore, it broke GHC (simpl014) thus:
389    {-# STR Sb #-}
390    f = \x. case x of (a,b) -> f x
391 If we specialise f we get
392    f = \x. case x of (a,b) -> fspec a b
393 But fspec doesn't have decent strictnes info.  As it happened,
394 (f x) :: IO t, so the state hack applied and we eta expanded fspec,
395 and hence f.  But now f's strictness is less than its arity, which
396 breaks an invariant.
397
398 Note [SpecConstrAnnotation]
399 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
400 SpecConstrAnnotation is defined in GHC.Exts, and is only guaranteed to
401 be available in stage 2 (well, until the bootstrap compiler can be
402 guaranteed to have it)
403
404 So we define it to be () in stage1 (ie when GHCI is undefined), and
405 '#ifdef' out the code that uses it.
406
407 See also Note [Forcing specialisation]
408
409 Note [Forcing specialisation]
410 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
411 With stream fusion and in other similar cases, we want to fully specialise
412 some (but not necessarily all!) loops regardless of their size and the
413 number of specialisations. We allow a library to specify this by annotating
414 a type with ForceSpecConstr and then adding a parameter of that type to the
415 loop. Here is a (simplified) example from the vector library:
416
417   data SPEC = SPEC | SPEC2
418   {-# ANN type SPEC ForceSpecConstr #-}
419
420   foldl :: (a -> b -> a) -> a -> Stream b -> a
421   {-# INLINE foldl #-}
422   foldl f z (Stream step s _) = foldl_loop SPEC z s
423     where
424       foldl_loop SPEC z s = case step s of
425                               Yield x s' -> foldl_loop SPEC (f z x) s'
426                               Skip       -> foldl_loop SPEC z s'
427                               Done       -> z
428
429 SpecConstr will spot the SPEC parameter and always fully specialise
430 foldl_loop. Note that we can't just annotate foldl_loop since it isn't a
431 top-level function but even if we could, inlining etc. could easily drop the
432 annotation. We also have to prevent the SPEC argument from being removed by
433 w/w which is why SPEC is a sum type. This is all quite ugly; we ought to come
434 up with a better design.
435
436 ForceSpecConstr arguments are spotted in scExpr' and scTopBinds which then set
437 force_spec to True when calling specLoop. This flag makes specLoop and
438 specialise ignore specConstrCount and specConstrThreshold when deciding
439 whether to specialise a function.
440
441 -----------------------------------------------------
442                 Stuff not yet handled
443 -----------------------------------------------------
444
445 Here are notes arising from Roman's work that I don't want to lose.
446
447 Example 1
448 ~~~~~~~~~
449     data T a = T !a
450
451     foo :: Int -> T Int -> Int
452     foo 0 t = 0
453     foo x t | even x    = case t of { T n -> foo (x-n) t }
454             | otherwise = foo (x-1) t
455
456 SpecConstr does no specialisation, because the second recursive call
457 looks like a boxed use of the argument.  A pity.
458
459     $wfoo_sFw :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int#
460     $wfoo_sFw =
461       \ (ww_sFo [Just L] :: GHC.Prim.Int#) (w_sFq [Just L] :: T.T GHC.Base.Int) ->
462          case ww_sFo of ds_Xw6 [Just L] {
463            __DEFAULT ->
464                 case GHC.Prim.remInt# ds_Xw6 2 of wild1_aEF [Dead Just A] {
465                   __DEFAULT -> $wfoo_sFw (GHC.Prim.-# ds_Xw6 1) w_sFq;
466                   0 ->
467                     case w_sFq of wild_Xy [Just L] { T.T n_ad5 [Just U(L)] ->
468                     case n_ad5 of wild1_aET [Just A] { GHC.Base.I# y_aES [Just L] ->
469                     $wfoo_sFw (GHC.Prim.-# ds_Xw6 y_aES) wild_Xy
470                     } } };
471            0 -> 0
472
473 Example 2
474 ~~~~~~~~~
475     data a :*: b = !a :*: !b
476     data T a = T !a
477
478     foo :: (Int :*: T Int) -> Int
479     foo (0 :*: t) = 0
480     foo (x :*: t) | even x    = case t of { T n -> foo ((x-n) :*: t) }
481                   | otherwise = foo ((x-1) :*: t)
482
483 Very similar to the previous one, except that the parameters are now in
484 a strict tuple. Before SpecConstr, we have
485
486     $wfoo_sG3 :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int#
487     $wfoo_sG3 =
488       \ (ww_sFU [Just L] :: GHC.Prim.Int#) (ww_sFW [Just L] :: T.T
489     GHC.Base.Int) ->
490         case ww_sFU of ds_Xws [Just L] {
491           __DEFAULT ->
492         case GHC.Prim.remInt# ds_Xws 2 of wild1_aEZ [Dead Just A] {
493           __DEFAULT ->
494             case ww_sFW of tpl_B2 [Just L] { T.T a_sFo [Just A] ->
495             $wfoo_sG3 (GHC.Prim.-# ds_Xws 1) tpl_B2             -- $wfoo1
496             };
497           0 ->
498             case ww_sFW of wild_XB [Just A] { T.T n_ad7 [Just S(L)] ->
499             case n_ad7 of wild1_aFd [Just L] { GHC.Base.I# y_aFc [Just L] ->
500             $wfoo_sG3 (GHC.Prim.-# ds_Xws y_aFc) wild_XB        -- $wfoo2
501             } } };
502           0 -> 0 }
503
504 We get two specialisations:
505 "SC:$wfoo1" [0] __forall {a_sFB :: GHC.Base.Int sc_sGC :: GHC.Prim.Int#}
506                   Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int a_sFB)
507                   = Foo.$s$wfoo1 a_sFB sc_sGC ;
508 "SC:$wfoo2" [0] __forall {y_aFp :: GHC.Prim.Int# sc_sGC :: GHC.Prim.Int#}
509                   Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int (GHC.Base.I# y_aFp))
510                   = Foo.$s$wfoo y_aFp sc_sGC ;
511
512 But perhaps the first one isn't good.  After all, we know that tpl_B2 is
513 a T (I# x) really, because T is strict and Int has one constructor.  (We can't
514 unbox the strict fields, becuase T is polymorphic!)
515
516 %************************************************************************
517 %*                                                                      *
518 \subsection{Top level wrapper stuff}
519 %*                                                                      *
520 %************************************************************************
521
522 \begin{code}
523 specConstrProgram :: ModGuts -> CoreM ModGuts
524 specConstrProgram guts
525   = do
526       dflags <- getDynFlags
527       us     <- getUniqueSupplyM
528       annos  <- getFirstAnnotations deserializeWithData guts
529       let binds' = fst $ initUs us (go (initScEnv dflags annos) (mg_binds guts))
530       return (guts { mg_binds = binds' })
531   where
532     go _   []           = return []
533     go env (bind:binds) = do (env', bind') <- scTopBind env bind
534                              binds' <- go env' binds
535                              return (bind' : binds')
536 \end{code}
537
538
539 %************************************************************************
540 %*                                                                      *
541 \subsection{Environment: goes downwards}
542 %*                                                                      *
543 %************************************************************************
544
545 \begin{code}
546 data ScEnv = SCE { sc_size  :: Maybe Int,       -- Size threshold
547                    sc_count :: Maybe Int,       -- Max # of specialisations for any one fn
548                                                 -- See Note [Avoiding exponential blowup]
549
550                    sc_subst :: Subst,           -- Current substitution
551                                                 -- Maps InIds to OutExprs
552
553                    sc_how_bound :: HowBoundEnv,
554                         -- Binds interesting non-top-level variables
555                         -- Domain is OutVars (*after* applying the substitution)
556
557                    sc_vals  :: ValueEnv,
558                         -- Domain is OutIds (*after* applying the substitution)
559                         -- Used even for top-level bindings (but not imported ones)
560
561                    sc_annotations :: UniqFM SpecConstrAnnotation
562              }
563
564 ---------------------
565 -- As we go, we apply a substitution (sc_subst) to the current term
566 type InExpr = CoreExpr          -- _Before_ applying the subst
567 type InVar  = Var
568
569 type OutExpr = CoreExpr         -- _After_ applying the subst
570 type OutId   = Id
571 type OutVar  = Var
572
573 ---------------------
574 type HowBoundEnv = VarEnv HowBound      -- Domain is OutVars
575
576 ---------------------
577 type ValueEnv = IdEnv Value             -- Domain is OutIds
578 data Value    = ConVal AltCon [CoreArg] -- _Saturated_ constructors
579                                         --   The AltCon is never DEFAULT
580               | LambdaVal               -- Inlinable lambdas or PAPs
581
582 instance Outputable Value where
583    ppr (ConVal con args) = ppr con <+> interpp'SP args
584    ppr LambdaVal         = ptext (sLit "<Lambda>")
585
586 ---------------------
587 initScEnv :: DynFlags -> UniqFM SpecConstrAnnotation -> ScEnv
588 initScEnv dflags anns
589   = SCE { sc_size = specConstrThreshold dflags,
590           sc_count = specConstrCount dflags,
591           sc_subst = emptySubst, 
592           sc_how_bound = emptyVarEnv, 
593           sc_vals = emptyVarEnv,
594           sc_annotations = anns }
595
596 data HowBound = RecFun  -- These are the recursive functions for which 
597                         -- we seek interesting call patterns
598
599               | RecArg  -- These are those functions' arguments, or their sub-components; 
600                         -- we gather occurrence information for these
601
602 instance Outputable HowBound where
603   ppr RecFun = text "RecFun"
604   ppr RecArg = text "RecArg"
605
606 lookupHowBound :: ScEnv -> Id -> Maybe HowBound
607 lookupHowBound env id = lookupVarEnv (sc_how_bound env) id
608
609 scSubstId :: ScEnv -> Id -> CoreExpr
610 scSubstId env v = lookupIdSubst (text "scSubstId") (sc_subst env) v
611
612 scSubstTy :: ScEnv -> Type -> Type
613 scSubstTy env ty = substTy (sc_subst env) ty
614
615 zapScSubst :: ScEnv -> ScEnv
616 zapScSubst env = env { sc_subst = zapSubstEnv (sc_subst env) }
617
618 extendScInScope :: ScEnv -> [Var] -> ScEnv
619         -- Bring the quantified variables into scope
620 extendScInScope env qvars = env { sc_subst = extendInScopeList (sc_subst env) qvars }
621
622         -- Extend the substitution
623 extendScSubst :: ScEnv -> Var -> OutExpr -> ScEnv
624 extendScSubst env var expr = env { sc_subst = extendSubst (sc_subst env) var expr }
625
626 extendScSubstList :: ScEnv -> [(Var,OutExpr)] -> ScEnv
627 extendScSubstList env prs = env { sc_subst = extendSubstList (sc_subst env) prs }
628
629 extendHowBound :: ScEnv -> [Var] -> HowBound -> ScEnv
630 extendHowBound env bndrs how_bound
631   = env { sc_how_bound = extendVarEnvList (sc_how_bound env)
632                             [(bndr,how_bound) | bndr <- bndrs] }
633
634 extendBndrsWith :: HowBound -> ScEnv -> [Var] -> (ScEnv, [Var])
635 extendBndrsWith how_bound env bndrs 
636   = (env { sc_subst = subst', sc_how_bound = hb_env' }, bndrs')
637   where
638     (subst', bndrs') = substBndrs (sc_subst env) bndrs
639     hb_env' = sc_how_bound env `extendVarEnvList` 
640                     [(bndr,how_bound) | bndr <- bndrs']
641
642 extendBndrWith :: HowBound -> ScEnv -> Var -> (ScEnv, Var)
643 extendBndrWith how_bound env bndr 
644   = (env { sc_subst = subst', sc_how_bound = hb_env' }, bndr')
645   where
646     (subst', bndr') = substBndr (sc_subst env) bndr
647     hb_env' = extendVarEnv (sc_how_bound env) bndr' how_bound
648
649 extendRecBndrs :: ScEnv -> [Var] -> (ScEnv, [Var])
650 extendRecBndrs env bndrs  = (env { sc_subst = subst' }, bndrs')
651                       where
652                         (subst', bndrs') = substRecBndrs (sc_subst env) bndrs
653
654 extendBndr :: ScEnv -> Var -> (ScEnv, Var)
655 extendBndr  env bndr  = (env { sc_subst = subst' }, bndr')
656                       where
657                         (subst', bndr') = substBndr (sc_subst env) bndr
658
659 extendValEnv :: ScEnv -> Id -> Maybe Value -> ScEnv
660 extendValEnv env _  Nothing   = env
661 extendValEnv env id (Just cv) = env { sc_vals = extendVarEnv (sc_vals env) id cv }
662
663 extendCaseBndrs :: ScEnv -> Id -> AltCon -> [Var] -> (ScEnv, [Var])
664 -- When we encounter
665 --      case scrut of b
666 --          C x y -> ...
667 -- we want to bind b, to (C x y)
668 -- NB1: Extends only the sc_vals part of the envt
669 -- NB2: Kill the dead-ness info on the pattern binders x,y, since
670 --      they are potentially made alive by the [b -> C x y] binding
671 extendCaseBndrs env case_bndr con alt_bndrs
672   | isDeadBinder case_bndr
673   = (env, alt_bndrs)
674   | otherwise
675   = (env1, map zap alt_bndrs)
676         -- NB: We used to bind v too, if scrut = (Var v); but
677         --     the simplifer has already done this so it seems
678         --     redundant to do so here
679         -- case scrut of
680         --      Var v  -> extendValEnv env1 v cval
681         --      _other -> env1
682  where
683    zap v | isTyCoVar v = v              -- See NB2 above
684          | otherwise = zapIdOccInfo v
685    env1 = extendValEnv env case_bndr cval
686    cval = case con of
687                 DEFAULT    -> Nothing
688                 LitAlt {}  -> Just (ConVal con [])
689                 DataAlt {} -> Just (ConVal con vanilla_args)
690                       where
691                         vanilla_args = map Type (tyConAppArgs (idType case_bndr)) ++
692                                        varsToCoreExprs alt_bndrs
693
694
695 decreaseSpecCount :: ScEnv -> Int -> ScEnv
696 -- See Note [Avoiding exponential blowup]
697 decreaseSpecCount env n_specs 
698   = env { sc_count = case sc_count env of
699                        Nothing -> Nothing
700                        Just n  -> Just (n `div` (n_specs + 1)) }
701         -- The "+1" takes account of the original function; 
702         -- See Note [Avoiding exponential blowup]
703
704 ---------------------------------------------------
705 -- See Note [SpecConstrAnnotation]
706 ignoreType    :: ScEnv -> Type   -> Bool
707 ignoreAltCon  :: ScEnv -> AltCon -> Bool
708 forceSpecBndr :: ScEnv -> Var    -> Bool
709 #ifndef GHCI
710 ignoreType    _ _ = False
711 ignoreAltCon  _ _ = False
712 forceSpecBndr _ _ = False
713
714 #else /* GHCI */
715
716 ignoreAltCon env (DataAlt dc) = ignoreTyCon env (dataConTyCon dc)
717 ignoreAltCon env (LitAlt lit) = ignoreType env (literalType lit)
718 ignoreAltCon _   DEFAULT      = panic "ignoreAltCon"  -- DEFAULT cannot be in a ConVal
719
720 ignoreType env ty
721   = case splitTyConApp_maybe ty of
722       Just (tycon, _) -> ignoreTyCon env tycon
723       _               -> False
724
725 ignoreTyCon :: ScEnv -> TyCon -> Bool
726 ignoreTyCon env tycon
727   = lookupUFM (sc_annotations env) tycon == Just NoSpecConstr
728
729 forceSpecBndr env var = forceSpecFunTy env . snd . splitForAllTys . varType $ var
730
731 forceSpecFunTy :: ScEnv -> Type -> Bool
732 forceSpecFunTy env = any (forceSpecArgTy env) . fst . splitFunTys
733
734 forceSpecArgTy :: ScEnv -> Type -> Bool
735 forceSpecArgTy env ty
736   | Just ty' <- coreView ty = forceSpecArgTy env ty'
737
738 forceSpecArgTy env ty
739   | Just (tycon, tys) <- splitTyConApp_maybe ty
740   , tycon /= funTyCon
741       = lookupUFM (sc_annotations env) tycon == Just ForceSpecConstr
742         || any (forceSpecArgTy env) tys
743
744 forceSpecArgTy _ _ = False
745 #endif /* GHCI */
746 \end{code}
747
748 Note [Avoiding exponential blowup]
749 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
750 The sc_count field of the ScEnv says how many times we are prepared to
751 duplicate a single function.  But we must take care with recursive
752 specialiations.  Consider
753
754         let $j1 = let $j2 = let $j3 = ...
755                             in 
756                             ...$j3...
757                   in 
758                   ...$j2...
759         in 
760         ...$j1...
761
762 If we specialise $j1 then in each specialisation (as well as the original)
763 we can specialise $j2, and similarly $j3.  Even if we make just *one*
764 specialisation of each, becuase we also have the original we'll get 2^n
765 copies of $j3, which is not good.
766
767 So when recursively specialising we divide the sc_count by the number of
768 copies we are making at this level, including the original.
769
770
771 %************************************************************************
772 %*                                                                      *
773 \subsection{Usage information: flows upwards}
774 %*                                                                      *
775 %************************************************************************
776
777 \begin{code}
778 data ScUsage
779    = SCU {
780         scu_calls :: CallEnv,           -- Calls
781                                         -- The functions are a subset of the 
782                                         --      RecFuns in the ScEnv
783
784         scu_occs :: !(IdEnv ArgOcc)     -- Information on argument occurrences
785      }                                  -- The domain is OutIds
786
787 type CallEnv = IdEnv [Call]
788 type Call = (ValueEnv, [CoreArg])
789         -- The arguments of the call, together with the
790         -- env giving the constructor bindings at the call site
791
792 nullUsage :: ScUsage
793 nullUsage = SCU { scu_calls = emptyVarEnv, scu_occs = emptyVarEnv }
794
795 combineCalls :: CallEnv -> CallEnv -> CallEnv
796 combineCalls = plusVarEnv_C (++)
797
798 combineUsage :: ScUsage -> ScUsage -> ScUsage
799 combineUsage u1 u2 = SCU { scu_calls = combineCalls (scu_calls u1) (scu_calls u2),
800                            scu_occs  = plusVarEnv_C combineOcc (scu_occs u1) (scu_occs u2) }
801
802 combineUsages :: [ScUsage] -> ScUsage
803 combineUsages [] = nullUsage
804 combineUsages us = foldr1 combineUsage us
805
806 lookupOcc :: ScUsage -> OutVar -> (ScUsage, ArgOcc)
807 lookupOcc (SCU { scu_calls = sc_calls, scu_occs = sc_occs }) bndr
808   = (SCU {scu_calls = sc_calls, scu_occs = delVarEnv sc_occs bndr},
809      lookupVarEnv sc_occs bndr `orElse` NoOcc)
810
811 lookupOccs :: ScUsage -> [OutVar] -> (ScUsage, [ArgOcc])
812 lookupOccs (SCU { scu_calls = sc_calls, scu_occs = sc_occs }) bndrs
813   = (SCU {scu_calls = sc_calls, scu_occs = delVarEnvList sc_occs bndrs},
814      [lookupVarEnv sc_occs b `orElse` NoOcc | b <- bndrs])
815
816 data ArgOcc = NoOcc     -- Doesn't occur at all; or a type argument
817             | UnkOcc    -- Used in some unknown way
818
819             | ScrutOcc (UniqFM [ArgOcc])        -- See Note [ScrutOcc]
820
821             | BothOcc   -- Definitely taken apart, *and* perhaps used in some other way
822
823 {-      Note  [ScrutOcc]
824
825 An occurrence of ScrutOcc indicates that the thing, or a `cast` version of the thing,
826 is *only* taken apart or applied.
827
828   Functions, literal: ScrutOcc emptyUFM
829   Data constructors:  ScrutOcc subs,
830
831 where (subs :: UniqFM [ArgOcc]) gives usage of the *pattern-bound* components,
832 The domain of the UniqFM is the Unique of the data constructor
833
834 The [ArgOcc] is the occurrences of the *pattern-bound* components 
835 of the data structure.  E.g.
836         data T a = forall b. MkT a b (b->a)
837 A pattern binds b, x::a, y::b, z::b->a, but not 'a'!
838
839 -}
840
841 instance Outputable ArgOcc where
842   ppr (ScrutOcc xs) = ptext (sLit "scrut-occ") <> ppr xs
843   ppr UnkOcc        = ptext (sLit "unk-occ")
844   ppr BothOcc       = ptext (sLit "both-occ")
845   ppr NoOcc         = ptext (sLit "no-occ")
846
847 -- Experimentally, this vesion of combineOcc makes ScrutOcc "win", so
848 -- that if the thing is scrutinised anywhere then we get to see that
849 -- in the overall result, even if it's also used in a boxed way
850 -- This might be too agressive; see Note [Reboxing] Alternative 3
851 combineOcc :: ArgOcc -> ArgOcc -> ArgOcc
852 combineOcc NoOcc         occ           = occ
853 combineOcc occ           NoOcc         = occ
854 combineOcc (ScrutOcc xs) (ScrutOcc ys) = ScrutOcc (plusUFM_C combineOccs xs ys)
855 combineOcc _occ          (ScrutOcc ys) = ScrutOcc ys
856 combineOcc (ScrutOcc xs) _occ          = ScrutOcc xs
857 combineOcc UnkOcc        UnkOcc        = UnkOcc
858 combineOcc _        _                  = BothOcc
859
860 combineOccs :: [ArgOcc] -> [ArgOcc] -> [ArgOcc]
861 combineOccs xs ys = zipWithEqual "combineOccs" combineOcc xs ys
862
863 setScrutOcc :: ScEnv -> ScUsage -> OutExpr -> ArgOcc -> ScUsage
864 -- _Overwrite_ the occurrence info for the scrutinee, if the scrutinee
865 -- is a variable, and an interesting variable
866 setScrutOcc env usg (Cast e _) occ = setScrutOcc env usg e occ
867 setScrutOcc env usg (Note _ e) occ = setScrutOcc env usg e occ
868 setScrutOcc env usg (Var v)    occ
869   | Just RecArg <- lookupHowBound env v = usg { scu_occs = extendVarEnv (scu_occs usg) v occ }
870   | otherwise                           = usg
871 setScrutOcc _env usg _other _occ        -- Catch-all
872   = usg 
873
874 conArgOccs :: ArgOcc -> AltCon -> [ArgOcc]
875 -- Find usage of components of data con; returns [UnkOcc...] if unknown
876 -- See Note [ScrutOcc] for the extra UnkOccs in the vanilla datacon case
877
878 conArgOccs (ScrutOcc fm) (DataAlt dc) 
879   | Just pat_arg_occs <- lookupUFM fm dc
880   = [UnkOcc | _ <- dataConUnivTyVars dc] ++ pat_arg_occs
881
882 conArgOccs _other _con = repeat UnkOcc
883 \end{code}
884
885 %************************************************************************
886 %*                                                                      *
887 \subsection{The main recursive function}
888 %*                                                                      *
889 %************************************************************************
890
891 The main recursive function gathers up usage information, and
892 creates specialised versions of functions.
893
894 \begin{code}
895 scExpr, scExpr' :: ScEnv -> CoreExpr -> UniqSM (ScUsage, CoreExpr)
896         -- The unique supply is needed when we invent
897         -- a new name for the specialised function and its args
898
899 scExpr env e = scExpr' env e
900
901
902 scExpr' env (Var v)     = case scSubstId env v of
903                             Var v' -> return (varUsage env v' UnkOcc, Var v')
904                             e'     -> scExpr (zapScSubst env) e'
905
906 scExpr' env (Type t)    = return (nullUsage, Type (scSubstTy env t))
907 scExpr' _   e@(Lit {})  = return (nullUsage, e)
908 scExpr' env (Note n e)  = do (usg,e') <- scExpr env e
909                              return (usg, Note n e')
910 scExpr' env (Cast e co) = do (usg, e') <- scExpr env e
911                              return (usg, Cast e' (scSubstTy env co))
912 scExpr' env e@(App _ _) = scApp env (collectArgs e)
913 scExpr' env (Lam b e)   = do let (env', b') = extendBndr env b
914                              (usg, e') <- scExpr env' e
915                              return (usg, Lam b' e')
916
917 scExpr' env (Case scrut b ty alts) 
918   = do  { (scrut_usg, scrut') <- scExpr env scrut
919         ; case isValue (sc_vals env) scrut' of
920                 Just (ConVal con args) -> sc_con_app con args scrut'
921                 _other                 -> sc_vanilla scrut_usg scrut'
922         }
923   where
924     sc_con_app con args scrut'  -- Known constructor; simplify
925         = do { let (_, bs, rhs) = findAlt con alts
926                                   `orElse` (DEFAULT, [], mkImpossibleExpr (coreAltsType alts))
927                    alt_env'  = extendScSubstList env ((b,scrut') : bs `zip` trimConArgs con args)
928              ; scExpr alt_env' rhs }
929                                 
930     sc_vanilla scrut_usg scrut' -- Normal case
931      = do { let (alt_env,b') = extendBndrWith RecArg env b
932                         -- Record RecArg for the components
933
934           ; (alt_usgs, alt_occs, alts')
935                 <- mapAndUnzip3M (sc_alt alt_env scrut' b') alts
936
937           ; let (alt_usg, b_occ) = lookupOcc (combineUsages alt_usgs) b'
938                 scrut_occ        = foldr combineOcc b_occ alt_occs
939                 scrut_usg'       = setScrutOcc env scrut_usg scrut' scrut_occ
940                 -- The combined usage of the scrutinee is given
941                 -- by scrut_occ, which is passed to scScrut, which
942                 -- in turn treats a bare-variable scrutinee specially
943
944           ; return (alt_usg `combineUsage` scrut_usg',
945                     Case scrut' b' (scSubstTy env ty) alts') }
946
947     sc_alt env _scrut' b' (con,bs,rhs)
948       = do { let (env1, bs1)  = extendBndrsWith RecArg env bs
949                  (env2, bs2) = extendCaseBndrs env1 b' con bs1
950            ; (usg,rhs') <- scExpr env2 rhs
951            ; let (usg', arg_occs) = lookupOccs usg bs2
952                  scrut_occ = case con of
953                                 DataAlt dc -> ScrutOcc (unitUFM dc arg_occs)
954                                 _          -> ScrutOcc emptyUFM
955            ; return (usg', scrut_occ, (con, bs2, rhs')) }
956
957 scExpr' env (Let (NonRec bndr rhs) body)
958   | isTyCoVar bndr      -- Type-lets may be created by doBeta
959   = scExpr' (extendScSubst env bndr rhs) body
960
961   | otherwise              -- Note [Local let bindings]
962   = do  { let (body_env, bndr') = extendBndr env bndr
963               body_env2 = extendHowBound body_env [bndr'] RecFun
964         ; (body_usg, body') <- scExpr body_env2 body
965
966         ; (rhs_usg, rhs_info) <- scRecRhs env (bndr',rhs)
967
968           -- NB: We don't use the ForceSpecConstr mechanism (see
969           -- Note [Forcing specialisation]) for non-recursive bindings
970           -- at the moment. I'm not sure if this is the right thing to do.
971         ; let force_spec = False
972         ; (spec_usg, specs) <- specialise env force_spec 
973                                           (scu_calls body_usg) 
974                                           rhs_info
975                                           (SI [] 0 (Just rhs_usg))
976
977         ; return (body_usg { scu_calls = scu_calls body_usg `delVarEnv` bndr' } 
978                     `combineUsage` spec_usg,
979                   mkLets [NonRec b r | (b,r) <- specInfoBinds rhs_info specs] body')
980         }
981
982
983 -- A *local* recursive group: see Note [Local recursive groups]
984 scExpr' env (Let (Rec prs) body)
985   = do  { let (bndrs,rhss) = unzip prs
986               (rhs_env1,bndrs') = extendRecBndrs env bndrs
987               rhs_env2 = extendHowBound rhs_env1 bndrs' RecFun
988               force_spec = any (forceSpecBndr env) bndrs'
989                 -- Note [Forcing specialisation]
990
991         ; (rhs_usgs, rhs_infos) <- mapAndUnzipM (scRecRhs rhs_env2) (bndrs' `zip` rhss)
992         ; (body_usg, body')     <- scExpr rhs_env2 body
993
994         -- NB: start specLoop from body_usg
995         ; (spec_usg, specs) <- specLoop rhs_env2 force_spec
996                                         (scu_calls body_usg) rhs_infos nullUsage
997                                         [SI [] 0 (Just usg) | usg <- rhs_usgs]
998                 -- Do not unconditionally use rhs_usgs. 
999                 -- Instead use them only if we find an unspecialised call
1000                 -- See Note [Local recursive groups]
1001
1002         ; let all_usg = spec_usg `combineUsage` body_usg
1003               bind'   = Rec (concat (zipWith specInfoBinds rhs_infos specs))
1004
1005         ; return (all_usg { scu_calls = scu_calls all_usg `delVarEnvList` bndrs' },
1006                   Let bind' body') }
1007 \end{code}
1008
1009 Note [Local let bindings]
1010 ~~~~~~~~~~~~~~~~~~~~~~~~~
1011 It is not uncommon to find this
1012
1013    let $j = \x. <blah> in ...$j True...$j True...
1014
1015 Here $j is an arbitrary let-bound function, but it often comes up for
1016 join points.  We might like to specialise $j for its call patterns.
1017 Notice the difference from a letrec, where we look for call patterns
1018 in the *RHS* of the function.  Here we look for call patterns in the
1019 *body* of the let.
1020
1021 At one point I predicated this on the RHS mentioning the outer
1022 recursive function, but that's not essential and might even be
1023 harmful.  I'm not sure.
1024
1025
1026 \begin{code}
1027 scApp :: ScEnv -> (InExpr, [InExpr]) -> UniqSM (ScUsage, CoreExpr)
1028
1029 scApp env (Var fn, args)        -- Function is a variable
1030   = ASSERT( not (null args) )
1031     do  { args_w_usgs <- mapM (scExpr env) args
1032         ; let (arg_usgs, args') = unzip args_w_usgs
1033               arg_usg = combineUsages arg_usgs
1034         ; case scSubstId env fn of
1035             fn'@(Lam {}) -> scExpr (zapScSubst env) (doBeta fn' args')
1036                         -- Do beta-reduction and try again
1037
1038             Var fn' -> return (arg_usg `combineUsage` fn_usg, mkApps (Var fn') args')
1039                 where
1040                   fn_usg = case lookupHowBound env fn' of
1041                                 Just RecFun -> SCU { scu_calls = unitVarEnv fn' [(sc_vals env, args')], 
1042                                                      scu_occs  = emptyVarEnv }
1043                                 Just RecArg -> SCU { scu_calls = emptyVarEnv,
1044                                                      scu_occs  = unitVarEnv fn' (ScrutOcc emptyUFM) }
1045                                 Nothing     -> nullUsage
1046
1047
1048             other_fn' -> return (arg_usg, mkApps other_fn' args') }
1049                 -- NB: doing this ignores any usage info from the substituted
1050                 --     function, but I don't think that matters.  If it does
1051                 --     we can fix it.
1052   where
1053     doBeta :: OutExpr -> [OutExpr] -> OutExpr
1054     -- ToDo: adjust for System IF
1055     doBeta (Lam bndr body) (arg : args) = Let (NonRec bndr arg) (doBeta body args)
1056     doBeta fn              args         = mkApps fn args
1057
1058 -- The function is almost always a variable, but not always.  
1059 -- In particular, if this pass follows float-in,
1060 -- which it may, we can get 
1061 --      (let f = ...f... in f) arg1 arg2
1062 scApp env (other_fn, args)
1063   = do  { (fn_usg,   fn')   <- scExpr env other_fn
1064         ; (arg_usgs, args') <- mapAndUnzipM (scExpr env) args
1065         ; return (combineUsages arg_usgs `combineUsage` fn_usg, mkApps fn' args') }
1066
1067 ----------------------
1068 scTopBind :: ScEnv -> CoreBind -> UniqSM (ScEnv, CoreBind)
1069 scTopBind env (Rec prs)
1070   | Just threshold <- sc_size env
1071   , not force_spec
1072   , not (all (couldBeSmallEnoughToInline threshold) rhss)
1073                 -- No specialisation
1074   = do  { let (rhs_env,bndrs') = extendRecBndrs env bndrs
1075         ; (_, rhss') <- mapAndUnzipM (scExpr rhs_env) rhss
1076         ; return (rhs_env, Rec (bndrs' `zip` rhss')) }
1077   | otherwise   -- Do specialisation
1078   = do  { let (rhs_env1,bndrs') = extendRecBndrs env bndrs
1079               rhs_env2 = extendHowBound rhs_env1 bndrs' RecFun
1080
1081         ; (rhs_usgs, rhs_infos) <- mapAndUnzipM (scRecRhs rhs_env2) (bndrs' `zip` rhss)
1082         ; let rhs_usg = combineUsages rhs_usgs
1083
1084         ; (_, specs) <- specLoop rhs_env2 force_spec
1085                                  (scu_calls rhs_usg) rhs_infos nullUsage
1086                                  [SI [] 0 Nothing | _ <- bndrs]
1087
1088         ; return (rhs_env1,  -- For the body of the letrec, delete the RecFun business
1089                   Rec (concat (zipWith specInfoBinds rhs_infos specs))) }
1090   where
1091     (bndrs,rhss) = unzip prs
1092     force_spec = any (forceSpecBndr env) bndrs
1093       -- Note [Forcing specialisation]
1094
1095 scTopBind env (NonRec bndr rhs)
1096   = do  { (_, rhs') <- scExpr env rhs
1097         ; let (env1, bndr') = extendBndr env bndr
1098               env2 = extendValEnv env1 bndr' (isValue (sc_vals env) rhs')
1099         ; return (env2, NonRec bndr' rhs') }
1100
1101 ----------------------
1102 scRecRhs :: ScEnv -> (OutId, InExpr) -> UniqSM (ScUsage, RhsInfo)
1103 scRecRhs env (bndr,rhs)
1104   = do  { let (arg_bndrs,body) = collectBinders rhs
1105               (body_env, arg_bndrs') = extendBndrsWith RecArg env arg_bndrs
1106         ; (body_usg, body') <- scExpr body_env body
1107         ; let (rhs_usg, arg_occs) = lookupOccs body_usg arg_bndrs'
1108         ; return (rhs_usg, RI bndr (mkLams arg_bndrs' body')
1109                                    arg_bndrs body arg_occs) }
1110                 -- The arg_occs says how the visible,
1111                 -- lambda-bound binders of the RHS are used
1112                 -- (including the TyVar binders)
1113                 -- Two pats are the same if they match both ways
1114
1115 ----------------------
1116 specInfoBinds :: RhsInfo -> SpecInfo -> [(Id,CoreExpr)]
1117 specInfoBinds (RI fn new_rhs _ _ _) (SI specs _ _)
1118   = [(id,rhs) | OS _ _ id rhs <- specs] ++ 
1119     [(fn `addIdSpecialisations` rules, new_rhs)]
1120   where
1121     rules = [r | OS _ r _ _ <- specs]
1122
1123 ----------------------
1124 varUsage :: ScEnv -> OutVar -> ArgOcc -> ScUsage
1125 varUsage env v use 
1126   | Just RecArg <- lookupHowBound env v = SCU { scu_calls = emptyVarEnv 
1127                                               , scu_occs = unitVarEnv v use }
1128   | otherwise                           = nullUsage
1129 \end{code}
1130
1131
1132 %************************************************************************
1133 %*                                                                      *
1134                 The specialiser itself
1135 %*                                                                      *
1136 %************************************************************************
1137
1138 \begin{code}
1139 data RhsInfo = RI OutId                 -- The binder
1140                   OutExpr               -- The new RHS
1141                   [InVar] InExpr        -- The *original* RHS (\xs.body)
1142                                         --   Note [Specialise original body]
1143                   [ArgOcc]              -- Info on how the xs occur in body
1144
1145 data SpecInfo = SI [OneSpec]            -- The specialisations we have generated
1146
1147                    Int                  -- Length of specs; used for numbering them
1148
1149                    (Maybe ScUsage)      -- Nothing => we have generated specialisations
1150                                         --            from calls in the *original* RHS
1151                                         -- Just cs => we haven't, and this is the usage
1152                                         --            of the original RHS
1153                                         -- See Note [Local recursive groups]
1154
1155         -- One specialisation: Rule plus definition
1156 data OneSpec  = OS CallPat              -- Call pattern that generated this specialisation
1157                    CoreRule             -- Rule connecting original id with the specialisation
1158                    OutId OutExpr        -- Spec id + its rhs
1159
1160
1161 specLoop :: ScEnv
1162          -> Bool                                -- force specialisation?
1163                                                 -- Note [Forcing specialisation]
1164          -> CallEnv
1165          -> [RhsInfo]
1166          -> ScUsage -> [SpecInfo]               -- One per binder; acccumulating parameter
1167          -> UniqSM (ScUsage, [SpecInfo])        -- ...ditto...
1168 specLoop env force_spec all_calls rhs_infos usg_so_far specs_so_far
1169   = do  { specs_w_usg <- zipWithM (specialise env force_spec all_calls) rhs_infos specs_so_far
1170         ; let (new_usg_s, all_specs) = unzip specs_w_usg
1171               new_usg   = combineUsages new_usg_s
1172               new_calls = scu_calls new_usg
1173               all_usg   = usg_so_far `combineUsage` new_usg
1174         ; if isEmptyVarEnv new_calls then
1175                 return (all_usg, all_specs) 
1176           else 
1177                 specLoop env force_spec new_calls rhs_infos all_usg all_specs }
1178
1179 specialise 
1180    :: ScEnv
1181    -> Bool                              -- force specialisation?
1182                                         --   Note [Forcing specialisation]
1183    -> CallEnv                           -- Info on calls
1184    -> RhsInfo
1185    -> SpecInfo                          -- Original RHS plus patterns dealt with
1186    -> UniqSM (ScUsage, SpecInfo)        -- New specialised versions and their usage
1187
1188 -- Note: the rhs here is the optimised version of the original rhs
1189 -- So when we make a specialised copy of the RHS, we're starting
1190 -- from an RHS whose nested functions have been optimised already.
1191
1192 specialise env force_spec bind_calls (RI fn _ arg_bndrs body arg_occs) 
1193                           spec_info@(SI specs spec_count mb_unspec)
1194   | not (isBottomingId fn)      -- Note [Do not specialise diverging functions]
1195   , not (isNeverActive (idInlineActivation fn)) -- See Note [Transfer activation]
1196   , notNull arg_bndrs           -- Only specialise functions
1197   , Just all_calls <- lookupVarEnv bind_calls fn
1198   = do  { (boring_call, pats) <- callsToPats env specs arg_occs all_calls
1199 --      ; pprTrace "specialise" (vcat [ ppr fn <+> text "with" <+> int (length pats) <+> text "good patterns"
1200 --                                      , text "arg_occs" <+> ppr arg_occs
1201 --                                    , text "calls" <+> ppr all_calls
1202 --                                    , text "good pats" <+> ppr pats])  $
1203 --        return ()
1204
1205                 -- Bale out if too many specialisations
1206         ; let n_pats      = length pats
1207               spec_count' = n_pats + spec_count
1208         ; case sc_count env of
1209             Just max | not force_spec && spec_count' > max
1210                 -> pprTrace "SpecConstr" msg $  
1211                    return (nullUsage, spec_info)
1212                 where
1213                    msg = vcat [ sep [ ptext (sLit "Function") <+> quotes (ppr fn)
1214                                     , nest 2 (ptext (sLit "has") <+> 
1215                                               speakNOf spec_count' (ptext (sLit "call pattern")) <> comma <+>
1216                                               ptext (sLit "but the limit is") <+> int max) ]
1217                               , ptext (sLit "Use -fspec-constr-count=n to set the bound")
1218                               , extra ]
1219                    extra | not opt_PprStyle_Debug = ptext (sLit "Use -dppr-debug to see specialisations")
1220                          | otherwise = ptext (sLit "Specialisations:") <+> ppr (pats ++ [p | OS p _ _ _ <- specs])
1221
1222             _normal_case -> do {
1223
1224           let spec_env = decreaseSpecCount env n_pats
1225         ; (spec_usgs, new_specs) <- mapAndUnzipM (spec_one spec_env fn arg_bndrs body)
1226                                                  (pats `zip` [spec_count..])
1227                 -- See Note [Specialise original body]
1228
1229         ; let spec_usg = combineUsages spec_usgs
1230               (new_usg, mb_unspec')
1231                   = case mb_unspec of
1232                       Just rhs_usg | boring_call -> (spec_usg `combineUsage` rhs_usg, Nothing)
1233                       _                          -> (spec_usg,                      mb_unspec)
1234             
1235         ; return (new_usg, SI (new_specs ++ specs) spec_count' mb_unspec') } }
1236   | otherwise
1237   = return (nullUsage, spec_info)               -- The boring case
1238
1239
1240 ---------------------
1241 spec_one :: ScEnv
1242          -> OutId       -- Function
1243          -> [InVar]     -- Lambda-binders of RHS; should match patterns
1244          -> InExpr      -- Body of the original function
1245          -> (CallPat, Int)
1246          -> UniqSM (ScUsage, OneSpec)   -- Rule and binding
1247
1248 -- spec_one creates a specialised copy of the function, together
1249 -- with a rule for using it.  I'm very proud of how short this
1250 -- function is, considering what it does :-).
1251
1252 {- 
1253   Example
1254   
1255      In-scope: a, x::a   
1256      f = /\b \y::[(a,b)] -> ....f (b,c) ((:) (a,(b,c)) (x,v) (h w))...
1257           [c::*, v::(b,c) are presumably bound by the (...) part]
1258   ==>
1259      f_spec = /\ b c \ v::(b,c) hw::[(a,(b,c))] ->
1260                   (...entire body of f...) [b -> (b,c), 
1261                                             y -> ((:) (a,(b,c)) (x,v) hw)]
1262   
1263      RULE:  forall b::* c::*,           -- Note, *not* forall a, x
1264                    v::(b,c),
1265                    hw::[(a,(b,c))] .
1266   
1267             f (b,c) ((:) (a,(b,c)) (x,v) hw) = f_spec b c v hw
1268 -}
1269
1270 spec_one env fn arg_bndrs body (call_pat@(qvars, pats), rule_number)
1271   = do  { spec_uniq <- getUniqueUs
1272         ; let spec_env = extendScSubstList (extendScInScope env qvars)
1273                                            (arg_bndrs `zip` pats)
1274               fn_name    = idName fn
1275               fn_loc     = nameSrcSpan fn_name
1276               spec_occ   = mkSpecOcc (nameOccName fn_name)
1277               rule_name  = mkFastString ("SC:" ++ showSDoc (ppr fn <> int rule_number))
1278               spec_name  = mkInternalName spec_uniq spec_occ fn_loc
1279 --      ; pprTrace "{spec_one" (ppr (sc_count env) <+> ppr fn <+> ppr pats <+> text "-->" <+> ppr spec_name) $ 
1280 --        return ()
1281
1282         -- Specialise the body
1283         ; (spec_usg, spec_body) <- scExpr spec_env body
1284
1285 --      ; pprTrace "done spec_one}" (ppr fn) $ 
1286 --        return ()
1287
1288                 -- And build the results
1289         ; let spec_id = mkLocalId spec_name (mkPiTypes spec_lam_args body_ty) 
1290                              `setIdStrictness` spec_str         -- See Note [Transfer strictness]
1291                              `setIdArity` count isId spec_lam_args
1292               spec_str   = calcSpecStrictness fn spec_lam_args pats
1293               (spec_lam_args, spec_call_args) = mkWorkerArgs qvars body_ty
1294                 -- Usual w/w hack to avoid generating 
1295                 -- a spec_rhs of unlifted type and no args
1296
1297               spec_rhs   = mkLams spec_lam_args spec_body
1298               body_ty    = exprType spec_body
1299               rule_rhs   = mkVarApps (Var spec_id) spec_call_args
1300               inline_act = idInlineActivation fn
1301               rule       = mkRule True {- Auto -} True {- Local -}
1302                                   rule_name inline_act fn_name qvars pats rule_rhs
1303                            -- See Note [Transfer activation]
1304         ; return (spec_usg, OS call_pat rule spec_id spec_rhs) }
1305
1306 calcSpecStrictness :: Id                     -- The original function
1307                    -> [Var] -> [CoreExpr]    -- Call pattern
1308                    -> StrictSig              -- Strictness of specialised thing
1309 -- See Note [Transfer strictness]
1310 calcSpecStrictness fn qvars pats
1311   = StrictSig (mkTopDmdType spec_dmds TopRes)
1312   where
1313     spec_dmds = [ lookupVarEnv dmd_env qv `orElse` lazyDmd | qv <- qvars, isId qv ]
1314     StrictSig (DmdType _ dmds _) = idStrictness fn
1315
1316     dmd_env = go emptyVarEnv dmds pats
1317
1318     go env ds (Type {} : pats) = go env ds pats
1319     go env (d:ds) (pat : pats) = go (go_one env d pat) ds pats
1320     go env _      _            = env
1321
1322     go_one env d   (Var v) = extendVarEnv_C both env v d
1323     go_one env (Box d)   e = go_one env d e
1324     go_one env (Eval (Prod ds)) e 
1325            | (Var _, args) <- collectArgs e = go env ds args
1326     go_one env _         _ = env
1327
1328 \end{code}
1329
1330 Note [Specialise original body]
1331 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1332 The RhsInfo for a binding keeps the *original* body of the binding.  We
1333 must specialise that, *not* the result of applying specExpr to the RHS
1334 (which is also kept in RhsInfo). Otherwise we end up specialising a
1335 specialised RHS, and that can lead directly to exponential behaviour.
1336
1337 Note [Transfer activation]
1338 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1339   This note is for SpecConstr, but exactly the same thing
1340   happens in the overloading specialiser; see
1341   Note [Auto-specialisation and RULES] in Specialise.
1342
1343 In which phase should the specialise-constructor rules be active?
1344 Originally I made them always-active, but Manuel found that this
1345 defeated some clever user-written rules.  Then I made them active only
1346 in Phase 0; after all, currently, the specConstr transformation is
1347 only run after the simplifier has reached Phase 0, but that meant
1348 that specialisations didn't fire inside wrappers; see test
1349 simplCore/should_compile/spec-inline.
1350
1351 So now I just use the inline-activation of the parent Id, as the
1352 activation for the specialiation RULE, just like the main specialiser;
1353
1354 This in turn means there is no point in specialising NOINLINE things,
1355 so we test for that.
1356
1357 Note [Transfer strictness]
1358 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1359 We must transfer strictness information from the original function to
1360 the specialised one.  Suppose, for example
1361
1362   f has strictness     SS
1363         and a RULE     f (a:as) b = f_spec a as b
1364
1365 Now we want f_spec to have strictess  LLS, otherwise we'll use call-by-need
1366 when calling f_spec instead of call-by-value.  And that can result in 
1367 unbounded worsening in space (cf the classic foldl vs foldl')
1368
1369 See Trac #3437 for a good example.
1370
1371 The function calcSpecStrictness performs the calculation.
1372
1373
1374 %************************************************************************
1375 %*                                                                      *
1376 \subsection{Argument analysis}
1377 %*                                                                      *
1378 %************************************************************************
1379
1380 This code deals with analysing call-site arguments to see whether
1381 they are constructor applications.
1382
1383
1384 \begin{code}
1385 type CallPat = ([Var], [CoreExpr])      -- Quantified variables and arguments
1386
1387
1388 callsToPats :: ScEnv -> [OneSpec] -> [ArgOcc] -> [Call] -> UniqSM (Bool, [CallPat])
1389         -- Result has no duplicate patterns, 
1390         -- nor ones mentioned in done_pats
1391         -- Bool indicates that there was at least one boring pattern
1392 callsToPats env done_specs bndr_occs calls
1393   = do  { mb_pats <- mapM (callToPats env bndr_occs) calls
1394
1395         ; let good_pats :: [([Var], [CoreArg])]
1396               good_pats = catMaybes mb_pats
1397               done_pats = [p | OS p _ _ _ <- done_specs] 
1398               is_done p = any (samePat p) done_pats
1399
1400         ; return (any isNothing mb_pats, 
1401                   filterOut is_done (nubBy samePat good_pats)) }
1402
1403 callToPats :: ScEnv -> [ArgOcc] -> Call -> UniqSM (Maybe CallPat)
1404         -- The [Var] is the variables to quantify over in the rule
1405         --      Type variables come first, since they may scope 
1406         --      over the following term variables
1407         -- The [CoreExpr] are the argument patterns for the rule
1408 callToPats env bndr_occs (con_env, args)
1409   | length args < length bndr_occs      -- Check saturated
1410   = return Nothing
1411   | otherwise
1412   = do  { let in_scope = substInScope (sc_subst env)
1413         ; prs <- argsToPats env in_scope con_env (args `zip` bndr_occs)
1414         ; let (interesting_s, pats) = unzip prs
1415               pat_fvs = varSetElems (exprsFreeVars pats)
1416               qvars   = filterOut (`elemInScopeSet` in_scope) pat_fvs
1417                 -- Quantify over variables that are not in sccpe
1418                 -- at the call site
1419                 -- See Note [Shadowing] at the top
1420                 
1421               (tvs, ids) = partition isTyCoVar qvars
1422               qvars'     = tvs ++ ids
1423                 -- Put the type variables first; the type of a term
1424                 -- variable may mention a type variable
1425
1426         ; -- pprTrace "callToPats"  (ppr args $$ ppr prs $$ ppr bndr_occs) $
1427           if or interesting_s
1428           then return (Just (qvars', pats))
1429           else return Nothing }
1430
1431     -- argToPat takes an actual argument, and returns an abstracted
1432     -- version, consisting of just the "constructor skeleton" of the
1433     -- argument, with non-constructor sub-expression replaced by new
1434     -- placeholder variables.  For example:
1435     --    C a (D (f x) (g y))  ==>  C p1 (D p2 p3)
1436
1437 argToPat :: ScEnv
1438          -> InScopeSet                  -- What's in scope at the fn defn site
1439          -> ValueEnv                    -- ValueEnv at the call site
1440          -> CoreArg                     -- A call arg (or component thereof)
1441          -> ArgOcc
1442          -> UniqSM (Bool, CoreArg)
1443 -- Returns (interesting, pat), 
1444 -- where pat is the pattern derived from the argument
1445 --            intersting=True if the pattern is non-trivial (not a variable or type)
1446 -- E.g.         x:xs         --> (True, x:xs)
1447 --              f xs         --> (False, w)        where w is a fresh wildcard
1448 --              (f xs, 'c')  --> (True, (w, 'c'))  where w is a fresh wildcard
1449 --              \x. x+y      --> (True, \x. x+y)
1450 --              lvl7         --> (True, lvl7)      if lvl7 is bound 
1451 --                                                 somewhere further out
1452
1453 argToPat _env _in_scope _val_env arg@(Type {}) _arg_occ
1454   = return (False, arg)
1455
1456 argToPat env in_scope val_env (Note _ arg) arg_occ
1457   = argToPat env in_scope val_env arg arg_occ
1458         -- Note [Notes in call patterns]
1459         -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1460         -- Ignore Notes.  In particular, we want to ignore any InlineMe notes
1461         -- Perhaps we should not ignore profiling notes, but I'm going to
1462         -- ride roughshod over them all for now.
1463         --- See Note [Notes in RULE matching] in Rules
1464
1465 argToPat env in_scope val_env (Let _ arg) arg_occ
1466   = argToPat env in_scope val_env arg arg_occ
1467         -- See Note [Matching lets] in Rule.lhs
1468         -- Look through let expressions
1469         -- e.g.         f (let v = rhs in (v,w))
1470         -- Here we can specialise for f (v,w)
1471         -- because the rule-matcher will look through the let.
1472
1473 {- Disabled; see Note [Matching cases] in Rule.lhs
1474 argToPat env in_scope val_env (Case scrut _ _ [(_, _, rhs)]) arg_occ
1475   | exprOkForSpeculation scrut  -- See Note [Matching cases] in Rule.hhs
1476   = argToPat env in_scope val_env rhs arg_occ
1477 -}
1478
1479 argToPat env in_scope val_env (Cast arg co) arg_occ
1480   | not (ignoreType env ty2)
1481   = do  { (interesting, arg') <- argToPat env in_scope val_env arg arg_occ
1482         ; if not interesting then 
1483                 wildCardPat ty2
1484           else do
1485         { -- Make a wild-card pattern for the coercion
1486           uniq <- getUniqueUs
1487         ; let co_name = mkSysTvName uniq (fsLit "sg")
1488               co_var = mkCoVar co_name (mkCoKind ty1 ty2)
1489         ; return (interesting, Cast arg' (mkTyVarTy co_var)) } }
1490   where
1491     (ty1, ty2) = coercionKind co
1492
1493     
1494
1495 {-      Disabling lambda specialisation for now
1496         It's fragile, and the spec_loop can be infinite
1497 argToPat in_scope val_env arg arg_occ
1498   | is_value_lam arg
1499   = return (True, arg)
1500   where
1501     is_value_lam (Lam v e)      -- Spot a value lambda, even if 
1502         | isId v = True         -- it is inside a type lambda
1503         | otherwise = is_value_lam e
1504     is_value_lam other = False
1505 -}
1506
1507   -- Check for a constructor application
1508   -- NB: this *precedes* the Var case, so that we catch nullary constrs
1509 argToPat env in_scope val_env arg arg_occ
1510   | Just (ConVal dc args) <- isValue val_env arg
1511   , not (ignoreAltCon env dc)
1512   , case arg_occ of
1513         ScrutOcc _ -> True              -- Used only by case scrutinee
1514         BothOcc    -> case arg of       -- Used elsewhere
1515                         App {} -> True  --     see Note [Reboxing]
1516                         _other -> False
1517         _other     -> False     -- No point; the arg is not decomposed
1518   = do  { args' <- argsToPats env in_scope val_env (args `zip` conArgOccs arg_occ dc)
1519         ; return (True, mk_con_app dc (map snd args')) }
1520
1521   -- Check if the argument is a variable that 
1522   -- is in scope at the function definition site
1523   -- It's worth specialising on this if
1524   --    (a) it's used in an interesting way in the body
1525   --    (b) we know what its value is
1526 argToPat env in_scope val_env (Var v) arg_occ
1527   | case arg_occ of { UnkOcc -> False; _other -> True },        -- (a)
1528     is_value,                                                   -- (b)
1529     not (ignoreType env (varType v))
1530   = return (True, Var v)
1531   where
1532     is_value 
1533         | isLocalId v = v `elemInScopeSet` in_scope 
1534                         && isJust (lookupVarEnv val_env v)
1535                 -- Local variables have values in val_env
1536         | otherwise   = isValueUnfolding (idUnfolding v)
1537                 -- Imports have unfoldings
1538
1539 --      I'm really not sure what this comment means
1540 --      And by not wild-carding we tend to get forall'd 
1541 --      variables that are in soope, which in turn can
1542 --      expose the weakness in let-matching
1543 --      See Note [Matching lets] in Rules
1544
1545   -- Check for a variable bound inside the function. 
1546   -- Don't make a wild-card, because we may usefully share
1547   --    e.g.  f a = let x = ... in f (x,x)
1548   -- NB: this case follows the lambda and con-app cases!!
1549 -- argToPat _in_scope _val_env (Var v) _arg_occ
1550 --   = return (False, Var v)
1551         -- SLPJ : disabling this to avoid proliferation of versions
1552         -- also works badly when thinking about seeding the loop
1553         -- from the body of the let
1554         --       f x y = letrec g z = ... in g (x,y)
1555         -- We don't want to specialise for that *particular* x,y
1556
1557   -- The default case: make a wild-card
1558 argToPat _env _in_scope _val_env arg _arg_occ
1559   = wildCardPat (exprType arg)
1560
1561 wildCardPat :: Type -> UniqSM (Bool, CoreArg)
1562 wildCardPat ty = do { uniq <- getUniqueUs
1563                     ; let id = mkSysLocal (fsLit "sc") uniq ty
1564                     ; return (False, Var id) }
1565
1566 argsToPats :: ScEnv -> InScopeSet -> ValueEnv
1567            -> [(CoreArg, ArgOcc)]
1568            -> UniqSM [(Bool, CoreArg)]
1569 argsToPats env in_scope val_env args
1570   = mapM do_one args
1571   where
1572     do_one (arg,occ) = argToPat env in_scope val_env arg occ
1573 \end{code}
1574
1575
1576 \begin{code}
1577 isValue :: ValueEnv -> CoreExpr -> Maybe Value
1578 isValue _env (Lit lit)
1579   = Just (ConVal (LitAlt lit) [])
1580
1581 isValue env (Var v)
1582   | Just stuff <- lookupVarEnv env v
1583   = Just stuff  -- You might think we could look in the idUnfolding here
1584                 -- but that doesn't take account of which branch of a 
1585                 -- case we are in, which is the whole point
1586
1587   | not (isLocalId v) && isCheapUnfolding unf
1588   = isValue env (unfoldingTemplate unf)
1589   where
1590     unf = idUnfolding v
1591         -- However we do want to consult the unfolding 
1592         -- as well, for let-bound constructors!
1593
1594 isValue env (Lam b e)
1595   | isTyCoVar b = case isValue env e of
1596                   Just _  -> Just LambdaVal
1597                   Nothing -> Nothing
1598   | otherwise = Just LambdaVal
1599
1600 isValue _env expr       -- Maybe it's a constructor application
1601   | (Var fun, args) <- collectArgs expr
1602   = case isDataConWorkId_maybe fun of
1603
1604         Just con | args `lengthAtLeast` dataConRepArity con 
1605                 -- Check saturated; might be > because the 
1606                 --                  arity excludes type args
1607                 -> Just (ConVal (DataAlt con) args)
1608
1609         _other | valArgCount args < idArity fun
1610                 -- Under-applied function
1611                -> Just LambdaVal        -- Partial application
1612
1613         _other -> Nothing
1614
1615 isValue _env _expr = Nothing
1616
1617 mk_con_app :: AltCon -> [CoreArg] -> CoreExpr
1618 mk_con_app (LitAlt lit)  []   = Lit lit
1619 mk_con_app (DataAlt con) args = mkConApp con args
1620 mk_con_app _other _args = panic "SpecConstr.mk_con_app"
1621
1622 samePat :: CallPat -> CallPat -> Bool
1623 samePat (vs1, as1) (vs2, as2)
1624   = all2 same as1 as2
1625   where
1626     same (Var v1) (Var v2) 
1627         | v1 `elem` vs1 = v2 `elem` vs2
1628         | v2 `elem` vs2 = False
1629         | otherwise     = v1 == v2
1630
1631     same (Lit l1)    (Lit l2)    = l1==l2
1632     same (App f1 a1) (App f2 a2) = same f1 f2 && same a1 a2
1633
1634     same (Type {}) (Type {}) = True     -- Note [Ignore type differences]
1635     same (Note _ e1) e2 = same e1 e2    -- Ignore casts and notes
1636     same (Cast e1 _) e2 = same e1 e2
1637     same e1 (Note _ e2) = same e1 e2
1638     same e1 (Cast e2 _) = same e1 e2
1639
1640     same e1 e2 = WARN( bad e1 || bad e2, ppr e1 $$ ppr e2) 
1641                  False  -- Let, lambda, case should not occur
1642     bad (Case {}) = True
1643     bad (Let {})  = True
1644     bad (Lam {})  = True
1645     bad _other    = False
1646 \end{code}
1647
1648 Note [Ignore type differences]
1649 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1650 We do not want to generate specialisations where the call patterns
1651 differ only in their type arguments!  Not only is it utterly useless,
1652 but it also means that (with polymorphic recursion) we can generate
1653 an infinite number of specialisations. Example is Data.Sequence.adjustTree, 
1654 I think.
1655