2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[CoreRules]{Transformation rules}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- | Functions for collecting together and applying rewrite rules to a module.
15 -- The 'CoreRule' datatype itself is declared elsewhere.
21 emptyRuleBase, mkRuleBase, extendRuleBaseList,
22 unionRuleBase, pprRuleBase,
24 -- ** Checking rule applications
27 -- ** Manipulating 'SpecInfo' rules
28 mkSpecInfo, extendSpecInfo, addSpecInfo,
31 -- * Misc. CoreRule helpers
32 rulesOfBinds, pprRulesForUser,
34 lookupRule, mkLocalRule, roughTopNames
37 #include "HsVersions.h"
39 import CoreSyn -- All of it
40 import OccurAnal ( occurAnalyseExpr )
41 import CoreFVs ( exprFreeVars, exprsFreeVars, bindFreeVars, rulesFreeVars )
42 import CoreUnfold ( isCheapUnfolding, unfoldingTemplate )
43 import CoreUtils ( tcEqExprX, exprType )
44 import PprCore ( pprRules )
45 import Type ( Type, TvSubstEnv )
46 import Coercion ( coercionKind )
47 import TcType ( tcSplitTyConApp_maybe )
48 import CoreTidy ( tidyRules )
50 import IdInfo ( SpecInfo( SpecInfo ) )
54 import Name ( Name, NamedThing(..) )
56 import Unify ( ruleMatchTyX, MatchEnv(..) )
57 import BasicTypes ( Activation, CompilerPhase, isActive )
58 import StaticFlags ( opt_PprStyle_Debug )
69 %************************************************************************
71 \subsection[specialisation-IdInfo]{Specialisation info about an @Id@}
73 %************************************************************************
75 A @CoreRule@ holds details of one rule for an @Id@, which
76 includes its specialisations.
78 For example, if a rule for @f@ contains the mapping:
80 forall a b d. [Type (List a), Type b, Var d] ===> f' a b
82 then when we find an application of f to matching types, we simply replace
83 it by the matching RHS:
85 f (List Int) Bool dict ===> f' Int Bool
87 All the stuff about how many dictionaries to discard, and what types
88 to apply the specialised function to, are handled by the fact that the
89 Rule contains a template for the result of the specialisation.
91 There is one more exciting case, which is dealt with in exactly the same
92 way. If the specialised value is unboxed then it is lifted at its
93 definition site and unlifted at its uses. For example:
95 pi :: forall a. Num a => a
97 might have a specialisation
99 [Int#] ===> (case pi' of Lift pi# -> pi#)
101 where pi' :: Lift Int# is the specialised version of pi.
104 mkLocalRule :: RuleName -> Activation
105 -> Name -> [CoreBndr] -> [CoreExpr] -> CoreExpr -> CoreRule
106 -- ^ Used to make 'CoreRule' for an 'Id' defined in the module being
107 -- compiled. See also 'CoreSyn.CoreRule'
108 mkLocalRule name act fn bndrs args rhs
109 = Rule { ru_name = name, ru_fn = fn, ru_act = act,
110 ru_bndrs = bndrs, ru_args = args,
111 ru_rhs = rhs, ru_rough = roughTopNames args,
115 roughTopNames :: [CoreExpr] -> [Maybe Name]
116 -- ^ Find the \"top\" free names of several expressions.
117 -- Such names are either:
119 -- 1. The function finally being applied to in an application chain
120 -- (if that name is a GlobalId: see "Var#globalvslocal"), or
122 -- 2. The 'TyCon' if the expression is a 'Type'
124 -- This is used for the fast-match-check for rules;
125 -- if the top names don't match, the rest can't
126 roughTopNames args = map roughTopName args
128 roughTopName :: CoreExpr -> Maybe Name
129 roughTopName (Type ty) = case tcSplitTyConApp_maybe ty of
130 Just (tc,_) -> Just (getName tc)
132 roughTopName (App f a) = roughTopName f
133 roughTopName (Var f) | isGlobalId f = Just (idName f)
134 | otherwise = Nothing
135 roughTopName other = Nothing
137 ruleCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
138 -- ^ @ruleCantMatch tpl actual@ returns True only if @actual@
139 -- definitely can't match @tpl@ by instantiating @tpl@.
140 -- It's only a one-way match; unlike instance matching we
141 -- don't consider unification.
144 -- @ruleCantMatch [Nothing] [Just n2] = False@
145 -- Reason: a template variable can be instantiated by a constant
147 -- @ruleCantMatch [Just n1] [Nothing] = False@
148 -- Reason: a local variable @v@ in the actuals might [_$_]
150 ruleCantMatch (Just n1 : ts) (Just n2 : as) = n1 /= n2 || ruleCantMatch ts as
151 ruleCantMatch (t : ts) (a : as) = ruleCantMatch ts as
152 ruleCantMatch ts as = False
156 pprRulesForUser :: [CoreRule] -> SDoc
157 -- (a) tidy the rules
158 -- (b) sort them into order based on the rule name
159 -- (c) suppress uniques (unless -dppr-debug is on)
160 -- This combination makes the output stable so we can use in testing
161 -- It's here rather than in PprCore because it calls tidyRules
162 pprRulesForUser rules
163 = withPprStyle defaultUserStyle $
166 tidyRules emptyTidyEnv rules
168 le_rule r1 r2 = ru_name r1 <= ru_name r2
172 %************************************************************************
174 SpecInfo: the rules in an IdInfo
176 %************************************************************************
179 -- | Make a 'SpecInfo' containing a number of 'CoreRule's, suitable
180 -- for putting into an 'IdInfo'
181 mkSpecInfo :: [CoreRule] -> SpecInfo
182 mkSpecInfo rules = SpecInfo rules (rulesFreeVars rules)
184 extendSpecInfo :: SpecInfo -> [CoreRule] -> SpecInfo
185 extendSpecInfo (SpecInfo rs1 fvs1) rs2
186 = SpecInfo (rs2 ++ rs1) (rulesFreeVars rs2 `unionVarSet` fvs1)
187 addSpecInfo :: SpecInfo -> SpecInfo -> SpecInfo
188 addSpecInfo (SpecInfo rs1 fvs1) (SpecInfo rs2 fvs2)
189 = SpecInfo (rs1 ++ rs2) (fvs1 `unionVarSet` fvs2)
191 addIdSpecialisations :: Id -> [CoreRule] -> Id
192 addIdSpecialisations id rules
193 = setIdSpecialisation id $
194 extendSpecInfo (idSpecialisation id) rules
196 -- | Gather all the rules for locally bound identifiers from the supplied bindings
197 rulesOfBinds :: [CoreBind] -> [CoreRule]
198 rulesOfBinds binds = concatMap (concatMap idCoreRules . bindersOf) binds
202 %************************************************************************
206 %************************************************************************
209 -- | Gathers a collection of 'CoreRule's. Maps (the name of) an 'Id' to its rules
210 type RuleBase = NameEnv [CoreRule]
211 -- The rules are are unordered;
212 -- we sort out any overlaps on lookup
214 emptyRuleBase = emptyNameEnv
216 mkRuleBase :: [CoreRule] -> RuleBase
217 mkRuleBase rules = extendRuleBaseList emptyRuleBase rules
219 extendRuleBaseList :: RuleBase -> [CoreRule] -> RuleBase
220 extendRuleBaseList rule_base new_guys
221 = foldl extendRuleBase rule_base new_guys
223 unionRuleBase :: RuleBase -> RuleBase -> RuleBase
224 unionRuleBase rb1 rb2 = plusNameEnv_C (++) rb1 rb2
226 extendRuleBase :: RuleBase -> CoreRule -> RuleBase
227 extendRuleBase rule_base rule
228 = extendNameEnv_Acc (:) singleton rule_base (ruleIdName rule) rule
230 pprRuleBase :: RuleBase -> SDoc
231 pprRuleBase rules = vcat [ pprRules (tidyRules emptyTidyEnv rs)
232 | rs <- nameEnvElts rules ]
236 %************************************************************************
238 \subsection{Matching}
240 %************************************************************************
242 Note [Extra args in rule matching]
243 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
244 If we find a matching rule, we return (Just (rule, rhs)),
245 but the rule firing has only consumed as many of the input args
246 as the ruleArity says. It's up to the caller to keep track
247 of any left-over args. E.g. if you call
248 lookupRule ... f [e1, e2, e3]
249 and it returns Just (r, rhs), where r has ruleArity 2
250 then the real rewrite is
251 f e1 e2 e3 ==> rhs e3
253 You might think it'd be cleaner for lookupRule to deal with the
254 leftover arguments, by applying 'rhs' to them, but the main call
255 in the Simplifier works better as it is. Reason: the 'args' passed
256 to lookupRule are the result of a lazy substitution
259 -- | The main rule matching function. Attempts to apply all the active
260 -- rules in a given 'RuleBase' to this instance of an application
261 -- in a given context, returning the rule applied and the resulting
262 -- expression if successful.
263 lookupRule :: (Activation -> Bool) -- ^ Activation test
264 -> InScopeSet -- ^ Variables that are in scope at this point
265 -> RuleBase -- ^ Imported rules
266 -> Id -- ^ Function 'Id' to lookup a rule by
267 -> [CoreExpr] -- ^ Arguments to function
268 -> Maybe (CoreRule, CoreExpr)
269 -- See Note [Extra argsin rule matching]
270 lookupRule is_active in_scope rule_base fn args
271 = matchRules is_active in_scope fn args (getRules rule_base fn)
273 getRules :: RuleBase -> Id -> [CoreRule]
274 -- The rules for an Id come from two places:
275 -- (a) the ones it is born with (idCoreRules fn)
276 -- (b) rules added in subsequent modules (extra_rules)
277 -- PrimOps, for example, are born with a bunch of rules under (a)
278 getRules rule_base fn
279 | isLocalId fn = idCoreRules fn
280 | otherwise = WARN( not (isPrimOpId fn) && notNull (idCoreRules fn),
281 ppr fn <+> ppr (idCoreRules fn) )
282 idCoreRules fn ++ (lookupNameEnv rule_base (idName fn) `orElse` [])
283 -- Only PrimOpIds have rules inside themselves, and perhaps more besides
285 matchRules :: (Activation -> Bool) -> InScopeSet
287 -> [CoreRule] -> Maybe (CoreRule, CoreExpr)
288 -- See comments on matchRule
289 matchRules is_active in_scope fn args rules
290 = -- pprTrace "matchRules" (ppr fn <+> ppr rules) $
293 (m:ms) -> Just (findBest (fn,args) m ms)
295 rough_args = map roughTopName args
297 go :: [(CoreRule,CoreExpr)] -> [CoreRule] -> [(CoreRule,CoreExpr)]
299 go ms (r:rs) = case (matchRule is_active in_scope args rough_args r) of
300 Just e -> go ((r,e):ms) rs
301 Nothing -> -- pprTrace "match failed" (ppr r $$ ppr args $$
302 -- ppr [(arg_id, unfoldingTemplate unf) | Var arg_id <- args, let unf = idUnfolding arg_id, isCheapUnfolding unf] )
305 findBest :: (Id, [CoreExpr])
306 -> (CoreRule,CoreExpr) -> [(CoreRule,CoreExpr)] -> (CoreRule,CoreExpr)
307 -- All these pairs matched the expression
308 -- Return the pair the the most specific rule
309 -- The (fn,args) is just for overlap reporting
311 findBest target (rule,ans) [] = (rule,ans)
312 findBest target (rule1,ans1) ((rule2,ans2):prs)
313 | rule1 `isMoreSpecific` rule2 = findBest target (rule1,ans1) prs
314 | rule2 `isMoreSpecific` rule1 = findBest target (rule2,ans2) prs
315 | debugIsOn = let pp_rule rule
316 | opt_PprStyle_Debug = ppr rule
317 | otherwise = doubleQuotes (ftext (ru_name rule))
318 in pprTrace "Rules.findBest: rule overlap (Rule 1 wins)"
319 (vcat [if opt_PprStyle_Debug then
320 ptext (sLit "Expression to match:") <+> ppr fn <+> sep (map ppr args)
322 ptext (sLit "Rule 1:") <+> pp_rule rule1,
323 ptext (sLit "Rule 2:") <+> pp_rule rule2]) $
324 findBest target (rule1,ans1) prs
325 | otherwise = findBest target (rule1,ans1) prs
329 isMoreSpecific :: CoreRule -> CoreRule -> Bool
330 isMoreSpecific (BuiltinRule {}) r2 = True
331 isMoreSpecific r1 (BuiltinRule {}) = False
332 isMoreSpecific (Rule { ru_bndrs = bndrs1, ru_args = args1 })
333 (Rule { ru_bndrs = bndrs2, ru_args = args2 })
334 = isJust (matchN in_scope bndrs2 args2 args1)
336 in_scope = mkInScopeSet (mkVarSet bndrs1)
337 -- Actually we should probably include the free vars
338 -- of rule1's args, but I can't be bothered
340 noBlackList :: Activation -> Bool
341 noBlackList act = False -- Nothing is black listed
343 matchRule :: (Activation -> Bool) -> InScopeSet
344 -> [CoreExpr] -> [Maybe Name]
345 -> CoreRule -> Maybe CoreExpr
347 -- If (matchRule rule args) returns Just (name,rhs)
348 -- then (f args) matches the rule, and the corresponding
349 -- rewritten RHS is rhs
351 -- The bndrs and rhs is occurrence-analysed
356 -- forall f g x. map f (map g x) ==> map (f . g) x
358 -- CoreRule "map/map"
359 -- [f,g,x] -- tpl_vars
360 -- [f,map g x] -- tpl_args
361 -- map (f.g) x) -- rhs
363 -- Then the call: matchRule the_rule [e1,map e2 e3]
364 -- = Just ("map/map", (\f,g,x -> rhs) e1 e2 e3)
366 -- Any 'surplus' arguments in the input are simply put on the end
369 matchRule is_active in_scope args rough_args
370 (BuiltinRule { ru_name = name, ru_try = match_fn })
371 = case match_fn args of
372 Just expr -> Just expr
375 matchRule is_active in_scope args rough_args
376 (Rule { ru_name = rn, ru_act = act, ru_rough = tpl_tops,
377 ru_bndrs = tpl_vars, ru_args = tpl_args,
379 | not (is_active act) = Nothing
380 | ruleCantMatch tpl_tops rough_args = Nothing
382 = case matchN in_scope tpl_vars tpl_args args of
384 Just (binds, tpl_vals) -> Just (mkLets binds $
385 rule_fn `mkApps` tpl_vals)
387 rule_fn = occurAnalyseExpr (mkLams tpl_vars rhs)
388 -- We could do this when putting things into the rulebase, I guess
392 -- For a given match template and context, find bindings to wrap around
393 -- the entire result and what should be substituted for each template variable.
394 -- Fail if there are two few actual arguments from the target to match the template
395 matchN :: InScopeSet -- ^ In-scope variables
396 -> [Var] -- ^ Match template type variables
397 -> [CoreExpr] -- ^ Match template
398 -> [CoreExpr] -- ^ Target; can have more elements than the template
399 -> Maybe ([CoreBind],
402 matchN in_scope tmpl_vars tmpl_es target_es
403 = do { (tv_subst, id_subst, binds)
404 <- go init_menv emptySubstEnv tmpl_es target_es
405 ; return (fromOL binds,
406 map (lookup_tmpl tv_subst id_subst) tmpl_vars') }
408 (init_rn_env, tmpl_vars') = mapAccumL rnBndrL (mkRnEnv2 in_scope) tmpl_vars
409 -- See Note [Template binders]
411 init_menv = ME { me_tmpls = mkVarSet tmpl_vars', me_env = init_rn_env }
413 go menv subst [] es = Just subst
414 go menv subst ts [] = Nothing -- Fail if too few actual args
415 go menv subst (t:ts) (e:es) = do { subst1 <- match menv subst t e
416 ; go menv subst1 ts es }
418 lookup_tmpl :: TvSubstEnv -> IdSubstEnv -> Var -> CoreExpr
419 lookup_tmpl tv_subst id_subst tmpl_var'
420 | isTyVar tmpl_var' = case lookupVarEnv tv_subst tmpl_var' of
422 Nothing -> unbound tmpl_var'
423 | otherwise = case lookupVarEnv id_subst tmpl_var' of
425 other -> unbound tmpl_var'
427 unbound var = pprPanic "Template variable unbound in rewrite rule"
428 (ppr var $$ ppr tmpl_vars $$ ppr tmpl_vars' $$ ppr tmpl_es $$ ppr target_es)
431 Note [Template binders]
432 ~~~~~~~~~~~~~~~~~~~~~~~
433 Consider the following match:
434 Template: forall x. f x
436 This should succeed, because the template variable 'x' has
437 nothing to do with the 'x' in the target.
439 On reflection, this case probably does just work, but this might not
440 Template: forall x. f (\x.x)
442 Here we want to clone when we find the \x, but to know that x must be in scope
444 To achive this, we use rnBndrL to rename the template variables if
445 necessary; the renamed ones are the tmpl_vars'
448 ---------------------------------------------
449 The inner workings of matching
450 ---------------------------------------------
453 -- These two definitions are not the same as in Subst,
454 -- but they simple and direct, and purely local to this module
456 -- * The domain of the TvSubstEnv and IdSubstEnv are the template
457 -- variables passed into the match.
459 -- * The (OrdList CoreBind) in a SubstEnv are the bindings floated out
460 -- from nested matches; see the Let case of match, below
462 type SubstEnv = (TvSubstEnv, IdSubstEnv, OrdList CoreBind)
463 type IdSubstEnv = IdEnv CoreExpr
465 emptySubstEnv :: SubstEnv
466 emptySubstEnv = (emptyVarEnv, emptyVarEnv, nilOL)
469 -- At one stage I tried to match even if there are more
470 -- template args than real args.
472 -- I now think this is probably a bad idea.
473 -- Should the template (map f xs) match (map g)? I think not.
474 -- For a start, in general eta expansion wastes work.
480 -> CoreExpr -- Template
481 -> CoreExpr -- Target
484 -- See the notes with Unify.match, which matches types
485 -- Everything is very similar for terms
487 -- Interesting examples:
489 -- \x->f against \f->f
490 -- When we meet the lambdas we must remember to rename f to f' in the
491 -- second expresion. The RnEnv2 does that.
494 -- forall a. \b->b against \a->3
495 -- We must rename the \a. Otherwise when we meet the lambdas we
496 -- might substitute [a/b] in the template, and then erroneously
497 -- succeed in matching what looks like the template variable 'a' against 3.
499 -- The Var case follows closely what happens in Unify.match
500 match menv subst (Var v1) e2
501 | Just subst <- match_var menv subst v1 e2
504 match menv subst e1 (Note n e2)
505 = match menv subst e1 e2
506 -- Note [Notes in RULE matching]
507 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
508 -- Look through Notes. In particular, we don't want to
509 -- be confused by InlineMe notes. Maybe we should be more
510 -- careful about profiling notes, but for now I'm just
511 -- riding roughshod over them.
512 --- See Note [Notes in call patterns] in SpecConstr
514 -- Here is another important rule: if the term being matched is a
515 -- variable, we expand it so long as its unfolding is a WHNF
516 -- (Its occurrence information is not necessarily up to date,
517 -- so we don't use it.)
518 match menv subst e1 (Var v2)
519 | isCheapUnfolding unfolding
520 = match menv subst e1 (unfoldingTemplate unfolding)
523 unfolding = idUnfolding (lookupRnInScope rn_env (rnOccR rn_env v2))
524 -- Notice that we look up v2 in the in-scope set
525 -- See Note [Lookup in-scope]
526 -- Remember to apply any renaming first (hence rnOccR)
528 -- Note [Matching lets]
529 -- ~~~~~~~~~~~~~~~~~~~~
530 -- Matching a let-expression. Consider
531 -- RULE forall x. f (g x) = <rhs>
532 -- and target expression
533 -- f (let { w=R } in g E))
534 -- Then we'd like the rule to match, to generate
535 -- let { w=R } in (\x. <rhs>) E
536 -- In effect, we want to float the let-binding outward, to enable
537 -- the match to happen. This is the WHOLE REASON for accumulating
538 -- bindings in the SubstEnv
540 -- We can only do this if
541 -- (a) Widening the scope of w does not capture any variables
542 -- We use a conservative test: w is not already in scope
543 -- If not, we clone the binders, and substitute
544 -- (b) The free variables of R are not bound by the part of the
545 -- target expression outside the let binding; e.g.
546 -- f (\v. let w = v+1 in g E)
547 -- Here we obviously cannot float the let-binding for w.
549 -- You may think rule (a) would never apply, because rule matching is
550 -- mostly invoked from the simplifier, when we have just run substExpr
551 -- over the argument, so there will be no shadowing anyway.
552 -- The fly in the ointment is that the forall'd variables of the
553 -- RULE itself are considered in scope.
555 -- I though of various cheapo ways to solve this tiresome problem,
556 -- but ended up doing the straightforward thing, which is to
557 -- clone the binders if they are in scope. It's tiresome, and
558 -- potentially inefficient, because of the calls to substExpr,
559 -- but I don't think it'll happen much in pracice.
561 {- Cases to think about
562 (let x=y+1 in \x. (x,x))
563 --> let x=y+1 in (\x1. (x1,x1))
564 (\x. let x = y+1 in (x,x))
565 --> let x1 = y+1 in (\x. (x1,x1)
566 (let x=y+1 in (x,x), let x=y-1 in (x,x))
567 --> let x=y+1 in let x1=y-1 in ((x,x),(x1,x1))
570 (let x=y+1 in let z=x+1 in (z,z)
571 --> matches (p,p) but watch out that the use of
573 I'm removing the cloning because that makes the above case
574 fail, because the inner let looks as if it has locally-bound vars -}
576 match menv subst@(tv_subst, id_subst, binds) e1 (Let bind e2)
577 | all freshly_bound bndrs,
578 not (any locally_bound bind_fvs)
579 = match (menv { me_env = rn_env' })
580 (tv_subst, id_subst, binds `snocOL` bind')
584 bndrs = bindersOf bind
585 bind_fvs = varSetElems (bindFreeVars bind)
586 locally_bound x = inRnEnvR rn_env x
587 freshly_bound x = not (x `rnInScope` rn_env)
590 rn_env' = extendRnInScopeList rn_env bndrs
592 (rn_env', bndrs') = mapAccumL rnBndrR rn_env bndrs
593 s_prs = [(bndr, Var bndr') | (bndr,bndr') <- zip bndrs bndrs', bndr /= bndr']
594 subst = mkSubst (rnInScopeSet rn_env) emptyVarEnv (mkVarEnv s_prs)
595 (bind', e2') | null s_prs = (bind, e2)
596 | otherwise = (s_bind, substExpr subst e2)
597 s_bind = case bind of
598 NonRec {} -> NonRec (head bndrs') (head rhss)
599 Rec {} -> Rec (bndrs' `zip` map (substExpr subst) rhss)
602 match menv subst (Lit lit1) (Lit lit2)
606 match menv subst (App f1 a1) (App f2 a2)
607 = do { subst' <- match menv subst f1 f2
608 ; match menv subst' a1 a2 }
610 match menv subst (Lam x1 e1) (Lam x2 e2)
611 = match menv' subst e1 e2
613 menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
615 -- This rule does eta expansion
616 -- (\x.M) ~ N iff M ~ N x
617 -- It's important that this is *after* the let rule,
618 -- so that (\x.M) ~ (let y = e in \y.N)
619 -- does the let thing, and then gets the lam/lam rule above
620 match menv subst (Lam x1 e1) e2
621 = match menv' subst e1 (App e2 (varToCoreExpr new_x))
623 (rn_env', new_x) = rnBndrL (me_env menv) x1
624 menv' = menv { me_env = rn_env' }
626 -- Eta expansion the other way
627 -- M ~ (\y.N) iff M y ~ N
628 match menv subst e1 (Lam x2 e2)
629 = match menv' subst (App e1 (varToCoreExpr new_x)) e2
631 (rn_env', new_x) = rnBndrR (me_env menv) x2
632 menv' = menv { me_env = rn_env' }
634 match menv subst (Case e1 x1 ty1 alts1) (Case e2 x2 ty2 alts2)
635 = do { subst1 <- match_ty menv subst ty1 ty2
636 ; subst2 <- match menv subst1 e1 e2
637 ; let menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
638 ; match_alts menv' subst2 alts1 alts2 -- Alts are both sorted
641 match menv subst (Type ty1) (Type ty2)
642 = match_ty menv subst ty1 ty2
644 match menv subst (Cast e1 co1) (Cast e2 co2)
645 = do { subst1 <- match_ty menv subst co1 co2
646 ; match menv subst1 e1 e2 }
648 {- REMOVING OLD CODE: I think that the above handling for let is
649 better than the stuff here, which looks
650 pretty suspicious to me. SLPJ Sept 06
651 -- This is an interesting rule: we simply ignore lets in the
652 -- term being matched against! The unfolding inside it is (by assumption)
653 -- already inside any occurrences of the bound variables, so we'll expand
654 -- them when we encounter them. This gives a chance of matching
655 -- forall x,y. f (g (x,y))
657 -- f (let v = (a,b) in g v)
659 match menv subst e1 (Let bind e2)
660 = match (menv { me_env = rn_env' }) subst e1 e2
662 (rn_env', _bndrs') = mapAccumL rnBndrR (me_env menv) (bindersOf bind)
663 -- It's important to do this renaming, so that the bndrs
664 -- are brought into the local scope. For example:
666 -- forall f,x,xs. f (x:xs)
668 -- f (let y = e in (y:[]))
669 -- We must not get success with x->y! So we record that y is
670 -- locally bound (with rnBndrR), and proceed. The Var case
671 -- will fail when trying to bind x->y
674 -- Everything else fails
675 match menv subst e1 e2 = -- pprTrace "Failing at" ((text "e1:" <+> ppr e1) $$ (text "e2:" <+> ppr e2)) $
678 ------------------------------------------
679 match_var :: MatchEnv
682 -> CoreExpr -- Target
684 match_var menv subst@(tv_subst, id_subst, binds) v1 e2
685 | v1' `elemVarSet` me_tmpls menv
686 = case lookupVarEnv id_subst v1' of
687 Nothing | any (inRnEnvR rn_env) (varSetElems (exprFreeVars e2))
688 -> Nothing -- Occurs check failure
689 -- e.g. match forall a. (\x-> a x) against (\y. y y)
691 | otherwise -- No renaming to do on e2, because no free var
692 -- of e2 is in the rnEnvR of the envt
693 -- Note [Matching variable types]
694 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
695 -- However, we must match the *types*; e.g.
696 -- forall (c::Char->Int) (x::Char).
697 -- f (c x) = "RULE FIRED"
698 -- We must only match on args that have the right type
699 -- It's actually quite difficult to come up with an example that shows
700 -- you need type matching, esp since matching is left-to-right, so type
701 -- args get matched first. But it's possible (e.g. simplrun008) and
702 -- this is the Right Thing to do
703 -> do { tv_subst' <- Unify.ruleMatchTyX menv tv_subst (idType v1') (exprType e2)
704 -- c.f. match_ty below
705 ; return (tv_subst', extendVarEnv id_subst v1' e2, binds) }
707 Just e1' | tcEqExprX (nukeRnEnvL rn_env) e1' e2
713 | otherwise -- v1 is not a template variable; check for an exact match with e2
715 Var v2 | v1' == rnOccR rn_env v2 -> Just subst
720 v1' = rnOccL rn_env v1
721 -- If the template is
722 -- forall x. f x (\x -> x) = ...
723 -- Then the x inside the lambda isn't the
724 -- template x, so we must rename first!
727 ------------------------------------------
728 match_alts :: MatchEnv
730 -> [CoreAlt] -- Template
731 -> [CoreAlt] -- Target
733 match_alts menv subst [] []
735 match_alts menv subst ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2)
737 = do { subst1 <- match menv' subst r1 r2
738 ; match_alts menv subst1 alts1 alts2 }
741 menv' = menv { me_env = rnBndrs2 (me_env menv) vs1 vs2 }
743 match_alts menv subst alts1 alts2
747 Matching Core types: use the matcher in TcType.
748 Notice that we treat newtypes as opaque. For example, suppose
749 we have a specialised version of a function at a newtype, say
751 We only want to replace (f T) with f', not (f Int).
754 ------------------------------------------
760 match_ty menv (tv_subst, id_subst, binds) ty1 ty2
761 = do { tv_subst' <- Unify.ruleMatchTyX menv tv_subst ty1 ty2
762 ; return (tv_subst', id_subst, binds) }
766 Note [Lookup in-scope]
767 ~~~~~~~~~~~~~~~~~~~~~~
768 Consider this example
769 foo :: Int -> Maybe Int -> Int
771 foo m (Just n) = foo (m-n) (Just n)
773 SpecConstr sees this fragment:
775 case w_smT of wild_Xf [Just A] {
776 Data.Maybe.Nothing -> lvl_smf;
777 Data.Maybe.Just n_acT [Just S(L)] ->
778 case n_acT of wild1_ams [Just A] { GHC.Base.I# y_amr [Just L] ->
779 \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
782 and correctly generates the rule
784 RULES: "SC:$wfoo1" [0] __forall {y_amr [Just L] :: GHC.Prim.Int#
785 sc_snn :: GHC.Prim.Int#}
786 \$wfoo_smW sc_snn (Data.Maybe.Just @ GHC.Base.Int (GHC.Base.I# y_amr))
787 = \$s\$wfoo_sno y_amr sc_snn ;]
789 BUT we must ensure that this rule matches in the original function!
790 Note that the call to \$wfoo is
791 \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
793 During matching we expand wild_Xf to (Just n_acT). But then we must also
794 expand n_acT to (I# y_amr). And we can only do that if we look up n_acT
795 in the in-scope set, because in wild_Xf's unfolding it won't have an unfolding
798 That is why the 'lookupRnInScope' call in the (Var v2) case of 'match'
802 %************************************************************************
804 \subsection{Checking a program for failing rule applications}
806 %************************************************************************
808 -----------------------------------------------------
810 -----------------------------------------------------
812 We want to know what sites have rules that could have fired but didn't.
813 This pass runs over the tree (without changing it) and reports such.
816 -- | Report partial matches for rules beginning with the specified
817 -- string for the purposes of error reporting
818 ruleCheckProgram :: CompilerPhase -- ^ Phase to check in
819 -> String -- ^ Rule pattern
820 -> RuleBase -- ^ Database of rules
821 -> [CoreBind] -- ^ Bindings to check in
822 -> SDoc -- ^ Resulting check message
823 ruleCheckProgram phase rule_pat rule_base binds
825 = text "Rule check results: no rule application sites"
827 = vcat [text "Rule check results:",
829 vcat [ p $$ line | p <- bagToList results ]
832 results = unionManyBags (map (ruleCheckBind (phase, rule_pat, rule_base)) binds)
833 line = text (replicate 20 '-')
835 type RuleCheckEnv = (CompilerPhase, String, RuleBase) -- Phase and Pattern
837 ruleCheckBind :: RuleCheckEnv -> CoreBind -> Bag SDoc
838 -- The Bag returned has one SDoc for each call site found
839 ruleCheckBind env (NonRec b r) = ruleCheck env r
840 ruleCheckBind env (Rec prs) = unionManyBags [ruleCheck env r | (b,r) <- prs]
842 ruleCheck :: RuleCheckEnv -> CoreExpr -> Bag SDoc
843 ruleCheck env (Var v) = emptyBag
844 ruleCheck env (Lit l) = emptyBag
845 ruleCheck env (Type ty) = emptyBag
846 ruleCheck env (App f a) = ruleCheckApp env (App f a) []
847 ruleCheck env (Note n e) = ruleCheck env e
848 ruleCheck env (Cast e co) = ruleCheck env e
849 ruleCheck env (Let bd e) = ruleCheckBind env bd `unionBags` ruleCheck env e
850 ruleCheck env (Lam b e) = ruleCheck env e
851 ruleCheck env (Case e _ _ as) = ruleCheck env e `unionBags`
852 unionManyBags [ruleCheck env r | (_,_,r) <- as]
854 ruleCheckApp env (App f a) as = ruleCheck env a `unionBags` ruleCheckApp env f (a:as)
855 ruleCheckApp env (Var f) as = ruleCheckFun env f as
856 ruleCheckApp env other as = ruleCheck env other
860 ruleCheckFun :: RuleCheckEnv -> Id -> [CoreExpr] -> Bag SDoc
861 -- Produce a report for all rules matching the predicate
862 -- saying why it doesn't match the specified application
864 ruleCheckFun (phase, pat, rule_base) fn args
865 | null name_match_rules = emptyBag
866 | otherwise = unitBag (ruleAppCheck_help phase fn args name_match_rules)
868 name_match_rules = filter match (getRules rule_base fn)
869 match rule = pat `isPrefixOf` unpackFS (ruleName rule)
871 ruleAppCheck_help :: CompilerPhase -> Id -> [CoreExpr] -> [CoreRule] -> SDoc
872 ruleAppCheck_help phase fn args rules
873 = -- The rules match the pattern, so we want to print something
874 vcat [text "Expression:" <+> ppr (mkApps (Var fn) args),
875 vcat (map check_rule rules)]
878 i_args = args `zip` [1::Int ..]
879 rough_args = map roughTopName args
881 check_rule rule = rule_herald rule <> colon <+> rule_info rule
883 rule_herald (BuiltinRule { ru_name = name })
884 = ptext (sLit "Builtin rule") <+> doubleQuotes (ftext name)
885 rule_herald (Rule { ru_name = name })
886 = ptext (sLit "Rule") <+> doubleQuotes (ftext name)
889 | Just _ <- matchRule noBlackList emptyInScopeSet args rough_args rule
890 = text "matches (which is very peculiar!)"
892 rule_info (BuiltinRule {}) = text "does not match"
894 rule_info (Rule { ru_name = name, ru_act = act,
895 ru_bndrs = rule_bndrs, ru_args = rule_args})
896 | not (isActive phase act) = text "active only in later phase"
897 | n_args < n_rule_args = text "too few arguments"
898 | n_mismatches == n_rule_args = text "no arguments match"
899 | n_mismatches == 0 = text "all arguments match (considered individually), but rule as a whole does not"
900 | otherwise = text "arguments" <+> ppr mismatches <+> text "do not match (1-indexing)"
902 n_rule_args = length rule_args
903 n_mismatches = length mismatches
904 mismatches = [i | (rule_arg, (arg,i)) <- rule_args `zip` i_args,
905 not (isJust (match_fn rule_arg arg))]
907 lhs_fvs = exprsFreeVars rule_args -- Includes template tyvars
908 match_fn rule_arg arg = match menv emptySubstEnv rule_arg arg
910 in_scope = lhs_fvs `unionVarSet` exprFreeVars arg
911 menv = ME { me_env = mkRnEnv2 (mkInScopeSet in_scope)
912 , me_tmpls = mkVarSet rule_bndrs }