2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section{Common subexpression}
11 #include "HsVersions.h"
13 import DynFlags ( DynFlag(..), DynFlags )
14 import Id ( Id, idType, idInlinePragma )
15 import CoreUtils ( hashExpr, cheapEqExpr, exprIsBig, mkAltExpr, exprIsCheap )
16 import DataCon ( isUnboxedTupleCon )
17 import Type ( tyConAppArgs )
20 import CoreLint ( showPass, endPass )
22 import StaticFlags ( opt_PprStyle_Debug )
23 import BasicTypes ( isAlwaysActive )
24 import Util ( lengthExceeds )
31 Simple common sub-expression
32 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
36 we build up a reverse mapping: C a b -> x1
38 and apply that to the rest of the program.
43 we replace the C a b with x1. But then we *dont* want to
44 add x1 -> y1 to the mapping. Rather, we want the reverse, y1 -> x1
45 so that a subsequent binding
47 will get transformed to C x1 b, and then to x2.
49 So we carry an extra var->var substitution which we apply *before* looking up in the
55 We have to be careful about shadowing.
57 f = \x -> let y = x+x in
61 Here we must *not* do CSE on the inner x+x! The simplifier used to guarantee no
62 shadowing, but it doesn't any more (it proved too hard), so we clone as we go.
63 We can simply add clones to the substitution already described.
65 However, we do NOT clone type variables. It's just too hard, because then we need
66 to run the substitution over types and IdInfo. No no no. Instead, we just throw
68 (In fact, I think the simplifier does guarantee no-shadowing for type variables.)
71 [Note: case binders 1]
72 ~~~~~~~~~~~~~~~~~~~~~~
75 f = \x -> case x of wild {
76 (a:as) -> case a of wild1 {
77 (p,q) -> ...(wild1:as)...
79 Here, (wild1:as) is morally the same as (a:as) and hence equal to wild.
80 But that's not quite obvious. In general we want to keep it as (wild1:as),
81 but for CSE purpose that's a bad idea.
83 So we add the binding (wild1 -> a) to the extra var->var mapping.
84 Notice this is exactly backwards to what the simplifier does, which is
85 to try to replaces uses of a with uses of wild1
87 [Note: case binders 2]
88 ~~~~~~~~~~~~~~~~~~~~~~
90 case (h x) of y -> ...(h x)...
92 We'd like to replace (h x) in the alternative, by y. But because of
93 the preceding [Note: case binders 1], we only want to add the mapping
94 scrutinee -> case binder
95 to the reverse CSE mapping if the scrutinee is a non-trivial expression.
96 (If the scrutinee is a simple variable we want to add the mapping
97 case binder -> scrutinee
100 [Note: unboxed tuple case binders]
101 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
103 case f x of t { (# a,b #) ->
108 We must not replace (f x) by t, because t is an unboxed-tuple binder.
109 Instead, we shoudl replace (f x) by (# a,b #). That is, the "reverse mapping" is
111 That is why the CSEMap has pairs of expressions.
113 Note [INLINE and NOINLINE]
114 ~~~~~~~~~~~~~~~~~~~~~~~~~~
115 We are careful to do no CSE inside functions that the user has marked as
116 INLINE or NOINLINE. In terms of Core, that means
118 a) we do not do CSE inside (Note InlineMe e)
120 b) we do not do CSE on the RHS of a binding b=e
121 unless b's InlinePragma is AlwaysActive
123 Here's why (examples from Roman Leshchinskiy). Consider
133 foo :: Int -> Int -> Int
137 {-# RULES "foo/no" foo no = id #-}
142 We do not expect the rule to fire. But if we do CSE, then we get
143 yes=no, and the rule does fire. Worse, whether we get yes=no or
144 no=yes depends on the order of the definitions.
146 In general, CSE should probably never touch things with INLINE pragmas
147 as this could lead to surprising results. Consider
153 bar = <rhs> -- Same rhs as foo
157 then foo will never be inlined (when it should be); but if it produces
159 bar will be inlined (when it should not be). Even if we remove INLINE foo,
160 we'd still like foo to be inlined if rhs is small. This won't happen
163 Not CSE-ing inside INLINE also solves an annoying bug in CSE. Consider
164 a worker/wrapper, in which the worker has turned into a single variable:
167 Now CSE may transoform to
169 But the WorkerInfo for f still says $wf, which is now dead! This won't
170 happen now that we don't look inside INLINEs (which wrappers are).
173 %************************************************************************
175 \section{Common subexpression}
177 %************************************************************************
180 cseProgram :: DynFlags -> [CoreBind] -> IO [CoreBind]
182 cseProgram dflags binds
184 showPass dflags "Common sub-expression";
185 let { binds' = cseBinds emptyCSEnv binds };
186 endPass dflags "Common sub-expression" Opt_D_dump_cse binds'
189 cseBinds :: CSEnv -> [CoreBind] -> [CoreBind]
191 cseBinds env (b:bs) = (b':bs')
193 (env1, b') = cseBind env b
194 bs' = cseBinds env1 bs
196 cseBind :: CSEnv -> CoreBind -> (CSEnv, CoreBind)
197 cseBind env (NonRec b e) = let (env', (b',e')) = do_one env (b, e)
198 in (env', NonRec b' e')
199 cseBind env (Rec pairs) = let (env', pairs') = mapAccumL do_one env pairs
200 in (env', Rec pairs')
204 = case lookupCSEnv env rhs' of
205 Just (Var other_id) -> (extendSubst env' id other_id, (id', Var other_id))
206 Just other_expr -> (env', (id', other_expr))
207 Nothing -> (addCSEnvItem env' rhs' (Var id'), (id', rhs'))
209 (env', id') = addBinder env id
210 rhs' | isAlwaysActive (idInlinePragma id) = cseExpr env' rhs
212 -- See Note [INLINE and NOINLINE]
214 tryForCSE :: CSEnv -> CoreExpr -> CoreExpr
215 tryForCSE env (Type t) = Type t
216 tryForCSE env expr = case lookupCSEnv env expr' of
217 Just smaller_expr -> smaller_expr
220 expr' = cseExpr env expr
222 cseExpr :: CSEnv -> CoreExpr -> CoreExpr
223 cseExpr env (Type t) = Type t
224 cseExpr env (Lit lit) = Lit lit
225 cseExpr env (Var v) = Var (lookupSubst env v)
226 cseExpr env (App f a) = App (cseExpr env f) (tryForCSE env a)
227 cseExpr evn (Note InlineMe e) = Note InlineMe e -- See Note [INLINE and NOINLINE]
228 cseExpr env (Note n e) = Note n (cseExpr env e)
229 cseExpr env (Cast e co) = Cast (cseExpr env e) co
230 cseExpr env (Lam b e) = let (env', b') = addBinder env b
231 in Lam b' (cseExpr env' e)
232 cseExpr env (Let bind e) = let (env', bind') = cseBind env bind
233 in Let bind' (cseExpr env' e)
234 cseExpr env (Case scrut bndr ty alts) = Case scrut' bndr' ty (cseAlts env' scrut' bndr bndr' alts)
236 scrut' = tryForCSE env scrut
237 (env', bndr') = addBinder env bndr
240 cseAlts env scrut' bndr bndr' [(DataAlt con, args, rhs)]
241 | isUnboxedTupleCon con
242 -- Unboxed tuples are special because the case binder isn't
243 -- a real values. See [Note: unboxed tuple case binders]
244 = [(DataAlt con, args', tryForCSE new_env rhs)]
246 (env', args') = addBinders env args
247 new_env | exprIsCheap scrut' = env'
248 | otherwise = extendCSEnv env' scrut' tup_value
249 tup_value = mkAltExpr (DataAlt con) args' (tyConAppArgs (idType bndr))
251 cseAlts env scrut' bndr bndr' alts
254 (con_target, alt_env)
256 Var v' -> (v', extendSubst env bndr v') -- See [Note: case binder 1]
259 other -> (bndr', extendCSEnv env scrut' (Var bndr')) -- See [Note: case binder 2]
260 -- map: scrut' -> bndr'
262 arg_tys = tyConAppArgs (idType bndr)
264 cse_alt (DataAlt con, args, rhs)
266 -- Don't try CSE if there are no args; it just increases the number
267 -- of live vars. E.g.
268 -- case x of { True -> ....True.... }
269 -- Don't replace True by x!
270 -- Hence the 'null args', which also deal with literals and DEFAULT
271 = (DataAlt con, args', tryForCSE new_env rhs)
273 (env', args') = addBinders alt_env args
274 new_env = extendCSEnv env' (mkAltExpr (DataAlt con) args' arg_tys)
277 cse_alt (con, args, rhs)
278 = (con, args', tryForCSE env' rhs)
280 (env', args') = addBinders alt_env args
284 %************************************************************************
286 \section{The CSE envt}
288 %************************************************************************
291 data CSEnv = CS CSEMap InScopeSet (IdEnv Id)
292 -- Simple substitution
294 type CSEMap = UniqFM [(CoreExpr, CoreExpr)] -- This is the reverse mapping
295 -- It maps the hash-code of an expression e to list of (e,e') pairs
296 -- This means that it's good to replace e by e'
297 -- INVARIANT: The expr in the range has already been CSE'd
299 emptyCSEnv = CS emptyUFM emptyInScopeSet emptyVarEnv
301 lookupCSEnv :: CSEnv -> CoreExpr -> Maybe CoreExpr
302 lookupCSEnv (CS cs _ _) expr
303 = case lookupUFM cs (hashExpr expr) of
305 Just pairs -> lookup_list pairs expr
307 lookup_list :: [(CoreExpr,CoreExpr)] -> CoreExpr -> Maybe CoreExpr
308 lookup_list [] expr = Nothing
309 lookup_list ((e,e'):es) expr | cheapEqExpr e expr = Just e'
310 | otherwise = lookup_list es expr
312 addCSEnvItem env expr expr' | exprIsBig expr = env
313 | otherwise = extendCSEnv env expr expr'
314 -- We don't try to CSE big expressions, because they are expensive to compare
315 -- (and are unlikely to be the same anyway)
317 extendCSEnv (CS cs in_scope sub) expr expr'
318 = CS (addToUFM_C combine cs hash [(expr, expr')]) in_scope sub
322 = WARN( result `lengthExceeds` 4, short_msg $$ nest 2 long_msg ) result
325 short_msg = ptext SLIT("extendCSEnv: long list, length") <+> int (length result)
326 long_msg | opt_PprStyle_Debug = (text "hash code" <+> text (show hash)) $$ ppr result
329 lookupSubst (CS _ _ sub) x = case lookupVarEnv sub x of
333 extendSubst (CS cs in_scope sub) x y = CS cs in_scope (extendVarEnv sub x y)
335 addBinder :: CSEnv -> Id -> (CSEnv, Id)
336 addBinder env@(CS cs in_scope sub) v
337 | not (v `elemInScopeSet` in_scope) = (CS cs (extendInScopeSet in_scope v) sub, v)
338 | isId v = (CS cs (extendInScopeSet in_scope v') (extendVarEnv sub v v'), v')
339 | otherwise = WARN( True, ppr v )
340 (CS emptyUFM in_scope sub, v)
341 -- This last case is the unusual situation where we have shadowing of
342 -- a type variable; we have to discard the CSE mapping
343 -- See "IMPORTANT NOTE" at the top
345 v' = uniqAway in_scope v
347 addBinders :: CSEnv -> [Id] -> (CSEnv, [Id])
348 addBinders env vs = mapAccumL addBinder env vs