PageRenderTime 58ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/specialise/SpecConstr.lhs

https://github.com/luite/ghc
Haskell | 1872 lines | 1278 code | 334 blank | 260 comment | 71 complexity | 7806c64adb5e6f9087b3fd713c4eb6c9 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. ToDo [Nov 2010]
  2. ~~~~~~~~~~~~~~~
  3. 1. Use a library type rather than an annotation for ForceSpecConstr
  4. 2. Nuke NoSpecConstr
  5. %
  6. % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
  7. %
  8. \section[SpecConstr]{Specialise over constructors}
  9. \begin{code}
  10. module SpecConstr(
  11. specConstrProgram
  12. #ifdef GHCI
  13. , SpecConstrAnnotation(..)
  14. #endif
  15. ) where
  16. #include "HsVersions.h"
  17. import CoreSyn
  18. import CoreSubst
  19. import CoreUtils
  20. import CoreUnfold ( couldBeSmallEnoughToInline )
  21. import CoreFVs ( exprsFreeVars )
  22. import CoreMonad
  23. import Literal ( litIsLifted )
  24. import HscTypes ( ModGuts(..) )
  25. import WwLib ( mkWorkerArgs )
  26. import DataCon
  27. import Coercion hiding( substTy, substCo )
  28. import Rules
  29. import Type hiding ( substTy )
  30. import TyCon ( isRecursiveTyCon )
  31. import Id
  32. import MkCore ( mkImpossibleExpr )
  33. import Var
  34. import VarEnv
  35. import VarSet
  36. import Name
  37. import BasicTypes
  38. import DynFlags ( DynFlags(..) )
  39. import StaticFlags ( opt_PprStyle_Debug )
  40. import Maybes ( orElse, catMaybes, isJust, isNothing )
  41. import Demand
  42. import Serialized ( deserializeWithData )
  43. import Util
  44. import Pair
  45. import UniqSupply
  46. import Outputable
  47. import FastString
  48. import UniqFM
  49. import MonadUtils
  50. import Control.Monad ( zipWithM )
  51. import Data.List
  52. -- See Note [SpecConstrAnnotation]
  53. #ifndef GHCI
  54. type SpecConstrAnnotation = ()
  55. #else
  56. import TyCon ( TyCon )
  57. import GHC.Exts( SpecConstrAnnotation(..) )
  58. #endif
  59. \end{code}
  60. -----------------------------------------------------
  61. Game plan
  62. -----------------------------------------------------
  63. Consider
  64. drop n [] = []
  65. drop 0 xs = []
  66. drop n (x:xs) = drop (n-1) xs
  67. After the first time round, we could pass n unboxed. This happens in
  68. numerical code too. Here's what it looks like in Core:
  69. drop n xs = case xs of
  70. [] -> []
  71. (y:ys) -> case n of
  72. I# n# -> case n# of
  73. 0 -> []
  74. _ -> drop (I# (n# -# 1#)) xs
  75. Notice that the recursive call has an explicit constructor as argument.
  76. Noticing this, we can make a specialised version of drop
  77. RULE: drop (I# n#) xs ==> drop' n# xs
  78. drop' n# xs = let n = I# n# in ...orig RHS...
  79. Now the simplifier will apply the specialisation in the rhs of drop', giving
  80. drop' n# xs = case xs of
  81. [] -> []
  82. (y:ys) -> case n# of
  83. 0 -> []
  84. _ -> drop' (n# -# 1#) xs
  85. Much better!
  86. We'd also like to catch cases where a parameter is carried along unchanged,
  87. but evaluated each time round the loop:
  88. f i n = if i>0 || i>n then i else f (i*2) n
  89. Here f isn't strict in n, but we'd like to avoid evaluating it each iteration.
  90. In Core, by the time we've w/wd (f is strict in i) we get
  91. f i# n = case i# ># 0 of
  92. False -> I# i#
  93. True -> case n of { I# n# ->
  94. case i# ># n# of
  95. False -> I# i#
  96. True -> f (i# *# 2#) n
  97. At the call to f, we see that the argument, n is known to be (I# n#),
  98. and n is evaluated elsewhere in the body of f, so we can play the same
  99. trick as above.
  100. Note [Reboxing]
  101. ~~~~~~~~~~~~~~~
  102. We must be careful not to allocate the same constructor twice. Consider
  103. f p = (...(case p of (a,b) -> e)...p...,
  104. ...let t = (r,s) in ...t...(f t)...)
  105. At the recursive call to f, we can see that t is a pair. But we do NOT want
  106. to make a specialised copy:
  107. f' a b = let p = (a,b) in (..., ...)
  108. because now t is allocated by the caller, then r and s are passed to the
  109. recursive call, which allocates the (r,s) pair again.
  110. This happens if
  111. (a) the argument p is used in other than a case-scrutinsation way.
  112. (b) the argument to the call is not a 'fresh' tuple; you have to
  113. look into its unfolding to see that it's a tuple
  114. Hence the "OR" part of Note [Good arguments] below.
  115. ALTERNATIVE 2: pass both boxed and unboxed versions. This no longer saves
  116. allocation, but does perhaps save evals. In the RULE we'd have
  117. something like
  118. f (I# x#) = f' (I# x#) x#
  119. If at the call site the (I# x) was an unfolding, then we'd have to
  120. rely on CSE to eliminate the duplicate allocation.... This alternative
  121. doesn't look attractive enough to pursue.
  122. ALTERNATIVE 3: ignore the reboxing problem. The trouble is that
  123. the conservative reboxing story prevents many useful functions from being
  124. specialised. Example:
  125. foo :: Maybe Int -> Int -> Int
  126. foo (Just m) 0 = 0
  127. foo x@(Just m) n = foo x (n-m)
  128. Here the use of 'x' will clearly not require boxing in the specialised function.
  129. The strictness analyser has the same problem, in fact. Example:
  130. f p@(a,b) = ...
  131. If we pass just 'a' and 'b' to the worker, it might need to rebox the
  132. pair to create (a,b). A more sophisticated analysis might figure out
  133. precisely the cases in which this could happen, but the strictness
  134. analyser does no such analysis; it just passes 'a' and 'b', and hopes
  135. for the best.
  136. So my current choice is to make SpecConstr similarly aggressive, and
  137. ignore the bad potential of reboxing.
  138. Note [Good arguments]
  139. ~~~~~~~~~~~~~~~~~~~~~
  140. So we look for
  141. * A self-recursive function. Ignore mutual recursion for now,
  142. because it's less common, and the code is simpler for self-recursion.
  143. * EITHER
  144. a) At a recursive call, one or more parameters is an explicit
  145. constructor application
  146. AND
  147. That same parameter is scrutinised by a case somewhere in
  148. the RHS of the function
  149. OR
  150. b) At a recursive call, one or more parameters has an unfolding
  151. that is an explicit constructor application
  152. AND
  153. That same parameter is scrutinised by a case somewhere in
  154. the RHS of the function
  155. AND
  156. Those are the only uses of the parameter (see Note [Reboxing])
  157. What to abstract over
  158. ~~~~~~~~~~~~~~~~~~~~~
  159. There's a bit of a complication with type arguments. If the call
  160. site looks like
  161. f p = ...f ((:) [a] x xs)...
  162. then our specialised function look like
  163. f_spec x xs = let p = (:) [a] x xs in ....as before....
  164. This only makes sense if either
  165. a) the type variable 'a' is in scope at the top of f, or
  166. b) the type variable 'a' is an argument to f (and hence fs)
  167. Actually, (a) may hold for value arguments too, in which case
  168. we may not want to pass them. Supose 'x' is in scope at f's
  169. defn, but xs is not. Then we'd like
  170. f_spec xs = let p = (:) [a] x xs in ....as before....
  171. Similarly (b) may hold too. If x is already an argument at the
  172. call, no need to pass it again.
  173. Finally, if 'a' is not in scope at the call site, we could abstract
  174. it as we do the term variables:
  175. f_spec a x xs = let p = (:) [a] x xs in ...as before...
  176. So the grand plan is:
  177. * abstract the call site to a constructor-only pattern
  178. e.g. C x (D (f p) (g q)) ==> C s1 (D s2 s3)
  179. * Find the free variables of the abstracted pattern
  180. * Pass these variables, less any that are in scope at
  181. the fn defn. But see Note [Shadowing] below.
  182. NOTICE that we only abstract over variables that are not in scope,
  183. so we're in no danger of shadowing variables used in "higher up"
  184. in f_spec's RHS.
  185. Note [Shadowing]
  186. ~~~~~~~~~~~~~~~~
  187. In this pass we gather up usage information that may mention variables
  188. that are bound between the usage site and the definition site; or (more
  189. seriously) may be bound to something different at the definition site.
  190. For example:
  191. f x = letrec g y v = let x = ...
  192. in ...(g (a,b) x)...
  193. Since 'x' is in scope at the call site, we may make a rewrite rule that
  194. looks like
  195. RULE forall a,b. g (a,b) x = ...
  196. But this rule will never match, because it's really a different 'x' at
  197. the call site -- and that difference will be manifest by the time the
  198. simplifier gets to it. [A worry: the simplifier doesn't *guarantee*
  199. no-shadowing, so perhaps it may not be distinct?]
  200. Anyway, the rule isn't actually wrong, it's just not useful. One possibility
  201. is to run deShadowBinds before running SpecConstr, but instead we run the
  202. simplifier. That gives the simplest possible program for SpecConstr to
  203. chew on; and it virtually guarantees no shadowing.
  204. Note [Specialising for constant parameters]
  205. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  206. This one is about specialising on a *constant* (but not necessarily
  207. constructor) argument
  208. foo :: Int -> (Int -> Int) -> Int
  209. foo 0 f = 0
  210. foo m f = foo (f m) (+1)
  211. It produces
  212. lvl_rmV :: GHC.Base.Int -> GHC.Base.Int
  213. lvl_rmV =
  214. \ (ds_dlk :: GHC.Base.Int) ->
  215. case ds_dlk of wild_alH { GHC.Base.I# x_alG ->
  216. GHC.Base.I# (GHC.Prim.+# x_alG 1)
  217. T.$wfoo :: GHC.Prim.Int# -> (GHC.Base.Int -> GHC.Base.Int) ->
  218. GHC.Prim.Int#
  219. T.$wfoo =
  220. \ (ww_sme :: GHC.Prim.Int#) (w_smg :: GHC.Base.Int -> GHC.Base.Int) ->
  221. case ww_sme of ds_Xlw {
  222. __DEFAULT ->
  223. case w_smg (GHC.Base.I# ds_Xlw) of w1_Xmo { GHC.Base.I# ww1_Xmz ->
  224. T.$wfoo ww1_Xmz lvl_rmV
  225. };
  226. 0 -> 0
  227. }
  228. The recursive call has lvl_rmV as its argument, so we could create a specialised copy
  229. with that argument baked in; that is, not passed at all. Now it can perhaps be inlined.
  230. When is this worth it? Call the constant 'lvl'
  231. - If 'lvl' has an unfolding that is a constructor, see if the corresponding
  232. parameter is scrutinised anywhere in the body.
  233. - If 'lvl' has an unfolding that is a inlinable function, see if the corresponding
  234. parameter is applied (...to enough arguments...?)
  235. Also do this is if the function has RULES?
  236. Also
  237. Note [Specialising for lambda parameters]
  238. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  239. foo :: Int -> (Int -> Int) -> Int
  240. foo 0 f = 0
  241. foo m f = foo (f m) (\n -> n-m)
  242. This is subtly different from the previous one in that we get an
  243. explicit lambda as the argument:
  244. T.$wfoo :: GHC.Prim.Int# -> (GHC.Base.Int -> GHC.Base.Int) ->
  245. GHC.Prim.Int#
  246. T.$wfoo =
  247. \ (ww_sm8 :: GHC.Prim.Int#) (w_sma :: GHC.Base.Int -> GHC.Base.Int) ->
  248. case ww_sm8 of ds_Xlr {
  249. __DEFAULT ->
  250. case w_sma (GHC.Base.I# ds_Xlr) of w1_Xmf { GHC.Base.I# ww1_Xmq ->
  251. T.$wfoo
  252. ww1_Xmq
  253. (\ (n_ad3 :: GHC.Base.Int) ->
  254. case n_ad3 of wild_alB { GHC.Base.I# x_alA ->
  255. GHC.Base.I# (GHC.Prim.-# x_alA ds_Xlr)
  256. })
  257. };
  258. 0 -> 0
  259. }
  260. I wonder if SpecConstr couldn't be extended to handle this? After all,
  261. lambda is a sort of constructor for functions and perhaps it already
  262. has most of the necessary machinery?
  263. Furthermore, there's an immediate win, because you don't need to allocate the lamda
  264. at the call site; and if perchance it's called in the recursive call, then you
  265. may avoid allocating it altogether. Just like for constructors.
  266. Looks cool, but probably rare...but it might be easy to implement.
  267. Note [SpecConstr for casts]
  268. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  269. Consider
  270. data family T a :: *
  271. data instance T Int = T Int
  272. foo n = ...
  273. where
  274. go (T 0) = 0
  275. go (T n) = go (T (n-1))
  276. The recursive call ends up looking like
  277. go (T (I# ...) `cast` g)
  278. So we want to spot the constructor application inside the cast.
  279. That's why we have the Cast case in argToPat
  280. Note [Local recursive groups]
  281. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  282. For a *local* recursive group, we can see all the calls to the
  283. function, so we seed the specialisation loop from the calls in the
  284. body, not from the calls in the RHS. Consider:
  285. bar m n = foo n (n,n) (n,n) (n,n) (n,n)
  286. where
  287. foo n p q r s
  288. | n == 0 = m
  289. | n > 3000 = case p of { (p1,p2) -> foo (n-1) (p2,p1) q r s }
  290. | n > 2000 = case q of { (q1,q2) -> foo (n-1) p (q2,q1) r s }
  291. | n > 1000 = case r of { (r1,r2) -> foo (n-1) p q (r2,r1) s }
  292. | otherwise = case s of { (s1,s2) -> foo (n-1) p q r (s2,s1) }
  293. If we start with the RHSs of 'foo', we get lots and lots of specialisations,
  294. most of which are not needed. But if we start with the (single) call
  295. in the rhs of 'bar' we get exactly one fully-specialised copy, and all
  296. the recursive calls go to this fully-specialised copy. Indeed, the original
  297. function is later collected as dead code. This is very important in
  298. specialising the loops arising from stream fusion, for example in NDP where
  299. we were getting literally hundreds of (mostly unused) specialisations of
  300. a local function.
  301. In a case like the above we end up never calling the original un-specialised
  302. function. (Although we still leave its code around just in case.)
  303. However, if we find any boring calls in the body, including *unsaturated*
  304. ones, such as
  305. letrec foo x y = ....foo...
  306. in map foo xs
  307. then we will end up calling the un-specialised function, so then we *should*
  308. use the calls in the un-specialised RHS as seeds. We call these
  309. "boring call patterns", and callsToPats reports if it finds any of these.
  310. Note [Do not specialise diverging functions]
  311. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  312. Specialising a function that just diverges is a waste of code.
  313. Furthermore, it broke GHC (simpl014) thus:
  314. {-# STR Sb #-}
  315. f = \x. case x of (a,b) -> f x
  316. If we specialise f we get
  317. f = \x. case x of (a,b) -> fspec a b
  318. But fspec doesn't have decent strictnes info. As it happened,
  319. (f x) :: IO t, so the state hack applied and we eta expanded fspec,
  320. and hence f. But now f's strictness is less than its arity, which
  321. breaks an invariant.
  322. Note [SpecConstrAnnotation]
  323. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  324. SpecConstrAnnotation is defined in GHC.Exts, and is only guaranteed to
  325. be available in stage 2 (well, until the bootstrap compiler can be
  326. guaranteed to have it)
  327. So we define it to be () in stage1 (ie when GHCI is undefined), and
  328. '#ifdef' out the code that uses it.
  329. See also Note [Forcing specialisation]
  330. Note [Forcing specialisation]
  331. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  332. With stream fusion and in other similar cases, we want to fully specialise
  333. some (but not necessarily all!) loops regardless of their size and the
  334. number of specialisations. We allow a library to specify this by annotating
  335. a type with ForceSpecConstr and then adding a parameter of that type to the
  336. loop. Here is a (simplified) example from the vector library:
  337. data SPEC = SPEC | SPEC2
  338. {-# ANN type SPEC ForceSpecConstr #-}
  339. foldl :: (a -> b -> a) -> a -> Stream b -> a
  340. {-# INLINE foldl #-}
  341. foldl f z (Stream step s _) = foldl_loop SPEC z s
  342. where
  343. foldl_loop !sPEC z s = case step s of
  344. Yield x s' -> foldl_loop sPEC (f z x) s'
  345. Skip -> foldl_loop sPEC z s'
  346. Done -> z
  347. SpecConstr will spot the SPEC parameter and always fully specialise
  348. foldl_loop. Note that
  349. * We have to prevent the SPEC argument from being removed by
  350. w/w which is why (a) SPEC is a sum type, and (b) we have to seq on
  351. the SPEC argument.
  352. * And lastly, the SPEC argument is ultimately eliminated by
  353. SpecConstr itself so there is no runtime overhead.
  354. This is all quite ugly; we ought to come up with a better design.
  355. ForceSpecConstr arguments are spotted in scExpr' and scTopBinds which then set
  356. sc_force to True when calling specLoop. This flag does three things:
  357. * Ignore specConstrThreshold, to specialise functions of arbitrary size
  358. (see scTopBind)
  359. * Ignore specConstrCount, to make arbitrary numbers of specialisations
  360. (see specialise)
  361. * Specialise even for arguments that are not scrutinised in the loop
  362. (see argToPat; Trac #4488)
  363. * Only specialise on recursive types a finite number of times
  364. (see is_too_recursive; Trac #5550)
  365. This flag is inherited for nested non-recursive bindings (which are likely to
  366. be join points and hence should be fully specialised) but reset for nested
  367. recursive bindings.
  368. What alternatives did I consider? Annotating the loop itself doesn't
  369. work because (a) it is local and (b) it will be w/w'ed and having
  370. w/w propagating annotations somehow doesn't seem like a good idea. The
  371. types of the loop arguments really seem to be the most persistent
  372. thing.
  373. Annotating the types that make up the loop state doesn't work,
  374. either, because (a) it would prevent us from using types like Either
  375. or tuples here, (b) we don't want to restrict the set of types that
  376. can be used in Stream states and (c) some types are fixed by the user
  377. (e.g., the accumulator here) but we still want to specialise as much
  378. as possible.
  379. ForceSpecConstr is done by way of an annotation:
  380. data SPEC = SPEC | SPEC2
  381. {-# ANN type SPEC ForceSpecConstr #-}
  382. But SPEC is the *only* type so annotated, so it'd be better to
  383. use a particular library type.
  384. Alternatives to ForceSpecConstr
  385. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  386. Instead of giving the loop an extra argument of type SPEC, we
  387. also considered *wrapping* arguments in SPEC, thus
  388. data SPEC a = SPEC a | SPEC2
  389. loop = \arg -> case arg of
  390. SPEC state ->
  391. case state of (x,y) -> ... loop (SPEC (x',y')) ...
  392. S2 -> error ...
  393. The idea is that a SPEC argument says "specialise this argument
  394. regardless of whether the function case-analyses it". But this
  395. doesn't work well:
  396. * SPEC must still be a sum type, else the strictness analyser
  397. eliminates it
  398. * But that means that 'loop' won't be strict in its real payload
  399. This loss of strictness in turn screws up specialisation, because
  400. we may end up with calls like
  401. loop (SPEC (case z of (p,q) -> (q,p)))
  402. Without the SPEC, if 'loop' were strict, the case would move out
  403. and we'd see loop applied to a pair. But if 'loop' isn't strict
  404. this doesn't look like a specialisable call.
  405. Note [NoSpecConstr]
  406. ~~~~~~~~~~~~~~~~~~~
  407. The ignoreDataCon stuff allows you to say
  408. {-# ANN type T NoSpecConstr #-}
  409. to mean "don't specialise on arguments of this type. It was added
  410. before we had ForceSpecConstr. Lacking ForceSpecConstr we specialised
  411. regardless of size; and then we needed a way to turn that *off*. Now
  412. that we have ForceSpecConstr, this NoSpecConstr is probably redundant.
  413. (Used only for PArray.)
  414. -----------------------------------------------------
  415. Stuff not yet handled
  416. -----------------------------------------------------
  417. Here are notes arising from Roman's work that I don't want to lose.
  418. Example 1
  419. ~~~~~~~~~
  420. data T a = T !a
  421. foo :: Int -> T Int -> Int
  422. foo 0 t = 0
  423. foo x t | even x = case t of { T n -> foo (x-n) t }
  424. | otherwise = foo (x-1) t
  425. SpecConstr does no specialisation, because the second recursive call
  426. looks like a boxed use of the argument. A pity.
  427. $wfoo_sFw :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int#
  428. $wfoo_sFw =
  429. \ (ww_sFo [Just L] :: GHC.Prim.Int#) (w_sFq [Just L] :: T.T GHC.Base.Int) ->
  430. case ww_sFo of ds_Xw6 [Just L] {
  431. __DEFAULT ->
  432. case GHC.Prim.remInt# ds_Xw6 2 of wild1_aEF [Dead Just A] {
  433. __DEFAULT -> $wfoo_sFw (GHC.Prim.-# ds_Xw6 1) w_sFq;
  434. 0 ->
  435. case w_sFq of wild_Xy [Just L] { T.T n_ad5 [Just U(L)] ->
  436. case n_ad5 of wild1_aET [Just A] { GHC.Base.I# y_aES [Just L] ->
  437. $wfoo_sFw (GHC.Prim.-# ds_Xw6 y_aES) wild_Xy
  438. } } };
  439. 0 -> 0
  440. Example 2
  441. ~~~~~~~~~
  442. data a :*: b = !a :*: !b
  443. data T a = T !a
  444. foo :: (Int :*: T Int) -> Int
  445. foo (0 :*: t) = 0
  446. foo (x :*: t) | even x = case t of { T n -> foo ((x-n) :*: t) }
  447. | otherwise = foo ((x-1) :*: t)
  448. Very similar to the previous one, except that the parameters are now in
  449. a strict tuple. Before SpecConstr, we have
  450. $wfoo_sG3 :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int#
  451. $wfoo_sG3 =
  452. \ (ww_sFU [Just L] :: GHC.Prim.Int#) (ww_sFW [Just L] :: T.T
  453. GHC.Base.Int) ->
  454. case ww_sFU of ds_Xws [Just L] {
  455. __DEFAULT ->
  456. case GHC.Prim.remInt# ds_Xws 2 of wild1_aEZ [Dead Just A] {
  457. __DEFAULT ->
  458. case ww_sFW of tpl_B2 [Just L] { T.T a_sFo [Just A] ->
  459. $wfoo_sG3 (GHC.Prim.-# ds_Xws 1) tpl_B2 -- $wfoo1
  460. };
  461. 0 ->
  462. case ww_sFW of wild_XB [Just A] { T.T n_ad7 [Just S(L)] ->
  463. case n_ad7 of wild1_aFd [Just L] { GHC.Base.I# y_aFc [Just L] ->
  464. $wfoo_sG3 (GHC.Prim.-# ds_Xws y_aFc) wild_XB -- $wfoo2
  465. } } };
  466. 0 -> 0 }
  467. We get two specialisations:
  468. "SC:$wfoo1" [0] __forall {a_sFB :: GHC.Base.Int sc_sGC :: GHC.Prim.Int#}
  469. Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int a_sFB)
  470. = Foo.$s$wfoo1 a_sFB sc_sGC ;
  471. "SC:$wfoo2" [0] __forall {y_aFp :: GHC.Prim.Int# sc_sGC :: GHC.Prim.Int#}
  472. Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int (GHC.Base.I# y_aFp))
  473. = Foo.$s$wfoo y_aFp sc_sGC ;
  474. But perhaps the first one isn't good. After all, we know that tpl_B2 is
  475. a T (I# x) really, because T is strict and Int has one constructor. (We can't
  476. unbox the strict fields, because T is polymorphic!)
  477. %************************************************************************
  478. %* *
  479. \subsection{Top level wrapper stuff}
  480. %* *
  481. %************************************************************************
  482. \begin{code}
  483. specConstrProgram :: ModGuts -> CoreM ModGuts
  484. specConstrProgram guts
  485. = do
  486. dflags <- getDynFlags
  487. us <- getUniqueSupplyM
  488. annos <- getFirstAnnotations deserializeWithData guts
  489. let binds' = fst $ initUs us (go (initScEnv dflags annos) (mg_binds guts))
  490. return (guts { mg_binds = binds' })
  491. where
  492. go _ [] = return []
  493. go env (bind:binds) = do (env', bind') <- scTopBind env bind
  494. binds' <- go env' binds
  495. return (bind' : binds')
  496. \end{code}
  497. %************************************************************************
  498. %* *
  499. \subsection{Environment: goes downwards}
  500. %* *
  501. %************************************************************************
  502. Note [Work-free values only in environment]
  503. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  504. The sc_vals field keeps track of in-scope value bindings, so
  505. that if we come across (case x of Just y ->...) we can reduce the
  506. case from knowing that x is bound to a pair.
  507. But only *work-free* values are ok here. For example if the envt had
  508. x -> Just (expensive v)
  509. then we do NOT want to expand to
  510. let y = expensive v in ...
  511. because the x-binding still exists and we've now duplicated (expensive v).
  512. This seldom happens because let-bound constructor applications are
  513. ANF-ised, but it can happen as a result of on-the-fly transformations in
  514. SpecConstr itself. Here is Trac #7865:
  515. let {
  516. a'_shr =
  517. case xs_af8 of _ {
  518. [] -> acc_af6;
  519. : ds_dgt [Dmd=<L,A>] ds_dgu [Dmd=<L,A>] ->
  520. (expensive x_af7, x_af7
  521. } } in
  522. let {
  523. ds_sht =
  524. case a'_shr of _ { (p'_afd, q'_afe) ->
  525. TSpecConstr_DoubleInline.recursive
  526. (GHC.Types.: @ GHC.Types.Int x_af7 wild_X6) (q'_afe, p'_afd)
  527. } } in
  528. When processed knowing that xs_af8 was bound to a cons, we simplify to
  529. a'_shr = (expensive x_af7, x_af7)
  530. and we do NOT want to inline that at the occurrence of a'_shr in ds_sht.
  531. (There are other occurrences of a'_shr.) No no no.
  532. It would be possible to do some on-the-fly ANF-ising, so that a'_shr turned
  533. into a work-free value again, thus
  534. a1 = expensive x_af7
  535. a'_shr = (a1, x_af7)
  536. but that's more work, so until its shown to be important I'm going to
  537. leave it for now.
  538. \begin{code}
  539. data ScEnv = SCE { sc_dflags :: DynFlags,
  540. sc_size :: Maybe Int, -- Size threshold
  541. sc_count :: Maybe Int, -- Max # of specialisations for any one fn
  542. -- See Note [Avoiding exponential blowup]
  543. sc_recursive :: Int, -- Max # of specialisations over recursive type.
  544. -- Stops ForceSpecConstr from diverging.
  545. sc_force :: Bool, -- Force specialisation?
  546. -- See Note [Forcing specialisation]
  547. sc_subst :: Subst, -- Current substitution
  548. -- Maps InIds to OutExprs
  549. sc_how_bound :: HowBoundEnv,
  550. -- Binds interesting non-top-level variables
  551. -- Domain is OutVars (*after* applying the substitution)
  552. sc_vals :: ValueEnv,
  553. -- Domain is OutIds (*after* applying the substitution)
  554. -- Used even for top-level bindings (but not imported ones)
  555. -- The range of the ValueEnv is *work-free* values
  556. -- such as (\x. blah), or (Just v)
  557. -- but NOT (Just (expensive v))
  558. -- See Note [Work-free values only in environment]
  559. sc_annotations :: UniqFM SpecConstrAnnotation
  560. }
  561. ---------------------
  562. -- As we go, we apply a substitution (sc_subst) to the current term
  563. type InExpr = CoreExpr -- _Before_ applying the subst
  564. type InVar = Var
  565. type OutExpr = CoreExpr -- _After_ applying the subst
  566. type OutId = Id
  567. type OutVar = Var
  568. ---------------------
  569. type HowBoundEnv = VarEnv HowBound -- Domain is OutVars
  570. ---------------------
  571. type ValueEnv = IdEnv Value -- Domain is OutIds
  572. data Value = ConVal AltCon [CoreArg] -- _Saturated_ constructors
  573. -- The AltCon is never DEFAULT
  574. | LambdaVal -- Inlinable lambdas or PAPs
  575. instance Outputable Value where
  576. ppr (ConVal con args) = ppr con <+> interpp'SP args
  577. ppr LambdaVal = ptext (sLit "<Lambda>")
  578. ---------------------
  579. initScEnv :: DynFlags -> UniqFM SpecConstrAnnotation -> ScEnv
  580. initScEnv dflags anns
  581. = SCE { sc_dflags = dflags,
  582. sc_size = specConstrThreshold dflags,
  583. sc_count = specConstrCount dflags,
  584. sc_recursive = specConstrRecursive dflags,
  585. sc_force = False,
  586. sc_subst = emptySubst,
  587. sc_how_bound = emptyVarEnv,
  588. sc_vals = emptyVarEnv,
  589. sc_annotations = anns }
  590. data HowBound = RecFun -- These are the recursive functions for which
  591. -- we seek interesting call patterns
  592. | RecArg -- These are those functions' arguments, or their sub-components;
  593. -- we gather occurrence information for these
  594. instance Outputable HowBound where
  595. ppr RecFun = text "RecFun"
  596. ppr RecArg = text "RecArg"
  597. scForce :: ScEnv -> Bool -> ScEnv
  598. scForce env b = env { sc_force = b }
  599. lookupHowBound :: ScEnv -> Id -> Maybe HowBound
  600. lookupHowBound env id = lookupVarEnv (sc_how_bound env) id
  601. scSubstId :: ScEnv -> Id -> CoreExpr
  602. scSubstId env v = lookupIdSubst (text "scSubstId") (sc_subst env) v
  603. scSubstTy :: ScEnv -> Type -> Type
  604. scSubstTy env ty = substTy (sc_subst env) ty
  605. scSubstCo :: ScEnv -> Coercion -> Coercion
  606. scSubstCo env co = substCo (sc_subst env) co
  607. zapScSubst :: ScEnv -> ScEnv
  608. zapScSubst env = env { sc_subst = zapSubstEnv (sc_subst env) }
  609. extendScInScope :: ScEnv -> [Var] -> ScEnv
  610. -- Bring the quantified variables into scope
  611. extendScInScope env qvars = env { sc_subst = extendInScopeList (sc_subst env) qvars }
  612. -- Extend the substitution
  613. extendScSubst :: ScEnv -> Var -> OutExpr -> ScEnv
  614. extendScSubst env var expr = env { sc_subst = extendSubst (sc_subst env) var expr }
  615. extendScSubstList :: ScEnv -> [(Var,OutExpr)] -> ScEnv
  616. extendScSubstList env prs = env { sc_subst = extendSubstList (sc_subst env) prs }
  617. extendHowBound :: ScEnv -> [Var] -> HowBound -> ScEnv
  618. extendHowBound env bndrs how_bound
  619. = env { sc_how_bound = extendVarEnvList (sc_how_bound env)
  620. [(bndr,how_bound) | bndr <- bndrs] }
  621. extendBndrsWith :: HowBound -> ScEnv -> [Var] -> (ScEnv, [Var])
  622. extendBndrsWith how_bound env bndrs
  623. = (env { sc_subst = subst', sc_how_bound = hb_env' }, bndrs')
  624. where
  625. (subst', bndrs') = substBndrs (sc_subst env) bndrs
  626. hb_env' = sc_how_bound env `extendVarEnvList`
  627. [(bndr,how_bound) | bndr <- bndrs']
  628. extendBndrWith :: HowBound -> ScEnv -> Var -> (ScEnv, Var)
  629. extendBndrWith how_bound env bndr
  630. = (env { sc_subst = subst', sc_how_bound = hb_env' }, bndr')
  631. where
  632. (subst', bndr') = substBndr (sc_subst env) bndr
  633. hb_env' = extendVarEnv (sc_how_bound env) bndr' how_bound
  634. extendRecBndrs :: ScEnv -> [Var] -> (ScEnv, [Var])
  635. extendRecBndrs env bndrs = (env { sc_subst = subst' }, bndrs')
  636. where
  637. (subst', bndrs') = substRecBndrs (sc_subst env) bndrs
  638. extendBndr :: ScEnv -> Var -> (ScEnv, Var)
  639. extendBndr env bndr = (env { sc_subst = subst' }, bndr')
  640. where
  641. (subst', bndr') = substBndr (sc_subst env) bndr
  642. extendValEnv :: ScEnv -> Id -> Maybe Value -> ScEnv
  643. extendValEnv env _ Nothing = env
  644. extendValEnv env id (Just cv)
  645. | valueIsWorkFree cv -- Don't duplicate work!! Trac #7865
  646. = env { sc_vals = extendVarEnv (sc_vals env) id cv }
  647. extendValEnv env _ _ = env
  648. extendCaseBndrs :: ScEnv -> OutExpr -> OutId -> AltCon -> [Var] -> (ScEnv, [Var])
  649. -- When we encounter
  650. -- case scrut of b
  651. -- C x y -> ...
  652. -- we want to bind b, to (C x y)
  653. -- NB1: Extends only the sc_vals part of the envt
  654. -- NB2: Kill the dead-ness info on the pattern binders x,y, since
  655. -- they are potentially made alive by the [b -> C x y] binding
  656. extendCaseBndrs env scrut case_bndr con alt_bndrs
  657. = (env2, alt_bndrs')
  658. where
  659. live_case_bndr = not (isDeadBinder case_bndr)
  660. env1 | Var v <- scrut = extendValEnv env v cval
  661. | otherwise = env -- See Note [Add scrutinee to ValueEnv too]
  662. env2 | live_case_bndr = extendValEnv env1 case_bndr cval
  663. | otherwise = env1
  664. alt_bndrs' | case scrut of { Var {} -> True; _ -> live_case_bndr }
  665. = map zap alt_bndrs
  666. | otherwise
  667. = alt_bndrs
  668. cval = case con of
  669. DEFAULT -> Nothing
  670. LitAlt {} -> Just (ConVal con [])
  671. DataAlt {} -> Just (ConVal con vanilla_args)
  672. where
  673. vanilla_args = map Type (tyConAppArgs (idType case_bndr)) ++
  674. varsToCoreExprs alt_bndrs
  675. zap v | isTyVar v = v -- See NB2 above
  676. | otherwise = zapIdOccInfo v
  677. decreaseSpecCount :: ScEnv -> Int -> ScEnv
  678. -- See Note [Avoiding exponential blowup]
  679. decreaseSpecCount env n_specs
  680. = env { sc_count = case sc_count env of
  681. Nothing -> Nothing
  682. Just n -> Just (n `div` (n_specs + 1)) }
  683. -- The "+1" takes account of the original function;
  684. -- See Note [Avoiding exponential blowup]
  685. ---------------------------------------------------
  686. -- See Note [SpecConstrAnnotation]
  687. ignoreType :: ScEnv -> Type -> Bool
  688. ignoreDataCon :: ScEnv -> DataCon -> Bool
  689. forceSpecBndr :: ScEnv -> Var -> Bool
  690. #ifndef GHCI
  691. ignoreType _ _ = False
  692. ignoreDataCon _ _ = False
  693. forceSpecBndr _ _ = False
  694. #else /* GHCI */
  695. ignoreDataCon env dc = ignoreTyCon env (dataConTyCon dc)
  696. ignoreType env ty
  697. = case tyConAppTyCon_maybe ty of
  698. Just tycon -> ignoreTyCon env tycon
  699. _ -> False
  700. ignoreTyCon :: ScEnv -> TyCon -> Bool
  701. ignoreTyCon env tycon
  702. = lookupUFM (sc_annotations env) tycon == Just NoSpecConstr
  703. forceSpecBndr env var = forceSpecFunTy env . snd . splitForAllTys . varType $ var
  704. forceSpecFunTy :: ScEnv -> Type -> Bool
  705. forceSpecFunTy env = any (forceSpecArgTy env) . fst . splitFunTys
  706. forceSpecArgTy :: ScEnv -> Type -> Bool
  707. forceSpecArgTy env ty
  708. | Just ty' <- coreView ty = forceSpecArgTy env ty'
  709. forceSpecArgTy env ty
  710. | Just (tycon, tys) <- splitTyConApp_maybe ty
  711. , tycon /= funTyCon
  712. = lookupUFM (sc_annotations env) tycon == Just ForceSpecConstr
  713. || any (forceSpecArgTy env) tys
  714. forceSpecArgTy _ _ = False
  715. #endif /* GHCI */
  716. \end{code}
  717. Note [Add scrutinee to ValueEnv too]
  718. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  719. Consider this:
  720. case x of y
  721. (a,b) -> case b of c
  722. I# v -> ...(f y)...
  723. By the time we get to the call (f y), the ValueEnv
  724. will have a binding for y, and for c
  725. y -> (a,b)
  726. c -> I# v
  727. BUT that's not enough! Looking at the call (f y) we
  728. see that y is pair (a,b), but we also need to know what 'b' is.
  729. So in extendCaseBndrs we must *also* add the binding
  730. b -> I# v
  731. else we lose a useful specialisation for f. This is necessary even
  732. though the simplifier has systematically replaced uses of 'x' with 'y'
  733. and 'b' with 'c' in the code. The use of 'b' in the ValueEnv came
  734. from outside the case. See Trac #4908 for the live example.
  735. Note [Avoiding exponential blowup]
  736. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  737. The sc_count field of the ScEnv says how many times we are prepared to
  738. duplicate a single function. But we must take care with recursive
  739. specialiations. Consider
  740. let $j1 = let $j2 = let $j3 = ...
  741. in
  742. ...$j3...
  743. in
  744. ...$j2...
  745. in
  746. ...$j1...
  747. If we specialise $j1 then in each specialisation (as well as the original)
  748. we can specialise $j2, and similarly $j3. Even if we make just *one*
  749. specialisation of each, because we also have the original we'll get 2^n
  750. copies of $j3, which is not good.
  751. So when recursively specialising we divide the sc_count by the number of
  752. copies we are making at this level, including the original.
  753. %************************************************************************
  754. %* *
  755. \subsection{Usage information: flows upwards}
  756. %* *
  757. %************************************************************************
  758. \begin{code}
  759. data ScUsage
  760. = SCU {
  761. scu_calls :: CallEnv, -- Calls
  762. -- The functions are a subset of the
  763. -- RecFuns in the ScEnv
  764. scu_occs :: !(IdEnv ArgOcc) -- Information on argument occurrences
  765. } -- The domain is OutIds
  766. type CallEnv = IdEnv [Call]
  767. type Call = (ValueEnv, [CoreArg])
  768. -- The arguments of the call, together with the
  769. -- env giving the constructor bindings at the call site
  770. nullUsage :: ScUsage
  771. nullUsage = SCU { scu_calls = emptyVarEnv, scu_occs = emptyVarEnv }
  772. combineCalls :: CallEnv -> CallEnv -> CallEnv
  773. combineCalls = plusVarEnv_C (++)
  774. combineUsage :: ScUsage -> ScUsage -> ScUsage
  775. combineUsage u1 u2 = SCU { scu_calls = combineCalls (scu_calls u1) (scu_calls u2),
  776. scu_occs = plusVarEnv_C combineOcc (scu_occs u1) (scu_occs u2) }
  777. combineUsages :: [ScUsage] -> ScUsage
  778. combineUsages [] = nullUsage
  779. combineUsages us = foldr1 combineUsage us
  780. lookupOccs :: ScUsage -> [OutVar] -> (ScUsage, [ArgOcc])
  781. lookupOccs (SCU { scu_calls = sc_calls, scu_occs = sc_occs }) bndrs
  782. = (SCU {scu_calls = sc_calls, scu_occs = delVarEnvList sc_occs bndrs},
  783. [lookupVarEnv sc_occs b `orElse` NoOcc | b <- bndrs])
  784. data ArgOcc = NoOcc -- Doesn't occur at all; or a type argument
  785. | UnkOcc -- Used in some unknown way
  786. | ScrutOcc -- See Note [ScrutOcc]
  787. (DataConEnv [ArgOcc]) -- How the sub-components are used
  788. type DataConEnv a = UniqFM a -- Keyed by DataCon
  789. {- Note [ScrutOcc]
  790. ~~~~~~~~~~~~~~~~~~~
  791. An occurrence of ScrutOcc indicates that the thing, or a `cast` version of the thing,
  792. is *only* taken apart or applied.
  793. Functions, literal: ScrutOcc emptyUFM
  794. Data constructors: ScrutOcc subs,
  795. where (subs :: UniqFM [ArgOcc]) gives usage of the *pattern-bound* components,
  796. The domain of the UniqFM is the Unique of the data constructor
  797. The [ArgOcc] is the occurrences of the *pattern-bound* components
  798. of the data structure. E.g.
  799. data T a = forall b. MkT a b (b->a)
  800. A pattern binds b, x::a, y::b, z::b->a, but not 'a'!
  801. -}
  802. instance Outputable ArgOcc where
  803. ppr (ScrutOcc xs) = ptext (sLit "scrut-occ") <> ppr xs
  804. ppr UnkOcc = ptext (sLit "unk-occ")
  805. ppr NoOcc = ptext (sLit "no-occ")
  806. evalScrutOcc :: ArgOcc
  807. evalScrutOcc = ScrutOcc emptyUFM
  808. -- Experimentally, this vesion of combineOcc makes ScrutOcc "win", so
  809. -- that if the thing is scrutinised anywhere then we get to see that
  810. -- in the overall result, even if it's also used in a boxed way
  811. -- This might be too agressive; see Note [Reboxing] Alternative 3
  812. combineOcc :: ArgOcc -> ArgOcc -> ArgOcc
  813. combineOcc NoOcc occ = occ
  814. combineOcc occ NoOcc = occ
  815. combineOcc (ScrutOcc xs) (ScrutOcc ys) = ScrutOcc (plusUFM_C combineOccs xs ys)
  816. combineOcc UnkOcc (ScrutOcc ys) = ScrutOcc ys
  817. combineOcc (ScrutOcc xs) UnkOcc = ScrutOcc xs
  818. combineOcc UnkOcc UnkOcc = UnkOcc
  819. combineOccs :: [ArgOcc] -> [ArgOcc] -> [ArgOcc]
  820. combineOccs xs ys = zipWithEqual "combineOccs" combineOcc xs ys
  821. setScrutOcc :: ScEnv -> ScUsage -> OutExpr -> ArgOcc -> ScUsage
  822. -- _Overwrite_ the occurrence info for the scrutinee, if the scrutinee
  823. -- is a variable, and an interesting variable
  824. setScrutOcc env usg (Cast e _) occ = setScrutOcc env usg e occ
  825. setScrutOcc env usg (Tick _ e) occ = setScrutOcc env usg e occ
  826. setScrutOcc env usg (Var v) occ
  827. | Just RecArg <- lookupHowBound env v = usg { scu_occs = extendVarEnv (scu_occs usg) v occ }
  828. | otherwise = usg
  829. setScrutOcc _env usg _other _occ -- Catch-all
  830. = usg
  831. \end{code}
  832. %************************************************************************
  833. %* *
  834. \subsection{The main recursive function}
  835. %* *
  836. %************************************************************************
  837. The main recursive function gathers up usage information, and
  838. creates specialised versions of functions.
  839. \begin{code}
  840. scExpr, scExpr' :: ScEnv -> CoreExpr -> UniqSM (ScUsage, CoreExpr)
  841. -- The unique supply is needed when we invent
  842. -- a new name for the specialised function and its args
  843. scExpr env e = scExpr' env e
  844. scExpr' env (Var v) = case scSubstId env v of
  845. Var v' -> return (mkVarUsage env v' [], Var v')
  846. e' -> scExpr (zapScSubst env) e'
  847. scExpr' env (Type t) = return (nullUsage, Type (scSubstTy env t))
  848. scExpr' env (Coercion c) = return (nullUsage, Coercion (scSubstCo env c))
  849. scExpr' _ e@(Lit {}) = return (nullUsage, e)
  850. scExpr' env (Tick t e) = do (usg, e') <- scExpr env e
  851. return (usg, Tick t e')
  852. scExpr' env (Cast e co) = do (usg, e') <- scExpr env e
  853. return (usg, Cast e' (scSubstCo env co))
  854. scExpr' env e@(App _ _) = scApp env (collectArgs e)
  855. scExpr' env (Lam b e) = do let (env', b') = extendBndr env b
  856. (usg, e') <- scExpr env' e
  857. return (usg, Lam b' e')
  858. scExpr' env (Case scrut b ty alts)
  859. = do { (scrut_usg, scrut') <- scExpr env scrut
  860. ; case isValue (sc_vals env) scrut' of
  861. Just (ConVal con args) -> sc_con_app con args scrut'
  862. _other -> sc_vanilla scrut_usg scrut'
  863. }
  864. where
  865. sc_con_app con args scrut' -- Known constructor; simplify
  866. = do { let (_, bs, rhs) = findAlt con alts
  867. `orElse` (DEFAULT, [], mkImpossibleExpr ty)
  868. alt_env' = extendScSubstList env ((b,scrut') : bs `zip` trimConArgs con args)
  869. ; scExpr alt_env' rhs }
  870. sc_vanilla scrut_usg scrut' -- Normal case
  871. = do { let (alt_env,b') = extendBndrWith RecArg env b
  872. -- Record RecArg for the components
  873. ; (alt_usgs, alt_occs, alts')
  874. <- mapAndUnzip3M (sc_alt alt_env scrut' b') alts
  875. ; let scrut_occ = foldr combineOcc NoOcc alt_occs
  876. scrut_usg' = setScrutOcc env scrut_usg scrut' scrut_occ
  877. -- The combined usage of the scrutinee is given
  878. -- by scrut_occ, which is passed to scScrut, which
  879. -- in turn treats a bare-variable scrutinee specially
  880. ; return (foldr combineUsage scrut_usg' alt_usgs,
  881. Case scrut' b' (scSubstTy env ty) alts') }
  882. sc_alt env scrut' b' (con,bs,rhs)
  883. = do { let (env1, bs1) = extendBndrsWith RecArg env bs
  884. (env2, bs2) = extendCaseBndrs env1 scrut' b' con bs1
  885. ; (usg, rhs') <- scExpr env2 rhs
  886. ; let (usg', b_occ:arg_occs) = lookupOccs usg (b':bs2)
  887. scrut_occ = case con of
  888. DataAlt dc -> ScrutOcc (unitUFM dc arg_occs)
  889. _ -> ScrutOcc emptyUFM
  890. ; return (usg', b_occ `combineOcc` scrut_occ, (con, bs2, rhs')) }
  891. scExpr' env (Let (NonRec bndr rhs) body)
  892. | isTyVar bndr -- Type-lets may be created by doBeta
  893. = scExpr' (extendScSubst env bndr rhs) body
  894. | otherwise
  895. = do { let (body_env, bndr') = extendBndr env bndr
  896. ; (rhs_usg, rhs_info) <- scRecRhs env (bndr',rhs)
  897. ; let body_env2 = extendHowBound body_env [bndr'] RecFun
  898. -- Note [Local let bindings]
  899. RI _ rhs' _ _ _ = rhs_info
  900. body_env3 = extendValEnv body_env2 bndr' (isValue (sc_vals env) rhs')
  901. ; (body_usg, body') <- scExpr body_env3 body
  902. -- NB: For non-recursive bindings we inherit sc_force flag from
  903. -- the parent function (see Note [Forcing specialisation])
  904. ; (spec_usg, specs) <- specialise env
  905. (scu_calls body_usg)
  906. rhs_info
  907. (SI [] 0 (Just rhs_usg))
  908. ; return (body_usg { scu_calls = scu_calls body_usg `delVarEnv` bndr' }
  909. `combineUsage` rhs_usg `combineUsage` spec_usg,
  910. mkLets [NonRec b r | (b,r) <- specInfoBinds rhs_info specs] body')
  911. }
  912. -- A *local* recursive group: see Note [Local recursive groups]
  913. scExpr' env (Let (Rec prs) body)
  914. = do { let (bndrs,rhss) = unzip prs
  915. (rhs_env1,bndrs') = extendRecBndrs env bndrs
  916. rhs_env2 = extendHowBound rhs_env1 bndrs' RecFun
  917. force_spec = any (forceSpecBndr env) bndrs'
  918. -- Note [Forcing specialisation]
  919. ; (rhs_usgs, rhs_infos) <- mapAndUnzipM (scRecRhs rhs_env2) (bndrs' `zip` rhss)
  920. ; (body_usg, body') <- scExpr rhs_env2 body
  921. -- NB: start specLoop from body_usg
  922. ; (spec_usg, specs) <- specLoop (scForce rhs_env2 force_spec)
  923. (scu_calls body_usg) rhs_infos nullUsage
  924. [SI [] 0 (Just usg) | usg <- rhs_usgs]
  925. -- Do not unconditionally generate specialisations from rhs_usgs
  926. -- Instead use them only if we find an unspecialised call
  927. -- See Note [Local recursive groups]
  928. ; let rhs_usg = combineUsages rhs_usgs
  929. all_usg = spec_usg `combineUsage` rhs_usg `combineUsage` body_usg
  930. bind' = Rec (concat (zipWith specInfoBinds rhs_infos specs))
  931. ; return (all_usg { scu_calls = scu_calls all_usg `delVarEnvList` bndrs' },
  932. Let bind' body') }
  933. \end{code}
  934. Note [Local let bindings]
  935. ~~~~~~~~~~~~~~~~~~~~~~~~~
  936. It is not uncommon to find this
  937. let $j = \x. <blah> in ...$j True...$j True...
  938. Here $j is an arbitrary let-bound function, but it often comes up for
  939. join points. We might like to specialise $j for its call patterns.
  940. Notice the difference from a letrec, where we look for call patterns
  941. in the *RHS* of the function. Here we look for call patterns in the
  942. *body* of the let.
  943. At one point I predicated this on the RHS mentioning the outer
  944. recursive function, but that's not essential and might even be
  945. harmful. I'm not sure.
  946. \begin{code}
  947. scApp :: ScEnv -> (InExpr, [InExpr]) -> UniqSM (ScUsage, CoreExpr)
  948. scApp env (Var fn, args) -- Function is a variable
  949. = ASSERT( not (null args) )
  950. do { args_w_usgs <- mapM (scExpr env) args
  951. ; let (arg_usgs, args') = unzip args_w_usgs
  952. arg_usg = combineUsages arg_usgs
  953. ; case scSubstId env fn of
  954. fn'@(Lam {}) -> scExpr (zapScSubst env) (doBeta fn' args')
  955. -- Do beta-reduction and try again
  956. Var fn' -> return (arg_usg `combineUsage` mkVarUsage env fn' args',
  957. mkApps (Var fn') args')
  958. other_fn' -> return (arg_usg, mkApps other_fn' args') }
  959. -- NB: doing this ignores any usage info from the substituted
  960. -- function, but I don't think that matters. If it does
  961. -- we can fix it.
  962. where
  963. doBeta :: OutExpr -> [OutExpr] -> OutExpr
  964. -- ToDo: adjust for System IF
  965. doBeta (Lam bndr body) (arg : args) = Let (NonRec bndr arg) (doBeta body args)
  966. doBeta fn args = mkApps fn args
  967. -- The function is almost always a variable, but not always.
  968. -- In particular, if this pass follows float-in,
  969. -- which it may, we can get
  970. -- (let f = ...f... in f) arg1 arg2
  971. scApp env (other_fn, args)
  972. = do { (fn_usg, fn') <- scExpr env other_fn
  973. ; (arg_usgs, args') <- mapAndUnzipM (scExpr env) args
  974. ; return (combineUsages arg_usgs `combineUsage` fn_usg, mkApps fn' args') }
  975. ----------------------
  976. mkVarUsage :: ScEnv -> Id -> [CoreExpr] -> ScUsage
  977. mkVarUsage env fn args
  978. = case lookupHowBound env fn of
  979. Just RecFun -> SCU { scu_calls = unitVarEnv fn [(sc_vals env, args)]
  980. , scu_occs = emptyVarEnv }
  981. Just RecArg -> SCU { scu_calls = emptyVarEnv
  982. , scu_occs = unitVarEnv fn arg_occ }
  983. Nothing -> nullUsage
  984. where
  985. -- I rather think we could use UnkOcc all the time
  986. arg_occ | null args = UnkOcc
  987. | otherwise = evalScrutOcc
  988. ----------------------
  989. scTopBind :: ScEnv -> CoreBind -> UniqSM (ScEnv, CoreBind)
  990. scTopBind env (Rec prs)
  991. | Just threshold <- sc_size env
  992. , not force_spec
  993. , not (all (couldBeSmallEnoughToInline (sc_dflags env) threshold) rhss)
  994. -- No specialisation
  995. = do { let (rhs_env,bndrs') = extendRecBndrs env bndrs
  996. ; (_, rhss') <- mapAndUnzipM (scExpr rhs_env) rhss
  997. ; return (rhs_env, Rec (bndrs' `zip` rhss')) }
  998. | otherwise -- Do specialisation
  999. = do { let (rhs_env1,bndrs') = extendRecBndrs env bndrs
  1000. rhs_env2 = extendHowBound rhs_env1 bndrs' RecFun
  1001. ; (rhs_usgs, rhs_infos) <- mapAndUnzipM (scRecRhs rhs_env2) (bndrs' `zip` rhss)
  1002. ; let rhs_usg = combineUsages rhs_usgs
  1003. ; (_, specs) <- specLoop (scForce rhs_env2 force_spec)
  1004. (scu_calls rhs_usg) rhs_infos nullUsage
  1005. [SI [] 0 Nothing | _ <- bndrs]
  1006. ; return (rhs_env1, -- For the body of the letrec, delete the RecFun business
  1007. Rec (concat (zipWith specInfoBinds rhs_infos specs))) }
  1008. where
  1009. (bndrs,rhss) = unzip prs
  1010. force_spec = any (forceSpecBndr env) bndrs
  1011. -- Note [Forcing specialisation]
  1012. scTopBind env (NonRec bndr rhs)
  1013. = do { (_, rhs') <- scExpr env rhs
  1014. ; let (env1, bndr') = extendBndr env bndr
  1015. env2 = extendValEnv env1 bndr' (isValue (sc_vals env) rhs')
  1016. ; return (env2, NonRec bndr' rhs') }
  1017. ----------------------
  1018. scRecRhs :: ScEnv -> (OutId, InExpr) -> UniqSM (ScUsage, RhsInfo)
  1019. scRecRhs env (bndr,rhs)
  1020. = do { let (arg_bndrs,body) = collectBinders rhs
  1021. (body_env, arg_bndrs') = extendBndrsWith RecArg env arg_bndrs
  1022. ; (body_usg, body') <- scExpr body_env body
  1023. ; let (rhs_usg, arg_occs) = lookupOccs body_usg arg_bndrs'
  1024. ; return (rhs_usg, RI bndr (mkLams arg_bndrs' body')
  1025. arg_bndrs body arg_occs) }
  1026. -- The arg_occs says how the visible,
  1027. -- lambda-bound binders of the RHS are used
  1028. -- (including the TyVar binders)
  1029. -- Two pats are the same if they match both ways
  1030. ----------------------
  1031. specInfoBinds :: RhsInfo -> SpecInfo -> [(Id,CoreExpr)]
  1032. specInfoBinds (RI fn new_rhs _ _ _) (SI specs _ _)
  1033. = [(id,rhs) | OS _ _ id rhs <- specs] ++
  1034. -- First the specialised bindings
  1035. [(fn `addIdSpecialisations` rules, new_rhs)]
  1036. -- And now the original binding
  1037. where
  1038. rules = [r | OS _ r _ _ <- specs]
  1039. \end{code}
  1040. %************************************************************************
  1041. %* *
  1042. The specialiser itself
  1043. %* *
  1044. %*************

Large files files are truncated, but you can click here to view the full file