PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/specialise/SpecConstr.hs

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

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