2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[Specialise]{Stamping out overloading, and (optionally) polymorphism}
7 module Specialise ( specProgram ) where
9 #include "HsVersions.h"
14 import CoreUnfold ( mkUnfolding, mkInlineRule )
19 import CoreUtils ( exprIsTrivial, applyTypeToArgs, mkPiTypes )
20 import CoreFVs ( exprFreeVars, exprsFreeVars, idFreeVars )
21 import UniqSupply ( UniqSupply, UniqSM, initUs_, MonadUnique(..) )
23 import MkId ( voidArgId, realWorldPrimId )
25 import Maybes ( catMaybes, isJust )
26 import BasicTypes ( isNeverActive, inlinePragmaActivation )
34 %************************************************************************
36 \subsection[notes-Specialise]{Implementation notes [SLPJ, Aug 18 1993]}
38 %************************************************************************
40 These notes describe how we implement specialisation to eliminate
43 The specialisation pass works on Core
44 syntax, complete with all the explicit dictionary application,
45 abstraction and construction as added by the type checker. The
46 existing type checker remains largely as it is.
48 One important thought: the {\em types} passed to an overloaded
49 function, and the {\em dictionaries} passed are mutually redundant.
50 If the same function is applied to the same type(s) then it is sure to
51 be applied to the same dictionary(s)---or rather to the same {\em
52 values}. (The arguments might look different but they will evaluate
55 Second important thought: we know that we can make progress by
56 treating dictionary arguments as static and worth specialising on. So
57 we can do without binding-time analysis, and instead specialise on
58 dictionary arguments and no others.
67 and suppose f is overloaded.
69 STEP 1: CALL-INSTANCE COLLECTION
71 We traverse <body>, accumulating all applications of f to types and
74 (Might there be partial applications, to just some of its types and
75 dictionaries? In principle yes, but in practice the type checker only
76 builds applications of f to all its types and dictionaries, so partial
77 applications could only arise as a result of transformation, and even
78 then I think it's unlikely. In any case, we simply don't accumulate such
79 partial applications.)
84 So now we have a collection of calls to f:
88 Notice that f may take several type arguments. To avoid ambiguity, we
89 say that f is called at type t1/t2 and t3/t4.
91 We take equivalence classes using equality of the *types* (ignoring
92 the dictionary args, which as mentioned previously are redundant).
94 STEP 3: SPECIALISATION
96 For each equivalence class, choose a representative (f t1 t2 d1 d2),
97 and create a local instance of f, defined thus:
99 f@t1/t2 = <f_rhs> t1 t2 d1 d2
101 f_rhs presumably has some big lambdas and dictionary lambdas, so lots
102 of simplification will now result. However we don't actually *do* that
103 simplification. Rather, we leave it for the simplifier to do. If we
104 *did* do it, though, we'd get more call instances from the specialised
105 RHS. We can work out what they are by instantiating the call-instance
106 set from f's RHS with the types t1, t2.
108 Add this new id to f's IdInfo, to record that f has a specialised version.
110 Before doing any of this, check that f's IdInfo doesn't already
111 tell us about an existing instance of f at the required type/s.
112 (This might happen if specialisation was applied more than once, or
113 it might arise from user SPECIALIZE pragmas.)
117 Wait a minute! What if f is recursive? Then we can't just plug in
118 its right-hand side, can we?
120 But it's ok. The type checker *always* creates non-recursive definitions
121 for overloaded recursive functions. For example:
123 f x = f (x+x) -- Yes I know its silly
127 f a (d::Num a) = let p = +.sel a d
129 letrec fl (y::a) = fl (p y y)
133 We still have recusion for non-overloaded functions which we
134 speciailise, but the recursive call should get specialised to the
135 same recursive version.
141 All this is crystal clear when the function is applied to *constant
142 types*; that is, types which have no type variables inside. But what if
143 it is applied to non-constant types? Suppose we find a call of f at type
144 t1/t2. There are two possibilities:
146 (a) The free type variables of t1, t2 are in scope at the definition point
147 of f. In this case there's no problem, we proceed just as before. A common
148 example is as follows. Here's the Haskell:
153 After typechecking we have
155 g a (d::Num a) (y::a) = let f b (d'::Num b) (x::b) = +.sel b d' x x
156 in +.sel a d (f a d y) (f a d y)
158 Notice that the call to f is at type type "a"; a non-constant type.
159 Both calls to f are at the same type, so we can specialise to give:
161 g a (d::Num a) (y::a) = let f@a (x::a) = +.sel a d x x
162 in +.sel a d (f@a y) (f@a y)
165 (b) The other case is when the type variables in the instance types
166 are *not* in scope at the definition point of f. The example we are
167 working with above is a good case. There are two instances of (+.sel a d),
168 but "a" is not in scope at the definition of +.sel. Can we do anything?
169 Yes, we can "common them up", a sort of limited common sub-expression deal.
172 g a (d::Num a) (y::a) = let +.sel@a = +.sel a d
173 f@a (x::a) = +.sel@a x x
174 in +.sel@a (f@a y) (f@a y)
176 This can save work, and can't be spotted by the type checker, because
177 the two instances of +.sel weren't originally at the same type.
181 * There are quite a few variations here. For example, the defn of
182 +.sel could be floated ouside the \y, to attempt to gain laziness.
183 It certainly mustn't be floated outside the \d because the d has to
186 * We don't want to inline f_rhs in this case, because
187 that will duplicate code. Just commoning up the call is the point.
189 * Nothing gets added to +.sel's IdInfo.
191 * Don't bother unless the equivalence class has more than one item!
193 Not clear whether this is all worth it. It is of course OK to
194 simply discard call-instances when passing a big lambda.
196 Polymorphism 2 -- Overloading
198 Consider a function whose most general type is
200 f :: forall a b. Ord a => [a] -> b -> b
202 There is really no point in making a version of g at Int/Int and another
203 at Int/Bool, because it's only instancing the type variable "a" which
204 buys us any efficiency. Since g is completely polymorphic in b there
205 ain't much point in making separate versions of g for the different
208 That suggests that we should identify which of g's type variables
209 are constrained (like "a") and which are unconstrained (like "b").
210 Then when taking equivalence classes in STEP 2, we ignore the type args
211 corresponding to unconstrained type variable. In STEP 3 we make
212 polymorphic versions. Thus:
214 f@t1/ = /\b -> <f_rhs> t1 b d1 d2
223 f a (d::Num a) = let g = ...
225 ...(let d1::Ord a = Num.Ord.sel a d in g a d1)...
227 Here, g is only called at one type, but the dictionary isn't in scope at the
228 definition point for g. Usually the type checker would build a
229 definition for d1 which enclosed g, but the transformation system
230 might have moved d1's defn inward. Solution: float dictionary bindings
231 outwards along with call instances.
235 f x = let g p q = p==q
241 Before specialisation, leaving out type abstractions we have
243 f df x = let g :: Eq a => a -> a -> Bool
245 h :: Num a => a -> a -> (a, Bool)
246 h dh r s = let deq = eqFromNum dh
247 in (+ dh r s, g deq r s)
251 After specialising h we get a specialised version of h, like this:
253 h' r s = let deq = eqFromNum df
254 in (+ df r s, g deq r s)
256 But we can't naively make an instance for g from this, because deq is not in scope
257 at the defn of g. Instead, we have to float out the (new) defn of deq
258 to widen its scope. Notice that this floating can't be done in advance -- it only
259 shows up when specialisation is done.
261 User SPECIALIZE pragmas
262 ~~~~~~~~~~~~~~~~~~~~~~~
263 Specialisation pragmas can be digested by the type checker, and implemented
264 by adding extra definitions along with that of f, in the same way as before
266 f@t1/t2 = <f_rhs> t1 t2 d1 d2
268 Indeed the pragmas *have* to be dealt with by the type checker, because
269 only it knows how to build the dictionaries d1 and d2! For example
271 g :: Ord a => [a] -> [a]
272 {-# SPECIALIZE f :: [Tree Int] -> [Tree Int] #-}
274 Here, the specialised version of g is an application of g's rhs to the
275 Ord dictionary for (Tree Int), which only the type checker can conjure
276 up. There might not even *be* one, if (Tree Int) is not an instance of
277 Ord! (All the other specialision has suitable dictionaries to hand
280 Problem. The type checker doesn't have to hand a convenient <f_rhs>, because
281 it is buried in a complex (as-yet-un-desugared) binding group.
284 f@t1/t2 = f* t1 t2 d1 d2
286 where f* is the Id f with an IdInfo which says "inline me regardless!".
287 Indeed all the specialisation could be done in this way.
288 That in turn means that the simplifier has to be prepared to inline absolutely
289 any in-scope let-bound thing.
292 Again, the pragma should permit polymorphism in unconstrained variables:
294 h :: Ord a => [a] -> b -> b
295 {-# SPECIALIZE h :: [Int] -> b -> b #-}
297 We *insist* that all overloaded type variables are specialised to ground types,
298 (and hence there can be no context inside a SPECIALIZE pragma).
299 We *permit* unconstrained type variables to be specialised to
301 - or left as a polymorphic type variable
302 but nothing in between. So
304 {-# SPECIALIZE h :: [Int] -> [c] -> [c] #-}
306 is *illegal*. (It can be handled, but it adds complication, and gains the
310 SPECIALISING INSTANCE DECLARATIONS
311 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
314 instance Foo a => Foo [a] where
316 {-# SPECIALIZE instance Foo [Int] #-}
318 The original instance decl creates a dictionary-function
321 dfun.Foo.List :: forall a. Foo a -> Foo [a]
323 The SPECIALIZE pragma just makes a specialised copy, just as for
324 ordinary function definitions:
326 dfun.Foo.List@Int :: Foo [Int]
327 dfun.Foo.List@Int = dfun.Foo.List Int dFooInt
329 The information about what instance of the dfun exist gets added to
330 the dfun's IdInfo in the same way as a user-defined function too.
333 Automatic instance decl specialisation?
334 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
335 Can instance decls be specialised automatically? It's tricky.
336 We could collect call-instance information for each dfun, but
337 then when we specialised their bodies we'd get new call-instances
338 for ordinary functions; and when we specialised their bodies, we might get
339 new call-instances of the dfuns, and so on. This all arises because of
340 the unrestricted mutual recursion between instance decls and value decls.
342 Still, there's no actual problem; it just means that we may not do all
343 the specialisation we could theoretically do.
345 Furthermore, instance decls are usually exported and used non-locally,
346 so we'll want to compile enough to get those specialisations done.
348 Lastly, there's no such thing as a local instance decl, so we can
349 survive solely by spitting out *usage* information, and then reading that
350 back in as a pragma when next compiling the file. So for now,
351 we only specialise instance decls in response to pragmas.
354 SPITTING OUT USAGE INFORMATION
355 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
357 To spit out usage information we need to traverse the code collecting
358 call-instance information for all imported (non-prelude?) functions
359 and data types. Then we equivalence-class it and spit it out.
361 This is done at the top-level when all the call instances which escape
362 must be for imported functions and data types.
364 *** Not currently done ***
367 Partial specialisation by pragmas
368 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
369 What about partial specialisation:
371 k :: (Ord a, Eq b) => [a] -> b -> b -> [a]
372 {-# SPECIALIZE k :: Eq b => [Int] -> b -> b -> [a] #-}
376 {-# SPECIALIZE k :: Eq b => [Int] -> [b] -> [b] -> [a] #-}
378 Seems quite reasonable. Similar things could be done with instance decls:
380 instance (Foo a, Foo b) => Foo (a,b) where
382 {-# SPECIALIZE instance Foo a => Foo (a,Int) #-}
383 {-# SPECIALIZE instance Foo b => Foo (Int,b) #-}
385 Ho hum. Things are complex enough without this. I pass.
388 Requirements for the simplifer
389 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
390 The simplifier has to be able to take advantage of the specialisation.
392 * When the simplifier finds an application of a polymorphic f, it looks in
393 f's IdInfo in case there is a suitable instance to call instead. This converts
395 f t1 t2 d1 d2 ===> f_t1_t2
397 Note that the dictionaries get eaten up too!
399 * Dictionary selection operations on constant dictionaries must be
402 +.sel Int d ===> +Int
404 The obvious way to do this is in the same way as other specialised
405 calls: +.sel has inside it some IdInfo which tells that if it's applied
406 to the type Int then it should eat a dictionary and transform to +Int.
408 In short, dictionary selectors need IdInfo inside them for constant
411 * Exactly the same applies if a superclass dictionary is being
414 Eq.sel Int d ===> dEqInt
416 * Something similar applies to dictionary construction too. Suppose
417 dfun.Eq.List is the function taking a dictionary for (Eq a) to
418 one for (Eq [a]). Then we want
420 dfun.Eq.List Int d ===> dEq.List_Int
422 Where does the Eq [Int] dictionary come from? It is built in
423 response to a SPECIALIZE pragma on the Eq [a] instance decl.
425 In short, dfun Ids need IdInfo with a specialisation for each
426 constant instance of their instance declaration.
428 All this uses a single mechanism: the SpecEnv inside an Id
431 What does the specialisation IdInfo look like?
432 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
434 The SpecEnv of an Id maps a list of types (the template) to an expression
438 For example, if f has this SpecInfo:
440 [Int, a] -> \d:Ord Int. f' a
442 it means that we can replace the call
444 f Int t ===> (\d. f' t)
446 This chucks one dictionary away and proceeds with the
447 specialised version of f, namely f'.
450 What can't be done this way?
451 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
452 There is no way, post-typechecker, to get a dictionary for (say)
453 Eq a from a dictionary for Eq [a]. So if we find
457 we can't transform to
462 eqList :: (a->a->Bool) -> [a] -> [a] -> Bool
464 Of course, we currently have no way to automatically derive
465 eqList, nor to connect it to the Eq [a] instance decl, but you
466 can imagine that it might somehow be possible. Taking advantage
467 of this is permanently ruled out.
469 Still, this is no great hardship, because we intend to eliminate
470 overloading altogether anyway!
472 A note about non-tyvar dictionaries
473 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
474 Some Ids have types like
476 forall a,b,c. Eq a -> Ord [a] -> tau
478 This seems curious at first, because we usually only have dictionary
479 args whose types are of the form (C a) where a is a type variable.
480 But this doesn't hold for the functions arising from instance decls,
481 which sometimes get arguements with types of form (C (T a)) for some
484 Should we specialise wrt this compound-type dictionary? We used to say
486 "This is a heuristic judgement, as indeed is the fact that we
487 specialise wrt only dictionaries. We choose *not* to specialise
488 wrt compound dictionaries because at the moment the only place
489 they show up is in instance decls, where they are simply plugged
490 into a returned dictionary. So nothing is gained by specialising
493 But it is simpler and more uniform to specialise wrt these dicts too;
494 and in future GHC is likely to support full fledged type signatures
496 f :: Eq [(a,b)] => ...
499 %************************************************************************
501 \subsubsection{The new specialiser}
503 %************************************************************************
505 Our basic game plan is this. For let(rec) bound function
506 f :: (C a, D c) => (a,b,c,d) -> Bool
508 * Find any specialised calls of f, (f ts ds), where
509 ts are the type arguments t1 .. t4, and
510 ds are the dictionary arguments d1 .. d2.
512 * Add a new definition for f1 (say):
514 f1 = /\ b d -> (..body of f..) t1 b t3 d d1 d2
516 Note that we abstract over the unconstrained type arguments.
520 [t1,b,t3,d] |-> \d1 d2 -> f1 b d
522 to the specialisations of f. This will be used by the
523 simplifier to replace calls
524 (f t1 t2 t3 t4) da db
526 (\d1 d1 -> f1 t2 t4) da db
528 All the stuff about how many dictionaries to discard, and what types
529 to apply the specialised function to, are handled by the fact that the
530 SpecEnv contains a template for the result of the specialisation.
532 We don't build *partial* specialisations for f. For example:
534 f :: Eq a => a -> a -> Bool
535 {-# SPECIALISE f :: (Eq b, Eq c) => (b,c) -> (b,c) -> Bool #-}
537 Here, little is gained by making a specialised copy of f.
538 There's a distinct danger that the specialised version would
539 first build a dictionary for (Eq b, Eq c), and then select the (==)
540 method from it! Even if it didn't, not a great deal is saved.
542 We do, however, generate polymorphic, but not overloaded, specialisations:
544 f :: Eq a => [a] -> b -> b -> b
545 {#- SPECIALISE f :: [Int] -> b -> b -> b #-}
547 Hence, the invariant is this:
549 *** no specialised version is overloaded ***
552 %************************************************************************
554 \subsubsection{The exported function}
556 %************************************************************************
559 specProgram :: UniqSupply -> [CoreBind] -> [CoreBind]
560 specProgram us binds = initSM us $
561 do { (binds', uds') <- go binds
562 ; return (wrapDictBinds (ud_binds uds') binds') }
564 -- We need to start with a Subst that knows all the things
565 -- that are in scope, so that the substitution engine doesn't
566 -- accidentally re-use a unique that's already in use
567 -- Easiest thing is to do it all at once, as if all the top-level
568 -- decls were mutually recursive
569 top_subst = mkEmptySubst (mkInScopeSet (mkVarSet (bindersOfBinds binds)))
571 go [] = return ([], emptyUDs)
572 go (bind:binds) = do (binds', uds) <- go binds
573 (bind', uds') <- specBind top_subst bind uds
574 return (bind' ++ binds', uds')
577 %************************************************************************
579 \subsubsection{@specExpr@: the main function}
581 %************************************************************************
584 specVar :: Subst -> Id -> CoreExpr
585 specVar subst v = lookupIdSubst (text "specVar") subst v
587 specExpr :: Subst -> CoreExpr -> SpecM (CoreExpr, UsageDetails)
588 -- We carry a substitution down:
589 -- a) we must clone any binding that might float outwards,
590 -- to avoid name clashes
591 -- b) we carry a type substitution to use when analysing
592 -- the RHS of specialised bindings (no type-let!)
594 ---------------- First the easy cases --------------------
595 specExpr subst (Type ty) = return (Type (CoreSubst.substTy subst ty), emptyUDs)
596 specExpr subst (Var v) = return (specVar subst v, emptyUDs)
597 specExpr _ (Lit lit) = return (Lit lit, emptyUDs)
598 specExpr subst (Cast e co) = do
599 (e', uds) <- specExpr subst e
600 return ((Cast e' (CoreSubst.substTy subst co)), uds)
601 specExpr subst (Note note body) = do
602 (body', uds) <- specExpr subst body
603 return (Note (specNote subst note) body', uds)
606 ---------------- Applications might generate a call instance --------------------
607 specExpr subst expr@(App {})
610 go (App fun arg) args = do (arg', uds_arg) <- specExpr subst arg
611 (fun', uds_app) <- go fun (arg':args)
612 return (App fun' arg', uds_arg `plusUDs` uds_app)
614 go (Var f) args = case specVar subst f of
615 Var f' -> return (Var f', mkCallUDs f' args)
616 e' -> return (e', emptyUDs) -- I don't expect this!
617 go other _ = specExpr subst other
619 ---------------- Lambda/case require dumping of usage details --------------------
620 specExpr subst e@(Lam _ _) = do
621 (body', uds) <- specExpr subst' body
622 let (free_uds, dumped_dbs) = dumpUDs bndrs' uds
623 return (mkLams bndrs' (wrapDictBindsE dumped_dbs body'), free_uds)
625 (bndrs, body) = collectBinders e
626 (subst', bndrs') = substBndrs subst bndrs
627 -- More efficient to collect a group of binders together all at once
628 -- and we don't want to split a lambda group with dumped bindings
630 specExpr subst (Case scrut case_bndr ty alts)
631 = do { (scrut', scrut_uds) <- specExpr subst scrut
632 ; (scrut'', case_bndr', alts', alts_uds)
633 <- specCase subst scrut' case_bndr alts
634 ; return (Case scrut'' case_bndr' (CoreSubst.substTy subst ty) alts'
635 , scrut_uds `plusUDs` alts_uds) }
637 ---------------- Finally, let is the interesting case --------------------
638 specExpr subst (Let bind body) = do
640 (rhs_subst, body_subst, bind') <- cloneBindSM subst bind
642 -- Deal with the body
643 (body', body_uds) <- specExpr body_subst body
645 -- Deal with the bindings
646 (binds', uds) <- specBind rhs_subst bind' body_uds
649 return (foldr Let body' binds', uds)
651 -- Must apply the type substitution to coerceions
652 specNote :: Subst -> Note -> Note
653 specNote _ note = note
657 -> CoreExpr -- Scrutinee, already done
659 -> SpecM ( CoreExpr -- New scrutinee
663 specCase subst scrut' case_bndr [(con, args, rhs)]
664 | isDictId case_bndr -- See Note [Floating dictionaries out of cases]
665 , interestingDict scrut'
666 , not (isDeadBinder case_bndr && null sc_args')
667 = do { (case_bndr_flt : sc_args_flt) <- mapM clone_me (case_bndr' : sc_args')
669 ; let sc_rhss = [ Case (Var case_bndr_flt) case_bndr' (idType sc_arg')
670 [(con, args', Var sc_arg')]
671 | sc_arg' <- sc_args' ]
673 -- Extend the substitution for RHS to map the *original* binders
674 -- to their floated verions. Attach an unfolding to these floated
675 -- binders so they look interesting to interestingDict
676 mb_sc_flts :: [Maybe DictId]
677 mb_sc_flts = map (lookupVarEnv clone_env) args'
678 clone_env = zipVarEnv sc_args' (zipWith add_unf sc_args_flt sc_rhss)
679 subst_prs = (case_bndr, Var (add_unf case_bndr_flt scrut'))
680 : [ (arg, Var sc_flt)
681 | (arg, Just sc_flt) <- args `zip` mb_sc_flts ]
682 subst_rhs' = extendIdSubstList subst_rhs subst_prs
684 ; (rhs', rhs_uds) <- specExpr subst_rhs' rhs
685 ; let scrut_bind = mkDB (NonRec case_bndr_flt scrut')
686 case_bndr_set = unitVarSet case_bndr_flt
687 sc_binds = [(NonRec sc_arg_flt sc_rhs, case_bndr_set)
688 | (sc_arg_flt, sc_rhs) <- sc_args_flt `zip` sc_rhss ]
689 flt_binds = scrut_bind : sc_binds
690 (free_uds, dumped_dbs) = dumpUDs (case_bndr':args') rhs_uds
691 all_uds = flt_binds `addDictBinds` free_uds
692 alt' = (con, args', wrapDictBindsE dumped_dbs rhs')
693 ; return (Var case_bndr_flt, case_bndr', [alt'], all_uds) }
695 (subst_rhs, (case_bndr':args')) = substBndrs subst (case_bndr:args)
696 sc_args' = filter is_flt_sc_arg args'
698 clone_me bndr = do { uniq <- getUniqueM
699 ; return (mkUserLocal occ uniq ty loc) }
703 occ = nameOccName name
704 loc = getSrcSpan name
706 add_unf sc_flt sc_rhs -- Sole purpose: make sc_flt respond True to interestingDictId
707 = setIdUnfolding sc_flt (mkUnfolding False False sc_rhs)
709 arg_set = mkVarSet args'
710 is_flt_sc_arg var = isId var
711 && not (isDeadBinder var)
713 && not (tyVarsOfType var_ty `intersectsVarSet` arg_set)
718 specCase subst scrut case_bndr alts
719 = do { (alts', uds_alts) <- mapAndCombineSM spec_alt alts
720 ; return (scrut, case_bndr', alts', uds_alts) }
722 (subst_alt, case_bndr') = substBndr subst case_bndr
723 spec_alt (con, args, rhs) = do
724 (rhs', uds) <- specExpr subst_rhs rhs
725 let (free_uds, dumped_dbs) = dumpUDs (case_bndr' : args') uds
726 return ((con, args', wrapDictBindsE dumped_dbs rhs'), free_uds)
728 (subst_rhs, args') = substBndrs subst_alt args
731 Note [Floating dictionaries out of cases]
732 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
734 g = \d. case d of { MkD sc ... -> ...(f sc)... }
735 Naively we can't float d2's binding out of the case expression,
736 because 'sc' is bound by the case, and that in turn means we can't
737 specialise f, which seems a pity.
739 So we invert the case, by floating out a binding
741 sc_flt = case d of { MkD sc ... -> sc }
742 Now we can float the call instance for 'f'. Indeed this is just
743 what'll happen if 'sc' was originally bound with a let binding,
744 but case is more efficient, and necessary with equalities. So it's
745 good to work with both.
747 You might think that this won't make any difference, because the
748 call instance will only get nuked by the \d. BUT if 'g' itself is
749 specialised, then transitively we should be able to specialise f.
752 case e of cb { MkD sc ... -> ...(f sc)... }
755 sc_flt = case cb_flt of { MkD sc ... -> sc }
757 case cb_flt of bg { MkD sc ... -> ....(f sc_flt)... }
759 The "_flt" things are the floated binds; we use the current substitution
760 to substitute sc -> sc_flt in the RHS
762 %************************************************************************
764 \subsubsection{Dealing with a binding}
766 %************************************************************************
769 specBind :: Subst -- Use this for RHSs
771 -> UsageDetails -- Info on how the scope of the binding
772 -> SpecM ([CoreBind], -- New bindings
773 UsageDetails) -- And info to pass upstream
775 -- Returned UsageDetails:
776 -- No calls for binders of this bind
777 specBind rhs_subst (NonRec fn rhs) body_uds
778 = do { (rhs', rhs_uds) <- specExpr rhs_subst rhs
779 ; (fn', spec_defns, body_uds1) <- specDefn rhs_subst body_uds fn rhs
781 ; let pairs = spec_defns ++ [(fn', rhs')]
782 -- fn' mentions the spec_defns in its rules,
783 -- so put the latter first
785 combined_uds = body_uds1 `plusUDs` rhs_uds
786 -- This way round a call in rhs_uds of a function f
787 -- at type T will override a call of f at T in body_uds1; and
788 -- that is good because it'll tend to keep "earlier" calls
789 -- See Note [Specialisation of dictionary functions]
791 (free_uds, dump_dbs, float_all) = dumpBindUDs [fn] combined_uds
792 -- See Note [From non-recursive to recursive]
794 final_binds | isEmptyBag dump_dbs = [NonRec b r | (b,r) <- pairs]
795 | otherwise = [Rec (flattenDictBinds dump_dbs pairs)]
798 -- Rather than discard the calls mentioning the bound variables
799 -- we float this binding along with the others
800 return ([], free_uds `snocDictBinds` final_binds)
802 -- No call in final_uds mentions bound variables,
803 -- so we can just leave the binding here
804 return (final_binds, free_uds) }
807 specBind rhs_subst (Rec pairs) body_uds
808 -- Note [Specialising a recursive group]
809 = do { let (bndrs,rhss) = unzip pairs
810 ; (rhss', rhs_uds) <- mapAndCombineSM (specExpr rhs_subst) rhss
811 ; let scope_uds = body_uds `plusUDs` rhs_uds
812 -- Includes binds and calls arising from rhss
814 ; (bndrs1, spec_defns1, uds1) <- specDefns rhs_subst scope_uds pairs
816 ; (bndrs3, spec_defns3, uds3)
817 <- if null spec_defns1 -- Common case: no specialisation
818 then return (bndrs1, [], uds1)
819 else do { -- Specialisation occurred; do it again
820 (bndrs2, spec_defns2, uds2)
821 <- specDefns rhs_subst uds1 (bndrs1 `zip` rhss)
822 ; return (bndrs2, spec_defns2 ++ spec_defns1, uds2) }
824 ; let (final_uds, dumped_dbs, float_all) = dumpBindUDs bndrs uds3
825 bind = Rec (flattenDictBinds dumped_dbs $
826 spec_defns3 ++ zip bndrs3 rhss')
829 return ([], final_uds `snocDictBind` bind)
831 return ([bind], final_uds) }
834 ---------------------------
836 -> UsageDetails -- Info on how it is used in its scope
837 -> [(Id,CoreExpr)] -- The things being bound and their un-processed RHS
838 -> SpecM ([Id], -- Original Ids with RULES added
839 [(Id,CoreExpr)], -- Extra, specialised bindings
840 UsageDetails) -- Stuff to fling upwards from the specialised versions
842 -- Specialise a list of bindings (the contents of a Rec), but flowing usages
843 -- upwards binding by binding. Example: { f = ...g ...; g = ...f .... }
844 -- Then if the input CallDetails has a specialised call for 'g', whose specialisation
845 -- in turn generates a specialised call for 'f', we catch that in this one sweep.
846 -- But not vice versa (it's a fixpoint problem).
848 specDefns _subst uds []
849 = return ([], [], uds)
850 specDefns subst uds ((bndr,rhs):pairs)
851 = do { (bndrs1, spec_defns1, uds1) <- specDefns subst uds pairs
852 ; (bndr1, spec_defns2, uds2) <- specDefn subst uds1 bndr rhs
853 ; return (bndr1 : bndrs1, spec_defns1 ++ spec_defns2, uds2) }
855 ---------------------------
857 -> UsageDetails -- Info on how it is used in its scope
858 -> Id -> CoreExpr -- The thing being bound and its un-processed RHS
859 -> SpecM (Id, -- Original Id with added RULES
860 [(Id,CoreExpr)], -- Extra, specialised bindings
861 UsageDetails) -- Stuff to fling upwards from the specialised versions
863 specDefn subst body_uds fn rhs
864 -- The first case is the interesting one
865 | rhs_tyvars `lengthIs` n_tyvars -- Rhs of fn's defn has right number of big lambdas
866 && rhs_ids `lengthAtLeast` n_dicts -- and enough dict args
867 && notNull calls_for_me -- And there are some calls to specialise
868 && not (isNeverActive (idInlineActivation fn))
869 -- Don't specialise NOINLINE things
870 -- See Note [Auto-specialisation and RULES]
872 -- && not (certainlyWillInline (idUnfolding fn)) -- And it's not small
873 -- See Note [Inline specialisation] for why we do not
874 -- switch off specialisation for inline functions
876 = -- pprTrace "specDefn: some" (ppr fn $$ ppr calls_for_me) $
877 do { -- Make a specialised version for each call in calls_for_me
878 stuff <- mapM spec_call calls_for_me
879 ; let (spec_defns, spec_uds, spec_rules) = unzip3 (catMaybes stuff)
880 fn' = addIdSpecialisations fn spec_rules
881 final_uds = body_uds_without_me `plusUDs` plusUDList spec_uds
882 -- It's important that the `plusUDs` is this way
883 -- round, because body_uds_without_me may bind
884 -- dictionaries that are used in calls_for_me passed
885 -- to specDefn. So the dictionary bindings in
886 -- spec_uds may mention dictionaries bound in
887 -- body_uds_without_me
889 ; return (fn', spec_defns, final_uds) }
891 | otherwise -- No calls or RHS doesn't fit our preconceptions
892 = WARN( notNull calls_for_me, ptext (sLit "Missed specialisation opportunity for") <+> ppr fn )
893 -- Note [Specialisation shape]
894 -- pprTrace "specDefn: none" (ppr fn $$ ppr calls_for_me) $
895 return (fn, [], body_uds_without_me)
899 fn_arity = idArity fn
900 fn_unf = realIdUnfolding fn -- Ignore loop-breaker-ness here
901 (tyvars, theta, _) = tcSplitSigmaTy fn_type
902 n_tyvars = length tyvars
903 n_dicts = length theta
904 inl_act = inlinePragmaActivation (idInlinePragma fn)
906 -- Figure out whether the function has an INLINE pragma
907 -- See Note [Inline specialisations]
908 fn_has_inline_rule :: Maybe Bool -- Derive sat-flag from existing thing
909 fn_has_inline_rule = case isInlineRule_maybe fn_unf of
910 Just (_,sat) -> Just sat
913 spec_arity = unfoldingArity fn_unf - n_dicts -- Arity of the *specialised* inline rule
915 (rhs_tyvars, rhs_ids, rhs_body) = collectTyAndValBinders rhs
917 (body_uds_without_me, calls_for_me) = callsForMe fn body_uds
919 rhs_dict_ids = take n_dicts rhs_ids
920 body = mkLams (drop n_dicts rhs_ids) rhs_body
921 -- Glue back on the non-dict lambdas
923 already_covered :: [CoreExpr] -> Bool
924 already_covered args -- Note [Specialisations already covered]
925 = isJust (lookupRule (const True) realIdUnfolding
927 fn args (idCoreRules fn))
929 mk_ty_args :: [Maybe Type] -> [CoreExpr]
930 mk_ty_args call_ts = zipWithEqual "spec_call" mk_ty_arg rhs_tyvars call_ts
932 mk_ty_arg rhs_tyvar Nothing = Type (mkTyVarTy rhs_tyvar)
933 mk_ty_arg _ (Just ty) = Type ty
935 ----------------------------------------------------------
936 -- Specialise to one particular call pattern
937 spec_call :: CallInfo -- Call instance
938 -> SpecM (Maybe ((Id,CoreExpr), -- Specialised definition
939 UsageDetails, -- Usage details from specialised body
940 CoreRule)) -- Info for the Id's SpecEnv
941 spec_call (CallKey call_ts, (call_ds, _))
942 = ASSERT( call_ts `lengthIs` n_tyvars && call_ds `lengthIs` n_dicts )
944 -- Suppose f's defn is f = /\ a b c -> \ d1 d2 -> rhs
945 -- Supppose the call is for f [Just t1, Nothing, Just t3] [dx1, dx2]
947 -- Construct the new binding
948 -- f1 = SUBST[a->t1,c->t3, d1->d1', d2->d2'] (/\ b -> rhs)
949 -- PLUS the usage-details
950 -- { d1' = dx1; d2' = dx2 }
951 -- where d1', d2' are cloned versions of d1,d2, with the type substitution
952 -- applied. These auxiliary bindings just avoid duplication of dx1, dx2
954 -- Note that the substitution is applied to the whole thing.
955 -- This is convenient, but just slightly fragile. Notably:
956 -- * There had better be no name clashes in a/b/c
958 -- poly_tyvars = [b] in the example above
959 -- spec_tyvars = [a,c]
960 -- ty_args = [t1,b,t3]
961 poly_tyvars = [tv | (tv, Nothing) <- rhs_tyvars `zip` call_ts]
962 spec_tv_binds = [(tv,ty) | (tv, Just ty) <- rhs_tyvars `zip` call_ts]
963 spec_ty_args = map snd spec_tv_binds
964 ty_args = mk_ty_args call_ts
965 rhs_subst = CoreSubst.extendTvSubstList subst spec_tv_binds
967 ; (rhs_subst1, inst_dict_ids) <- newDictBndrs rhs_subst rhs_dict_ids
968 -- Clone rhs_dicts, including instantiating their types
970 ; let (rhs_subst2, dx_binds) = bindAuxiliaryDicts rhs_subst1 $
971 (my_zipEqual rhs_dict_ids inst_dict_ids call_ds)
972 inst_args = ty_args ++ map Var inst_dict_ids
974 ; if already_covered inst_args then
977 { -- Figure out the type of the specialised function
978 let body_ty = applyTypeToArgs rhs fn_type inst_args
979 (lam_args, app_args) -- Add a dummy argument if body_ty is unlifted
980 | isUnLiftedType body_ty -- C.f. WwLib.mkWorkerArgs
981 = (poly_tyvars ++ [voidArgId], poly_tyvars ++ [realWorldPrimId])
982 | otherwise = (poly_tyvars, poly_tyvars)
983 spec_id_ty = mkPiTypes lam_args body_ty
985 ; spec_f <- newSpecIdSM fn spec_id_ty
986 ; (spec_rhs, rhs_uds) <- specExpr rhs_subst2 (mkLams lam_args body)
988 -- The rule to put in the function's specialisation is:
989 -- forall b, d1',d2'. f t1 b t3 d1' d2' = f1 b
990 rule_name = mkFastString ("SPEC " ++ showSDoc (ppr fn <+> ppr spec_ty_args))
991 spec_env_rule = mkLocalRule
993 inl_act -- Note [Auto-specialisation and RULES]
995 (poly_tyvars ++ inst_dict_ids)
997 (mkVarApps (Var spec_f) app_args)
999 -- Add the { d1' = dx1; d2' = dx2 } usage stuff
1000 final_uds = foldr consDictBind rhs_uds dx_binds
1002 -- Adding arity information just propagates it a bit faster
1003 -- See Note [Arity decrease] in Simplify
1004 -- Copy InlinePragma information from the parent Id.
1005 -- So if f has INLINE[1] so does spec_f
1006 spec_f_w_arity = spec_f `setIdArity` max 0 (fn_arity - n_dicts)
1007 `setInlineActivation` inl_act
1009 -- Add an InlineRule if the parent has one
1010 -- See Note [Inline specialisations]
1012 | Just sat <- fn_has_inline_rule
1014 mb_spec_arity = if sat then Just spec_arity else Nothing
1016 spec_f_w_arity `setIdUnfolding` mkInlineRule spec_rhs mb_spec_arity
1020 ; return (Just ((final_spec_f, spec_rhs), final_uds, spec_env_rule)) } }
1022 my_zipEqual xs ys zs
1023 | debugIsOn && not (equalLength xs ys && equalLength ys zs)
1024 = pprPanic "my_zipEqual" (vcat [ ppr xs, ppr ys
1025 , ppr fn <+> ppr call_ts
1026 , ppr (idType fn), ppr theta
1027 , ppr n_dicts, ppr rhs_dict_ids
1029 | otherwise = zip3 xs ys zs
1033 -> [(DictId,DictId,CoreExpr)] -- (orig_dict, inst_dict, dx)
1034 -> (Subst, -- Substitute for all orig_dicts
1035 [CoreBind]) -- Auxiliary bindings
1036 -- Bind any dictionary arguments to fresh names, to preserve sharing
1037 -- Substitution already substitutes orig_dict -> inst_dict
1038 bindAuxiliaryDicts subst triples = go subst [] triples
1040 go subst binds [] = (subst, binds)
1041 go subst binds ((d, dx_id, dx) : pairs)
1042 | exprIsTrivial dx = go (extendIdSubst subst d dx) binds pairs
1043 -- No auxiliary binding necessary
1044 -- Note that we bind the *original* dict in the substitution,
1045 -- overriding any d->dx_id binding put there by substBndrs
1047 | otherwise = go subst_w_unf (NonRec dx_id dx : binds) pairs
1049 dx_id1 = dx_id `setIdUnfolding` mkUnfolding False False dx
1050 subst_w_unf = extendIdSubst subst d (Var dx_id1)
1051 -- Important! We're going to substitute dx_id1 for d
1052 -- and we want it to look "interesting", else we won't gather *any*
1053 -- consequential calls. E.g.
1055 -- If we specialise f for a call (f (dfun dNumInt)), we'll get
1056 -- a consequent call (g d') with an auxiliary definition
1058 -- We want that consequent call to look interesting
1060 -- Again, note that we bind the *original* dict in the substitution,
1061 -- overriding any d->dx_id binding put there by substBndrs
1064 Note [From non-recursive to recursive]
1065 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1066 Even in the non-recursive case, if any dict-binds depend on 'fn' we might
1067 have built a recursive knot
1070 MkUD { ud_binds = d7 = MkD ..f..
1071 , ud_calls = ...(f T d7)... }
1075 Rec { fs x = <blah>[T/a, d7/d]
1080 Here the recursion is only through the RULE.
1083 Note [Specialisation of dictionary functions]
1084 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1085 Here is a nasty example that bit us badly: see Trac #3591
1087 dfun a d = MkD a d (meth d)
1093 None of these definitions is recursive. What happened was that we
1094 generated a specialisation:
1096 RULE forall d. dfun T d = dT
1097 dT = (MkD a d (meth d)) [T/a, d1/d]
1098 = MkD T d1 (meth d1)
1100 But now we use the RULE on the RHS of d2, to get
1102 d2 = dT = MkD d1 (meth d1)
1105 and now d1 is bottom! The problem is that when specialising 'dfun' we
1106 should first dump "below" the binding all floated dictionary bindings
1107 that mention 'dfun' itself. So d2 and d3 (and hence d1) must be
1108 placed below 'dfun', and thus unavailable to it when specialising
1109 'dfun'. That in turn means that the call (dfun T d1) must be
1110 discarded. On the other hand, the call (dfun T d4) is fine, assuming
1111 d4 doesn't mention dfun.
1115 class C a where { foo,bar :: [a] -> [a] }
1117 instance C Int where
1121 r_bar :: C a => [a] -> [a]
1122 r_bar xs = bar (xs ++ xs)
1126 r_bar a (c::C a) (xs::[a]) = bar a d (xs ++ xs)
1128 Rec { $fCInt :: C Int = MkC foo_help reverse
1129 foo_help (xs::[Int]) = r_bar Int $fCInt xs }
1131 The call (r_bar $fCInt) mentions $fCInt,
1132 which mentions foo_help,
1133 which mentions r_bar
1134 But we DO want to specialise r_bar at Int:
1136 Rec { $fCInt :: C Int = MkC foo_help reverse
1137 foo_help (xs::[Int]) = r_bar Int $fCInt xs
1139 r_bar a (c::C a) (xs::[a]) = bar a d (xs ++ xs)
1140 RULE r_bar Int _ = r_bar_Int
1142 r_bar_Int xs = bar Int $fCInt (xs ++ xs)
1145 Note that, because of its RULE, r_bar joins the recursive
1146 group. (In this case it'll unravel a short moment later.)
1149 Conclusion: we catch the nasty case using filter_dfuns in
1150 callsForMe To be honest I'm not 100% certain that this is 100%
1151 right, but it works. Sigh.
1154 Note [Specialising a recursive group]
1155 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1157 let rec { f x = ...g x'...
1158 ; g y = ...f y'.... }
1160 Here we specialise 'f' at Char; but that is very likely to lead to
1161 a specialisation of 'g' at Char. We must do the latter, else the
1162 whole point of specialisation is lost.
1164 But we do not want to keep iterating to a fixpoint, because in the
1165 presence of polymorphic recursion we might generate an infinite number
1168 So we use the following heuristic:
1169 * Arrange the rec block in dependency order, so far as possible
1170 (the occurrence analyser already does this)
1172 * Specialise it much like a sequence of lets
1174 * Then go through the block a second time, feeding call-info from
1175 the RHSs back in the bottom, as it were
1177 In effect, the ordering maxmimises the effectiveness of each sweep,
1178 and we do just two sweeps. This should catch almost every case of
1179 monomorphic recursion -- the exception could be a very knotted-up
1180 recursion with multiple cycles tied up together.
1182 This plan is implemented in the Rec case of specBindItself.
1184 Note [Specialisations already covered]
1185 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1186 We obviously don't want to generate two specialisations for the same
1187 argument pattern. There are two wrinkles
1189 1. We do the already-covered test in specDefn, not when we generate
1190 the CallInfo in mkCallUDs. We used to test in the latter place, but
1191 we now iterate the specialiser somewhat, and the Id at the call site
1192 might therefore not have all the RULES that we can see in specDefn
1194 2. What about two specialisations where the second is an *instance*
1195 of the first? If the more specific one shows up first, we'll generate
1196 specialisations for both. If the *less* specific one shows up first,
1197 we *don't* currently generate a specialisation for the more specific
1198 one. (See the call to lookupRule in already_covered.) Reasons:
1199 (a) lookupRule doesn't say which matches are exact (bad reason)
1200 (b) if the earlier specialisation is user-provided, it's
1201 far from clear that we should auto-specialise further
1203 Note [Auto-specialisation and RULES]
1204 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1206 g :: Num a => a -> a
1209 f :: (Int -> Int) -> Int
1211 {-# RULE f g = 0 #-}
1213 Suppose that auto-specialisation makes a specialised version of
1214 g::Int->Int That version won't appear in the LHS of the RULE for f.
1215 So if the specialisation rule fires too early, the rule for f may
1218 It might be possible to add new rules, to "complete" the rewrite system.
1220 RULE forall d. g Int d = g_spec
1224 But that's a bit complicated. For now we ask the programmer's help,
1225 by *copying the INLINE activation pragma* to the auto-specialised
1226 rule. So if g says {-# NOINLINE[2] g #-}, then the auto-spec rule
1227 will also not be active until phase 2. And that's what programmers
1228 should jolly well do anyway, even aside from specialisation, to ensure
1229 that g doesn't inline too early.
1231 This in turn means that the RULE would never fire for a NOINLINE
1232 thing so not much point in generating a specialisation at all.
1234 Note [Specialisation shape]
1235 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1236 We only specialise a function if it has visible top-level lambdas
1237 corresponding to its overloading. E.g. if
1238 f :: forall a. Eq a => ....
1239 then its body must look like
1242 Reason: when specialising the body for a call (f ty dexp), we want to
1243 substitute dexp for d, and pick up specialised calls in the body of f.
1245 This doesn't always work. One example I came across was this:
1246 newtype Gen a = MkGen{ unGen :: Int -> a }
1248 choose :: Eq a => a -> Gen a
1249 choose n = MkGen (\r -> n)
1251 oneof = choose (1::Int)
1253 It's a silly exapmle, but we get
1254 choose = /\a. g `cast` co
1255 where choose doesn't have any dict arguments. Thus far I have not
1256 tried to fix this (wait till there's a real example).
1258 Note [Inline specialisations]
1259 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1260 We transfer to the specialised function any INLINE stuff from the
1261 original. This means
1262 (a) the Activation for its inlining (from its InlinePragma)
1265 This is a change (Jun06). Previously the idea is that the point of
1266 inlining was precisely to specialise the function at its call site,
1267 and that's not so important for the specialised copies. But
1268 *pragma-directed* specialisation now takes place in the
1269 typechecker/desugarer, with manually specified INLINEs. The
1270 specialiation here is automatic. It'd be very odd if a function
1271 marked INLINE was specialised (because of some local use), and then
1272 forever after (including importing modules) the specialised version
1273 wasn't INLINEd. After all, the programmer said INLINE!
1275 You might wonder why we don't just not specialise INLINE functions.
1276 It's because even INLINE functions are sometimes not inlined, when
1277 they aren't applied to interesting arguments. But perhaps the type
1278 arguments alone are enough to specialise (even though the args are too
1279 boring to trigger inlining), and it's certainly better to call the
1280 specialised version.
1283 %************************************************************************
1285 \subsubsection{UsageDetails and suchlike}
1287 %************************************************************************
1292 ud_binds :: !(Bag DictBind),
1293 -- Floated dictionary bindings
1294 -- The order is important;
1295 -- in ds1 `union` ds2, bindings in ds2 can depend on those in ds1
1296 -- (Remember, Bags preserve order in GHC.)
1298 ud_calls :: !CallDetails
1300 -- INVARIANT: suppose bs = bindersOf ud_binds
1301 -- Then 'calls' may *mention* 'bs',
1302 -- but there should be no calls *for* bs
1305 instance Outputable UsageDetails where
1306 ppr (MkUD { ud_binds = dbs, ud_calls = calls })
1307 = ptext (sLit "MkUD") <+> braces (sep (punctuate comma
1308 [ptext (sLit "binds") <+> equals <+> ppr dbs,
1309 ptext (sLit "calls") <+> equals <+> ppr calls]))
1311 type DictBind = (CoreBind, VarSet)
1312 -- The set is the free vars of the binding
1313 -- both tyvars and dicts
1315 type DictExpr = CoreExpr
1317 emptyUDs :: UsageDetails
1318 emptyUDs = MkUD { ud_binds = emptyBag, ud_calls = emptyVarEnv }
1320 ------------------------------------------------------------
1321 type CallDetails = IdEnv CallInfoSet
1322 newtype CallKey = CallKey [Maybe Type] -- Nothing => unconstrained type argument
1324 -- CallInfo uses a FiniteMap, thereby ensuring that
1325 -- we record only one call instance for any key
1327 -- The list of types and dictionaries is guaranteed to
1328 -- match the type of f
1329 type CallInfoSet = FiniteMap CallKey ([DictExpr], VarSet)
1330 -- Range is dict args and the vars of the whole
1331 -- call (including tyvars)
1332 -- [*not* include the main id itself, of course]
1334 type CallInfo = (CallKey, ([DictExpr], VarSet))
1336 instance Outputable CallKey where
1337 ppr (CallKey ts) = ppr ts
1339 -- Type isn't an instance of Ord, so that we can control which
1340 -- instance we use. That's tiresome here. Oh well
1341 instance Eq CallKey where
1342 k1 == k2 = case k1 `compare` k2 of { EQ -> True; _ -> False }
1344 instance Ord CallKey where
1345 compare (CallKey k1) (CallKey k2) = cmpList cmp k1 k2
1347 cmp Nothing Nothing = EQ
1348 cmp Nothing (Just _) = LT
1349 cmp (Just _) Nothing = GT
1350 cmp (Just t1) (Just t2) = tcCmpType t1 t2
1352 unionCalls :: CallDetails -> CallDetails -> CallDetails
1353 unionCalls c1 c2 = plusVarEnv_C plusFM c1 c2
1355 -- plusCalls :: UsageDetails -> CallDetails -> UsageDetails
1356 -- plusCalls uds call_ds = uds { ud_calls = ud_calls uds `unionCalls` call_ds }
1358 callDetailsFVs :: CallDetails -> VarSet
1359 callDetailsFVs calls = foldVarEnv (unionVarSet . callInfoFVs) emptyVarSet calls
1361 callInfoFVs :: CallInfoSet -> VarSet
1362 callInfoFVs call_info = foldFM (\_ (_,fv) vs -> unionVarSet fv vs) emptyVarSet call_info
1364 ------------------------------------------------------------
1365 singleCall :: Id -> [Maybe Type] -> [DictExpr] -> UsageDetails
1366 singleCall id tys dicts
1367 = MkUD {ud_binds = emptyBag,
1368 ud_calls = unitVarEnv id (unitFM (CallKey tys) (dicts, call_fvs)) }
1370 call_fvs = exprsFreeVars dicts `unionVarSet` tys_fvs
1371 tys_fvs = tyVarsOfTypes (catMaybes tys)
1372 -- The type args (tys) are guaranteed to be part of the dictionary
1373 -- types, because they are just the constrained types,
1374 -- and the dictionary is therefore sure to be bound
1375 -- inside the binding for any type variables free in the type;
1376 -- hence it's safe to neglect tyvars free in tys when making
1377 -- the free-var set for this call
1378 -- BUT I don't trust this reasoning; play safe and include tys_fvs
1380 -- We don't include the 'id' itself.
1382 mkCallUDs :: Id -> [CoreExpr] -> UsageDetails
1384 | not (isLocalId f) -- Imported from elsewhere
1385 || null theta -- Not overloaded
1386 || not (all isClassPred theta)
1387 -- Only specialise if all overloading is on class params.
1388 -- In ptic, with implicit params, the type args
1389 -- *don't* say what the value of the implicit param is!
1390 || not (spec_tys `lengthIs` n_tyvars)
1391 || not ( dicts `lengthIs` n_dicts)
1392 || not (any interestingDict dicts) -- Note [Interesting dictionary arguments]
1393 -- See also Note [Specialisations already covered]
1394 = -- pprTrace "mkCallUDs: discarding" (vcat [ppr f, ppr args, ppr n_tyvars, ppr n_dicts, ppr (map interestingDict dicts)])
1395 emptyUDs -- Not overloaded, or no specialisation wanted
1398 = -- pprTrace "mkCallUDs: keeping" (vcat [ppr f, ppr args, ppr n_tyvars, ppr n_dicts, ppr (map interestingDict dicts)])
1399 singleCall f spec_tys dicts
1401 (tyvars, theta, _) = tcSplitSigmaTy (idType f)
1402 constrained_tyvars = tyVarsOfTheta theta
1403 n_tyvars = length tyvars
1404 n_dicts = length theta
1406 spec_tys = [mk_spec_ty tv ty | (tv, Type ty) <- tyvars `zip` args]
1407 dicts = [dict_expr | (_, dict_expr) <- theta `zip` (drop n_tyvars args)]
1410 | tyvar `elemVarSet` constrained_tyvars = Just ty
1411 | otherwise = Nothing
1414 Note [Interesting dictionary arguments]
1415 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1417 \a.\d:Eq a. let f = ... in ...(f d)...
1418 There really is not much point in specialising f wrt the dictionary d,
1419 because the code for the specialised f is not improved at all, because
1420 d is lambda-bound. We simply get junk specialisations.
1422 What is "interesting"? Just that it has *some* structure.
1425 interestingDict :: CoreExpr -> Bool
1426 -- A dictionary argument is interesting if it has *some* structure
1427 interestingDict (Var v) = hasSomeUnfolding (idUnfolding v)
1428 || isDataConWorkId v
1429 interestingDict (Type _) = False
1430 interestingDict (App fn (Type _)) = interestingDict fn
1431 interestingDict (Note _ a) = interestingDict a
1432 interestingDict (Cast e _) = interestingDict e
1433 interestingDict _ = True
1437 plusUDs :: UsageDetails -> UsageDetails -> UsageDetails
1438 plusUDs (MkUD {ud_binds = db1, ud_calls = calls1})
1439 (MkUD {ud_binds = db2, ud_calls = calls2})
1440 = MkUD { ud_binds = db1 `unionBags` db2
1441 , ud_calls = calls1 `unionCalls` calls2 }
1443 plusUDList :: [UsageDetails] -> UsageDetails
1444 plusUDList = foldr plusUDs emptyUDs
1446 -----------------------------
1447 _dictBindBndrs :: Bag DictBind -> [Id]
1448 _dictBindBndrs dbs = foldrBag ((++) . bindersOf . fst) [] dbs
1450 mkDB :: CoreBind -> DictBind
1451 mkDB bind = (bind, bind_fvs bind)
1453 bind_fvs :: CoreBind -> VarSet
1454 bind_fvs (NonRec bndr rhs) = pair_fvs (bndr,rhs)
1455 bind_fvs (Rec prs) = foldl delVarSet rhs_fvs bndrs
1458 rhs_fvs = unionVarSets (map pair_fvs prs)
1460 pair_fvs :: (Id, CoreExpr) -> VarSet
1461 pair_fvs (bndr, rhs) = exprFreeVars rhs `unionVarSet` idFreeVars bndr
1462 -- Don't forget variables mentioned in the
1463 -- rules of the bndr. C.f. OccAnal.addRuleUsage
1464 -- Also tyvars mentioned in its type; they may not appear in the RHS
1468 flattenDictBinds :: Bag DictBind -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
1469 flattenDictBinds dbs pairs
1470 = foldrBag add pairs dbs
1472 add (NonRec b r,_) pairs = (b,r) : pairs
1473 add (Rec prs1, _) pairs = prs1 ++ pairs
1475 snocDictBinds :: UsageDetails -> [CoreBind] -> UsageDetails
1476 -- Add ud_binds to the tail end of the bindings in uds
1477 snocDictBinds uds dbs
1478 = uds { ud_binds = ud_binds uds `unionBags`
1479 foldr (consBag . mkDB) emptyBag dbs }
1481 consDictBind :: CoreBind -> UsageDetails -> UsageDetails
1482 consDictBind bind uds = uds { ud_binds = mkDB bind `consBag` ud_binds uds }
1484 addDictBinds :: [DictBind] -> UsageDetails -> UsageDetails
1485 addDictBinds binds uds = uds { ud_binds = listToBag binds `unionBags` ud_binds uds }
1487 snocDictBind :: UsageDetails -> CoreBind -> UsageDetails
1488 snocDictBind uds bind = uds { ud_binds = ud_binds uds `snocBag` mkDB bind }
1490 wrapDictBinds :: Bag DictBind -> [CoreBind] -> [CoreBind]
1491 wrapDictBinds dbs binds
1492 = foldrBag add binds dbs
1494 add (bind,_) binds = bind : binds
1496 wrapDictBindsE :: Bag DictBind -> CoreExpr -> CoreExpr
1497 wrapDictBindsE dbs expr
1498 = foldrBag add expr dbs
1500 add (bind,_) expr = Let bind expr
1502 ----------------------
1503 dumpUDs :: [CoreBndr] -> UsageDetails -> (UsageDetails, Bag DictBind)
1504 -- Used at a lambda or case binder; just dump anything mentioning the binder
1505 dumpUDs bndrs uds@(MkUD { ud_binds = orig_dbs, ud_calls = orig_calls })
1506 | null bndrs = (uds, emptyBag) -- Common in case alternatives
1507 | otherwise = -- pprTrace "dumpUDs" (ppr bndrs $$ ppr free_uds $$ ppr dump_dbs) $
1508 (free_uds, dump_dbs)
1510 free_uds = MkUD { ud_binds = free_dbs, ud_calls = free_calls }
1511 bndr_set = mkVarSet bndrs
1512 (free_dbs, dump_dbs, dump_set) = splitDictBinds orig_dbs bndr_set
1513 free_calls = deleteCallsMentioning dump_set $ -- Drop calls mentioning bndr_set on the floor
1514 deleteCallsFor bndrs orig_calls -- Discard calls for bndr_set; there should be
1515 -- no calls for any of the dicts in dump_dbs
1517 dumpBindUDs :: [CoreBndr] -> UsageDetails -> (UsageDetails, Bag DictBind, Bool)
1518 -- Used at a lambda or case binder; just dump anything mentioning the binder
1519 dumpBindUDs bndrs (MkUD { ud_binds = orig_dbs, ud_calls = orig_calls })
1520 = -- pprTrace "dumpBindUDs" (ppr bndrs $$ ppr free_uds $$ ppr dump_dbs) $
1521 (free_uds, dump_dbs, float_all)
1523 free_uds = MkUD { ud_binds = free_dbs, ud_calls = free_calls }
1524 bndr_set = mkVarSet bndrs
1525 (free_dbs, dump_dbs, dump_set) = splitDictBinds orig_dbs bndr_set
1526 free_calls = deleteCallsFor bndrs orig_calls
1527 float_all = dump_set `intersectsVarSet` callDetailsFVs free_calls
1529 callsForMe :: Id -> UsageDetails -> (UsageDetails, [CallInfo])
1530 callsForMe fn (MkUD { ud_binds = orig_dbs, ud_calls = orig_calls })
1531 = -- pprTrace ("callsForMe")
1533 -- text "Orig dbs =" <+> ppr (_dictBindBndrs orig_dbs),
1534 -- text "Orig calls =" <+> ppr orig_calls,
1535 -- text "Dep set =" <+> ppr dep_set,
1536 -- text "Calls for me =" <+> ppr calls_for_me]) $
1537 (uds_without_me, calls_for_me)
1539 uds_without_me = MkUD { ud_binds = orig_dbs, ud_calls = delVarEnv orig_calls fn }
1540 calls_for_me = case lookupVarEnv orig_calls fn of
1542 Just cs -> filter_dfuns (fmToList cs)
1544 dep_set = foldlBag go (unitVarSet fn) orig_dbs
1545 go dep_set (db,fvs) | fvs `intersectsVarSet` dep_set
1546 = extendVarSetList dep_set (bindersOf db)
1547 | otherwise = dep_set
1549 -- Note [Specialisation of dictionary functions]
1550 filter_dfuns | isDFunId fn = filter ok_call
1551 | otherwise = \cs -> cs
1553 ok_call (_, (_,fvs)) = not (fvs `intersectsVarSet` dep_set)
1555 ----------------------
1556 splitDictBinds :: Bag DictBind -> IdSet -> (Bag DictBind, Bag DictBind, IdSet)
1557 -- Returns (free_dbs, dump_dbs, dump_set)
1558 splitDictBinds dbs bndr_set
1559 = foldlBag split_db (emptyBag, emptyBag, bndr_set) dbs
1560 -- Important that it's foldl not foldr;
1561 -- we're accumulating the set of dumped ids in dump_set
1563 split_db (free_dbs, dump_dbs, dump_idset) db@(bind, fvs)
1564 | dump_idset `intersectsVarSet` fvs -- Dump it
1565 = (free_dbs, dump_dbs `snocBag` db,
1566 extendVarSetList dump_idset (bindersOf bind))
1568 | otherwise -- Don't dump it
1569 = (free_dbs `snocBag` db, dump_dbs, dump_idset)
1572 ----------------------
1573 deleteCallsMentioning :: VarSet -> CallDetails -> CallDetails
1574 -- Remove calls *mentioning* bs
1575 deleteCallsMentioning bs calls
1576 = mapVarEnv filter_calls calls
1578 filter_calls :: CallInfoSet -> CallInfoSet
1579 filter_calls = filterFM (\_ (_, fvs) -> not (fvs `intersectsVarSet` bs))
1581 deleteCallsFor :: [Id] -> CallDetails -> CallDetails
1582 -- Remove calls *for* bs
1583 deleteCallsFor bs calls = delVarEnvList calls bs
1587 %************************************************************************
1589 \subsubsection{Boring helper functions}
1591 %************************************************************************
1594 type SpecM a = UniqSM a
1596 initSM :: UniqSupply -> SpecM a -> a
1599 mapAndCombineSM :: (a -> SpecM (b, UsageDetails)) -> [a] -> SpecM ([b], UsageDetails)
1600 mapAndCombineSM _ [] = return ([], emptyUDs)
1601 mapAndCombineSM f (x:xs) = do (y, uds1) <- f x
1602 (ys, uds2) <- mapAndCombineSM f xs
1603 return (y:ys, uds1 `plusUDs` uds2)
1605 cloneBindSM :: Subst -> CoreBind -> SpecM (Subst, Subst, CoreBind)
1606 -- Clone the binders of the bind; return new bind with the cloned binders
1607 -- Return the substitution to use for RHSs, and the one to use for the body
1608 cloneBindSM subst (NonRec bndr rhs) = do
1609 us <- getUniqueSupplyM
1610 let (subst', bndr') = cloneIdBndr subst us bndr
1611 return (subst, subst', NonRec bndr' rhs)
1613 cloneBindSM subst (Rec pairs) = do
1614 us <- getUniqueSupplyM
1615 let (subst', bndrs') = cloneRecIdBndrs subst us (map fst pairs)
1616 return (subst', subst', Rec (bndrs' `zip` map snd pairs))
1618 newDictBndrs :: Subst -> [CoreBndr] -> SpecM (Subst, [CoreBndr])
1619 -- Make up completely fresh binders for the dictionaries
1620 -- Their bindings are going to float outwards
1621 newDictBndrs subst bndrs
1622 = do { bndrs' <- mapM new bndrs
1623 ; let subst' = extendIdSubstList subst
1624 [(d, Var d') | (d,d') <- bndrs `zip` bndrs']
1625 ; return (subst', bndrs' ) }
1627 new b = do { uniq <- getUniqueM
1629 ty' = CoreSubst.substTy subst (idType b)
1630 ; return (mkUserLocal (nameOccName n) uniq ty' (getSrcSpan n)) }
1632 newSpecIdSM :: Id -> Type -> SpecM Id
1633 -- Give the new Id a similar occurrence name to the old one
1634 newSpecIdSM old_id new_ty
1635 = do { uniq <- getUniqueM
1636 ; let name = idName old_id
1637 new_occ = mkSpecOcc (nameOccName name)
1638 new_id = mkUserLocal new_occ uniq new_ty (getSrcSpan name)
1643 Old (but interesting) stuff about unboxed bindings
1644 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1646 What should we do when a value is specialised to a *strict* unboxed value?
1648 map_*_* f (x:xs) = let h = f x
1652 Could convert let to case:
1654 map_*_Int# f (x:xs) = case f x of h# ->
1658 This may be undesirable since it forces evaluation here, but the value
1659 may not be used in all branches of the body. In the general case this
1660 transformation is impossible since the mutual recursion in a letrec
1661 cannot be expressed as a case.
1663 There is also a problem with top-level unboxed values, since our
1664 implementation cannot handle unboxed values at the top level.
1666 Solution: Lift the binding of the unboxed value and extract it when it
1669 map_*_Int# f (x:xs) = let h = case (f x) of h# -> _Lift h#
1674 Now give it to the simplifier and the _Lifting will be optimised away.
1676 The benfit is that we have given the specialised "unboxed" values a
1677 very simplep lifted semantics and then leave it up to the simplifier to
1678 optimise it --- knowing that the overheads will be removed in nearly
1681 In particular, the value will only be evaluted in the branches of the
1682 program which use it, rather than being forced at the point where the
1683 value is bound. For example:
1685 filtermap_*_* p f (x:xs)
1692 filtermap_*_Int# p f (x:xs)
1693 = let h = case (f x) of h# -> _Lift h#
1696 True -> case h of _Lift h#
1700 The binding for h can still be inlined in the one branch and the
1701 _Lifting eliminated.
1704 Question: When won't the _Lifting be eliminated?
1706 Answer: When they at the top-level (where it is necessary) or when
1707 inlining would duplicate work (or possibly code depending on
1708 options). However, the _Lifting will still be eliminated if the
1709 strictness analyser deems the lifted binding strict.