PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/compiler/simplCore/FloatIn.lhs

https://bitbucket.org/khibino/ghc-hack
Haskell | 522 lines | 371 code | 96 blank | 55 comment | 21 complexity | 1b5032d850337c41b468e43cae97e5d9 MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause, LGPL-3.0
  1. %
  2. % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
  3. %
  4. %************************************************************************
  5. %* *
  6. \section[FloatIn]{Floating Inwards pass}
  7. %* *
  8. %************************************************************************
  9. The main purpose of @floatInwards@ is floating into branches of a
  10. case, so that we don't allocate things, save them on the stack, and
  11. then discover that they aren't needed in the chosen branch.
  12. \begin{code}
  13. {-# OPTIONS -fno-warn-tabs #-}
  14. -- The above warning supression flag is a temporary kludge.
  15. -- While working on this module you are encouraged to remove it and
  16. -- detab the module (please do the detabbing in a separate patch). See
  17. -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
  18. -- for details
  19. module FloatIn ( floatInwards ) where
  20. #include "HsVersions.h"
  21. import CoreSyn
  22. import MkCore
  23. import CoreUtils ( exprIsDupable, exprIsExpandable, exprOkForSideEffects )
  24. import CoreFVs ( CoreExprWithFVs, freeVars, freeVarsOf, idRuleAndUnfoldingVars )
  25. import Id ( isOneShotBndr, idType )
  26. import Var
  27. import Type ( isUnLiftedType )
  28. import VarSet
  29. import Util ( zipEqual, zipWithEqual, count )
  30. import UniqFM
  31. import Outputable
  32. \end{code}
  33. Top-level interface function, @floatInwards@. Note that we do not
  34. actually float any bindings downwards from the top-level.
  35. \begin{code}
  36. floatInwards :: CoreProgram -> CoreProgram
  37. floatInwards = map fi_top_bind
  38. where
  39. fi_top_bind (NonRec binder rhs)
  40. = NonRec binder (fiExpr [] (freeVars rhs))
  41. fi_top_bind (Rec pairs)
  42. = Rec [ (b, fiExpr [] (freeVars rhs)) | (b, rhs) <- pairs ]
  43. \end{code}
  44. %************************************************************************
  45. %* *
  46. \subsection{Mail from Andr\'e [edited]}
  47. %* *
  48. %************************************************************************
  49. {\em Will wrote: What??? I thought the idea was to float as far
  50. inwards as possible, no matter what. This is dropping all bindings
  51. every time it sees a lambda of any kind. Help! }
  52. You are assuming we DO DO full laziness AFTER floating inwards! We
  53. have to [not float inside lambdas] if we don't.
  54. If we indeed do full laziness after the floating inwards (we could
  55. check the compilation flags for that) then I agree we could be more
  56. aggressive and do float inwards past lambdas.
  57. Actually we are not doing a proper full laziness (see below), which
  58. was another reason for not floating inwards past a lambda.
  59. This can easily be fixed. The problem is that we float lets outwards,
  60. but there are a few expressions which are not let bound, like case
  61. scrutinees and case alternatives. After floating inwards the
  62. simplifier could decide to inline the let and the laziness would be
  63. lost, e.g.
  64. \begin{verbatim}
  65. let a = expensive ==> \b -> case expensive of ...
  66. in \ b -> case a of ...
  67. \end{verbatim}
  68. The fix is
  69. \begin{enumerate}
  70. \item
  71. to let bind the algebraic case scrutinees (done, I think) and
  72. the case alternatives (except the ones with an
  73. unboxed type)(not done, I think). This is best done in the
  74. SetLevels.lhs module, which tags things with their level numbers.
  75. \item
  76. do the full laziness pass (floating lets outwards).
  77. \item
  78. simplify. The simplifier inlines the (trivial) lets that were
  79. created but were not floated outwards.
  80. \end{enumerate}
  81. With the fix I think Will's suggestion that we can gain even more from
  82. strictness by floating inwards past lambdas makes sense.
  83. We still gain even without going past lambdas, as things may be
  84. strict in the (new) context of a branch (where it was floated to) or
  85. of a let rhs, e.g.
  86. \begin{verbatim}
  87. let a = something case x of
  88. in case x of alt1 -> case something of a -> a + a
  89. alt1 -> a + a ==> alt2 -> b
  90. alt2 -> b
  91. let a = something let b = case something of a -> a + a
  92. in let b = a + a ==> in (b,b)
  93. in (b,b)
  94. \end{verbatim}
  95. Also, even if a is not found to be strict in the new context and is
  96. still left as a let, if the branch is not taken (or b is not entered)
  97. the closure for a is not built.
  98. %************************************************************************
  99. %* *
  100. \subsection{Main floating-inwards code}
  101. %* *
  102. %************************************************************************
  103. \begin{code}
  104. type FreeVarSet = IdSet
  105. type BoundVarSet = IdSet
  106. data FloatInBind = FB BoundVarSet FreeVarSet FloatBind
  107. -- The FreeVarSet is the free variables of the binding. In the case
  108. -- of recursive bindings, the set doesn't include the bound
  109. -- variables.
  110. type FloatInBinds = [FloatInBind]
  111. -- In reverse dependency order (innermost binder first)
  112. fiExpr :: FloatInBinds -- Binds we're trying to drop
  113. -- as far "inwards" as possible
  114. -> CoreExprWithFVs -- Input expr
  115. -> CoreExpr -- Result
  116. fiExpr to_drop (_, AnnLit lit) = ASSERT( null to_drop ) Lit lit
  117. fiExpr to_drop (_, AnnType ty) = ASSERT( null to_drop ) Type ty
  118. fiExpr to_drop (_, AnnVar v) = wrapFloats to_drop (Var v)
  119. fiExpr to_drop (_, AnnCoercion co) = wrapFloats to_drop (Coercion co)
  120. fiExpr to_drop (_, AnnCast expr (fvs_co, co))
  121. = wrapFloats (drop_here ++ co_drop) $
  122. Cast (fiExpr e_drop expr) co
  123. where
  124. [drop_here, e_drop, co_drop] = sepBindsByDropPoint False [freeVarsOf expr, fvs_co] to_drop
  125. \end{code}
  126. Applications: we do float inside applications, mainly because we
  127. need to get at all the arguments. The next simplifier run will
  128. pull out any silly ones.
  129. \begin{code}
  130. fiExpr to_drop (_,AnnApp fun arg@(arg_fvs, ann_arg))
  131. | noFloatIntoRhs ann_arg = wrapFloats drop_here $ wrapFloats arg_drop $
  132. App (fiExpr fun_drop fun) (fiExpr [] arg)
  133. -- It's inconvenient to test for an unlifted arg here,
  134. -- and it really doesn't matter if we float into one
  135. | otherwise = wrapFloats drop_here $
  136. App (fiExpr fun_drop fun) (fiExpr arg_drop arg)
  137. where
  138. [drop_here, fun_drop, arg_drop]
  139. = sepBindsByDropPoint False [freeVarsOf fun, arg_fvs] to_drop
  140. \end{code}
  141. Note [Floating in past a lambda group]
  142. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  143. * We must be careful about floating inside inside a value lambda.
  144. That risks losing laziness.
  145. The float-out pass might rescue us, but then again it might not.
  146. * We must be careful about type lambdas too. At one time we did, and
  147. there is no risk of duplicating work thereby, but we do need to be
  148. careful. In particular, here is a bad case (it happened in the
  149. cichelli benchmark:
  150. let v = ...
  151. in let f = /\t -> \a -> ...
  152. ==>
  153. let f = /\t -> let v = ... in \a -> ...
  154. This is bad as now f is an updatable closure (update PAP)
  155. and has arity 0.
  156. * Hack alert! We only float in through one-shot lambdas,
  157. not (as you might guess) through lone big lambdas.
  158. Reason: we float *out* past big lambdas (see the test in the Lam
  159. case of FloatOut.floatExpr) and we don't want to float straight
  160. back in again.
  161. It *is* important to float into one-shot lambdas, however;
  162. see the remarks with noFloatIntoRhs.
  163. So we treat lambda in groups, using the following rule:
  164. Float in if (a) there is at least one Id,
  165. and (b) there are no non-one-shot Ids
  166. Otherwise drop all the bindings outside the group.
  167. This is what the 'go' function in the AnnLam case is doing.
  168. Urk! if all are tyvars, and we don't float in, we may miss an
  169. opportunity to float inside a nested case branch
  170. \begin{code}
  171. fiExpr to_drop lam@(_, AnnLam _ _)
  172. | go False bndrs -- Float in
  173. = mkLams bndrs (fiExpr to_drop body)
  174. | otherwise -- Dump it all here
  175. = wrapFloats to_drop (mkLams bndrs (fiExpr [] body))
  176. where
  177. (bndrs, body) = collectAnnBndrs lam
  178. go seen_one_shot_id [] = seen_one_shot_id
  179. go seen_one_shot_id (b:bs)
  180. | isTyVar b = go seen_one_shot_id bs
  181. | isOneShotBndr b = go True bs
  182. | otherwise = False -- Give up at a non-one-shot Id
  183. \end{code}
  184. We don't float lets inwards past an SCC.
  185. ToDo: keep info on current cc, and when passing
  186. one, if it is not the same, annotate all lets in binds with current
  187. cc, change current cc to the new one and float binds into expr.
  188. \begin{code}
  189. fiExpr to_drop (_, AnnTick tickish expr)
  190. | tickishScoped tickish
  191. = -- Wimp out for now - we could push values in
  192. wrapFloats to_drop (Tick tickish (fiExpr [] expr))
  193. | otherwise
  194. = Tick tickish (fiExpr to_drop expr)
  195. \end{code}
  196. For @Lets@, the possible ``drop points'' for the \tr{to_drop}
  197. bindings are: (a)~in the body, (b1)~in the RHS of a NonRec binding,
  198. or~(b2), in each of the RHSs of the pairs of a @Rec@.
  199. Note that we do {\em weird things} with this let's binding. Consider:
  200. \begin{verbatim}
  201. let
  202. w = ...
  203. in {
  204. let v = ... w ...
  205. in ... v .. w ...
  206. }
  207. \end{verbatim}
  208. Look at the inner \tr{let}. As \tr{w} is used in both the bind and
  209. body of the inner let, we could panic and leave \tr{w}'s binding where
  210. it is. But \tr{v} is floatable further into the body of the inner let, and
  211. {\em then} \tr{w} will also be only in the body of that inner let.
  212. So: rather than drop \tr{w}'s binding here, we add it onto the list of
  213. things to drop in the outer let's body, and let nature take its
  214. course.
  215. Note [extra_fvs (1): avoid floating into RHS]
  216. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  217. Consdider let x=\y....t... in body. We do not necessarily want to float
  218. a binding for t into the RHS, because it'll immediately be floated out
  219. again. (It won't go inside the lambda else we risk losing work.)
  220. In letrec, we need to be more careful still. We don't want to transform
  221. let x# = y# +# 1#
  222. in
  223. letrec f = \z. ...x#...f...
  224. in ...
  225. into
  226. letrec f = let x# = y# +# 1# in \z. ...x#...f... in ...
  227. because now we can't float the let out again, because a letrec
  228. can't have unboxed bindings.
  229. So we make "extra_fvs" which is the rhs_fvs of such bindings, and
  230. arrange to dump bindings that bind extra_fvs before the entire let.
  231. Note [extra_fvs (2): free variables of rules]
  232. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  233. Consider
  234. let x{rule mentioning y} = rhs in body
  235. Here y is not free in rhs or body; but we still want to dump bindings
  236. that bind y outside the let. So we augment extra_fvs with the
  237. idRuleAndUnfoldingVars of x. No need for type variables, hence not using
  238. idFreeVars.
  239. \begin{code}
  240. fiExpr to_drop (_,AnnLet (AnnNonRec id rhs@(rhs_fvs, ann_rhs)) body)
  241. = fiExpr new_to_drop body
  242. where
  243. body_fvs = freeVarsOf body `delVarSet` id
  244. rule_fvs = idRuleAndUnfoldingVars id -- See Note [extra_fvs (2): free variables of rules]
  245. extra_fvs | noFloatIntoRhs ann_rhs
  246. || isUnLiftedType (idType id) = rule_fvs `unionVarSet` rhs_fvs
  247. | otherwise = rule_fvs
  248. -- See Note [extra_fvs (1): avoid floating into RHS]
  249. -- No point in floating in only to float straight out again
  250. -- Ditto ok-for-speculation unlifted RHSs
  251. [shared_binds, extra_binds, rhs_binds, body_binds]
  252. = sepBindsByDropPoint False [extra_fvs, rhs_fvs, body_fvs] to_drop
  253. new_to_drop = body_binds ++ -- the bindings used only in the body
  254. [FB (unitVarSet id) rhs_fvs'
  255. (FloatLet (NonRec id rhs'))] ++ -- the new binding itself
  256. extra_binds ++ -- bindings from extra_fvs
  257. shared_binds -- the bindings used both in rhs and body
  258. -- Push rhs_binds into the right hand side of the binding
  259. rhs' = fiExpr rhs_binds rhs
  260. rhs_fvs' = rhs_fvs `unionVarSet` floatedBindsFVs rhs_binds `unionVarSet` rule_fvs
  261. -- Don't forget the rule_fvs; the binding mentions them!
  262. fiExpr to_drop (_,AnnLet (AnnRec bindings) body)
  263. = fiExpr new_to_drop body
  264. where
  265. (ids, rhss) = unzip bindings
  266. rhss_fvs = map freeVarsOf rhss
  267. body_fvs = freeVarsOf body
  268. -- See Note [extra_fvs (1,2)]
  269. rule_fvs = foldr (unionVarSet . idRuleAndUnfoldingVars) emptyVarSet ids
  270. extra_fvs = rule_fvs `unionVarSet`
  271. unionVarSets [ fvs | (fvs, rhs) <- rhss
  272. , noFloatIntoRhs rhs ]
  273. (shared_binds:extra_binds:body_binds:rhss_binds)
  274. = sepBindsByDropPoint False (extra_fvs:body_fvs:rhss_fvs) to_drop
  275. new_to_drop = body_binds ++ -- the bindings used only in the body
  276. [FB (mkVarSet ids) rhs_fvs'
  277. (FloatLet (Rec (fi_bind rhss_binds bindings)))] ++
  278. -- The new binding itself
  279. extra_binds ++ -- Note [extra_fvs (1,2)]
  280. shared_binds -- Used in more than one place
  281. rhs_fvs' = unionVarSets rhss_fvs `unionVarSet`
  282. unionVarSets (map floatedBindsFVs rhss_binds) `unionVarSet`
  283. rule_fvs -- Don't forget the rule variables!
  284. -- Push rhs_binds into the right hand side of the binding
  285. fi_bind :: [FloatInBinds] -- one per "drop pt" conjured w/ fvs_of_rhss
  286. -> [(Id, CoreExprWithFVs)]
  287. -> [(Id, CoreExpr)]
  288. fi_bind to_drops pairs
  289. = [ (binder, fiExpr to_drop rhs)
  290. | ((binder, rhs), to_drop) <- zipEqual "fi_bind" pairs to_drops ]
  291. \end{code}
  292. For @Case@, the possible ``drop points'' for the \tr{to_drop}
  293. bindings are: (a)~inside the scrutinee, (b)~inside one of the
  294. alternatives/default [default FVs always {\em first}!].
  295. \begin{code}
  296. fiExpr to_drop (_, AnnCase scrut case_bndr _ [(DEFAULT,[],rhs)])
  297. | isUnLiftedType (idType case_bndr)
  298. , exprOkForSideEffects (deAnnotate scrut)
  299. = wrapFloats shared_binds $
  300. fiExpr (case_float : rhs_binds) rhs
  301. where
  302. case_float = FB (unitVarSet case_bndr) scrut_fvs
  303. (FloatCase scrut' case_bndr DEFAULT [])
  304. scrut' = fiExpr scrut_binds scrut
  305. [shared_binds, scrut_binds, rhs_binds]
  306. = sepBindsByDropPoint False [freeVarsOf scrut, rhs_fvs] to_drop
  307. rhs_fvs = freeVarsOf rhs `delVarSet` case_bndr
  308. scrut_fvs = freeVarsOf scrut
  309. fiExpr to_drop (_, AnnCase scrut case_bndr ty alts)
  310. = wrapFloats drop_here1 $
  311. wrapFloats drop_here2 $
  312. Case (fiExpr scrut_drops scrut) case_bndr ty
  313. (zipWith fi_alt alts_drops_s alts)
  314. where
  315. -- Float into the scrut and alts-considered-together just like App
  316. [drop_here1, scrut_drops, alts_drops]
  317. = sepBindsByDropPoint False [scrut_fvs, all_alts_fvs] to_drop
  318. -- Float into the alts with the is_case flag set
  319. (drop_here2 : alts_drops_s) = sepBindsByDropPoint True alts_fvs alts_drops
  320. scrut_fvs = freeVarsOf scrut
  321. alts_fvs = map alt_fvs alts
  322. all_alts_fvs = unionVarSets alts_fvs
  323. alt_fvs (_con, args, rhs) = foldl delVarSet (freeVarsOf rhs) (case_bndr:args)
  324. -- Delete case_bndr and args from free vars of rhs
  325. -- to get free vars of alt
  326. fi_alt to_drop (con, args, rhs) = (con, args, fiExpr to_drop rhs)
  327. noFloatIntoRhs :: AnnExpr' Var (UniqFM Var) -> Bool
  328. noFloatIntoRhs (AnnLam b _) = not (is_one_shot b)
  329. -- IMPORTANT: don't say 'True' for a RHS with a one-shot lambda at the top.
  330. -- This makes a big difference for things like
  331. -- f x# = let x = I# x#
  332. -- in let j = \() -> ...x...
  333. -- in if <condition> then normal-path else j ()
  334. -- If x is used only in the error case join point, j, we must float the
  335. -- boxing constructor into it, else we box it every time which is very bad
  336. -- news indeed.
  337. noFloatIntoRhs rhs = exprIsExpandable (deAnnotate' rhs)
  338. -- We'd just float right back out again...
  339. -- Should match the test in SimplEnv.doFloatFromRhs
  340. is_one_shot :: Var -> Bool
  341. is_one_shot b = isId b && isOneShotBndr b
  342. \end{code}
  343. %************************************************************************
  344. %* *
  345. \subsection{@sepBindsByDropPoint@}
  346. %* *
  347. %************************************************************************
  348. This is the crucial function. The idea is: We have a wad of bindings
  349. that we'd like to distribute inside a collection of {\em drop points};
  350. insides the alternatives of a \tr{case} would be one example of some
  351. drop points; the RHS and body of a non-recursive \tr{let} binding
  352. would be another (2-element) collection.
  353. So: We're given a list of sets-of-free-variables, one per drop point,
  354. and a list of floating-inwards bindings. If a binding can go into
  355. only one drop point (without suddenly making something out-of-scope),
  356. in it goes. If a binding is used inside {\em multiple} drop points,
  357. then it has to go in a you-must-drop-it-above-all-these-drop-points
  358. point.
  359. We have to maintain the order on these drop-point-related lists.
  360. \begin{code}
  361. sepBindsByDropPoint
  362. :: Bool -- True <=> is case expression
  363. -> [FreeVarSet] -- One set of FVs per drop point
  364. -> FloatInBinds -- Candidate floaters
  365. -> [FloatInBinds] -- FIRST one is bindings which must not be floated
  366. -- inside any drop point; the rest correspond
  367. -- one-to-one with the input list of FV sets
  368. -- Every input floater is returned somewhere in the result;
  369. -- none are dropped, not even ones which don't seem to be
  370. -- free in *any* of the drop-point fvs. Why? Because, for example,
  371. -- a binding (let x = E in B) might have a specialised version of
  372. -- x (say x') stored inside x, but x' isn't free in E or B.
  373. type DropBox = (FreeVarSet, FloatInBinds)
  374. sepBindsByDropPoint _is_case drop_pts []
  375. = [] : [[] | _ <- drop_pts] -- cut to the chase scene; it happens
  376. sepBindsByDropPoint is_case drop_pts floaters
  377. = go floaters (map (\fvs -> (fvs, [])) (emptyVarSet : drop_pts))
  378. where
  379. go :: FloatInBinds -> [DropBox] -> [FloatInBinds]
  380. -- The *first* one in the argument list is the drop_here set
  381. -- The FloatInBinds in the lists are in the reverse of
  382. -- the normal FloatInBinds order; that is, they are the right way round!
  383. go [] drop_boxes = map (reverse . snd) drop_boxes
  384. go (bind_w_fvs@(FB bndrs bind_fvs bind) : binds) drop_boxes@(here_box : fork_boxes)
  385. = go binds new_boxes
  386. where
  387. -- "here" means the group of bindings dropped at the top of the fork
  388. (used_here : used_in_flags) = [ fvs `intersectsVarSet` bndrs
  389. | (fvs, _) <- drop_boxes]
  390. drop_here = used_here || not can_push
  391. -- For case expressions we duplicate the binding if it is
  392. -- reasonably small, and if it is not used in all the RHSs
  393. -- This is good for situations like
  394. -- let x = I# y in
  395. -- case e of
  396. -- C -> error x
  397. -- D -> error x
  398. -- E -> ...not mentioning x...
  399. n_alts = length used_in_flags
  400. n_used_alts = count id used_in_flags -- returns number of Trues in list.
  401. can_push = n_used_alts == 1 -- Used in just one branch
  402. || (is_case && -- We are looking at case alternatives
  403. n_used_alts > 1 && -- It's used in more than one
  404. n_used_alts < n_alts && -- ...but not all
  405. floatIsDupable bind) -- and we can duplicate the binding
  406. new_boxes | drop_here = (insert here_box : fork_boxes)
  407. | otherwise = (here_box : new_fork_boxes)
  408. new_fork_boxes = zipWithEqual "FloatIn.sepBinds" insert_maybe fork_boxes used_in_flags
  409. insert :: DropBox -> DropBox
  410. insert (fvs,drops) = (fvs `unionVarSet` bind_fvs, bind_w_fvs:drops)
  411. insert_maybe box True = insert box
  412. insert_maybe box False = box
  413. go _ _ = panic "sepBindsByDropPoint/go"
  414. floatedBindsFVs :: FloatInBinds -> FreeVarSet
  415. floatedBindsFVs binds = foldr (unionVarSet . fbFVs) emptyVarSet binds
  416. fbFVs :: FloatInBind -> VarSet
  417. fbFVs (FB _ fvs _) = fvs
  418. wrapFloats :: FloatInBinds -> CoreExpr -> CoreExpr
  419. -- Remember FloatInBinds is in *reverse* dependency order
  420. wrapFloats [] e = e
  421. wrapFloats (FB _ _ fl : bs) e = wrapFloats bs (wrapFloat fl e)
  422. floatIsDupable :: FloatBind -> Bool
  423. floatIsDupable (FloatCase scrut _ _ _) = exprIsDupable scrut
  424. floatIsDupable (FloatLet (Rec prs)) = all (exprIsDupable . snd) prs
  425. floatIsDupable (FloatLet (NonRec _ r)) = exprIsDupable r
  426. \end{code}