PageRenderTime 74ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/specialise/SpecConstr.lhs

http://github.com/ghc/ghc
Haskell | 1956 lines | 1333 code | 353 blank | 270 comment | 78 complexity | 53edf0410f8822fcc0a4ee6344898371 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, GPL-3.0

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-scrutinisation 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 [Top-level recursive groups]
  311. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  312. If all the bindings in a top-level recursive group are not exported,
  313. all the calls are in the rest of the top-level bindings.
  314. This means we can specialise with those call patterns instead of with the RHSs
  315. of the recursive group.
  316. To get the call usage information, we work backwards through the top-level bindings
  317. so we see the usage before we get to the binding of the function.
  318. Before we can collect the usage though, we go through all the bindings and add them
  319. to the environment. This is necessary because usage is only tracked for functions
  320. in the environment.
  321. The actual seeding of the specialisation is very similar to Note [Local recursive group].
  322. Note [Do not specialise diverging functions]
  323. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  324. Specialising a function that just diverges is a waste of code.
  325. Furthermore, it broke GHC (simpl014) thus:
  326. {-# STR Sb #-}
  327. f = \x. case x of (a,b) -> f x
  328. If we specialise f we get
  329. f = \x. case x of (a,b) -> fspec a b
  330. But fspec doesn't have decent strictness info. As it happened,
  331. (f x) :: IO t, so the state hack applied and we eta expanded fspec,
  332. and hence f. But now f's strictness is less than its arity, which
  333. breaks an invariant.
  334. Note [SpecConstrAnnotation]
  335. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  336. SpecConstrAnnotation is defined in GHC.Exts, and is only guaranteed to
  337. be available in stage 2 (well, until the bootstrap compiler can be
  338. guaranteed to have it)
  339. So we define it to be () in stage1 (ie when GHCI is undefined), and
  340. '#ifdef' out the code that uses it.
  341. See also Note [Forcing specialisation]
  342. Note [Forcing specialisation]
  343. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  344. With stream fusion and in other similar cases, we want to fully specialise
  345. some (but not necessarily all!) loops regardless of their size and the
  346. number of specialisations. We allow a library to specify this by annotating
  347. a type with ForceSpecConstr and then adding a parameter of that type to the
  348. loop. Here is a (simplified) example from the vector library:
  349. data SPEC = SPEC | SPEC2
  350. {-# ANN type SPEC ForceSpecConstr #-}
  351. foldl :: (a -> b -> a) -> a -> Stream b -> a
  352. {-# INLINE foldl #-}
  353. foldl f z (Stream step s _) = foldl_loop SPEC z s
  354. where
  355. foldl_loop !sPEC z s = case step s of
  356. Yield x s' -> foldl_loop sPEC (f z x) s'
  357. Skip -> foldl_loop sPEC z s'
  358. Done -> z
  359. SpecConstr will spot the SPEC parameter and always fully specialise
  360. foldl_loop. Note that
  361. * We have to prevent the SPEC argument from being removed by
  362. w/w which is why (a) SPEC is a sum type, and (b) we have to seq on
  363. the SPEC argument.
  364. * And lastly, the SPEC argument is ultimately eliminated by
  365. SpecConstr itself so there is no runtime overhead.
  366. This is all quite ugly; we ought to come up with a better design.
  367. ForceSpecConstr arguments are spotted in scExpr' and scTopBinds which then set
  368. sc_force to True when calling specLoop. This flag does four things:
  369. * Ignore specConstrThreshold, to specialise functions of arbitrary size
  370. (see scTopBind)
  371. * Ignore specConstrCount, to make arbitrary numbers of specialisations
  372. (see specialise)
  373. * Specialise even for arguments that are not scrutinised in the loop
  374. (see argToPat; Trac #4488)
  375. * Only specialise on recursive types a finite number of times
  376. (see is_too_recursive; Trac #5550; Note [Limit recursive specialisation])
  377. This flag is inherited for nested non-recursive bindings (which are likely to
  378. be join points and hence should be fully specialised) but reset for nested
  379. recursive bindings.
  380. What alternatives did I consider? Annotating the loop itself doesn't
  381. work because (a) it is local and (b) it will be w/w'ed and having
  382. w/w propagating annotations somehow doesn't seem like a good idea. The
  383. types of the loop arguments really seem to be the most persistent
  384. thing.
  385. Annotating the types that make up the loop state doesn't work,
  386. either, because (a) it would prevent us from using types like Either
  387. or tuples here, (b) we don't want to restrict the set of types that
  388. can be used in Stream states and (c) some types are fixed by the user
  389. (e.g., the accumulator here) but we still want to specialise as much
  390. as possible.
  391. ForceSpecConstr is done by way of an annotation:
  392. data SPEC = SPEC | SPEC2
  393. {-# ANN type SPEC ForceSpecConstr #-}
  394. But SPEC is the *only* type so annotated, so it'd be better to
  395. use a particular library type.
  396. Alternatives to ForceSpecConstr
  397. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  398. Instead of giving the loop an extra argument of type SPEC, we
  399. also considered *wrapping* arguments in SPEC, thus
  400. data SPEC a = SPEC a | SPEC2
  401. loop = \arg -> case arg of
  402. SPEC state ->
  403. case state of (x,y) -> ... loop (SPEC (x',y')) ...
  404. S2 -> error ...
  405. The idea is that a SPEC argument says "specialise this argument
  406. regardless of whether the function case-analyses it". But this
  407. doesn't work well:
  408. * SPEC must still be a sum type, else the strictness analyser
  409. eliminates it
  410. * But that means that 'loop' won't be strict in its real payload
  411. This loss of strictness in turn screws up specialisation, because
  412. we may end up with calls like
  413. loop (SPEC (case z of (p,q) -> (q,p)))
  414. Without the SPEC, if 'loop' were strict, the case would move out
  415. and we'd see loop applied to a pair. But if 'loop' isn't strict
  416. this doesn't look like a specialisable call.
  417. Note [Limit recursive specialisation]
  418. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  419. It is possible for ForceSpecConstr to cause an infinite loop of specialisation.
  420. Because there is no limit on the number of specialisations, a recursive call with
  421. a recursive constructor as an argument (for example, list cons) will generate
  422. a specialisation for that constructor. If the resulting specialisation also
  423. contains a recursive call with the constructor, this could proceed indefinitely.
  424. For example, if ForceSpecConstr is on:
  425. loop :: [Int] -> [Int] -> [Int]
  426. loop z [] = z
  427. loop z (x:xs) = loop (x:z) xs
  428. this example will create a specialisation for the pattern
  429. loop (a:b) c = loop' a b c
  430. loop' a b [] = (a:b)
  431. loop' a b (x:xs) = loop (x:(a:b)) xs
  432. and a new pattern is found:
  433. loop (a:(b:c)) d = loop'' a b c d
  434. which can continue indefinitely.
  435. Roman's suggestion to fix this was to stop after a couple of times on recursive types,
  436. but still specialising on non-recursive types as much as possible.
  437. To implement this, we count the number of recursive constructors in each
  438. function argument. If the maximum is greater than the specConstrRecursive limit,
  439. do not specialise on that pattern.
  440. This is only necessary when ForceSpecConstr is on: otherwise the specConstrCount
  441. will force termination anyway.
  442. See Trac #5550.
  443. Note [NoSpecConstr]
  444. ~~~~~~~~~~~~~~~~~~~
  445. The ignoreDataCon stuff allows you to say
  446. {-# ANN type T NoSpecConstr #-}
  447. to mean "don't specialise on arguments of this type". It was added
  448. before we had ForceSpecConstr. Lacking ForceSpecConstr we specialised
  449. regardless of size; and then we needed a way to turn that *off*. Now
  450. that we have ForceSpecConstr, this NoSpecConstr is probably redundant.
  451. (Used only for PArray.)
  452. -----------------------------------------------------
  453. Stuff not yet handled
  454. -----------------------------------------------------
  455. Here are notes arising from Roman's work that I don't want to lose.
  456. Example 1
  457. ~~~~~~~~~
  458. data T a = T !a
  459. foo :: Int -> T Int -> Int
  460. foo 0 t = 0
  461. foo x t | even x = case t of { T n -> foo (x-n) t }
  462. | otherwise = foo (x-1) t
  463. SpecConstr does no specialisation, because the second recursive call
  464. looks like a boxed use of the argument. A pity.
  465. $wfoo_sFw :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int#
  466. $wfoo_sFw =
  467. \ (ww_sFo [Just L] :: GHC.Prim.Int#) (w_sFq [Just L] :: T.T GHC.Base.Int) ->
  468. case ww_sFo of ds_Xw6 [Just L] {
  469. __DEFAULT ->
  470. case GHC.Prim.remInt# ds_Xw6 2 of wild1_aEF [Dead Just A] {
  471. __DEFAULT -> $wfoo_sFw (GHC.Prim.-# ds_Xw6 1) w_sFq;
  472. 0 ->
  473. case w_sFq of wild_Xy [Just L] { T.T n_ad5 [Just U(L)] ->
  474. case n_ad5 of wild1_aET [Just A] { GHC.Base.I# y_aES [Just L] ->
  475. $wfoo_sFw (GHC.Prim.-# ds_Xw6 y_aES) wild_Xy
  476. } } };
  477. 0 -> 0
  478. Example 2
  479. ~~~~~~~~~
  480. data a :*: b = !a :*: !b
  481. data T a = T !a
  482. foo :: (Int :*: T Int) -> Int
  483. foo (0 :*: t) = 0
  484. foo (x :*: t) | even x = case t of { T n -> foo ((x-n) :*: t) }
  485. | otherwise = foo ((x-1) :*: t)
  486. Very similar to the previous one, except that the parameters are now in
  487. a strict tuple. Before SpecConstr, we have
  488. $wfoo_sG3 :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int#
  489. $wfoo_sG3 =
  490. \ (ww_sFU [Just L] :: GHC.Prim.Int#) (ww_sFW [Just L] :: T.T
  491. GHC.Base.Int) ->
  492. case ww_sFU of ds_Xws [Just L] {
  493. __DEFAULT ->
  494. case GHC.Prim.remInt# ds_Xws 2 of wild1_aEZ [Dead Just A] {
  495. __DEFAULT ->
  496. case ww_sFW of tpl_B2 [Just L] { T.T a_sFo [Just A] ->
  497. $wfoo_sG3 (GHC.Prim.-# ds_Xws 1) tpl_B2 -- $wfoo1
  498. };
  499. 0 ->
  500. case ww_sFW of wild_XB [Just A] { T.T n_ad7 [Just S(L)] ->
  501. case n_ad7 of wild1_aFd [Just L] { GHC.Base.I# y_aFc [Just L] ->
  502. $wfoo_sG3 (GHC.Prim.-# ds_Xws y_aFc) wild_XB -- $wfoo2
  503. } } };
  504. 0 -> 0 }
  505. We get two specialisations:
  506. "SC:$wfoo1" [0] __forall {a_sFB :: GHC.Base.Int sc_sGC :: GHC.Prim.Int#}
  507. Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int a_sFB)
  508. = Foo.$s$wfoo1 a_sFB sc_sGC ;
  509. "SC:$wfoo2" [0] __forall {y_aFp :: GHC.Prim.Int# sc_sGC :: GHC.Prim.Int#}
  510. Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int (GHC.Base.I# y_aFp))
  511. = Foo.$s$wfoo y_aFp sc_sGC ;
  512. But perhaps the first one isn't good. After all, we know that tpl_B2 is
  513. a T (I# x) really, because T is strict and Int has one constructor. (We can't
  514. unbox the strict fields, because T is polymorphic!)
  515. %************************************************************************
  516. %* *
  517. \subsection{Top level wrapper stuff}
  518. %* *
  519. %************************************************************************
  520. \begin{code}
  521. specConstrProgram :: ModGuts -> CoreM ModGuts
  522. specConstrProgram guts
  523. = do
  524. dflags <- getDynFlags
  525. us <- getUniqueSupplyM
  526. annos <- getFirstAnnotations deserializeWithData guts
  527. let binds' = reverse $ fst $ initUs us $ do
  528. -- Note [Top-level recursive groups]
  529. (env, binds) <- goEnv (initScEnv dflags annos) (mg_binds guts)
  530. go env nullUsage (reverse binds)
  531. return (guts { mg_binds = binds' })
  532. where
  533. goEnv env [] = return (env, [])
  534. goEnv env (bind:binds) = do (env', bind') <- scTopBindEnv env bind
  535. (env'', binds') <- goEnv env' binds
  536. return (env'', bind' : binds')
  537. go _ _ [] = return []
  538. go env usg (bind:binds) = do (usg', bind') <- scTopBind env usg bind
  539. binds' <- go env usg' binds
  540. return (bind' : binds')
  541. \end{code}
  542. %************************************************************************
  543. %* *
  544. \subsection{Environment: goes downwards}
  545. %* *
  546. %************************************************************************
  547. Note [Work-free values only in environment]
  548. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  549. The sc_vals field keeps track of in-scope value bindings, so
  550. that if we come across (case x of Just y ->...) we can reduce the
  551. case from knowing that x is bound to a pair.
  552. But only *work-free* values are ok here. For example if the envt had
  553. x -> Just (expensive v)
  554. then we do NOT want to expand to
  555. let y = expensive v in ...
  556. because the x-binding still exists and we've now duplicated (expensive v).
  557. This seldom happens because let-bound constructor applications are
  558. ANF-ised, but it can happen as a result of on-the-fly transformations in
  559. SpecConstr itself. Here is Trac #7865:
  560. let {
  561. a'_shr =
  562. case xs_af8 of _ {
  563. [] -> acc_af6;
  564. : ds_dgt [Dmd=<L,A>] ds_dgu [Dmd=<L,A>] ->
  565. (expensive x_af7, x_af7
  566. } } in
  567. let {
  568. ds_sht =
  569. case a'_shr of _ { (p'_afd, q'_afe) ->
  570. TSpecConstr_DoubleInline.recursive
  571. (GHC.Types.: @ GHC.Types.Int x_af7 wild_X6) (q'_afe, p'_afd)
  572. } } in
  573. When processed knowing that xs_af8 was bound to a cons, we simplify to
  574. a'_shr = (expensive x_af7, x_af7)
  575. and we do NOT want to inline that at the occurrence of a'_shr in ds_sht.
  576. (There are other occurrences of a'_shr.) No no no.
  577. It would be possible to do some on-the-fly ANF-ising, so that a'_shr turned
  578. into a work-free value again, thus
  579. a1 = expensive x_af7
  580. a'_shr = (a1, x_af7)
  581. but that's more work, so until its shown to be important I'm going to
  582. leave it for now.
  583. \begin{code}
  584. data ScEnv = SCE { sc_dflags :: DynFlags,
  585. sc_size :: Maybe Int, -- Size threshold
  586. sc_count :: Maybe Int, -- Max # of specialisations for any one fn
  587. -- See Note [Avoiding exponential blowup]
  588. sc_recursive :: Int, -- Max # of specialisations over recursive type.
  589. -- Stops ForceSpecConstr from diverging.
  590. sc_force :: Bool, -- Force specialisation?
  591. -- See Note [Forcing specialisation]
  592. sc_subst :: Subst, -- Current substitution
  593. -- Maps InIds to OutExprs
  594. sc_how_bound :: HowBoundEnv,
  595. -- Binds interesting non-top-level variables
  596. -- Domain is OutVars (*after* applying the substitution)
  597. sc_vals :: ValueEnv,
  598. -- Domain is OutIds (*after* applying the substitution)
  599. -- Used even for top-level bindings (but not imported ones)
  600. -- The range of the ValueEnv is *work-free* values
  601. -- such as (\x. blah), or (Just v)
  602. -- but NOT (Just (expensive v))
  603. -- See Note [Work-free values only in environment]
  604. sc_annotations :: UniqFM SpecConstrAnnotation
  605. }
  606. ---------------------
  607. -- As we go, we apply a substitution (sc_subst) to the current term
  608. type InExpr = CoreExpr -- _Before_ applying the subst
  609. type InVar = Var
  610. type OutExpr = CoreExpr -- _After_ applying the subst
  611. type OutId = Id
  612. type OutVar = Var
  613. ---------------------
  614. type HowBoundEnv = VarEnv HowBound -- Domain is OutVars
  615. ---------------------
  616. type ValueEnv = IdEnv Value -- Domain is OutIds
  617. data Value = ConVal AltCon [CoreArg] -- _Saturated_ constructors
  618. -- The AltCon is never DEFAULT
  619. | LambdaVal -- Inlinable lambdas or PAPs
  620. instance Outputable Value where
  621. ppr (ConVal con args) = ppr con <+> interpp'SP args
  622. ppr LambdaVal = ptext (sLit "<Lambda>")
  623. ---------------------
  624. initScEnv :: DynFlags -> UniqFM SpecConstrAnnotation -> ScEnv
  625. initScEnv dflags anns
  626. = SCE { sc_dflags = dflags,
  627. sc_size = specConstrThreshold dflags,
  628. sc_count = specConstrCount dflags,
  629. sc_recursive = specConstrRecursive dflags,
  630. sc_force = False,
  631. sc_subst = emptySubst,
  632. sc_how_bound = emptyVarEnv,
  633. sc_vals = emptyVarEnv,
  634. sc_annotations = anns }
  635. data HowBound = RecFun -- These are the recursive functions for which
  636. -- we seek interesting call patterns
  637. | RecArg -- These are those functions' arguments, or their sub-components;
  638. -- we gather occurrence information for these
  639. instance Outputable HowBound where
  640. ppr RecFun = text "RecFun"
  641. ppr RecArg = text "RecArg"
  642. scForce :: ScEnv -> Bool -> ScEnv
  643. scForce env b = env { sc_force = b }
  644. lookupHowBound :: ScEnv -> Id -> Maybe HowBound
  645. lookupHowBound env id = lookupVarEnv (sc_how_bound env) id
  646. scSubstId :: ScEnv -> Id -> CoreExpr
  647. scSubstId env v = lookupIdSubst (text "scSubstId") (sc_subst env) v
  648. scSubstTy :: ScEnv -> Type -> Type
  649. scSubstTy env ty = substTy (sc_subst env) ty
  650. scSubstCo :: ScEnv -> Coercion -> Coercion
  651. scSubstCo env co = substCo (sc_subst env) co
  652. zapScSubst :: ScEnv -> ScEnv
  653. zapScSubst env = env { sc_subst = zapSubstEnv (sc_subst env) }
  654. extendScInScope :: ScEnv -> [Var] -> ScEnv
  655. -- Bring the quantified variables into scope
  656. extendScInScope env qvars = env { sc_subst = extendInScopeList (sc_subst env) qvars }
  657. -- Extend the substitution
  658. extendScSubst :: ScEnv -> Var -> OutExpr -> ScEnv
  659. extendScSubst env var expr = env { sc_subst = extendSubst (sc_subst env) var expr }
  660. extendScSubstList :: ScEnv -> [(Var,OutExpr)] -> ScEnv
  661. extendScSubstList env prs = env { sc_subst = extendSubstList (sc_subst env) prs }
  662. extendHowBound :: ScEnv -> [Var] -> HowBound -> ScEnv
  663. extendHowBound env bndrs how_bound
  664. = env { sc_how_bound = extendVarEnvList (sc_how_bound env)
  665. [(bndr,how_bound) | bndr <- bndrs] }
  666. extendBndrsWith :: HowBound -> ScEnv -> [Var] -> (ScEnv, [Var])
  667. extendBndrsWith how_bound env bndrs
  668. = (env { sc_subst = subst', sc_how_bound = hb_env' }, bndrs')
  669. where
  670. (subst', bndrs') = substBndrs (sc_subst env) bndrs
  671. hb_env' = sc_how_bound env `extendVarEnvList`
  672. [(bndr,how_bound) | bndr <- bndrs']
  673. extendBndrWith :: HowBound -> ScEnv -> Var -> (ScEnv, Var)
  674. extendBndrWith how_bound env bndr
  675. = (env { sc_subst = subst', sc_how_bound = hb_env' }, bndr')
  676. where
  677. (subst', bndr') = substBndr (sc_subst env) bndr
  678. hb_env' = extendVarEnv (sc_how_bound env) bndr' how_bound
  679. extendRecBndrs :: ScEnv -> [Var] -> (ScEnv, [Var])
  680. extendRecBndrs env bndrs = (env { sc_subst = subst' }, bndrs')
  681. where
  682. (subst', bndrs') = substRecBndrs (sc_subst env) bndrs
  683. extendBndr :: ScEnv -> Var -> (ScEnv, Var)
  684. extendBndr env bndr = (env { sc_subst = subst' }, bndr')
  685. where
  686. (subst', bndr') = substBndr (sc_subst env) bndr
  687. extendValEnv :: ScEnv -> Id -> Maybe Value -> ScEnv
  688. extendValEnv env _ Nothing = env
  689. extendValEnv env id (Just cv)
  690. | valueIsWorkFree cv -- Don't duplicate work!! Trac #7865
  691. = env { sc_vals = extendVarEnv (sc_vals env) id cv }
  692. extendValEnv env _ _ = env
  693. extendCaseBndrs :: ScEnv -> OutExpr -> OutId -> AltCon -> [Var] -> (ScEnv, [Var])
  694. -- When we encounter
  695. -- case scrut of b
  696. -- C x y -> ...
  697. -- we want to bind b, to (C x y)
  698. -- NB1: Extends only the sc_vals part of the envt
  699. -- NB2: Kill the dead-ness info on the pattern binders x,y, since
  700. -- they are potentially made alive by the [b -> C x y] binding
  701. extendCaseBndrs env scrut case_bndr con alt_bndrs
  702. = (env2, alt_bndrs')
  703. where
  704. live_case_bndr = not (isDeadBinder case_bndr)
  705. env1 | Var v <- scrut = extendValEnv env v cval
  706. | otherwise = env -- See Note [Add scrutinee to ValueEnv too]
  707. env2 | live_case_bndr = extendValEnv env1 case_bndr cval
  708. | otherwise = env1
  709. alt_bndrs' | case scrut of { Var {} -> True; _ -> live_case_bndr }
  710. = map zap alt_bndrs
  711. | otherwise
  712. = alt_bndrs
  713. cval = case con of
  714. DEFAULT -> Nothing
  715. LitAlt {} -> Just (ConVal con [])
  716. DataAlt {} -> Just (ConVal con vanilla_args)
  717. where
  718. vanilla_args = map Type (tyConAppArgs (idType case_bndr)) ++
  719. varsToCoreExprs alt_bndrs
  720. zap v | isTyVar v = v -- See NB2 above
  721. | otherwise = zapIdOccInfo v
  722. decreaseSpecCount :: ScEnv -> Int -> ScEnv
  723. -- See Note [Avoiding exponential blowup]
  724. decreaseSpecCount env n_specs
  725. = env { sc_count = case sc_count env of
  726. Nothing -> Nothing
  727. Just n -> Just (n `div` (n_specs + 1)) }
  728. -- The "+1" takes account of the original function;
  729. -- See Note [Avoiding exponential blowup]
  730. ---------------------------------------------------
  731. -- See Note [SpecConstrAnnotation]
  732. ignoreType :: ScEnv -> Type -> Bool
  733. ignoreDataCon :: ScEnv -> DataCon -> Bool
  734. forceSpecBndr :: ScEnv -> Var -> Bool
  735. #ifndef GHCI
  736. ignoreType _ _ = False
  737. ignoreDataCon _ _ = False
  738. forceSpecBndr _ _ = False
  739. #else /* GHCI */
  740. ignoreDataCon env dc = ignoreTyCon env (dataConTyCon dc)
  741. ignoreType env ty
  742. = case tyConAppTyCon_maybe ty of
  743. Just tycon -> ignoreTyCon env tycon
  744. _ -> False
  745. ignoreTyCon :: ScEnv -> TyCon -> Bool
  746. ignoreTyCon env tycon
  747. = lookupUFM (sc_annotations env) tycon == Just NoSpecConstr
  748. forceSpecBndr env var = forceSpecFunTy env . snd . splitForAllTys . varType $ var
  749. forceSpecFunTy :: ScEnv -> Type -> Bool
  750. forceSpecFunTy env = any (forceSpecArgTy env) . fst . splitFunTys
  751. forceSpecArgTy :: ScEnv -> Type -> Bool
  752. forceSpecArgTy env ty
  753. | Just ty' <- coreView ty = forceSpecArgTy env ty'
  754. forceSpecArgTy env ty
  755. | Just (tycon, tys) <- splitTyConApp_maybe ty
  756. , tycon /= funTyCon
  757. = lookupUFM (sc_annotations env) tycon == Just ForceSpecConstr
  758. || any (forceSpecArgTy env) tys
  759. forceSpecArgTy _ _ = False
  760. #endif /* GHCI */
  761. \end{code}
  762. Note [Add scrutinee to ValueEnv too]
  763. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  764. Consider this:
  765. case x of y
  766. (a,b) -> case b of c
  767. I# v -> ...(f y)...
  768. By the time we get to the call (f y), the ValueEnv
  769. will have a binding for y, and for c
  770. y -> (a,b)
  771. c -> I# v
  772. BUT that's not enough! Looking at the call (f y) we
  773. see that y is pair (a,b), but we also need to know what 'b' is.
  774. So in extendCaseBndrs we must *also* add the binding
  775. b -> I# v
  776. else we lose a useful specialisation for f. This is necessary even
  777. though the simplifier has systematically replaced uses of 'x' with 'y'
  778. and 'b' with 'c' in the code. The use of 'b' in the ValueEnv came
  779. from outside the case. See Trac #4908 for the live example.
  780. Note [Avoiding exponential blowup]
  781. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  782. The sc_count field of the ScEnv says how many times we are prepared to
  783. duplicate a single function. But we must take care with recursive
  784. specialisations. Consider
  785. let $j1 = let $j2 = let $j3 = ...
  786. in
  787. ...$j3...
  788. in
  789. ...$j2...
  790. in
  791. ...$j1...
  792. If we specialise $j1 then in each specialisation (as well as the original)
  793. we can specialise $j2, and similarly $j3. Even if we make just *one*
  794. specialisation of each, because we also have the original we'll get 2^n
  795. copies of $j3, which is not good.
  796. So when recursively specialising we divide the sc_count by the number of
  797. copies we are making at this level, including the original.
  798. %************************************************************************
  799. %* *
  800. \subsection{Usage information: flows upwards}
  801. %* *
  802. %************************************************************************
  803. \begin{code}
  804. data ScUsage
  805. = SCU {
  806. scu_calls :: CallEnv, -- Calls
  807. -- The functions are a subset of the
  808. -- RecFuns in the ScEnv
  809. scu_occs :: !(IdEnv ArgOcc) -- Information on argument occurrences
  810. } -- The domain is OutIds
  811. type CallEnv = IdEnv [Call]
  812. type Call = (ValueEnv, [CoreArg])
  813. -- The arguments of the call, together with the
  814. -- env giving the constructor bindings at the call site
  815. nullUsage :: ScUsage
  816. nullUsage = SCU { scu_calls = emptyVarEnv, scu_occs = emptyVarEnv }
  817. combineCalls :: CallEnv -> CallEnv -> CallEnv
  818. combineCalls = plusVarEnv_C (++)
  819. combineUsage :: ScUsage -> ScUsage -> ScUsage
  820. combineUsage u1 u2 = SCU { scu_calls = combineCalls (scu_calls u1) (scu_calls u2),
  821. scu_occs = plusVarEnv_C combineOcc (scu_occs u1) (scu_occs u2) }
  822. combineUsages :: [ScUsage] -> ScUsage
  823. combineUsages [] = nullUsage
  824. combineUsages us = foldr1 combineUsage us
  825. lookupOccs :: ScUsage -> [OutVar] -> (ScUsage, [ArgOcc])
  826. lookupOccs (SCU { scu_calls = sc_calls, scu_occs = sc_occs }) bndrs
  827. = (SCU {scu_calls = sc_calls, scu_occs = delVarEnvList sc_occs bndrs},
  828. [lookupVarEnv sc_occs b `orElse` NoOcc | b <- bndrs])
  829. data ArgOcc = NoOcc -- Doesn't occur at all; or a type argument
  830. | UnkOcc -- Used in some unknown way
  831. | ScrutOcc -- See Note [ScrutOcc]
  832. (DataConEnv [ArgOcc]) -- How the sub-components are used
  833. type DataConEnv a = UniqFM a -- Keyed by DataCon
  834. {- Note [ScrutOcc]
  835. ~~~~~~~~~~~~~~~~~~~
  836. An occurrence of ScrutOcc indicates that the thing, or a `cast` version of the thing,
  837. is *only* taken apart or applied.
  838. Functions, literal: ScrutOcc emptyUFM
  839. Data constructors: ScrutOcc subs,
  840. where (subs :: UniqFM [ArgOcc]) gives usage of the *pattern-bound* components,
  841. The domain of the UniqFM is the Unique of the data constructor
  842. The [ArgOcc] is the occurrences of the *pattern-bound* components
  843. of the data structure. E.g.
  844. data T a = forall b. MkT a b (b->a)
  845. A pattern binds b, x::a, y::b, z::b->a, but not 'a'!
  846. -}
  847. instance Outputable ArgOcc where
  848. ppr (ScrutOcc xs) = ptext (sLit "scrut-occ") <> ppr xs
  849. ppr UnkOcc = ptext (sLit "unk-occ")
  850. ppr NoOcc = ptext (sLit "no-occ")
  851. evalScrutOcc :: ArgOcc
  852. evalScrutOcc = ScrutOcc emptyUFM
  853. -- Experimentally, this vesion of combineOcc makes ScrutOcc "win", so
  854. -- that if the thing is scrutinised anywhere then we get to see that
  855. -- in the overall result, even if it's also used in a boxed way
  856. -- This might be too agressive; see Note [Reboxing] Alternative 3
  857. combineOcc :: ArgOcc -> ArgOcc -> ArgOcc
  858. combineOcc NoOcc occ = occ
  859. combineOcc occ NoOcc = occ
  860. combineOcc (ScrutOcc xs) (ScrutOcc ys) = ScrutOcc (plusUFM_C combineOccs xs ys)
  861. combineOcc UnkOcc (ScrutOcc ys) = ScrutOcc ys
  862. combineOcc (ScrutOcc xs) UnkOcc = ScrutOcc xs
  863. combineOcc UnkOcc UnkOcc = UnkOcc
  864. combineOccs :: [ArgOcc] -> [ArgOcc] -> [ArgOcc]
  865. combineOccs xs ys = zipWithEqual "combineOccs" combineOcc xs ys
  866. setScrutOcc :: ScEnv -> ScUsage -> OutExpr -> ArgOcc -> ScUsage
  867. -- _Overwrite_ the occurrence info for the scrutinee, if the scrutinee
  868. -- is a variable, and an interesting variable
  869. setScrutOcc env usg (Cast e _) occ = setScrutOcc env usg e occ
  870. setScrutOcc env usg (Tick _ e) occ = setScrutOcc env usg e occ
  871. setScrutOcc env usg (Var v) occ
  872. | Just RecArg <- lookupHowBound env v = usg { scu_occs = extendVarEnv (scu_occs usg) v occ }
  873. | otherwise = usg
  874. setScrutOcc _env usg _other _occ -- Catch-all
  875. = usg
  876. \end{code}
  877. %************************************************************************
  878. %* *
  879. \subsection{The main recursive function}
  880. %* *
  881. %************************************************************************
  882. The main recursive function gathers up usage information, and
  883. creates specialised versions of functions.
  884. \begin{code}
  885. scExpr, scExpr' :: ScEnv -> CoreExpr -> UniqSM (ScUsage, CoreExpr)
  886. -- The unique supply is needed when we invent
  887. -- a new name for the specialised function and its args
  888. scExpr env e = scExpr' env e
  889. scExpr' env (Var v) = case scSubstId env v of
  890. Var v' -> return (mkVarUsage env v' [], Var v')
  891. e' -> scExpr (zapScSubst env) e'
  892. scExpr' env (Type t) = return (nullUsage, Type (scSubstTy env t))
  893. scExpr' env (Coercion c) = return (nullUsage, Coercion (scSubstCo env c))
  894. scExpr' _ e@(Lit {}) = return (nullUsage, e)
  895. scExpr' env (Tick t e) = do (usg, e') <- scExpr env e
  896. return (usg, Tick t e')
  897. scExpr' env (Cast e co) = do (usg, e') <- scExpr env e
  898. return (usg, Cast e' (scSubstCo env co))
  899. scExpr' env e@(App _ _) = scApp env (collectArgs e)
  900. scExpr' env (Lam b e) = do let (env', b') = extendBndr env b
  901. (usg, e') <- scExpr env' e
  902. return (usg, Lam b' e')
  903. scExpr' env (Case scrut b ty alts)
  904. = do { (scrut_usg, scrut') <- scExpr env scrut
  905. ; case isValue (sc_vals env) scrut' of
  906. Just (ConVal con args) -> sc_con_app con args scrut'
  907. _other -> sc_vanilla scrut_usg scrut'
  908. }
  909. where
  910. sc_con_app con args scrut' -- Known constructor; simplify
  911. = do { let (_, bs, rhs) = findAlt con alts
  912. `orElse` (DEFAULT, [], mkImpossibleExpr ty)
  913. alt_env' = extendScSubstList env ((b,scrut') : bs `zip` trimConArgs con args)
  914. ; scExpr alt_env' rhs }
  915. sc_vanilla scrut_usg scrut' -- Normal case
  916. = do { let (alt_env,b') = extendBndrWith RecArg env b
  917. -- Record RecArg for the components
  918. ; (alt_usgs, alt_occs, alts')
  919. <- mapAndUnzip3M (sc_alt alt_env scrut' b') alts
  920. ; let scrut_occ = foldr combineOcc NoOcc alt_occs
  921. scrut_usg' = setScrutOcc env scrut_usg scrut' scrut_occ
  922. -- The combined usage of the scrutinee is given
  923. -- by scrut_occ, which is passed to scScrut, which
  924. -- in turn treats a bare-variable scrutinee specially
  925. ; return (foldr combineUsage scrut_usg' alt_usgs,
  926. Case scrut' b' (scSubstTy env ty) alts') }
  927. sc_alt env scrut' b' (con,bs,rhs)
  928. = do { let (env1, bs1) = extendBndrsWith RecArg env bs
  929. (env2, bs2) = extendCaseBndrs env1 scrut' b' con bs1
  930. ; (usg, rhs') <- scExpr env2 rhs
  931. ; let (usg', b_occ:arg_occs) = lookupOccs usg (b':bs2)
  932. scrut_occ = case con of
  933. DataAlt dc -> ScrutOcc (unitUFM dc arg_occs)
  934. _ -> ScrutOcc emptyUFM
  935. ; return (usg', b_occ `combineOcc` scrut_occ, (con, bs2, rhs')) }
  936. scExpr' env (Let (NonRec bndr rhs) body)
  937. | isTyVar bndr -- Type-lets may be created by doBeta
  938. = scExpr' (extendScSubst env bndr rhs) body
  939. | otherwise
  940. = do { let (body_env, bndr') = extendBndr env bndr
  941. ; (rhs_usg, rhs_info) <- scRecRhs env (bndr',rhs)
  942. ; let body_env2 = extendHowBound body_env [bndr'] RecFun
  943. -- Note [Local let bindings]
  944. RI _ rhs' _ _ _ = rhs_info
  945. body_env3 = extendValEnv body_env2 bndr' (isValue (sc_vals env) rhs')
  946. ; (body_usg, body') <- scExpr body_env3 body
  947. -- NB: For non-recursive bindings we inherit sc_force flag from
  948. -- the parent function (see Note [Forcing specialisation])
  949. ; (spec_usg, specs) <- specialise env
  950. (scu_calls body_usg)
  951. rhs_info
  952. (SI [] 0 (Just rhs_usg))
  953. ; return (body_usg { scu_calls = scu_calls body_usg `delVarEnv` bndr' }
  954. `combineUsage` rhs_usg `combineUsage` spec_usg,
  955. mkLets [NonRec b r | (b,r) <- specInfoBinds rhs_info specs] body')
  956. }
  957. -- A *local* recursive group: see Note [Local recursive groups]
  958. scExpr' env (Let (Rec prs) body)
  959. = do { let (bndrs,rhss) = unzip prs
  960. (rhs_env1,bndrs') = extendRecBndrs env bndrs
  961. rhs_env2 = extendHowBound rhs_env1 bndrs' RecFun
  962. force_spec = any (forceSpecBndr env) bndrs'
  963. -- Note [Forcing specialisation]
  964. ; (rhs_usgs, rhs_infos) <- mapAndUnzipM (scRecRhs rhs_env2) (bndrs' `zip` rhss)
  965. ; (body_usg, body') <- scExpr rhs_env2 body
  966. -- NB: start specLoop from body_usg
  967. ; (spec_usg, specs) <- specLoop (scForce rhs_env2 force_spec)
  968. (scu_calls body_usg) rhs_infos nullUsage
  969. [SI [] 0 (Just usg) | usg <- rhs_usgs]
  970. -- Do not unconditionally generate specialisations from rhs_usgs
  971. -- Instead use them only if we find an unspecialised call
  972. -- See Note [Local recursive groups]
  973. ; let rhs_usg = combineUsages rhs_usgs
  974. all_usg = spec_usg `combineUsage` rhs_usg `combineUsage` body_usg
  975. bind' = Rec (concat (zipWith specInfoBinds rhs_infos specs))
  976. ; return (all_usg { scu_calls = scu_calls all_usg `delVarEnvList` bndrs' },
  977. Let bind' body') }
  978. \end{code}
  979. Note [Local let bindings]
  980. ~~~~~~~~~~~~~~~~~~~~~~~~~
  981. It is not uncommon to find this
  982. let $j = \x. <blah> in ...$j True...$j True...
  983. Here $j is an arbitrary let-bound function, but it often comes up for
  984. join points. We might like to specialise $j for its call patterns.
  985. Notice the difference from a letrec, where we look for call patterns
  986. in the *RHS* of the function. Here we look for call patterns in the
  987. *body* of the let.
  988. At one point I predicated this on the RHS mentioning the outer
  989. recursive function, but that's not essential and might even be
  990. harmful. I'm not sure.
  991. \begin{code}
  992. scApp :: ScEnv -> (InExpr, [InExpr]) -> UniqSM (ScUsage, CoreExpr)
  993. scApp env (Var fn, args) -- Function is a variable
  994. = ASSERT( not (null args) )
  995. do { args_w_usgs <- mapM (scExpr env) args
  996. ; let (arg_usgs, args') = unzip args_w_usgs
  997. arg_usg = combineUsages arg_usgs
  998. ; case scSubstId env fn of
  999. fn'@(Lam {}) -> scExpr (zapScSubst env) (doBeta fn' args')
  1000. -- Do beta-reduction and try again
  1001. Var fn' -> return (arg_usg `combineUsage` mkVarUsage env fn' args',
  1002. mkApps (Var fn') args')
  1003. other_fn' -> return (arg_usg, mkApps other_fn' args') }
  1004. -- NB: doing this ignores any usage info from the substituted
  1005. -- function, but I don't think that matters. If it does
  1006. -- we can fix it.
  1007. where
  1008. doBeta :: OutExpr -> [OutExpr] -> OutExpr
  1009. -- ToDo: adjust for System IF
  1010. doBeta (Lam bndr body) (arg : args) = Let (NonRec bndr arg) (doBeta body args)
  1011. doBeta fn args = mkApps fn args
  1012. -- The function is almost always a variable, but not always.
  1013. -- In particular, if this pass follows float-in,
  1014. -- which it may, we can get
  1015. -- (let f = ...f... in f) arg1 arg2
  1016. scApp env (other_fn, args)
  1017. = do { (fn_usg, fn') <- scExpr env other_fn
  1018. ; (arg_usgs, args') <- mapAndUnzipM (scExpr env) args
  1019. ; return (combineUsages arg_usgs `combineUsage` fn_usg, mkApps fn' args') }
  1020. ----------------------
  1021. mkVarUsage :: ScEnv -> Id -> [CoreExpr] -> ScUsage
  1022. mkVarUsage env fn args
  1023. = case lookupHowBound env fn of
  1024. Just RecFun -> SCU { scu_calls = unitVarEnv fn [(sc_vals env, args)]
  1025. , scu_occs = emptyVarEnv }
  1026. Just RecArg -> SCU { scu_calls = emptyVarEnv
  1027. , scu_occs = unitVarEnv fn arg_occ }
  1028. Nothing -> nullUsage
  1029. where
  1030. -- I rather think we could use UnkOcc all the time
  1031. arg_occ | null args = UnkOcc
  1032. | otherwise = evalScrutOcc
  1033. ----------------------
  1034. scTopBindEnv :: ScEnv -> CoreBind -> UniqSM (ScEnv, CoreBind)
  1035. scTopBindEnv env (Rec prs)
  1036. = do { let (rhs_env1,bndrs') = extendRecBndrs env bndrs
  1037. rhs_env2 = extendHowBound rhs_env1 bndrs RecFun
  1038. prs' = zip bndrs' rhss
  1039. ; return (r

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