92d3fbc22313c23f5fc65a30fbdc185b91b0989b
[ghc-hetmet.git] / compiler / specialise / Rules.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[CoreRules]{Transformation rules}
5
6 \begin{code}
7 module Rules (
8         RuleBase, emptyRuleBase, mkRuleBase, extendRuleBaseList, 
9         unionRuleBase, pprRuleBase, ruleCheckProgram,
10
11         mkSpecInfo, extendSpecInfo, addSpecInfo,
12         rulesOfBinds, addIdSpecialisations, 
13         
14         matchN,
15
16         lookupRule, mkLocalRule, roughTopNames
17     ) where
18
19 #include "HsVersions.h"
20
21 import CoreSyn          -- All of it
22 import OccurAnal        ( occurAnalyseExpr )
23 import CoreFVs          ( exprFreeVars, exprsFreeVars, bindFreeVars, rulesRhsFreeVars )
24 import CoreUnfold       ( isCheapUnfolding, unfoldingTemplate )
25 import CoreUtils        ( tcEqExprX, exprType )
26 import PprCore          ( pprRules )
27 import Type             ( Type, TvSubstEnv )
28 import Coercion         ( coercionKind )
29 import TcType           ( tcSplitTyConApp_maybe )
30 import CoreTidy         ( tidyRules )
31 import Id               ( Id, idUnfolding, isLocalId, isGlobalId, idName, idType,
32                           idSpecialisation, idCoreRules, setIdSpecialisation ) 
33 import IdInfo           ( SpecInfo( SpecInfo ) )
34 import Var              ( Var )
35 import VarEnv
36 import VarSet
37 import Name             ( Name, NamedThing(..) )
38 import NameEnv
39 import Unify            ( ruleMatchTyX, MatchEnv(..) )
40 import BasicTypes       ( Activation, CompilerPhase, isActive )
41 import Outputable
42 import FastString
43 import Maybes
44 import OrdList
45 import Bag
46 import Util
47 import List hiding( mapAccumL ) -- Also defined in Util
48 \end{code}
49
50
51 %************************************************************************
52 %*                                                                      *
53 \subsection[specialisation-IdInfo]{Specialisation info about an @Id@}
54 %*                                                                      *
55 %************************************************************************
56
57 A @CoreRule@ holds details of one rule for an @Id@, which
58 includes its specialisations.
59
60 For example, if a rule for @f@ contains the mapping:
61 \begin{verbatim}
62         forall a b d. [Type (List a), Type b, Var d]  ===>  f' a b
63 \end{verbatim}
64 then when we find an application of f to matching types, we simply replace
65 it by the matching RHS:
66 \begin{verbatim}
67         f (List Int) Bool dict ===>  f' Int Bool
68 \end{verbatim}
69 All the stuff about how many dictionaries to discard, and what types
70 to apply the specialised function to, are handled by the fact that the
71 Rule contains a template for the result of the specialisation.
72
73 There is one more exciting case, which is dealt with in exactly the same
74 way.  If the specialised value is unboxed then it is lifted at its
75 definition site and unlifted at its uses.  For example:
76
77         pi :: forall a. Num a => a
78
79 might have a specialisation
80
81         [Int#] ===>  (case pi' of Lift pi# -> pi#)
82
83 where pi' :: Lift Int# is the specialised version of pi.
84
85 \begin{code}
86 mkLocalRule :: RuleName -> Activation 
87             -> Name -> [CoreBndr] -> [CoreExpr] -> CoreExpr -> CoreRule
88 -- Used to make CoreRule for an Id defined in this module
89 mkLocalRule name act fn bndrs args rhs
90   = Rule { ru_name = name, ru_fn = fn, ru_act = act,
91            ru_bndrs = bndrs, ru_args = args,
92            ru_rhs = rhs, ru_rough = roughTopNames args,
93            ru_local = True }
94
95 --------------
96 roughTopNames :: [CoreExpr] -> [Maybe Name]
97 roughTopNames args = map roughTopName args
98
99 roughTopName :: CoreExpr -> Maybe Name
100 -- Find the "top" free name of an expression
101 -- a) the function in an App chain (if a GlobalId)
102 -- b) the TyCon in a type
103 -- This is used for the fast-match-check for rules; 
104 --      if the top names don't match, the rest can't
105 roughTopName (Type ty) = case tcSplitTyConApp_maybe ty of
106                           Just (tc,_) -> Just (getName tc)
107                           Nothing     -> Nothing
108 roughTopName (App f a) = roughTopName f
109 roughTopName (Var f) | isGlobalId f = Just (idName f)
110                      | otherwise    = Nothing
111 roughTopName other = Nothing
112
113 ruleCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
114 -- (ruleCantMatch tpl actual) returns True only if 'actual'
115 -- definitely can't match 'tpl' by instantiating 'tpl'.  
116 -- It's only a one-way match; unlike instance matching we 
117 -- don't consider unification
118 -- 
119 -- Notice that there is no case
120 --      ruleCantMatch (Just n1 : ts) (Nothing : as) = True
121 -- Reason: a local variable 'v' in the actuals might 
122 --         have an unfolding which is a global.
123 --         This quite often happens with case scrutinees.
124 ruleCantMatch (Just n1 : ts) (Just n2 : as) = n1 /= n2 || ruleCantMatch ts as
125 ruleCantMatch (t       : ts) (a       : as) = ruleCantMatch ts as
126 ruleCantMatch ts             as             = False
127 \end{code}
128
129
130 %************************************************************************
131 %*                                                                      *
132                 SpecInfo: the rules in an IdInfo
133 %*                                                                      *
134 %************************************************************************
135
136 \begin{code}
137 mkSpecInfo :: [CoreRule] -> SpecInfo
138 mkSpecInfo rules = SpecInfo rules (rulesRhsFreeVars rules)
139
140 extendSpecInfo :: SpecInfo -> [CoreRule] -> SpecInfo
141 extendSpecInfo (SpecInfo rs1 fvs1) rs2
142   = SpecInfo (rs2 ++ rs1) (rulesRhsFreeVars rs2 `unionVarSet` fvs1)
143
144 addSpecInfo :: SpecInfo -> SpecInfo -> SpecInfo
145 addSpecInfo (SpecInfo rs1 fvs1) (SpecInfo rs2 fvs2) 
146   = SpecInfo (rs1 ++ rs2) (fvs1 `unionVarSet` fvs2)
147
148 addIdSpecialisations :: Id -> [CoreRule] -> Id
149 addIdSpecialisations id rules
150   = setIdSpecialisation id $
151     extendSpecInfo (idSpecialisation id) rules
152
153 rulesOfBinds :: [CoreBind] -> [CoreRule]
154 rulesOfBinds binds = concatMap (concatMap idCoreRules . bindersOf) binds
155 \end{code}
156
157
158 %************************************************************************
159 %*                                                                      *
160                 RuleBase
161 %*                                                                      *
162 %************************************************************************
163
164 \begin{code}
165 type RuleBase = NameEnv [CoreRule]
166         -- Maps (the name of) an Id to its rules
167         -- The rules are are unordered; 
168         -- we sort out any overlaps on lookup
169
170 emptyRuleBase = emptyNameEnv
171
172 mkRuleBase :: [CoreRule] -> RuleBase
173 mkRuleBase rules = extendRuleBaseList emptyRuleBase rules
174
175 extendRuleBaseList :: RuleBase -> [CoreRule] -> RuleBase
176 extendRuleBaseList rule_base new_guys
177   = foldl extendRuleBase rule_base new_guys
178
179 unionRuleBase :: RuleBase -> RuleBase -> RuleBase
180 unionRuleBase rb1 rb2 = plusNameEnv_C (++) rb1 rb2
181
182 extendRuleBase :: RuleBase -> CoreRule -> RuleBase
183 extendRuleBase rule_base rule
184   = extendNameEnv_Acc (:) singleton rule_base (ruleIdName rule) rule
185
186 pprRuleBase :: RuleBase -> SDoc
187 pprRuleBase rules = vcat [ pprRules (tidyRules emptyTidyEnv rs) 
188                          | rs <- nameEnvElts rules ]
189 \end{code}
190
191
192 %************************************************************************
193 %*                                                                      *
194 \subsection{Matching}
195 %*                                                                      *
196 %************************************************************************
197
198 \begin{code}
199 lookupRule :: (Activation -> Bool) -> InScopeSet
200            -> RuleBase  -- Imported rules
201            -> Id -> [CoreExpr] -> Maybe (CoreRule, CoreExpr)
202 lookupRule is_active in_scope rule_base fn args
203   = matchRules is_active in_scope fn args rules
204   where
205         -- The rules for an Id come from two places:
206         --      (a) the ones it is born with (idCoreRules fn)
207         --      (b) rules added in subsequent modules (extra_rules)
208         -- PrimOps, for example, are born with a bunch of rules under (a)
209     rules = extra_rules ++ idCoreRules fn
210     extra_rules | isLocalId fn = []
211                 | otherwise    = lookupNameEnv rule_base (idName fn) `orElse` []
212
213 matchRules :: (Activation -> Bool) -> InScopeSet
214            -> Id -> [CoreExpr]
215            -> [CoreRule] -> Maybe (CoreRule, CoreExpr)
216 -- See comments on matchRule
217 matchRules is_active in_scope fn args rules
218   = -- pprTrace "matchRules" (ppr fn <+> ppr rules) $
219     case go [] rules of
220         []     -> Nothing
221         (m:ms) -> Just (findBest (fn,args) m ms)
222   where
223     rough_args = map roughTopName args
224
225     go :: [(CoreRule,CoreExpr)] -> [CoreRule] -> [(CoreRule,CoreExpr)]
226     go ms []           = ms
227     go ms (r:rs) = case (matchRule is_active in_scope args rough_args r) of
228                         Just e  -> go ((r,e):ms) rs
229                         Nothing -> -- pprTrace "match failed" (ppr r $$ ppr args $$ 
230                                    --   ppr [(arg_id, unfoldingTemplate unf) | Var arg_id <- args, let unf = idUnfolding arg_id, isCheapUnfolding unf] )
231                                    go ms         rs
232
233 findBest :: (Id, [CoreExpr])
234          -> (CoreRule,CoreExpr) -> [(CoreRule,CoreExpr)] -> (CoreRule,CoreExpr)
235 -- All these pairs matched the expression
236 -- Return the pair the the most specific rule
237 -- The (fn,args) is just for overlap reporting
238
239 findBest target (rule,ans)   [] = (rule,ans)
240 findBest target (rule1,ans1) ((rule2,ans2):prs)
241   | rule1 `isMoreSpecific` rule2 = findBest target (rule1,ans1) prs
242   | rule2 `isMoreSpecific` rule1 = findBest target (rule2,ans2) prs
243 #ifdef DEBUG
244   | otherwise = pprTrace "Rules.findBest: rule overlap (Rule 1 wins)"
245                          (vcat [ptext SLIT("Expression to match:") <+> ppr fn <+> sep (map ppr args),
246                                 ptext SLIT("Rule 1:") <+> ppr rule1, 
247                                 ptext SLIT("Rule 2:") <+> ppr rule2]) $
248                 findBest target (rule1,ans1) prs
249 #else
250   | otherwise = findBest target (rule1,ans1) prs
251 #endif
252   where
253     (fn,args) = target
254
255 isMoreSpecific :: CoreRule -> CoreRule -> Bool
256 isMoreSpecific (BuiltinRule {}) r2 = True
257 isMoreSpecific r1 (BuiltinRule {}) = False
258 isMoreSpecific (Rule { ru_bndrs = bndrs1, ru_args = args1 })
259                (Rule { ru_bndrs = bndrs2, ru_args = args2 })
260   = isJust (matchN in_scope bndrs2 args2 args1)
261   where
262    in_scope = mkInScopeSet (mkVarSet bndrs1)
263         -- Actually we should probably include the free vars 
264         -- of rule1's args, but I can't be bothered
265
266 noBlackList :: Activation -> Bool
267 noBlackList act = False         -- Nothing is black listed
268
269 matchRule :: (Activation -> Bool) -> InScopeSet
270           -> [CoreExpr] -> [Maybe Name]
271           -> CoreRule -> Maybe CoreExpr
272
273 -- If (matchRule rule args) returns Just (name,rhs)
274 -- then (f args) matches the rule, and the corresponding
275 -- rewritten RHS is rhs
276 --
277 -- The bndrs and rhs is occurrence-analysed
278 --
279 --      Example
280 --
281 -- The rule
282 --      forall f g x. map f (map g x) ==> map (f . g) x
283 -- is stored
284 --      CoreRule "map/map" 
285 --               [f,g,x]                -- tpl_vars
286 --               [f,map g x]            -- tpl_args
287 --               map (f.g) x)           -- rhs
288 --        
289 -- Then the call: matchRule the_rule [e1,map e2 e3]
290 --        = Just ("map/map", (\f,g,x -> rhs) e1 e2 e3)
291 --
292 -- Any 'surplus' arguments in the input are simply put on the end
293 -- of the output.
294
295 matchRule is_active in_scope args rough_args
296           (BuiltinRule { ru_name = name, ru_try = match_fn })
297   = case match_fn args of
298         Just expr -> Just expr
299         Nothing   -> Nothing
300
301 matchRule is_active in_scope args rough_args
302           (Rule { ru_name = rn, ru_act = act, ru_rough = tpl_tops,
303                   ru_bndrs = tpl_vars, ru_args = tpl_args,
304                   ru_rhs = rhs })
305   | not (is_active act)               = Nothing
306   | ruleCantMatch tpl_tops rough_args = Nothing
307   | otherwise
308   = case matchN in_scope tpl_vars tpl_args args of
309         Nothing                -> Nothing
310         Just (binds, tpl_vals) -> Just (mkLets binds $
311                                         rule_fn `mkApps` tpl_vals)
312   where
313     rule_fn = occurAnalyseExpr (mkLams tpl_vars rhs)
314         -- We could do this when putting things into the rulebase, I guess
315 \end{code}
316
317 \begin{code}
318 matchN  :: InScopeSet
319         -> [Var]                -- Template tyvars
320         -> [CoreExpr]           -- Template
321         -> [CoreExpr]           -- Target; can have more elts than template
322         -> Maybe ([CoreBind],   -- Bindings to wrap around the entire result
323                   [CoreExpr])   -- What is substituted for each template var
324
325 matchN in_scope tmpl_vars tmpl_es target_es
326   = do  { (tv_subst, id_subst, binds)
327                 <- go init_menv emptySubstEnv tmpl_es target_es
328         ; return (fromOL binds, 
329                   map (lookup_tmpl tv_subst id_subst) tmpl_vars') }
330   where
331     (init_rn_env, tmpl_vars') = mapAccumL rnBndrL (mkRnEnv2 in_scope) tmpl_vars
332         -- See Note [Template binders]
333
334     init_menv = ME { me_tmpls = mkVarSet tmpl_vars', me_env = init_rn_env }
335                 
336     go menv subst []     es     = Just subst
337     go menv subst ts     []     = Nothing       -- Fail if too few actual args
338     go menv subst (t:ts) (e:es) = do { subst1 <- match menv subst t e 
339                                      ; go menv subst1 ts es }
340
341     lookup_tmpl :: TvSubstEnv -> IdSubstEnv -> Var -> CoreExpr
342     lookup_tmpl tv_subst id_subst tmpl_var'
343         | isTyVar tmpl_var' = case lookupVarEnv tv_subst tmpl_var' of
344                                 Just ty         -> Type ty
345                                 Nothing         -> unbound tmpl_var'
346         | otherwise         = case lookupVarEnv id_subst tmpl_var' of
347                                 Just e -> e
348                                 other  -> unbound tmpl_var'
349  
350     unbound var = pprPanic "Template variable unbound in rewrite rule" 
351                         (ppr var $$ ppr tmpl_vars $$ ppr tmpl_vars' $$ ppr tmpl_es $$ ppr target_es)
352 \end{code}
353
354 Note [Template binders]
355 ~~~~~~~~~~~~~~~~~~~~~~~
356 Consider the following match:
357         Template:  forall x.  f x 
358         Target:     f (x+1)
359 This should succeed, because the template variable 'x' has 
360 nothing to do with the 'x' in the target. 
361
362 On reflection, this case probably does just work, but this might not
363         Template:  forall x. f (\x.x) 
364         Target:    f (\y.y)
365 Here we want to clone when we find the \x, but to know that x must be in scope
366
367 To achive this, we use rnBndrL to rename the template variables if
368 necessary; the renamed ones are the tmpl_vars'
369
370
371         ---------------------------------------------
372                 The inner workings of matching
373         ---------------------------------------------
374
375 \begin{code}
376 -- These two definitions are not the same as in Subst,
377 -- but they simple and direct, and purely local to this module
378 --
379 -- * The domain of the TvSubstEnv and IdSubstEnv are the template
380 --   variables passed into the match.
381 --
382 -- * The (OrdList CoreBind) in a SubstEnv are the bindings floated out
383 --   from nested matches; see the Let case of match, below
384 --
385 type SubstEnv   = (TvSubstEnv, IdSubstEnv, OrdList CoreBind)
386 type IdSubstEnv = IdEnv CoreExpr                
387
388 emptySubstEnv :: SubstEnv
389 emptySubstEnv = (emptyVarEnv, emptyVarEnv, nilOL)
390
391
392 --      At one stage I tried to match even if there are more 
393 --      template args than real args.
394
395 --      I now think this is probably a bad idea.
396 --      Should the template (map f xs) match (map g)?  I think not.
397 --      For a start, in general eta expansion wastes work.
398 --      SLPJ July 99
399
400
401 match :: MatchEnv
402       -> SubstEnv
403       -> CoreExpr               -- Template
404       -> CoreExpr               -- Target
405       -> Maybe SubstEnv
406
407 -- See the notes with Unify.match, which matches types
408 -- Everything is very similar for terms
409
410 -- Interesting examples:
411 -- Consider matching
412 --      \x->f      against    \f->f
413 -- When we meet the lambdas we must remember to rename f to f' in the
414 -- second expresion.  The RnEnv2 does that.
415 --
416 -- Consider matching 
417 --      forall a. \b->b    against   \a->3
418 -- We must rename the \a.  Otherwise when we meet the lambdas we 
419 -- might substitute [a/b] in the template, and then erroneously 
420 -- succeed in matching what looks like the template variable 'a' against 3.
421
422 -- The Var case follows closely what happens in Unify.match
423 match menv subst (Var v1) e2 
424   | Just subst <- match_var menv subst v1 e2
425   = Just subst
426
427 match menv subst e1 (Note n e2)
428   = match menv subst e1 e2
429         -- Note [Notes in RULE matching]
430         -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
431         -- Look through Notes.  In particular, we don't want to
432         -- be confused by InlineMe notes.  Maybe we should be more
433         -- careful about profiling notes, but for now I'm just
434         -- riding roughshod over them.  
435         --- See Note [Notes in call patterns] in SpecConstr
436
437 -- Here is another important rule: if the term being matched is a
438 -- variable, we expand it so long as its unfolding is a WHNF
439 -- (Its occurrence information is not necessarily up to date,
440 --  so we don't use it.)
441 match menv subst e1 (Var v2)
442   | isCheapUnfolding unfolding
443   = match menv subst e1 (unfoldingTemplate unfolding)
444   where
445     rn_env    = me_env menv
446     unfolding = idUnfolding (lookupRnInScope rn_env (rnOccR rn_env v2))
447         -- Notice that we look up v2 in the in-scope set
448         -- See Note [Lookup in-scope]
449         -- Remember to apply any renaming first (hence rnOccR)
450
451 -- Note [Matching lets]
452 -- ~~~~~~~~~~~~~~~~~~~~
453 -- Matching a let-expression.  Consider
454 --      RULE forall x.  f (g x) = <rhs>
455 -- and target expression
456 --      f (let { w=R } in g E))
457 -- Then we'd like the rule to match, to generate
458 --      let { w=R } in (\x. <rhs>) E
459 -- In effect, we want to float the let-binding outward, to enable
460 -- the match to happen.  This is the WHOLE REASON for accumulating
461 -- bindings in the SubstEnv
462 --
463 -- We can only do this if
464 --      (a) Widening the scope of w does not capture any variables
465 --          We use a conservative test: w is not already in scope
466 --          If not, we clone the binders, and substitute
467 --      (b) The free variables of R are not bound by the part of the
468 --          target expression outside the let binding; e.g.
469 --              f (\v. let w = v+1 in g E)
470 --          Here we obviously cannot float the let-binding for w.
471 --
472 -- You may think rule (a) would never apply, because rule matching is
473 -- mostly invoked from the simplifier, when we have just run substExpr 
474 -- over the argument, so there will be no shadowing anyway.
475 -- The fly in the ointment is that the forall'd variables of the
476 -- RULE itself are considered in scope.
477 --
478 -- I though of various cheapo ways to solve this tiresome problem,
479 -- but ended up doing the straightforward thing, which is to 
480 -- clone the binders if they are in scope.  It's tiresome, and
481 -- potentially inefficient, because of the calls to substExpr,
482 -- but I don't think it'll happen much in pracice.
483
484 {-  Cases to think about
485         (let x=y+1 in \x. (x,x))
486                 --> let x=y+1 in (\x1. (x1,x1))
487         (\x. let x = y+1 in (x,x))
488                 --> let x1 = y+1 in (\x. (x1,x1)
489         (let x=y+1 in (x,x), let x=y-1 in (x,x))
490                 --> let x=y+1 in let x1=y-1 in ((x,x),(x1,x1))
491
492 Watch out!
493         (let x=y+1 in let z=x+1 in (z,z)
494                 --> matches (p,p) but watch out that the use of 
495                         x on z's rhs is OK!
496 I'm removing the cloning because that makes the above case
497 fail, because the inner let looks as if it has locally-bound vars -}
498
499 match menv subst@(tv_subst, id_subst, binds) e1 (Let bind e2)
500   | all freshly_bound bndrs,
501     not (any locally_bound bind_fvs)
502   = match (menv { me_env = rn_env' }) 
503           (tv_subst, id_subst, binds `snocOL` bind')
504           e1 e2'
505   where
506     rn_env   = me_env menv
507     bndrs    = bindersOf  bind
508     bind_fvs = varSetElems (bindFreeVars bind)
509     locally_bound x   = inRnEnvR rn_env x
510     freshly_bound x = not (x `rnInScope` rn_env)
511     bind' = bind
512     e2'   = e2
513     rn_env' = extendRnInScopeList rn_env bndrs
514 {-
515     (rn_env', bndrs') = mapAccumL rnBndrR rn_env bndrs
516     s_prs = [(bndr, Var bndr') | (bndr,bndr') <- zip bndrs bndrs', bndr /= bndr']
517     subst = mkSubst (rnInScopeSet rn_env) emptyVarEnv (mkVarEnv s_prs)
518     (bind', e2') | null s_prs = (bind,   e2)
519                  | otherwise  = (s_bind, substExpr subst e2)
520     s_bind = case bind of
521                 NonRec {} -> NonRec (head bndrs') (head rhss)
522                 Rec {}    -> Rec (bndrs' `zip` map (substExpr subst) rhss)
523 -}
524
525 match menv subst (Lit lit1) (Lit lit2)
526   | lit1 == lit2
527   = Just subst
528
529 match menv subst (App f1 a1) (App f2 a2)
530   = do  { subst' <- match menv subst f1 f2
531         ; match menv subst' a1 a2 }
532
533 match menv subst (Lam x1 e1) (Lam x2 e2)
534   = match menv' subst e1 e2
535   where
536     menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
537
538 -- This rule does eta expansion
539 --              (\x.M)  ~  N    iff     M  ~  N x
540 -- It's important that this is *after* the let rule,
541 -- so that      (\x.M)  ~  (let y = e in \y.N)
542 -- does the let thing, and then gets the lam/lam rule above
543 match menv subst (Lam x1 e1) e2
544   = match menv' subst e1 (App e2 (varToCoreExpr new_x))
545   where
546     (rn_env', new_x) = rnBndrL (me_env menv) x1
547     menv' = menv { me_env = rn_env' }
548
549 -- Eta expansion the other way
550 --      M  ~  (\y.N)    iff   M y     ~  N
551 match menv subst e1 (Lam x2 e2)
552   = match menv' subst (App e1 (varToCoreExpr new_x)) e2
553   where
554     (rn_env', new_x) = rnBndrR (me_env menv) x2
555     menv' = menv { me_env = rn_env' }
556
557 match menv subst (Case e1 x1 ty1 alts1) (Case e2 x2 ty2 alts2)
558   = do  { subst1 <- match_ty menv subst ty1 ty2
559         ; subst2 <- match menv subst1 e1 e2
560         ; let menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
561         ; match_alts menv' subst2 alts1 alts2   -- Alts are both sorted
562         }
563
564 match menv subst (Type ty1) (Type ty2)
565   = match_ty menv subst ty1 ty2
566
567 match menv subst (Cast e1 co1) (Cast e2 co2)
568   | (from1, to1) <- coercionKind co1
569   , (from2, to2) <- coercionKind co2
570   = do  { subst1 <- match_ty menv subst  to1   to2
571         ; subst2 <- match_ty menv subst1 from1 from2
572         ; match menv subst2 e1 e2 }
573
574 {-      REMOVING OLD CODE: I think that the above handling for let is 
575                            better than the stuff here, which looks 
576                            pretty suspicious to me.  SLPJ Sept 06
577 -- This is an interesting rule: we simply ignore lets in the 
578 -- term being matched against!  The unfolding inside it is (by assumption)
579 -- already inside any occurrences of the bound variables, so we'll expand
580 -- them when we encounter them.  This gives a chance of matching
581 --      forall x,y.  f (g (x,y))
582 -- against
583 --      f (let v = (a,b) in g v)
584
585 match menv subst e1 (Let bind e2)
586   = match (menv { me_env = rn_env' }) subst e1 e2
587   where
588     (rn_env', _bndrs') = mapAccumL rnBndrR (me_env menv) (bindersOf bind)
589         -- It's important to do this renaming, so that the bndrs
590         -- are brought into the local scope. For example:
591         -- Matching
592         --      forall f,x,xs. f (x:xs)
593         --   against
594         --      f (let y = e in (y:[]))
595         -- We must not get success with x->y!  So we record that y is
596         -- locally bound (with rnBndrR), and proceed.  The Var case
597         -- will fail when trying to bind x->y
598 -}
599
600 -- Everything else fails
601 match menv subst e1 e2 = -- pprTrace "Failing at" ((text "e1:" <+> ppr e1) $$ (text "e2:" <+> ppr e2)) $ 
602                          Nothing
603
604 ------------------------------------------
605 match_var :: MatchEnv
606           -> SubstEnv
607           -> Var                -- Template
608           -> CoreExpr           -- Target
609           -> Maybe SubstEnv
610 match_var menv subst@(tv_subst, id_subst, binds) v1 e2
611   | v1' `elemVarSet` me_tmpls menv
612   = case lookupVarEnv id_subst v1' of
613         Nothing | any (inRnEnvR rn_env) (varSetElems (exprFreeVars e2))
614                 -> Nothing      -- Occurs check failure
615                 -- e.g. match forall a. (\x-> a x) against (\y. y y)
616
617                 | otherwise     -- No renaming to do on e2, because no free var
618                                 -- of e2 is in the rnEnvR of the envt
619                 -- However, we must match the *types*; e.g.
620                 --   forall (c::Char->Int) (x::Char). 
621                 --      f (c x) = "RULE FIRED"
622                 -- We must only match on args that have the right type
623                 -- It's actually quite difficult to come up with an example that shows
624                 -- you need type matching, esp since matching is left-to-right, so type
625                 -- args get matched first.  But it's possible (e.g. simplrun008) and
626                 -- this is the Right Thing to do
627                 -> do   { tv_subst' <- Unify.ruleMatchTyX menv tv_subst (idType v1') (exprType e2)
628                                                 -- c.f. match_ty below
629                         ; return (tv_subst', extendVarEnv id_subst v1' e2, binds) }
630
631         Just e1' | tcEqExprX (nukeRnEnvL rn_env) e1' e2 
632                  -> Just subst
633
634                  | otherwise
635                  -> Nothing
636
637   | otherwise   -- v1 is not a template variable; check for an exact match with e2
638   = case e2 of
639        Var v2 | v1' == rnOccR rn_env v2 -> Just subst
640        other                            -> Nothing
641
642   where
643     rn_env = me_env menv
644     v1'    = rnOccL rn_env v1   
645         -- If the template is
646         --      forall x. f x (\x -> x) = ...
647         -- Then the x inside the lambda isn't the 
648         -- template x, so we must rename first!
649                                 
650
651 ------------------------------------------
652 match_alts :: MatchEnv
653       -> SubstEnv
654       -> [CoreAlt]              -- Template
655       -> [CoreAlt]              -- Target
656       -> Maybe SubstEnv
657 match_alts menv subst [] []
658   = return subst
659 match_alts menv subst ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2)
660   | c1 == c2
661   = do  { subst1 <- match menv' subst r1 r2
662         ; match_alts menv subst1 alts1 alts2 }
663   where
664     menv' :: MatchEnv
665     menv' = menv { me_env = rnBndrs2 (me_env menv) vs1 vs2 }
666
667 match_alts menv subst alts1 alts2 
668   = Nothing
669 \end{code}
670
671 Matching Core types: use the matcher in TcType.
672 Notice that we treat newtypes as opaque.  For example, suppose 
673 we have a specialised version of a function at a newtype, say 
674         newtype T = MkT Int
675 We only want to replace (f T) with f', not (f Int).
676
677 \begin{code}
678 ------------------------------------------
679 match_ty :: MatchEnv
680          -> SubstEnv
681          -> Type                -- Template
682          -> Type                -- Target
683          -> Maybe SubstEnv
684 match_ty menv (tv_subst, id_subst, binds) ty1 ty2
685   = do  { tv_subst' <- Unify.ruleMatchTyX menv tv_subst ty1 ty2
686         ; return (tv_subst', id_subst, binds) }
687 \end{code}
688
689
690 Note [Lookup in-scope]
691 ~~~~~~~~~~~~~~~~~~~~~~
692 Consider this example
693         foo :: Int -> Maybe Int -> Int
694         foo 0 (Just n) = n
695         foo m (Just n) = foo (m-n) (Just n)
696
697 SpecConstr sees this fragment:
698
699         case w_smT of wild_Xf [Just A] {
700           Data.Maybe.Nothing -> lvl_smf;
701           Data.Maybe.Just n_acT [Just S(L)] ->
702             case n_acT of wild1_ams [Just A] { GHC.Base.I# y_amr [Just L] ->
703             $wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
704             }};
705
706 and correctly generates the rule
707
708         RULES: "SC:$wfoo1" [0] __forall {y_amr [Just L] :: GHC.Prim.Int#
709                                           sc_snn :: GHC.Prim.Int#}
710           $wfoo_smW sc_snn (Data.Maybe.Just @ GHC.Base.Int (GHC.Base.I# y_amr))
711           = $s$wfoo_sno y_amr sc_snn ;]
712
713 BUT we must ensure that this rule matches in the original function!
714 Note that the call to $wfoo is
715             $wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
716
717 During matching we expand wild_Xf to (Just n_acT).  But then we must also
718 expand n_acT to (I# y_amr).  And we can only do that if we look up n_acT
719 in the in-scope set, because in wild_Xf's unfolding it won't have an unfolding
720 at all. 
721
722 That is why the 'lookupRnInScope' call in the (Var v2) case of 'match'
723 is so important.
724
725
726 %************************************************************************
727 %*                                                                      *
728 \subsection{Checking a program for failing rule applications}
729 %*                                                                      *
730 %************************************************************************
731
732 -----------------------------------------------------
733                         Game plan
734 -----------------------------------------------------
735
736 We want to know what sites have rules that could have fired but didn't.
737 This pass runs over the tree (without changing it) and reports such.
738
739 NB: we assume that this follows a run of the simplifier, so every Id
740 occurrence (including occurrences of imported Ids) is decorated with
741 all its (active) rules.  No need to construct a rule base or anything
742 like that.
743
744 \begin{code}
745 ruleCheckProgram :: CompilerPhase -> String -> [CoreBind] -> SDoc
746 -- Report partial matches for rules beginning 
747 -- with the specified string
748 ruleCheckProgram phase rule_pat binds 
749   | isEmptyBag results
750   = text "Rule check results: no rule application sites"
751   | otherwise
752   = vcat [text "Rule check results:",
753           line,
754           vcat [ p $$ line | p <- bagToList results ]
755          ]
756   where
757     results = unionManyBags (map (ruleCheckBind (phase, rule_pat)) binds)
758     line = text (replicate 20 '-')
759           
760 type RuleCheckEnv = (CompilerPhase, String)     -- Phase and Pattern
761
762 ruleCheckBind :: RuleCheckEnv -> CoreBind -> Bag SDoc
763    -- The Bag returned has one SDoc for each call site found
764 ruleCheckBind env (NonRec b r) = ruleCheck env r
765 ruleCheckBind env (Rec prs)    = unionManyBags [ruleCheck env r | (b,r) <- prs]
766
767 ruleCheck :: RuleCheckEnv -> CoreExpr -> Bag SDoc
768 ruleCheck env (Var v)       = emptyBag
769 ruleCheck env (Lit l)       = emptyBag
770 ruleCheck env (Type ty)     = emptyBag
771 ruleCheck env (App f a)     = ruleCheckApp env (App f a) []
772 ruleCheck env (Note n e)    = ruleCheck env e
773 ruleCheck env (Cast e co)   = ruleCheck env e
774 ruleCheck env (Let bd e)    = ruleCheckBind env bd `unionBags` ruleCheck env e
775 ruleCheck env (Lam b e)     = ruleCheck env e
776 ruleCheck env (Case e _ _ as) = ruleCheck env e `unionBags` 
777                                 unionManyBags [ruleCheck env r | (_,_,r) <- as]
778
779 ruleCheckApp env (App f a) as = ruleCheck env a `unionBags` ruleCheckApp env f (a:as)
780 ruleCheckApp env (Var f) as   = ruleCheckFun env f as
781 ruleCheckApp env other as     = ruleCheck env other
782 \end{code}
783
784 \begin{code}
785 ruleCheckFun :: RuleCheckEnv -> Id -> [CoreExpr] -> Bag SDoc
786 -- Produce a report for all rules matching the predicate
787 -- saying why it doesn't match the specified application
788
789 ruleCheckFun (phase, pat) fn args
790   | null name_match_rules = emptyBag
791   | otherwise             = unitBag (ruleAppCheck_help phase fn args name_match_rules)
792   where
793     name_match_rules = filter match (idCoreRules fn)
794     match rule = pat `isPrefixOf` unpackFS (ruleName rule)
795
796 ruleAppCheck_help :: CompilerPhase -> Id -> [CoreExpr] -> [CoreRule] -> SDoc
797 ruleAppCheck_help phase fn args rules
798   =     -- The rules match the pattern, so we want to print something
799     vcat [text "Expression:" <+> ppr (mkApps (Var fn) args),
800           vcat (map check_rule rules)]
801   where
802     n_args = length args
803     i_args = args `zip` [1::Int ..]
804     rough_args = map roughTopName args
805
806     check_rule rule = rule_herald rule <> colon <+> rule_info rule
807
808     rule_herald (BuiltinRule { ru_name = name })
809         = ptext SLIT("Builtin rule") <+> doubleQuotes (ftext name)
810     rule_herald (Rule { ru_name = name })
811         = ptext SLIT("Rule") <+> doubleQuotes (ftext name)
812
813     rule_info rule
814         | Just _ <- matchRule noBlackList emptyInScopeSet args rough_args rule
815         = text "matches (which is very peculiar!)"
816
817     rule_info (BuiltinRule {}) = text "does not match"
818
819     rule_info (Rule { ru_name = name, ru_act = act, 
820                       ru_bndrs = rule_bndrs, ru_args = rule_args})
821         | not (isActive phase act)    = text "active only in later phase"
822         | n_args < n_rule_args        = text "too few arguments"
823         | n_mismatches == n_rule_args = text "no arguments match"
824         | n_mismatches == 0           = text "all arguments match (considered individually), but rule as a whole does not"
825         | otherwise                   = text "arguments" <+> ppr mismatches <+> text "do not match (1-indexing)"
826         where
827           n_rule_args  = length rule_args
828           n_mismatches = length mismatches
829           mismatches   = [i | (rule_arg, (arg,i)) <- rule_args `zip` i_args,
830                               not (isJust (match_fn rule_arg arg))]
831
832           lhs_fvs = exprsFreeVars rule_args     -- Includes template tyvars
833           match_fn rule_arg arg = match menv emptySubstEnv rule_arg arg
834                 where
835                   in_scope = lhs_fvs `unionVarSet` exprFreeVars arg
836                   menv = ME { me_env   = mkRnEnv2 (mkInScopeSet in_scope)
837                             , me_tmpls = mkVarSet rule_bndrs }
838 \end{code}
839