add -fsimpleopt-before-flatten
[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 -- | Functions for collecting together and applying rewrite rules to a module.
8 -- The 'CoreRule' datatype itself is declared elsewhere.
9 module Rules (
10         -- * RuleBase
11         RuleBase, 
12         
13         -- ** Constructing 
14         emptyRuleBase, mkRuleBase, extendRuleBaseList, 
15         unionRuleBase, pprRuleBase, 
16         
17         -- ** Checking rule applications
18         ruleCheckProgram,
19
20         -- ** Manipulating 'SpecInfo' rules
21         mkSpecInfo, extendSpecInfo, addSpecInfo,
22         addIdSpecialisations, 
23         
24         -- * Misc. CoreRule helpers
25         rulesOfBinds, getRules, pprRulesForUser, 
26         
27         lookupRule, mkRule, roughTopNames
28     ) where
29
30 #include "HsVersions.h"
31
32 import CoreSyn          -- All of it
33 import CoreSubst
34 import OccurAnal        ( occurAnalyseExpr )
35 import CoreFVs          ( exprFreeVars, exprsFreeVars, bindFreeVars, rulesFreeVars )
36 import CoreUtils        ( exprType, eqExpr )
37 import PprCore          ( pprRules )
38 import Type             ( Type )
39 import TcType           ( tcSplitTyConApp_maybe )
40 import CoreTidy         ( tidyRules )
41 import Id
42 import IdInfo           ( SpecInfo( SpecInfo ) )
43 import Var              ( Var )
44 import VarEnv
45 import VarSet
46 import Name             ( Name, NamedThing(..) )
47 import NameEnv
48 import Unify            ( ruleMatchTyX, MatchEnv(..) )
49 import BasicTypes       ( Activation, CompilerPhase, isActive )
50 import StaticFlags      ( opt_PprStyle_Debug )
51 import Outputable
52 import FastString
53 import Maybes
54 import Bag
55 import Util
56 import Data.List
57 \end{code}
58
59
60 Note [Overall plumbing for rules]
61 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
62 * After the desugarer:
63    - The ModGuts initially contains mg_rules :: [CoreRule] of
64      locally-declared rules for imported Ids.  
65    - Locally-declared rules for locally-declared Ids are attached to
66      the IdInfo for that Id.  See Note [Attach rules to local ids] in
67      DsBinds
68  
69 * TidyPgm strips off all the rules from local Ids and adds them to
70   mg_rules, so that the ModGuts has *all* the locally-declared rules.
71
72 * The HomePackageTable contains a ModDetails for each home package
73   module.  Each contains md_rules :: [CoreRule] of rules declared in
74   that module.  The HomePackageTable grows as ghc --make does its
75   up-sweep.  In batch mode (ghc -c), the HPT is empty; all imported modules
76   are treated by the "external" route, discussed next, regardless of
77   which package they come from.
78
79 * The ExternalPackageState has a single eps_rule_base :: RuleBase for
80   Ids in other packages.  This RuleBase simply grow monotonically, as
81   ghc --make compiles one module after another.
82
83   During simplification, interface files may get demand-loaded,
84   as the simplifier explores the unfoldings for Ids it has in 
85   its hand.  (Via an unsafePerformIO; the EPS is really a cache.)
86   That in turn may make the EPS rule-base grow.  In contrast, the
87   HPT never grows in this way.
88
89 * The result of all this is that during Core-to-Core optimisation
90   there are four sources of rules:
91
92     (a) Rules in the IdInfo of the Id they are a rule for.  These are
93         easy: fast to look up, and if you apply a substitution then
94         it'll be applied to the IdInfo as a matter of course.
95
96     (b) Rules declared in this module for imported Ids, kept in the
97         ModGuts. If you do a substitution, you'd better apply the
98         substitution to these.  There are seldom many of these.
99
100     (c) Rules declared in the HomePackageTable.  These never change.
101
102     (d) Rules in the ExternalPackageTable. These can grow in response
103         to lazy demand-loading of interfaces.
104
105 * At the moment (c) is carried in a reader-monad way by the CoreMonad.
106   The HomePackageTable doesn't have a single RuleBase because technically
107   we should only be able to "see" rules "below" this module; so we
108   generate a RuleBase for (c) by combing rules from all the modules
109   "below" us.  That's why we can't just select the home-package RuleBase
110   from HscEnv.
111
112   [NB: we are inconsistent here.  We should do the same for external
113   pacakges, but we don't.  Same for type-class instances.]
114
115 * So in the outer simplifier loop, we combine (b-d) into a single
116   RuleBase, reading 
117      (b) from the ModGuts, 
118      (c) from the CoreMonad, and
119      (d) from its mutable variable
120   [Of coures this means that we won't see new EPS rules that come in
121   during a single simplifier iteration, but that probably does not
122   matter.]
123
124
125 %************************************************************************
126 %*                                                                      *
127 \subsection[specialisation-IdInfo]{Specialisation info about an @Id@}
128 %*                                                                      *
129 %************************************************************************
130
131 A @CoreRule@ holds details of one rule for an @Id@, which
132 includes its specialisations.
133
134 For example, if a rule for @f@ contains the mapping:
135 \begin{verbatim}
136         forall a b d. [Type (List a), Type b, Var d]  ===>  f' a b
137 \end{verbatim}
138 then when we find an application of f to matching types, we simply replace
139 it by the matching RHS:
140 \begin{verbatim}
141         f (List Int) Bool dict ===>  f' Int Bool
142 \end{verbatim}
143 All the stuff about how many dictionaries to discard, and what types
144 to apply the specialised function to, are handled by the fact that the
145 Rule contains a template for the result of the specialisation.
146
147 There is one more exciting case, which is dealt with in exactly the same
148 way.  If the specialised value is unboxed then it is lifted at its
149 definition site and unlifted at its uses.  For example:
150
151         pi :: forall a. Num a => a
152
153 might have a specialisation
154
155         [Int#] ===>  (case pi' of Lift pi# -> pi#)
156
157 where pi' :: Lift Int# is the specialised version of pi.
158
159 \begin{code}
160 mkRule :: Bool -> Bool -> RuleName -> Activation 
161        -> Name -> [CoreBndr] -> [CoreExpr] -> CoreExpr -> CoreRule
162 -- ^ Used to make 'CoreRule' for an 'Id' defined in the module being 
163 -- compiled. See also 'CoreSyn.CoreRule'
164 mkRule is_auto is_local name act fn bndrs args rhs
165   = Rule { ru_name = name, ru_fn = fn, ru_act = act,
166            ru_bndrs = bndrs, ru_args = args,
167            ru_rhs = occurAnalyseExpr rhs, 
168            ru_rough = roughTopNames args,
169            ru_auto = is_auto, ru_local = is_local }
170
171 --------------
172 roughTopNames :: [CoreExpr] -> [Maybe Name]
173 -- ^ Find the \"top\" free names of several expressions. 
174 -- Such names are either:
175 --
176 -- 1. The function finally being applied to in an application chain
177 --    (if that name is a GlobalId: see "Var#globalvslocal"), or
178 --
179 -- 2. The 'TyCon' if the expression is a 'Type'
180 --
181 -- This is used for the fast-match-check for rules; 
182 --      if the top names don't match, the rest can't
183 roughTopNames args = map roughTopName args
184
185 roughTopName :: CoreExpr -> Maybe Name
186 roughTopName (Type ty) = case tcSplitTyConApp_maybe ty of
187                           Just (tc,_) -> Just (getName tc)
188                           Nothing     -> Nothing
189 roughTopName (App f _) = roughTopName f
190 roughTopName (Var f)   | isGlobalId f   -- Note [Care with roughTopName]
191                        , isDataConWorkId f || idArity f > 0
192                        = Just (idName f)
193 roughTopName _ = Nothing
194
195 ruleCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
196 -- ^ @ruleCantMatch tpl actual@ returns True only if @actual@
197 -- definitely can't match @tpl@ by instantiating @tpl@.  
198 -- It's only a one-way match; unlike instance matching we 
199 -- don't consider unification.
200 -- 
201 -- Notice that [_$_]
202 --      @ruleCantMatch [Nothing] [Just n2] = False@
203 --      Reason: a template variable can be instantiated by a constant
204 -- Also:
205 --      @ruleCantMatch [Just n1] [Nothing] = False@
206 --      Reason: a local variable @v@ in the actuals might [_$_]
207
208 ruleCantMatch (Just n1 : ts) (Just n2 : as) = n1 /= n2 || ruleCantMatch ts as
209 ruleCantMatch (_       : ts) (_       : as) = ruleCantMatch ts as
210 ruleCantMatch _              _              = False
211 \end{code}
212
213 Note [Care with roughTopName]
214 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
215 Consider this
216     module M where { x = a:b }
217     module N where { ...f x...
218                      RULE f (p:q) = ... }
219 You'd expect the rule to match, because the matcher can 
220 look through the unfolding of 'x'.  So we must avoid roughTopName
221 returning 'M.x' for the call (f x), or else it'll say "can't match"
222 and we won't even try!!
223
224 However, suppose we have
225          RULE g (M.h x) = ...
226          foo = ...(g (M.k v))....
227 where k is a *function* exported by M.  We never really match
228 functions (lambdas) except by name, so in this case it seems like
229 a good idea to treat 'M.k' as a roughTopName of the call.
230
231     
232 \begin{code}
233 pprRulesForUser :: [CoreRule] -> SDoc
234 -- (a) tidy the rules
235 -- (b) sort them into order based on the rule name
236 -- (c) suppress uniques (unless -dppr-debug is on)
237 -- This combination makes the output stable so we can use in testing
238 -- It's here rather than in PprCore because it calls tidyRules
239 pprRulesForUser rules
240   = withPprStyle defaultUserStyle $
241     pprRules $
242     sortLe le_rule  $
243     tidyRules emptyTidyEnv rules
244   where 
245     le_rule r1 r2 = ru_name r1 <= ru_name r2
246 \end{code}
247
248
249 %************************************************************************
250 %*                                                                      *
251                 SpecInfo: the rules in an IdInfo
252 %*                                                                      *
253 %************************************************************************
254
255 \begin{code}
256 -- | Make a 'SpecInfo' containing a number of 'CoreRule's, suitable
257 -- for putting into an 'IdInfo'
258 mkSpecInfo :: [CoreRule] -> SpecInfo
259 mkSpecInfo rules = SpecInfo rules (rulesFreeVars rules)
260
261 extendSpecInfo :: SpecInfo -> [CoreRule] -> SpecInfo
262 extendSpecInfo (SpecInfo rs1 fvs1) rs2
263   = SpecInfo (rs2 ++ rs1) (rulesFreeVars rs2 `unionVarSet` fvs1)
264
265 addSpecInfo :: SpecInfo -> SpecInfo -> SpecInfo
266 addSpecInfo (SpecInfo rs1 fvs1) (SpecInfo rs2 fvs2) 
267   = SpecInfo (rs1 ++ rs2) (fvs1 `unionVarSet` fvs2)
268
269 addIdSpecialisations :: Id -> [CoreRule] -> Id
270 addIdSpecialisations id []
271   = id
272 addIdSpecialisations id rules
273   = setIdSpecialisation id $
274     extendSpecInfo (idSpecialisation id) rules
275
276 -- | Gather all the rules for locally bound identifiers from the supplied bindings
277 rulesOfBinds :: [CoreBind] -> [CoreRule]
278 rulesOfBinds binds = concatMap (concatMap idCoreRules . bindersOf) binds
279
280 getRules :: RuleBase -> Id -> [CoreRule]
281 -- See Note [Where rules are found]
282 getRules rule_base fn
283   = idCoreRules fn ++ imp_rules
284   where
285     imp_rules = lookupNameEnv rule_base (idName fn) `orElse` []
286 \end{code}
287
288 Note [Where rules are found]
289 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
290 The rules for an Id come from two places:
291   (a) the ones it is born with, stored inside the Id iself (idCoreRules fn),
292   (b) rules added in other modules, stored in the global RuleBase (imp_rules)
293
294 It's tempting to think that 
295      - LocalIds have only (a)
296      - non-LocalIds have only (b)
297
298 but that isn't quite right:
299
300      - PrimOps and ClassOps are born with a bunch of rules inside the Id,
301        even when they are imported
302
303      - The rules in PrelRules.builtinRules should be active even
304        in the module defining the Id (when it's a LocalId), but 
305        the rules are kept in the global RuleBase
306
307
308 %************************************************************************
309 %*                                                                      *
310                 RuleBase
311 %*                                                                      *
312 %************************************************************************
313
314 \begin{code}
315 -- | Gathers a collection of 'CoreRule's. Maps (the name of) an 'Id' to its rules
316 type RuleBase = NameEnv [CoreRule]
317         -- The rules are are unordered; 
318         -- we sort out any overlaps on lookup
319
320 emptyRuleBase :: RuleBase
321 emptyRuleBase = emptyNameEnv
322
323 mkRuleBase :: [CoreRule] -> RuleBase
324 mkRuleBase rules = extendRuleBaseList emptyRuleBase rules
325
326 extendRuleBaseList :: RuleBase -> [CoreRule] -> RuleBase
327 extendRuleBaseList rule_base new_guys
328   = foldl extendRuleBase rule_base new_guys
329
330 unionRuleBase :: RuleBase -> RuleBase -> RuleBase
331 unionRuleBase rb1 rb2 = plusNameEnv_C (++) rb1 rb2
332
333 extendRuleBase :: RuleBase -> CoreRule -> RuleBase
334 extendRuleBase rule_base rule
335   = extendNameEnv_Acc (:) singleton rule_base (ruleIdName rule) rule
336
337 pprRuleBase :: RuleBase -> SDoc
338 pprRuleBase rules = vcat [ pprRules (tidyRules emptyTidyEnv rs) 
339                          | rs <- nameEnvElts rules ]
340 \end{code}
341
342
343 %************************************************************************
344 %*                                                                      *
345                         Matching
346 %*                                                                      *
347 %************************************************************************
348
349 \begin{code}
350 -- | The main rule matching function. Attempts to apply all (active)
351 -- supplied rules to this instance of an application in a given
352 -- context, returning the rule applied and the resulting expression if
353 -- successful.
354 lookupRule :: (Activation -> Bool)      -- When rule is active
355             -> IdUnfoldingFun           -- When Id can be unfolded
356             -> InScopeSet
357             -> Id -> [CoreExpr]
358             -> [CoreRule] -> Maybe (CoreRule, CoreExpr)
359
360 -- See Note [Extra args in rule matching]
361 -- See comments on matchRule
362 lookupRule is_active id_unf in_scope fn args rules
363   = -- pprTrace "matchRules" (ppr fn <+> ppr args $$ ppr rules ) $
364     case go [] rules of
365         []     -> Nothing
366         (m:ms) -> Just (findBest (fn,args) m ms)
367   where
368     rough_args = map roughTopName args
369
370     go :: [(CoreRule,CoreExpr)] -> [CoreRule] -> [(CoreRule,CoreExpr)]
371     go ms []           = ms
372     go ms (r:rs) = case (matchRule is_active id_unf in_scope args rough_args r) of
373                         Just e  -> go ((r,e):ms) rs
374                         Nothing -> -- pprTrace "match failed" (ppr r $$ ppr args $$ 
375                                    --   ppr [ (arg_id, unfoldingTemplate unf) 
376                                    --       | Var arg_id <- args
377                                    --       , let unf = idUnfolding arg_id
378                                    --       , isCheapUnfolding unf] )
379                                    go ms rs
380
381 findBest :: (Id, [CoreExpr])
382          -> (CoreRule,CoreExpr) -> [(CoreRule,CoreExpr)] -> (CoreRule,CoreExpr)
383 -- All these pairs matched the expression
384 -- Return the pair the the most specific rule
385 -- The (fn,args) is just for overlap reporting
386
387 findBest _      (rule,ans)   [] = (rule,ans)
388 findBest target (rule1,ans1) ((rule2,ans2):prs)
389   | rule1 `isMoreSpecific` rule2 = findBest target (rule1,ans1) prs
390   | rule2 `isMoreSpecific` rule1 = findBest target (rule2,ans2) prs
391   | debugIsOn = let pp_rule rule
392                         | opt_PprStyle_Debug = ppr rule
393                         | otherwise          = doubleQuotes (ftext (ru_name rule))
394                 in pprTrace "Rules.findBest: rule overlap (Rule 1 wins)"
395                          (vcat [if opt_PprStyle_Debug then 
396                                    ptext (sLit "Expression to match:") <+> ppr fn <+> sep (map ppr args)
397                                 else empty,
398                                 ptext (sLit "Rule 1:") <+> pp_rule rule1, 
399                                 ptext (sLit "Rule 2:") <+> pp_rule rule2]) $
400                 findBest target (rule1,ans1) prs
401   | otherwise = findBest target (rule1,ans1) prs
402   where
403     (fn,args) = target
404
405 isMoreSpecific :: CoreRule -> CoreRule -> Bool
406 -- This tests if one rule is more specific than another
407 -- We take the view that a BuiltinRule is less specific than
408 -- anything else, because we want user-define rules to "win"
409 -- In particular, class ops have a built-in rule, but we
410 -- any user-specific rules to win
411 --   eg (Trac #4397)   
412 --      truncate :: (RealFrac a, Integral b) => a -> b
413 --      {-# RULES "truncate/Double->Int" truncate = double2Int #-}
414 --      double2Int :: Double -> Int
415 --   We want the specific RULE to beat the built-in class-op rule
416 isMoreSpecific (BuiltinRule {}) _                = False
417 isMoreSpecific (Rule {})        (BuiltinRule {}) = True
418 isMoreSpecific (Rule { ru_bndrs = bndrs1, ru_args = args1 })
419                (Rule { ru_bndrs = bndrs2, ru_args = args2 })
420   = isJust (matchN id_unfolding_fun in_scope bndrs2 args2 args1)
421   where
422    id_unfolding_fun _ = NoUnfolding     -- Don't expand in templates
423    in_scope = mkInScopeSet (mkVarSet bndrs1)
424         -- Actually we should probably include the free vars 
425         -- of rule1's args, but I can't be bothered
426
427 noBlackList :: Activation -> Bool
428 noBlackList _ = False           -- Nothing is black listed
429 \end{code}
430
431 Note [Extra args in rule matching]
432 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
433 If we find a matching rule, we return (Just (rule, rhs)), 
434 but the rule firing has only consumed as many of the input args
435 as the ruleArity says.  It's up to the caller to keep track
436 of any left-over args.  E.g. if you call
437         lookupRule ... f [e1, e2, e3]
438 and it returns Just (r, rhs), where r has ruleArity 2
439 then the real rewrite is
440         f e1 e2 e3 ==> rhs e3
441
442 You might think it'd be cleaner for lookupRule to deal with the
443 leftover arguments, by applying 'rhs' to them, but the main call
444 in the Simplifier works better as it is.  Reason: the 'args' passed
445 to lookupRule are the result of a lazy substitution
446
447 \begin{code}
448 ------------------------------------
449 matchRule :: (Activation -> Bool) -> IdUnfoldingFun
450           -> InScopeSet
451           -> [CoreExpr] -> [Maybe Name]
452           -> CoreRule -> Maybe CoreExpr
453
454 -- If (matchRule rule args) returns Just (name,rhs)
455 -- then (f args) matches the rule, and the corresponding
456 -- rewritten RHS is rhs
457 --
458 -- The bndrs and rhs is occurrence-analysed
459 --
460 --      Example
461 --
462 -- The rule
463 --      forall f g x. map f (map g x) ==> map (f . g) x
464 -- is stored
465 --      CoreRule "map/map" 
466 --               [f,g,x]                -- tpl_vars
467 --               [f,map g x]            -- tpl_args
468 --               map (f.g) x)           -- rhs
469 --        
470 -- Then the call: matchRule the_rule [e1,map e2 e3]
471 --        = Just ("map/map", (\f,g,x -> rhs) e1 e2 e3)
472 --
473 -- Any 'surplus' arguments in the input are simply put on the end
474 -- of the output.
475
476 matchRule _is_active id_unf _in_scope args _rough_args
477           (BuiltinRule { ru_try = match_fn })
478 -- Built-in rules can't be switched off, it seems
479   = case match_fn id_unf args of
480         Just expr -> Just expr
481         Nothing   -> Nothing
482
483 matchRule is_active id_unf in_scope args rough_args
484           (Rule { ru_act = act, ru_rough = tpl_tops,
485                   ru_bndrs = tpl_vars, ru_args = tpl_args,
486                   ru_rhs = rhs })
487   | not (is_active act)               = Nothing
488   | ruleCantMatch tpl_tops rough_args = Nothing
489   | otherwise
490   = case matchN id_unf in_scope tpl_vars tpl_args args of
491         Nothing                        -> Nothing
492         Just (bind_wrapper, tpl_vals) -> Just (bind_wrapper $
493                                                rule_fn `mkApps` tpl_vals)
494   where
495     rule_fn = occurAnalyseExpr (mkLams tpl_vars rhs)
496         -- We could do this when putting things into the rulebase, I guess
497
498 ---------------------------------------
499 matchN  :: IdUnfoldingFun
500         -> InScopeSet           -- ^ In-scope variables
501         -> [Var]                -- ^ Match template type variables
502         -> [CoreExpr]           -- ^ Match template
503         -> [CoreExpr]           -- ^ Target; can have more elements than the template
504         -> Maybe (BindWrapper,  -- Floated bindings; see Note [Matching lets]
505                   [CoreExpr])
506 -- For a given match template and context, find bindings to wrap around 
507 -- the entire result and what should be substituted for each template variable.
508 -- Fail if there are two few actual arguments from the target to match the template
509
510 matchN id_unf in_scope tmpl_vars tmpl_es target_es
511   = do  { subst <- go init_menv emptyRuleSubst tmpl_es target_es
512         ; return (rs_binds subst,
513                   map (lookup_tmpl subst) tmpl_vars') }
514   where
515     (init_rn_env, tmpl_vars') = mapAccumL rnBndrL (mkRnEnv2 in_scope) tmpl_vars
516         -- See Note [Template binders]
517
518     init_menv = RV { rv_tmpls = mkVarSet tmpl_vars', rv_lcl = init_rn_env
519                    , rv_fltR = mkEmptySubst (rnInScopeSet init_rn_env)
520                    , rv_unf = id_unf }
521                 
522     go _    subst []     _      = Just subst
523     go _    _     _      []     = Nothing       -- Fail if too few actual args
524     go menv subst (t:ts) (e:es) = do { subst1 <- match menv subst t e
525                                      ; go menv subst1 ts es }
526
527     lookup_tmpl :: RuleSubst -> Var -> CoreExpr
528     lookup_tmpl (RS { rs_tv_subst = tv_subst, rs_id_subst = id_subst }) tmpl_var'
529         | isId tmpl_var' = case lookupVarEnv id_subst tmpl_var' of
530                              Just e -> e
531                              _      -> unbound tmpl_var'
532         | otherwise      = case lookupVarEnv tv_subst tmpl_var' of
533                              Just ty -> Type ty
534                              Nothing -> unbound tmpl_var'
535
536     unbound var = pprPanic "Template variable unbound in rewrite rule" 
537                         (ppr var $$ ppr tmpl_vars $$ ppr tmpl_vars' $$ ppr tmpl_es $$ ppr target_es)
538 \end{code}
539
540 Note [Template binders]
541 ~~~~~~~~~~~~~~~~~~~~~~~
542 Consider the following match:
543         Template:  forall x.  f x 
544         Target:     f (x+1)
545 This should succeed, because the template variable 'x' has 
546 nothing to do with the 'x' in the target. 
547
548 On reflection, this case probably does just work, but this might not
549         Template:  forall x. f (\x.x) 
550         Target:    f (\y.y)
551 Here we want to clone when we find the \x, but to know that x must be in scope
552
553 To achive this, we use rnBndrL to rename the template variables if
554 necessary; the renamed ones are the tmpl_vars'
555
556
557 %************************************************************************
558 %*                                                                      *
559                    The main matcher
560 %*                                                                      *
561 %************************************************************************
562
563         ---------------------------------------------
564                 The inner workings of matching
565         ---------------------------------------------
566
567 \begin{code}
568 -- * The domain of the TvSubstEnv and IdSubstEnv are the template
569 --   variables passed into the match.
570 --
571 -- * The BindWrapper in a RuleSubst are the bindings floated out
572 --   from nested matches; see the Let case of match, below
573 --
574 data RuleEnv = RV { rv_tmpls :: VarSet          -- Template variables
575                   , rv_lcl   :: RnEnv2          -- Renamings for *local bindings*
576                                                 --   (lambda/case)
577                   , rv_fltR  :: Subst           -- Renamings for floated let-bindings
578                                                 --   domain disjoint from envR of rv_lcl
579                                                 -- See Note [Matching lets]
580                   , rv_unf :: IdUnfoldingFun
581                   }
582
583 data RuleSubst = RS { rs_tv_subst :: TvSubstEnv   -- Range is the
584                     , rs_id_subst :: IdSubstEnv   --   template variables
585                     , rs_binds    :: BindWrapper  -- Floated bindings
586                     , rs_bndrs    :: VarSet       -- Variables bound by floated lets
587                     }
588
589 type BindWrapper = CoreExpr -> CoreExpr
590   -- See Notes [Matching lets] and [Matching cases]
591   -- we represent the floated bindings as a core-to-core function
592
593 emptyRuleSubst :: RuleSubst
594 emptyRuleSubst = RS { rs_tv_subst = emptyVarEnv, rs_id_subst = emptyVarEnv
595                     , rs_binds = \e -> e, rs_bndrs = emptyVarSet }
596
597 --      At one stage I tried to match even if there are more 
598 --      template args than real args.
599
600 --      I now think this is probably a bad idea.
601 --      Should the template (map f xs) match (map g)?  I think not.
602 --      For a start, in general eta expansion wastes work.
603 --      SLPJ July 99
604
605
606 match :: RuleEnv
607       -> RuleSubst
608       -> CoreExpr               -- Template
609       -> CoreExpr               -- Target
610       -> Maybe RuleSubst
611
612 -- See the notes with Unify.match, which matches types
613 -- Everything is very similar for terms
614
615 -- Interesting examples:
616 -- Consider matching
617 --      \x->f      against    \f->f
618 -- When we meet the lambdas we must remember to rename f to f' in the
619 -- second expresion.  The RnEnv2 does that.
620 --
621 -- Consider matching 
622 --      forall a. \b->b    against   \a->3
623 -- We must rename the \a.  Otherwise when we meet the lambdas we 
624 -- might substitute [a/b] in the template, and then erroneously 
625 -- succeed in matching what looks like the template variable 'a' against 3.
626
627 -- The Var case follows closely what happens in Unify.match
628 match renv subst (Var v1) e2
629   | Just subst <- match_var renv subst v1 e2
630   = Just subst
631
632 match renv subst (Note _ e1) e2 = match renv subst e1 e2
633 match renv subst e1 (Note _ e2) = match renv subst e1 e2
634       -- Ignore notes in both template and thing to be matched
635       -- See Note [Notes in RULE matching]
636
637 match renv subst e1 (Var v2)      -- Note [Expanding variables]
638   | not (inRnEnvR rn_env v2) -- Note [Do not expand locally-bound variables]
639   , Just e2' <- expandUnfolding_maybe (rv_unf renv v2')
640   = match (renv { rv_lcl = nukeRnEnvR rn_env }) subst e1 e2'
641   where
642     v2'    = lookupRnInScope rn_env v2
643     rn_env = rv_lcl renv
644         -- Notice that we look up v2 in the in-scope set
645         -- See Note [Lookup in-scope]
646         -- No need to apply any renaming first (hence no rnOccR)
647         -- because of the not-inRnEnvR
648
649 match renv subst e1 (Let bind e2)
650   | okToFloat (rv_lcl renv) (bindFreeVars bind)        -- See Note [Matching lets]
651   = match (renv { rv_fltR = flt_subst' })
652           (subst { rs_binds = rs_binds subst . Let bind'
653                  , rs_bndrs = extendVarSetList (rs_bndrs subst) new_bndrs })
654           e1 e2
655   where
656     flt_subst = addInScopeSet (rv_fltR renv) (rs_bndrs subst)
657     (flt_subst', bind') = substBind flt_subst bind
658     new_bndrs = bindersOf bind'
659
660 {- Disabled: see Note [Matching cases] below
661 match renv (tv_subst, id_subst, binds) e1 
662       (Case scrut case_bndr ty [(con, alt_bndrs, rhs)])
663   | exprOkForSpeculation scrut  -- See Note [Matching cases]
664   , okToFloat rn_env bndrs (exprFreeVars scrut)
665   = match (renv { me_env = rn_env' })
666           (tv_subst, id_subst, binds . case_wrap)
667           e1 rhs 
668   where
669     rn_env   = me_env renv
670     rn_env'  = extendRnInScopeList rn_env bndrs
671     bndrs    = case_bndr : alt_bndrs
672     case_wrap rhs' = Case scrut case_bndr ty [(con, alt_bndrs, rhs')]
673 -}
674
675 match _ subst (Lit lit1) (Lit lit2)
676   | lit1 == lit2
677   = Just subst
678
679 match renv subst (App f1 a1) (App f2 a2)
680   = do  { subst' <- match renv subst f1 f2
681         ; match renv subst' a1 a2 }
682
683 match renv subst (Lam x1 e1) (Lam x2 e2)
684   = match renv' subst e1 e2
685   where
686     renv' = renv { rv_lcl = rnBndr2 (rv_lcl renv) x1 x2
687                  , rv_fltR = delBndr (rv_fltR renv) x2 }
688
689 -- This rule does eta expansion
690 --              (\x.M)  ~  N    iff     M  ~  N x
691 -- It's important that this is *after* the let rule,
692 -- so that      (\x.M)  ~  (let y = e in \y.N)
693 -- does the let thing, and then gets the lam/lam rule above
694 match renv subst (Lam x1 e1) e2
695   = match renv' subst e1 (App e2 (varToCoreExpr new_x))
696   where
697     (rn_env', new_x) = rnEtaL (rv_lcl renv) x1
698     renv' = renv { rv_lcl = rn_env' }
699
700 -- Eta expansion the other way
701 --      M  ~  (\y.N)    iff   M y     ~  N
702 match renv subst e1 (Lam x2 e2)
703   = match renv' subst (App e1 (varToCoreExpr new_x)) e2
704   where
705     (rn_env', new_x) = rnEtaR (rv_lcl renv) x2
706     renv' = renv { rv_lcl = rn_env' }
707
708 match renv subst (Case e1 x1 ty1 alts1) (Case e2 x2 ty2 alts2)
709   = do  { subst1 <- match_ty renv subst ty1 ty2
710         ; subst2 <- match renv subst1 e1 e2
711         ; let renv' = rnMatchBndr2 renv subst x1 x2
712         ; match_alts renv' subst2 alts1 alts2   -- Alts are both sorted
713         }
714
715 match renv subst (Type ty1) (Type ty2)
716   = match_ty renv subst ty1 ty2
717
718 match renv subst (Cast e1 co1) (Cast e2 co2)
719   = do  { subst1 <- match_ty renv subst co1 co2
720         ; match renv subst1 e1 e2 }
721
722 -- Everything else fails
723 match _ _ _e1 _e2 = -- pprTrace "Failing at" ((text "e1:" <+> ppr _e1) $$ (text "e2:" <+> ppr _e2)) $
724                     Nothing
725
726 rnMatchBndr2 :: RuleEnv -> RuleSubst -> Var -> Var -> RuleEnv
727 rnMatchBndr2 renv subst x1 x2
728   = renv { rv_lcl  = rnBndr2 rn_env x1 x2
729          , rv_fltR = delBndr (rv_fltR renv) x2 }
730   where
731     rn_env = addRnInScopeSet (rv_lcl renv) (rs_bndrs subst)
732     -- Typically this is a no-op, but it may matter if
733     -- there are some floated let-bindings
734
735 ------------------------------------------
736 match_alts :: RuleEnv
737            -> RuleSubst
738            -> [CoreAlt]         -- Template
739            -> [CoreAlt]         -- Target
740            -> Maybe RuleSubst
741 match_alts _ subst [] []
742   = return subst
743 match_alts renv subst ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2)
744   | c1 == c2
745   = do  { subst1 <- match renv' subst r1 r2
746         ; match_alts renv subst1 alts1 alts2 }
747   where
748     renv' = foldl mb renv (vs1 `zip` vs2)
749     mb renv (v1,v2) = rnMatchBndr2 renv subst v1 v2
750
751 match_alts _ _ _ _
752   = Nothing
753
754 ------------------------------------------
755 okToFloat :: RnEnv2 -> VarSet -> Bool
756 okToFloat rn_env bind_fvs
757   = foldVarSet ((&&) . not_captured) True bind_fvs
758   where
759     not_captured fv = not (inRnEnvR rn_env fv)
760
761 ------------------------------------------
762 match_var :: RuleEnv
763           -> RuleSubst
764           -> Var                -- Template
765           -> CoreExpr        -- Target
766           -> Maybe RuleSubst
767 match_var renv@(RV { rv_tmpls = tmpls, rv_lcl = rn_env, rv_fltR = flt_env })
768           subst v1 e2
769   | v1' `elemVarSet` tmpls
770   = match_tmpl_var renv subst v1' e2
771
772   | otherwise   -- v1' is not a template variable; check for an exact match with e2
773   = case e2 of  -- Remember, envR of rn_env is disjoint from rv_fltR
774        Var v2 | v1' == rnOccR rn_env v2
775               -> Just subst
776
777               | Var v2' <- lookupIdSubst (text "match_var") flt_env v2
778               , v1' == v2'
779               -> Just subst
780
781        _ -> Nothing
782
783   where
784     v1' = rnOccL rn_env v1
785         -- If the template is
786         --      forall x. f x (\x -> x) = ...
787         -- Then the x inside the lambda isn't the 
788         -- template x, so we must rename first!
789
790 ------------------------------------------
791 match_tmpl_var :: RuleEnv
792                -> RuleSubst
793                -> Var                -- Template
794                -> CoreExpr              -- Target
795                -> Maybe RuleSubst
796
797 match_tmpl_var renv@(RV { rv_lcl = rn_env, rv_fltR = flt_env })
798                subst@(RS { rs_id_subst = id_subst, rs_bndrs = let_bndrs })
799                v1' e2
800   | any (inRnEnvR rn_env) (varSetElems (exprFreeVars e2))
801   = Nothing     -- Occurs check failure
802                 -- e.g. match forall a. (\x-> a x) against (\y. y y)
803
804   | Just e1' <- lookupVarEnv id_subst v1'
805   = if eqExpr (rnInScopeSet rn_env) e1' e2'
806     then Just subst
807     else Nothing
808
809   | otherwise
810   =             -- Note [Matching variable types]
811                 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
812                 -- However, we must match the *types*; e.g.
813                 --   forall (c::Char->Int) (x::Char). 
814                 --      f (c x) = "RULE FIRED"
815                 -- We must only match on args that have the right type
816                 -- It's actually quite difficult to come up with an example that shows
817                 -- you need type matching, esp since matching is left-to-right, so type
818                 -- args get matched first.  But it's possible (e.g. simplrun008) and
819                 -- this is the Right Thing to do
820     do { subst' <- match_ty renv subst (idType v1') (exprType e2)
821        ; return (subst' { rs_id_subst = id_subst' }) }
822   where
823     -- e2' is the result of applying flt_env to e2
824     e2' | isEmptyVarSet let_bndrs = e2
825         | otherwise = substExpr (text "match_tmpl_var") flt_env e2
826
827     id_subst' = extendVarEnv (rs_id_subst subst) v1' e2'
828          -- No further renaming to do on e2',
829          -- because no free var of e2' is in the rnEnvR of the envt
830
831 ------------------------------------------
832 match_ty :: RuleEnv
833          -> RuleSubst
834          -> Type                -- Template
835          -> Type                -- Target
836          -> Maybe RuleSubst
837 -- Matching Core types: use the matcher in TcType.
838 -- Notice that we treat newtypes as opaque.  For example, suppose 
839 -- we have a specialised version of a function at a newtype, say 
840 --      newtype T = MkT Int
841 -- We only want to replace (f T) with f', not (f Int).
842
843 match_ty renv subst ty1 ty2
844   = do  { tv_subst' <- Unify.ruleMatchTyX menv tv_subst ty1 ty2
845         ; return (subst { rs_tv_subst = tv_subst' }) }
846   where
847     tv_subst = rs_tv_subst subst
848     menv = ME { me_tmpls = rv_tmpls renv, me_env = rv_lcl renv }
849 \end{code}
850
851 Note [Expanding variables]
852 ~~~~~~~~~~~~~~~~~~~~~~~~~~
853 Here is another Very Important rule: if the term being matched is a
854 variable, we expand it so long as its unfolding is "expandable". (Its
855 occurrence information is not necessarily up to date, so we don't use
856 it.)  By "expandable" we mean a WHNF or a "constructor-like" application.
857 This is the key reason for "constructor-like" Ids.  If we have
858      {-# NOINLINE [1] CONLIKE g #-}
859      {-# RULE f (g x) = h x #-}
860 then in the term
861    let v = g 3 in ....(f v)....
862 we want to make the rule fire, to replace (f v) with (h 3). 
863
864 Note [Do not expand locally-bound variables]
865 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
866 Do *not* expand locally-bound variables, else there's a worry that the
867 unfolding might mention variables that are themselves renamed.
868 Example
869           case x of y { (p,q) -> ...y... }
870 Don't expand 'y' to (p,q) because p,q might themselves have been 
871 renamed.  Essentially we only expand unfoldings that are "outside" 
872 the entire match.
873
874 Hence, (a) the guard (not (isLocallyBoundR v2))
875        (b) when we expand we nuke the renaming envt (nukeRnEnvR).
876
877 Note [Notes in RULE matching]
878 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
879 Look through Notes in both template and expression being matched.  In
880 particular, we don't want to be confused by InlineMe notes.  Maybe we
881 should be more careful about profiling notes, but for now I'm just
882 riding roughshod over them.  cf Note [Notes in call patterns] in
883 SpecConstr
884
885 Note [Matching lets]
886 ~~~~~~~~~~~~~~~~~~~~
887 Matching a let-expression.  Consider
888         RULE forall x.  f (g x) = <rhs>
889 and target expression
890         f (let { w=R } in g E))
891 Then we'd like the rule to match, to generate
892         let { w=R } in (\x. <rhs>) E
893 In effect, we want to float the let-binding outward, to enable
894 the match to happen.  This is the WHOLE REASON for accumulating
895 bindings in the RuleSubst
896
897 We can only do this if the free variables of R are not bound by the
898 part of the target expression outside the let binding; e.g.
899         f (\v. let w = v+1 in g E)
900 Here we obviously cannot float the let-binding for w.  Hence the
901 use of okToFloat.
902
903 There are a couple of tricky points.
904   (a) What if floating the binding captures a variable?
905         f (let v = x+1 in v) v
906       --> NOT!
907         let v = x+1 in f (x+1) v
908
909   (b) What if two non-nested let bindings bind the same variable?
910         f (let v = e1 in b1) (let v = e2 in b2)
911       --> NOT!
912         let v = e1 in let v = e2 in (f b2 b2)
913       See testsuite test "RuleFloatLet".
914
915 Our cunning plan is this:
916   * Along with the growing substitution for template variables
917     we maintain a growing set of floated let-bindings (rs_binds)
918     plus the set of variables thus bound.
919
920   * The RnEnv2 in the MatchEnv binds only the local binders
921     in the term (lambdas, case)
922
923   * When we encounter a let in the term to be matched, we
924     check that does not mention any locally bound (lambda, case)
925     variables.  If so we fail
926
927   * We use CoreSubst.substBind to freshen the binding, using an
928     in-scope set that is the original in-scope variables plus the
929     rs_bndrs (currently floated let-bindings).  So in (a) above
930     we'll freshen the 'v' binding; in (b) above we'll freshen
931     the *second* 'v' binding.
932
933   * We apply that freshening substitution, in a lexically-scoped
934     way to the term, although lazily; this is the rv_fltR field.
935
936
937 Note [Matching cases]
938 ~~~~~~~~~~~~~~~~~~~~~
939 {- NOTE: This idea is currently disabled.  It really only works if
940          the primops involved are OkForSpeculation, and, since
941          they have side effects readIntOfAddr and touch are not.
942          Maybe we'll get back to this later .  -}
943   
944 Consider
945    f (case readIntOffAddr# p# i# realWorld# of { (# s#, n# #) ->
946       case touch# fp s# of { _ -> 
947       I# n# } } )
948 This happened in a tight loop generated by stream fusion that 
949 Roman encountered.  We'd like to treat this just like the let 
950 case, because the primops concerned are ok-for-speculation.
951 That is, we'd like to behave as if it had been
952    case readIntOffAddr# p# i# realWorld# of { (# s#, n# #) ->
953    case touch# fp s# of { _ -> 
954    f (I# n# } } )
955   
956 Note [Lookup in-scope]
957 ~~~~~~~~~~~~~~~~~~~~~~
958 Consider this example
959         foo :: Int -> Maybe Int -> Int
960         foo 0 (Just n) = n
961         foo m (Just n) = foo (m-n) (Just n)
962
963 SpecConstr sees this fragment:
964
965         case w_smT of wild_Xf [Just A] {
966           Data.Maybe.Nothing -> lvl_smf;
967           Data.Maybe.Just n_acT [Just S(L)] ->
968             case n_acT of wild1_ams [Just A] { GHC.Base.I# y_amr [Just L] ->
969             \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
970             }};
971
972 and correctly generates the rule
973
974         RULES: "SC:$wfoo1" [0] __forall {y_amr [Just L] :: GHC.Prim.Int#
975                                           sc_snn :: GHC.Prim.Int#}
976           \$wfoo_smW sc_snn (Data.Maybe.Just @ GHC.Base.Int (GHC.Base.I# y_amr))
977           = \$s\$wfoo_sno y_amr sc_snn ;]
978
979 BUT we must ensure that this rule matches in the original function!
980 Note that the call to \$wfoo is
981             \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
982
983 During matching we expand wild_Xf to (Just n_acT).  But then we must also
984 expand n_acT to (I# y_amr).  And we can only do that if we look up n_acT
985 in the in-scope set, because in wild_Xf's unfolding it won't have an unfolding
986 at all. 
987
988 That is why the 'lookupRnInScope' call in the (Var v2) case of 'match'
989 is so important.
990
991 %************************************************************************
992 %*                                                                      *
993                    Rule-check the program                                                                               
994 %*                                                                      *
995 %************************************************************************
996
997    We want to know what sites have rules that could have fired but didn't.
998    This pass runs over the tree (without changing it) and reports such.
999
1000 \begin{code}
1001 -- | Report partial matches for rules beginning with the specified
1002 -- string for the purposes of error reporting
1003 ruleCheckProgram :: CompilerPhase               -- ^ Rule activation test
1004                  -> String                      -- ^ Rule pattern
1005                  -> RuleBase                    -- ^ Database of rules
1006                  -> [CoreBind]                  -- ^ Bindings to check in
1007                  -> SDoc                        -- ^ Resulting check message
1008 ruleCheckProgram phase rule_pat rule_base binds 
1009   | isEmptyBag results
1010   = text "Rule check results: no rule application sites"
1011   | otherwise
1012   = vcat [text "Rule check results:",
1013           line,
1014           vcat [ p $$ line | p <- bagToList results ]
1015          ]
1016   where
1017     env = RuleCheckEnv { rc_is_active = isActive phase
1018                        , rc_id_unf    = idUnfolding     -- Not quite right
1019                                                         -- Should use activeUnfolding
1020                        , rc_pattern   = rule_pat
1021                        , rc_rule_base = rule_base }
1022     results = unionManyBags (map (ruleCheckBind env) binds)
1023     line = text (replicate 20 '-')
1024           
1025 data RuleCheckEnv = RuleCheckEnv {
1026     rc_is_active :: Activation -> Bool, 
1027     rc_id_unf  :: IdUnfoldingFun,
1028     rc_pattern :: String, 
1029     rc_rule_base :: RuleBase
1030 }
1031
1032 ruleCheckBind :: RuleCheckEnv -> CoreBind -> Bag SDoc
1033    -- The Bag returned has one SDoc for each call site found
1034 ruleCheckBind env (NonRec _ r) = ruleCheck env r
1035 ruleCheckBind env (Rec prs)    = unionManyBags [ruleCheck env r | (_,r) <- prs]
1036
1037 ruleCheck :: RuleCheckEnv -> CoreExpr -> Bag SDoc
1038 ruleCheck _   (Var _)       = emptyBag
1039 ruleCheck _   (Lit _)       = emptyBag
1040 ruleCheck _   (Type _)      = emptyBag
1041 ruleCheck env (App f a)     = ruleCheckApp env (App f a) []
1042 ruleCheck env (Note _ e)    = ruleCheck env e
1043 ruleCheck env (Cast e _)    = ruleCheck env e
1044 ruleCheck env (Let bd e)    = ruleCheckBind env bd `unionBags` ruleCheck env e
1045 ruleCheck env (Lam _ e)     = ruleCheck env e
1046 ruleCheck env (Case e _ _ as) = ruleCheck env e `unionBags` 
1047                                 unionManyBags [ruleCheck env r | (_,_,r) <- as]
1048
1049 ruleCheckApp :: RuleCheckEnv -> Expr CoreBndr -> [Arg CoreBndr] -> Bag SDoc
1050 ruleCheckApp env (App f a) as = ruleCheck env a `unionBags` ruleCheckApp env f (a:as)
1051 ruleCheckApp env (Var f) as   = ruleCheckFun env f as
1052 ruleCheckApp env other _      = ruleCheck env other
1053 \end{code}
1054
1055 \begin{code}
1056 ruleCheckFun :: RuleCheckEnv -> Id -> [CoreExpr] -> Bag SDoc
1057 -- Produce a report for all rules matching the predicate
1058 -- saying why it doesn't match the specified application
1059
1060 ruleCheckFun env fn args
1061   | null name_match_rules = emptyBag
1062   | otherwise             = unitBag (ruleAppCheck_help env fn args name_match_rules)
1063   where
1064     name_match_rules = filter match (getRules (rc_rule_base env) fn)
1065     match rule = (rc_pattern env) `isPrefixOf` unpackFS (ruleName rule)
1066
1067 ruleAppCheck_help :: RuleCheckEnv -> Id -> [CoreExpr] -> [CoreRule] -> SDoc
1068 ruleAppCheck_help env fn args rules
1069   =     -- The rules match the pattern, so we want to print something
1070     vcat [text "Expression:" <+> ppr (mkApps (Var fn) args),
1071           vcat (map check_rule rules)]
1072   where
1073     n_args = length args
1074     i_args = args `zip` [1::Int ..]
1075     rough_args = map roughTopName args
1076
1077     check_rule rule = rule_herald rule <> colon <+> rule_info rule
1078
1079     rule_herald (BuiltinRule { ru_name = name })
1080         = ptext (sLit "Builtin rule") <+> doubleQuotes (ftext name)
1081     rule_herald (Rule { ru_name = name })
1082         = ptext (sLit "Rule") <+> doubleQuotes (ftext name)
1083
1084     rule_info rule
1085         | Just _ <- matchRule noBlackList (rc_id_unf env) emptyInScopeSet args rough_args rule
1086         = text "matches (which is very peculiar!)"
1087
1088     rule_info (BuiltinRule {}) = text "does not match"
1089
1090     rule_info (Rule { ru_act = act, 
1091                       ru_bndrs = rule_bndrs, ru_args = rule_args})
1092         | not (rc_is_active env act)  = text "active only in later phase"
1093         | n_args < n_rule_args        = text "too few arguments"
1094         | n_mismatches == n_rule_args = text "no arguments match"
1095         | n_mismatches == 0           = text "all arguments match (considered individually), but rule as a whole does not"
1096         | otherwise                   = text "arguments" <+> ppr mismatches <+> text "do not match (1-indexing)"
1097         where
1098           n_rule_args  = length rule_args
1099           n_mismatches = length mismatches
1100           mismatches   = [i | (rule_arg, (arg,i)) <- rule_args `zip` i_args,
1101                               not (isJust (match_fn rule_arg arg))]
1102
1103           lhs_fvs = exprsFreeVars rule_args     -- Includes template tyvars
1104           match_fn rule_arg arg = match renv emptyRuleSubst rule_arg arg
1105                 where
1106                   in_scope = mkInScopeSet (lhs_fvs `unionVarSet` exprFreeVars arg)
1107                   renv = RV { rv_lcl   = mkRnEnv2 in_scope
1108                             , rv_tmpls = mkVarSet rule_bndrs
1109                             , rv_fltR  = mkEmptySubst in_scope
1110                             , rv_unf   = rc_id_unf env }
1111 \end{code}
1112