PageRenderTime 69ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 1ms

/ghc-7.0.4/compiler/simplCore/OccurAnal.lhs

http://picorec.googlecode.com/
Haskell | 1693 lines | 1155 code | 295 blank | 243 comment | 76 complexity | f398f09772414abaf938f8e8e123fb96 MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause

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

  1. %
  2. % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
  3. %
  4. %************************************************************************
  5. %* *
  6. \section[OccurAnal]{Occurrence analysis pass}
  7. %* *
  8. %************************************************************************
  9. The occurrence analyser re-typechecks a core expression, returning a new
  10. core expression with (hopefully) improved usage information.
  11. \begin{code}
  12. module OccurAnal (
  13. occurAnalysePgm, occurAnalyseExpr
  14. ) where
  15. #include "HsVersions.h"
  16. import CoreSyn
  17. import CoreFVs
  18. import Type ( tyVarsOfType )
  19. import CoreUtils ( exprIsTrivial, isDefaultAlt, mkCoerceI, isExpandableApp )
  20. import Coercion ( CoercionI(..), mkSymCoI )
  21. import Id
  22. import NameEnv
  23. import NameSet
  24. import Name ( Name, localiseName )
  25. import BasicTypes
  26. import VarSet
  27. import VarEnv
  28. import Var ( varUnique )
  29. import Maybes ( orElse )
  30. import Digraph ( SCC(..), stronglyConnCompFromEdgedVerticesR )
  31. import PrelNames ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
  32. import Unique
  33. import UniqFM
  34. import Util ( mapAndUnzip, filterOut )
  35. import Bag
  36. import Outputable
  37. import FastString
  38. import Data.List
  39. \end{code}
  40. %************************************************************************
  41. %* *
  42. \subsection[OccurAnal-main]{Counting occurrences: main function}
  43. %* *
  44. %************************************************************************
  45. Here's the externally-callable interface:
  46. \begin{code}
  47. occurAnalysePgm :: Maybe (Activation -> Bool) -> [CoreRule]
  48. -> [CoreBind] -> [CoreBind]
  49. occurAnalysePgm active_rule imp_rules binds
  50. = snd (go (initOccEnv active_rule imp_rules) binds)
  51. where
  52. initial_uds = addIdOccs emptyDetails (rulesFreeVars imp_rules)
  53. -- The RULES keep things alive!
  54. go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
  55. go _ []
  56. = (initial_uds, [])
  57. go env (bind:binds)
  58. = (final_usage, bind' ++ binds')
  59. where
  60. (bs_usage, binds') = go env binds
  61. (final_usage, bind') = occAnalBind env env bind bs_usage
  62. occurAnalyseExpr :: CoreExpr -> CoreExpr
  63. -- Do occurrence analysis, and discard occurence info returned
  64. occurAnalyseExpr expr
  65. = snd (occAnal (initOccEnv all_active_rules []) expr)
  66. where
  67. -- To be conservative, we say that all inlines and rules are active
  68. all_active_rules = Just (\_ -> True)
  69. \end{code}
  70. %************************************************************************
  71. %* *
  72. \subsection[OccurAnal-main]{Counting occurrences: main function}
  73. %* *
  74. %************************************************************************
  75. Bindings
  76. ~~~~~~~~
  77. \begin{code}
  78. occAnalBind :: OccEnv -- The incoming OccEnv
  79. -> OccEnv -- Same, but trimmed by (binderOf bind)
  80. -> CoreBind
  81. -> UsageDetails -- Usage details of scope
  82. -> (UsageDetails, -- Of the whole let(rec)
  83. [CoreBind])
  84. occAnalBind env _ (NonRec binder rhs) body_usage
  85. | isTyCoVar binder -- A type let; we don't gather usage info
  86. = (body_usage, [NonRec binder rhs])
  87. | not (binder `usedIn` body_usage) -- It's not mentioned
  88. = (body_usage, [])
  89. | otherwise -- It's mentioned in the body
  90. = (body_usage' +++ rhs_usage3, [NonRec tagged_binder rhs'])
  91. where
  92. (body_usage', tagged_binder) = tagBinder body_usage binder
  93. (rhs_usage1, rhs') = occAnalRhs env (idOccInfo tagged_binder) rhs
  94. rhs_usage2 = addIdOccs rhs_usage1 (idUnfoldingVars binder)
  95. rhs_usage3 = addIdOccs rhs_usage2 (idRuleVars binder)
  96. -- See Note [Rules are extra RHSs] and Note [Rule dependency info]
  97. \end{code}
  98. Note [Dead code]
  99. ~~~~~~~~~~~~~~~~
  100. Dropping dead code for recursive bindings is done in a very simple way:
  101. the entire set of bindings is dropped if none of its binders are
  102. mentioned in its body; otherwise none are.
  103. This seems to miss an obvious improvement.
  104. letrec f = ...g...
  105. g = ...f...
  106. in
  107. ...g...
  108. ===>
  109. letrec f = ...g...
  110. g = ...(...g...)...
  111. in
  112. ...g...
  113. Now 'f' is unused! But it's OK! Dependency analysis will sort this
  114. out into a letrec for 'g' and a 'let' for 'f', and then 'f' will get
  115. dropped. It isn't easy to do a perfect job in one blow. Consider
  116. letrec f = ...g...
  117. g = ...h...
  118. h = ...k...
  119. k = ...m...
  120. m = ...m...
  121. in
  122. ...m...
  123. Note [Loop breaking and RULES]
  124. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  125. Loop breaking is surprisingly subtle. First read the section 4 of
  126. "Secrets of the GHC inliner". This describes our basic plan.
  127. However things are made quite a bit more complicated by RULES. Remember
  128. * Note [Rules are extra RHSs]
  129. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  130. A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
  131. keeps the specialised "children" alive. If the parent dies
  132. (because it isn't referenced any more), then the children will die
  133. too (unless they are already referenced directly).
  134. To that end, we build a Rec group for each cyclic strongly
  135. connected component,
  136. *treating f's rules as extra RHSs for 'f'*.
  137. More concretely, the SCC analysis runs on a graph with an edge
  138. from f -> g iff g is mentioned in
  139. (a) f's rhs
  140. (b) f's RULES
  141. These are rec_edges.
  142. Under (b) we include variables free in *either* LHS *or* RHS of
  143. the rule. The former might seems silly, but see Note [Rule
  144. dependency info]. So in Example [eftInt], eftInt and eftIntFB
  145. will be put in the same Rec, even though their 'main' RHSs are
  146. both non-recursive.
  147. * Note [Rules are visible in their own rec group]
  148. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  149. We want the rules for 'f' to be visible in f's right-hand side.
  150. And we'd like them to be visible in other functions in f's Rec
  151. group. E.g. in Example [Specialisation rules] we want f' rule
  152. to be visible in both f's RHS, and fs's RHS.
  153. This means that we must simplify the RULEs first, before looking
  154. at any of the definitions. This is done by Simplify.simplRecBind,
  155. when it calls addLetIdInfo.
  156. * Note [Choosing loop breakers]
  157. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  158. We avoid infinite inlinings by choosing loop breakers, and
  159. ensuring that a loop breaker cuts each loop. But what is a
  160. "loop"? In particular, a RULE is like an equation for 'f' that
  161. is *always* inlined if it is applicable. We do *not* disable
  162. rules for loop-breakers. It's up to whoever makes the rules to
  163. make sure that the rules themselves always terminate. See Note
  164. [Rules for recursive functions] in Simplify.lhs
  165. Hence, if
  166. f's RHS (or its INLINE template if it has one) mentions g, and
  167. g has a RULE that mentions h, and
  168. h has a RULE that mentions f
  169. then we *must* choose f to be a loop breaker. In general, take the
  170. free variables of f's RHS, and augment it with all the variables
  171. reachable by RULES from those starting points. That is the whole
  172. reason for computing rule_fv_env in occAnalBind. (Of course we
  173. only consider free vars that are also binders in this Rec group.)
  174. See also Note [Finding rule RHS free vars]
  175. Note that when we compute this rule_fv_env, we only consider variables
  176. free in the *RHS* of the rule, in contrast to the way we build the
  177. Rec group in the first place (Note [Rule dependency info])
  178. Note that if 'g' has RHS that mentions 'w', we should add w to
  179. g's loop-breaker edges. More concretely there is an edge from f -> g
  180. iff
  181. (a) g is mentioned in f's RHS
  182. (b) h is mentioned in f's RHS, and
  183. g appears in the RHS of a RULE of h
  184. or a transitive sequence of rules starting with h
  185. Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
  186. chosen as a loop breaker, because their RHSs don't mention each other.
  187. And indeed both can be inlined safely.
  188. Note that the edges of the graph we use for computing loop breakers
  189. are not the same as the edges we use for computing the Rec blocks.
  190. That's why we compute
  191. rec_edges for the Rec block analysis
  192. loop_breaker_edges for the loop breaker analysis
  193. * Note [Finding rule RHS free vars]
  194. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  195. Consider this real example from Data Parallel Haskell
  196. tagZero :: Array Int -> Array Tag
  197. {-# INLINE [1] tagZeroes #-}
  198. tagZero xs = pmap (\x -> fromBool (x==0)) xs
  199. {-# RULES "tagZero" [~1] forall xs n.
  200. pmap fromBool <blah blah> = tagZero xs #-}
  201. So tagZero's RHS mentions pmap, and pmap's RULE mentions tagZero.
  202. However, tagZero can only be inlined in phase 1 and later, while
  203. the RULE is only active *before* phase 1. So there's no problem.
  204. To make this work, we look for the RHS free vars only for
  205. *active* rules. That's the reason for the is_active argument
  206. to idRhsRuleVars, and the occ_rule_act field of the OccEnv.
  207. * Note [Weak loop breakers]
  208. ~~~~~~~~~~~~~~~~~~~~~~~~~
  209. There is a last nasty wrinkle. Suppose we have
  210. Rec { f = f_rhs
  211. RULE f [] = g
  212. h = h_rhs
  213. g = h
  214. ...more...
  215. }
  216. Remember that we simplify the RULES before any RHS (see Note
  217. [Rules are visible in their own rec group] above).
  218. So we must *not* postInlineUnconditionally 'g', even though
  219. its RHS turns out to be trivial. (I'm assuming that 'g' is
  220. not choosen as a loop breaker.) Why not? Because then we
  221. drop the binding for 'g', which leaves it out of scope in the
  222. RULE!
  223. We "solve" this by making g a "weak" or "rules-only" loop breaker,
  224. with OccInfo = IAmLoopBreaker True. A normal "strong" loop breaker
  225. has IAmLoopBreaker False. So
  226. Inline postInlineUnconditionally
  227. IAmLoopBreaker False no no
  228. IAmLoopBreaker True yes no
  229. other yes yes
  230. The **sole** reason for this kind of loop breaker is so that
  231. postInlineUnconditionally does not fire. Ugh.
  232. * Note [Rule dependency info]
  233. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  234. The VarSet in a SpecInfo is used for dependency analysis in the
  235. occurrence analyser. We must track free vars in *both* lhs and rhs.
  236. Hence use of idRuleVars, rather than idRuleRhsVars in occAnalBind.
  237. Why both? Consider
  238. x = y
  239. RULE f x = 4
  240. Then if we substitute y for x, we'd better do so in the
  241. rule's LHS too, so we'd better ensure the dependency is respected
  242. * Note [Inline rules]
  243. ~~~~~~~~~~~~~~~~~~~
  244. None of the above stuff about RULES applies to Inline Rules,
  245. stored in a CoreUnfolding. The unfolding, if any, is simplified
  246. at the same time as the regular RHS of the function, so it should
  247. be treated *exactly* like an extra RHS.
  248. There is a danger that we'll be sub-optimal if we see this
  249. f = ...f...
  250. [INLINE f = ..no f...]
  251. where f is recursive, but the INLINE is not. This can just about
  252. happen with a sufficiently odd set of rules; eg
  253. foo :: Int -> Int
  254. {-# INLINE [1] foo #-}
  255. foo x = x+1
  256. bar :: Int -> Int
  257. {-# INLINE [1] bar #-}
  258. bar x = foo x + 1
  259. {-# RULES "foo" [~1] forall x. foo x = bar x #-}
  260. Here the RULE makes bar recursive; but it's INLINE pragma remains
  261. non-recursive. It's tempting to then say that 'bar' should not be
  262. a loop breaker, but an attempt to do so goes wrong in two ways:
  263. a) We may get
  264. $df = ...$cfoo...
  265. $cfoo = ...$df....
  266. [INLINE $cfoo = ...no-$df...]
  267. But we want $cfoo to depend on $df explicitly so that we
  268. put the bindings in the right order to inline $df in $cfoo
  269. and perhaps break the loop altogether. (Maybe this
  270. b)
  271. Example [eftInt]
  272. ~~~~~~~~~~~~~~~
  273. Example (from GHC.Enum):
  274. eftInt :: Int# -> Int# -> [Int]
  275. eftInt x y = ...(non-recursive)...
  276. {-# INLINE [0] eftIntFB #-}
  277. eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
  278. eftIntFB c n x y = ...(non-recursive)...
  279. {-# RULES
  280. "eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
  281. "eftIntList" [1] eftIntFB (:) [] = eftInt
  282. #-}
  283. Example [Specialisation rules]
  284. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  285. Consider this group, which is typical of what SpecConstr builds:
  286. fs a = ....f (C a)....
  287. f x = ....f (C a)....
  288. {-# RULE f (C a) = fs a #-}
  289. So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
  290. But watch out! If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
  291. - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
  292. - fs is inlined (say it's small)
  293. - now there's another opportunity to apply the RULE
  294. This showed up when compiling Control.Concurrent.Chan.getChanContents.
  295. \begin{code}
  296. occAnalBind _ env (Rec pairs) body_usage
  297. = foldr (occAnalRec env) (body_usage, []) sccs
  298. -- For a recursive group, we
  299. -- * occ-analyse all the RHSs
  300. -- * compute strongly-connected components
  301. -- * feed those components to occAnalRec
  302. where
  303. -------------Dependency analysis ------------------------------
  304. bndr_set = mkVarSet (map fst pairs)
  305. sccs :: [SCC (Node Details)]
  306. sccs = {-# SCC "occAnalBind.scc" #-} stronglyConnCompFromEdgedVerticesR rec_edges
  307. rec_edges :: [Node Details]
  308. rec_edges = {-# SCC "occAnalBind.assoc" #-} map make_node pairs
  309. make_node (bndr, rhs)
  310. = (details, varUnique bndr, keysUFM out_edges)
  311. where
  312. details = ND { nd_bndr = bndr, nd_rhs = rhs'
  313. , nd_uds = rhs_usage3, nd_inl = inl_fvs}
  314. (rhs_usage1, rhs') = occAnalRhs env NoOccInfo rhs
  315. rhs_usage2 = addIdOccs rhs_usage1 rule_fvs -- Note [Rules are extra RHSs]
  316. rhs_usage3 = addIdOccs rhs_usage2 unf_fvs
  317. unf = realIdUnfolding bndr -- Ignore any current loop-breaker flag
  318. unf_fvs = stableUnfoldingVars unf
  319. rule_fvs = idRuleVars bndr -- See Note [Rule dependency info]
  320. inl_fvs = rhs_fvs `unionVarSet` unf_fvs
  321. rhs_fvs = intersectUFM_C (\b _ -> b) bndr_set rhs_usage1
  322. out_edges = intersectUFM_C (\b _ -> b) bndr_set rhs_usage3
  323. -- (a -> b) means a mentions b
  324. -- Given the usage details (a UFM that gives occ info for each free var of
  325. -- the RHS) we can get the list of free vars -- or rather their Int keys --
  326. -- by just extracting the keys from the finite map. Grimy, but fast.
  327. -- Previously we had this:
  328. -- [ bndr | bndr <- bndrs,
  329. -- maybeToBool (lookupVarEnv rhs_usage bndr)]
  330. -- which has n**2 cost, and this meant that edges_from alone
  331. -- consumed 10% of total runtime!
  332. -----------------------------
  333. occAnalRec :: OccEnv -> SCC (Node Details)
  334. -> (UsageDetails, [CoreBind])
  335. -> (UsageDetails, [CoreBind])
  336. -- The NonRec case is just like a Let (NonRec ...) above
  337. occAnalRec _ (AcyclicSCC (ND { nd_bndr = bndr, nd_rhs = rhs, nd_uds = rhs_usage}, _, _))
  338. (body_usage, binds)
  339. | not (bndr `usedIn` body_usage)
  340. = (body_usage, binds)
  341. | otherwise -- It's mentioned in the body
  342. = (body_usage' +++ rhs_usage,
  343. NonRec tagged_bndr rhs : binds)
  344. where
  345. (body_usage', tagged_bndr) = tagBinder body_usage bndr
  346. -- The Rec case is the interesting one
  347. -- See Note [Loop breaking]
  348. occAnalRec env (CyclicSCC nodes) (body_usage, binds)
  349. | not (any (`usedIn` body_usage) bndrs) -- NB: look at body_usage, not total_usage
  350. = (body_usage, binds) -- Dead code
  351. | otherwise -- At this point we always build a single Rec
  352. = (final_usage, Rec pairs : binds)
  353. where
  354. bndrs = [b | (ND { nd_bndr = b }, _, _) <- nodes]
  355. bndr_set = mkVarSet bndrs
  356. non_boring bndr = isId bndr &&
  357. (isStableUnfolding (realIdUnfolding bndr) || idHasRules bndr)
  358. ----------------------------
  359. -- Tag the binders with their occurrence info
  360. total_usage = foldl add_usage body_usage nodes
  361. add_usage usage_so_far (ND { nd_uds = rhs_usage }, _, _) = usage_so_far +++ rhs_usage
  362. (final_usage, tagged_nodes) = mapAccumL tag_node total_usage nodes
  363. tag_node :: UsageDetails -> Node Details -> (UsageDetails, Node Details)
  364. -- (a) Tag the binders in the details with occ info
  365. -- (b) Mark the binder with "weak loop-breaker" OccInfo
  366. -- saying "no preInlineUnconditionally" if it is used
  367. -- in any rule (lhs or rhs) of the recursive group
  368. -- See Note [Weak loop breakers]
  369. tag_node usage (details@ND { nd_bndr = bndr }, k, ks)
  370. = (usage `delVarEnv` bndr, (details { nd_bndr = bndr2 }, k, ks))
  371. where
  372. bndr2 | bndr `elemVarSet` all_rule_fvs = makeLoopBreaker True bndr1
  373. | otherwise = bndr1
  374. bndr1 = setBinderOcc usage bndr
  375. all_rule_fvs = bndr_set `intersectVarSet` foldr (unionVarSet . idRuleVars)
  376. emptyVarSet bndrs
  377. ----------------------------
  378. -- Now reconstruct the cycle
  379. pairs | any non_boring bndrs
  380. = foldr (reOrderRec 0) [] $
  381. stronglyConnCompFromEdgedVerticesR loop_breaker_edges
  382. | otherwise
  383. = reOrderCycle 0 tagged_nodes []
  384. -- See Note [Choosing loop breakers] for loop_breaker_edges
  385. loop_breaker_edges = map mk_node tagged_nodes
  386. mk_node (details@(ND { nd_inl = inl_fvs }), k, _) = (details, k, new_ks)
  387. where
  388. new_ks = keysUFM (fst (extendFvs rule_fv_env inl_fvs))
  389. ------------------------------------
  390. rule_fv_env :: IdEnv IdSet -- Variables from this group mentioned in RHS of rules
  391. -- Domain is *subset* of bound vars (others have no rule fvs)
  392. rule_fv_env = transClosureFV init_rule_fvs
  393. init_rule_fvs
  394. | Just is_active <- occ_rule_act env -- See Note [Finding rule RHS free vars]
  395. = [ (b, rule_fvs)
  396. | b <- bndrs
  397. , isId b
  398. , let rule_fvs = idRuleRhsVars is_active b
  399. `intersectVarSet` bndr_set
  400. , not (isEmptyVarSet rule_fvs)]
  401. | otherwise
  402. = []
  403. \end{code}
  404. @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
  405. strongly connected component (there's guaranteed to be a cycle). It returns the
  406. same pairs, but
  407. a) in a better order,
  408. b) with some of the Ids having a IAmALoopBreaker pragma
  409. The "loop-breaker" Ids are sufficient to break all cycles in the SCC. This means
  410. that the simplifier can guarantee not to loop provided it never records an inlining
  411. for these no-inline guys.
  412. Furthermore, the order of the binds is such that if we neglect dependencies
  413. on the no-inline Ids then the binds are topologically sorted. This means
  414. that the simplifier will generally do a good job if it works from top bottom,
  415. recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
  416. ==============
  417. [June 98: I don't understand the following paragraphs, and I've
  418. changed the a=b case again so that it isn't a special case any more.]
  419. Here's a case that bit me:
  420. letrec
  421. a = b
  422. b = \x. BIG
  423. in
  424. ...a...a...a....
  425. Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
  426. My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
  427. Perhaps something cleverer would suffice.
  428. ===============
  429. \begin{code}
  430. type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
  431. -- which is gotten from the Id.
  432. data Details
  433. = ND { nd_bndr :: Id -- Binder
  434. , nd_rhs :: CoreExpr -- RHS
  435. , nd_uds :: UsageDetails -- Usage from RHS,
  436. -- including RULES and InlineRule unfolding
  437. , nd_inl :: IdSet -- Other binders *from this Rec group* mentioned in
  438. } -- its InlineRule unfolding (if present)
  439. -- AND the RHS
  440. -- but *excluding* any RULES
  441. -- This is the IdSet that may be used if the Id is inlined
  442. reOrderRec :: Int -> SCC (Node Details)
  443. -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
  444. -- Sorted into a plausible order. Enough of the Ids have
  445. -- IAmALoopBreaker pragmas that there are no loops left.
  446. reOrderRec _ (AcyclicSCC (ND { nd_bndr = bndr, nd_rhs = rhs }, _, _))
  447. pairs = (bndr, rhs) : pairs
  448. reOrderRec depth (CyclicSCC cycle) pairs = reOrderCycle depth cycle pairs
  449. reOrderCycle :: Int -> [Node Details] -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
  450. reOrderCycle _ [] _
  451. = panic "reOrderCycle"
  452. reOrderCycle _ [(ND { nd_bndr = bndr, nd_rhs = rhs }, _, _)] pairs
  453. = -- Common case of simple self-recursion
  454. (makeLoopBreaker False bndr, rhs) : pairs
  455. reOrderCycle depth (bind : binds) pairs
  456. = -- Choose a loop breaker, mark it no-inline,
  457. -- do SCC analysis on the rest, and recursively sort them out
  458. -- pprTrace "reOrderCycle" (ppr [b | (ND { nd_bndr = b }, _, _) <- bind:binds]) $
  459. foldr (reOrderRec new_depth)
  460. ([ (makeLoopBreaker False bndr, rhs)
  461. | (ND { nd_bndr = bndr, nd_rhs = rhs }, _, _) <- chosen_binds] ++ pairs)
  462. (stronglyConnCompFromEdgedVerticesR unchosen)
  463. where
  464. (chosen_binds, unchosen) = choose_loop_breaker [bind] (score bind) [] binds
  465. approximate_loop_breaker = depth >= 2
  466. new_depth | approximate_loop_breaker = 0
  467. | otherwise = depth+1
  468. -- After two iterations (d=0, d=1) give up
  469. -- and approximate, returning to d=0
  470. -- This loop looks for the bind with the lowest score
  471. -- to pick as the loop breaker. The rest accumulate in
  472. choose_loop_breaker loop_binds _loop_sc acc []
  473. = (loop_binds, acc) -- Done
  474. -- If approximate_loop_breaker is True, we pick *all*
  475. -- nodes with lowest score, else just one
  476. -- See Note [Complexity of loop breaking]
  477. choose_loop_breaker loop_binds loop_sc acc (bind : binds)
  478. | sc < loop_sc -- Lower score so pick this new one
  479. = choose_loop_breaker [bind] sc (loop_binds ++ acc) binds
  480. | approximate_loop_breaker && sc == loop_sc
  481. = choose_loop_breaker (bind : loop_binds) loop_sc acc binds
  482. | otherwise -- Higher score so don't pick it
  483. = choose_loop_breaker loop_binds loop_sc (bind : acc) binds
  484. where
  485. sc = score bind
  486. score :: Node Details -> Int -- Higher score => less likely to be picked as loop breaker
  487. score (ND { nd_bndr = bndr, nd_rhs = rhs }, _, _)
  488. | not (isId bndr) = 100 -- A type or cercion variable is never a loop breaker
  489. | isDFunId bndr = 9 -- Never choose a DFun as a loop breaker
  490. -- Note [DFuns should not be loop breakers]
  491. | Just inl_source <- isStableCoreUnfolding_maybe (idUnfolding bndr)
  492. = case inl_source of
  493. InlineWrapper {} -> 10 -- Note [INLINE pragmas]
  494. _other -> 3 -- Data structures are more important than this
  495. -- so that dictionary/method recursion unravels
  496. -- Note that this case hits all InlineRule things, so we
  497. -- never look at 'rhs for InlineRule stuff. That's right, because
  498. -- 'rhs' is irrelevant for inlining things with an InlineRule
  499. | is_con_app rhs = 5 -- Data types help with cases: Note [Constructor applications]
  500. | exprIsTrivial rhs = 10 -- Practically certain to be inlined
  501. -- Used to have also: && not (isExportedId bndr)
  502. -- But I found this sometimes cost an extra iteration when we have
  503. -- rec { d = (a,b); a = ...df...; b = ...df...; df = d }
  504. -- where df is the exported dictionary. Then df makes a really
  505. -- bad choice for loop breaker
  506. -- If an Id is marked "never inline" then it makes a great loop breaker
  507. -- The only reason for not checking that here is that it is rare
  508. -- and I've never seen a situation where it makes a difference,
  509. -- so it probably isn't worth the time to test on every binder
  510. -- | isNeverActive (idInlinePragma bndr) = -10
  511. | isOneOcc (idOccInfo bndr) = 2 -- Likely to be inlined
  512. | canUnfold (realIdUnfolding bndr) = 1
  513. -- The Id has some kind of unfolding
  514. -- Ignore loop-breaker-ness here because that is what we are setting!
  515. | otherwise = 0
  516. -- Checking for a constructor application
  517. -- Cheap and cheerful; the simplifer moves casts out of the way
  518. -- The lambda case is important to spot x = /\a. C (f a)
  519. -- which comes up when C is a dictionary constructor and
  520. -- f is a default method.
  521. -- Example: the instance for Show (ST s a) in GHC.ST
  522. --
  523. -- However we *also* treat (\x. C p q) as a con-app-like thing,
  524. -- Note [Closure conversion]
  525. is_con_app (Var v) = isConLikeId v
  526. is_con_app (App f _) = is_con_app f
  527. is_con_app (Lam _ e) = is_con_app e
  528. is_con_app (Note _ e) = is_con_app e
  529. is_con_app _ = False
  530. makeLoopBreaker :: Bool -> Id -> Id
  531. -- Set the loop-breaker flag: see Note [Weak loop breakers]
  532. makeLoopBreaker weak bndr
  533. = ASSERT2( isId bndr, ppr bndr ) setIdOccInfo bndr (IAmALoopBreaker weak)
  534. \end{code}
  535. Note [Complexity of loop breaking]
  536. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  537. The loop-breaking algorithm knocks out one binder at a time, and
  538. performs a new SCC analysis on the remaining binders. That can
  539. behave very badly in tightly-coupled groups of bindings; in the
  540. worst case it can be (N**2)*log N, because it does a full SCC
  541. on N, then N-1, then N-2 and so on.
  542. To avoid this, we switch plans after 2 (or whatever) attempts:
  543. Plan A: pick one binder with the lowest score, make it
  544. a loop breaker, and try again
  545. Plan B: pick *all* binders with the lowest score, make them
  546. all loop breakers, and try again
  547. Since there are only a small finite number of scores, this will
  548. terminate in a constant number of iterations, rather than O(N)
  549. iterations.
  550. You might thing that it's very unlikely, but RULES make it much
  551. more likely. Here's a real example from Trac #1969:
  552. Rec { $dm = \d.\x. op d
  553. {-# RULES forall d. $dm Int d = $s$dm1
  554. forall d. $dm Bool d = $s$dm2 #-}
  555. dInt = MkD .... opInt ...
  556. dInt = MkD .... opBool ...
  557. opInt = $dm dInt
  558. opBool = $dm dBool
  559. $s$dm1 = \x. op dInt
  560. $s$dm2 = \x. op dBool }
  561. The RULES stuff means that we can't choose $dm as a loop breaker
  562. (Note [Choosing loop breakers]), so we must choose at least (say)
  563. opInt *and* opBool, and so on. The number of loop breakders is
  564. linear in the number of instance declarations.
  565. Note [INLINE pragmas]
  566. ~~~~~~~~~~~~~~~~~~~~~
  567. Avoid choosing a function with an INLINE pramga as the loop breaker!
  568. If such a function is mutually-recursive with a non-INLINE thing,
  569. then the latter should be the loop-breaker.
  570. Usually this is just a question of optimisation. But a particularly
  571. bad case is wrappers generated by the demand analyser: if you make
  572. then into a loop breaker you may get an infinite inlining loop. For
  573. example:
  574. rec {
  575. $wfoo x = ....foo x....
  576. {-loop brk-} foo x = ...$wfoo x...
  577. }
  578. The interface file sees the unfolding for $wfoo, and sees that foo is
  579. strict (and hence it gets an auto-generated wrapper). Result: an
  580. infinite inlining in the importing scope. So be a bit careful if you
  581. change this. A good example is Tree.repTree in
  582. nofib/spectral/minimax. If the repTree wrapper is chosen as the loop
  583. breaker then compiling Game.hs goes into an infinite loop. This
  584. happened when we gave is_con_app a lower score than inline candidates:
  585. Tree.repTree
  586. = __inline_me (/\a. \w w1 w2 ->
  587. case Tree.$wrepTree @ a w w1 w2 of
  588. { (# ww1, ww2 #) -> Branch @ a ww1 ww2 })
  589. Tree.$wrepTree
  590. = /\a w w1 w2 ->
  591. (# w2_smP, map a (Tree a) (Tree.repTree a w1 w) (w w2) #)
  592. Here we do *not* want to choose 'repTree' as the loop breaker.
  593. Note [DFuns should not be loop breakers]
  594. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  595. It's particularly bad to make a DFun into a loop breaker. See
  596. Note [How instance declarations are translated] in TcInstDcls
  597. We give DFuns a higher score than ordinary CONLIKE things because
  598. if there's a choice we want the DFun to be the non-looop breker. Eg
  599. rec { sc = /\ a \$dC. $fBWrap (T a) ($fCT @ a $dC)
  600. $fCT :: forall a_afE. (Roman.C a_afE) => Roman.C (Roman.T a_afE)
  601. {-# DFUN #-}
  602. $fCT = /\a \$dC. MkD (T a) ((sc @ a $dC) |> blah) ($ctoF @ a $dC)
  603. }
  604. Here 'sc' (the superclass) looks CONLIKE, but we'll never get to it
  605. if we can't unravel the DFun first.
  606. Note [Constructor applications]
  607. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  608. It's really really important to inline dictionaries. Real
  609. example (the Enum Ordering instance from GHC.Base):
  610. rec f = \ x -> case d of (p,q,r) -> p x
  611. g = \ x -> case d of (p,q,r) -> q x
  612. d = (v, f, g)
  613. Here, f and g occur just once; but we can't inline them into d.
  614. On the other hand we *could* simplify those case expressions if
  615. we didn't stupidly choose d as the loop breaker.
  616. But we won't because constructor args are marked "Many".
  617. Inlining dictionaries is really essential to unravelling
  618. the loops in static numeric dictionaries, see GHC.Float.
  619. Note [Closure conversion]
  620. ~~~~~~~~~~~~~~~~~~~~~~~~~
  621. We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
  622. The immediate motivation came from the result of a closure-conversion transformation
  623. which generated code like this:
  624. data Clo a b = forall c. Clo (c -> a -> b) c
  625. ($:) :: Clo a b -> a -> b
  626. Clo f env $: x = f env x
  627. rec { plus = Clo plus1 ()
  628. ; plus1 _ n = Clo plus2 n
  629. ; plus2 Zero n = n
  630. ; plus2 (Succ m) n = Succ (plus $: m $: n) }
  631. If we inline 'plus' and 'plus1', everything unravels nicely. But if
  632. we choose 'plus1' as the loop breaker (which is entirely possible
  633. otherwise), the loop does not unravel nicely.
  634. @occAnalRhs@ deals with the question of bindings where the Id is marked
  635. by an INLINE pragma. For these we record that anything which occurs
  636. in its RHS occurs many times. This pessimistically assumes that ths
  637. inlined binder also occurs many times in its scope, but if it doesn't
  638. we'll catch it next time round. At worst this costs an extra simplifier pass.
  639. ToDo: try using the occurrence info for the inline'd binder.
  640. [March 97] We do the same for atomic RHSs. Reason: see notes with reOrderRec.
  641. [June 98, SLPJ] I've undone this change; I don't understand it. See notes with reOrderRec.
  642. \begin{code}
  643. occAnalRhs :: OccEnv
  644. -> OccInfo -> CoreExpr -- Binder and rhs
  645. -- For non-recs the binder is alrady tagged
  646. -- with occurrence info
  647. -> (UsageDetails, CoreExpr)
  648. -- Returned usage details covers only the RHS,
  649. -- and *not* the RULE or INLINE template for the Id
  650. occAnalRhs env occ rhs
  651. = occAnal ctxt rhs
  652. where
  653. ctxt | certainly_inline = env
  654. | otherwise = rhsCtxt env
  655. -- Note that we generally use an rhsCtxt. This tells the occ anal n
  656. -- that it's looking at an RHS, which has an effect in occAnalApp
  657. --
  658. -- But there's a problem. Consider
  659. -- x1 = a0 : []
  660. -- x2 = a1 : x1
  661. -- x3 = a2 : x2
  662. -- g = f x3
  663. -- First time round, it looks as if x1 and x2 occur as an arg of a
  664. -- let-bound constructor ==> give them a many-occurrence.
  665. -- But then x3 is inlined (unconditionally as it happens) and
  666. -- next time round, x2 will be, and the next time round x1 will be
  667. -- Result: multiple simplifier iterations. Sigh.
  668. -- Crude solution: use rhsCtxt for things that occur just once...
  669. certainly_inline = case occ of
  670. OneOcc in_lam one_br _ -> not in_lam && one_br
  671. _ -> False
  672. addIdOccs :: UsageDetails -> VarSet -> UsageDetails
  673. addIdOccs usage id_set = foldVarSet add usage id_set
  674. where
  675. add v u | isId v = addOneOcc u v NoOccInfo
  676. | otherwise = u
  677. -- Give a non-committal binder info (i.e NoOccInfo) because
  678. -- a) Many copies of the specialised thing can appear
  679. -- b) We don't want to substitute a BIG expression inside a RULE
  680. -- even if that's the only occurrence of the thing
  681. -- (Same goes for INLINE.)
  682. \end{code}
  683. Expressions
  684. ~~~~~~~~~~~
  685. \begin{code}
  686. occAnal :: OccEnv
  687. -> CoreExpr
  688. -> (UsageDetails, -- Gives info only about the "interesting" Ids
  689. CoreExpr)
  690. occAnal _ (Type t) = (emptyDetails, Type t)
  691. occAnal env (Var v) = (mkOneOcc env v False, Var v)
  692. -- At one stage, I gathered the idRuleVars for v here too,
  693. -- which in a way is the right thing to do.
  694. -- But that went wrong right after specialisation, when
  695. -- the *occurrences* of the overloaded function didn't have any
  696. -- rules in them, so the *specialised* versions looked as if they
  697. -- weren't used at all.
  698. \end{code}
  699. We regard variables that occur as constructor arguments as "dangerousToDup":
  700. \begin{verbatim}
  701. module A where
  702. f x = let y = expensive x in
  703. let z = (True,y) in
  704. (case z of {(p,q)->q}, case z of {(p,q)->q})
  705. \end{verbatim}
  706. We feel free to duplicate the WHNF (True,y), but that means
  707. that y may be duplicated thereby.
  708. If we aren't careful we duplicate the (expensive x) call!
  709. Constructors are rather like lambdas in this way.
  710. \begin{code}
  711. occAnal _ expr@(Lit _) = (emptyDetails, expr)
  712. \end{code}
  713. \begin{code}
  714. occAnal env (Note note@(SCC _) body)
  715. = case occAnal env body of { (usage, body') ->
  716. (mapVarEnv markInsideSCC usage, Note note body')
  717. }
  718. occAnal env (Note note body)
  719. = case occAnal env body of { (usage, body') ->
  720. (usage, Note note body')
  721. }
  722. occAnal env (Cast expr co)
  723. = case occAnal env expr of { (usage, expr') ->
  724. (markManyIf (isRhsEnv env) usage, Cast expr' co)
  725. -- If we see let x = y `cast` co
  726. -- then mark y as 'Many' so that we don't
  727. -- immediately inline y again.
  728. }
  729. \end{code}
  730. \begin{code}
  731. occAnal env app@(App _ _)
  732. = occAnalApp env (collectArgs app)
  733. -- Ignore type variables altogether
  734. -- (a) occurrences inside type lambdas only not marked as InsideLam
  735. -- (b) type variables not in environment
  736. occAnal env (Lam x body) | isTyCoVar x
  737. = case occAnal env body of { (body_usage, body') ->
  738. (body_usage, Lam x body')
  739. }
  740. -- For value lambdas we do a special hack. Consider
  741. -- (\x. \y. ...x...)
  742. -- If we did nothing, x is used inside the \y, so would be marked
  743. -- as dangerous to dup. But in the common case where the abstraction
  744. -- is applied to two arguments this is over-pessimistic.
  745. -- So instead, we just mark each binder with its occurrence
  746. -- info in the *body* of the multiple lambda.
  747. -- Then, the simplifier is careful when partially applying lambdas.
  748. occAnal env expr@(Lam _ _)
  749. = case occAnal env_body body of { (body_usage, body') ->
  750. let
  751. (final_usage, tagged_binders) = tagLamBinders body_usage binders'
  752. -- Use binders' to put one-shot info on the lambdas
  753. -- URGH! Sept 99: we don't seem to be able to use binders' here, because
  754. -- we get linear-typed things in the resulting program that we can't handle yet.
  755. -- (e.g. PrelShow) TODO
  756. really_final_usage = if linear then
  757. final_usage
  758. else
  759. mapVarEnv markInsideLam final_usage
  760. in
  761. (really_final_usage,
  762. mkLams tagged_binders body') }
  763. where
  764. env_body = vanillaCtxt (trimOccEnv env binders)
  765. -- Body is (no longer) an RhsContext
  766. (binders, body) = collectBinders expr
  767. binders' = oneShotGroup env binders
  768. linear = all is_one_shot binders'
  769. is_one_shot b = isId b && isOneShotBndr b
  770. occAnal env (Case scrut bndr ty alts)
  771. = case occ_anal_scrut scrut alts of { (scrut_usage, scrut') ->
  772. case mapAndUnzip occ_anal_alt alts of { (alts_usage_s, alts') ->
  773. let
  774. alts_usage = foldr1 combineAltsUsageDetails alts_usage_s
  775. (alts_usage1, tagged_bndr) = tag_case_bndr alts_usage bndr
  776. total_usage = scrut_usage +++ alts_usage1
  777. in
  778. total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
  779. where
  780. -- Note [Case binder usage]
  781. -- ~~~~~~~~~~~~~~~~~~~~~~~~
  782. -- The case binder gets a usage of either "many" or "dead", never "one".
  783. -- Reason: we like to inline single occurrences, to eliminate a binding,
  784. -- but inlining a case binder *doesn't* eliminate a binding.
  785. -- We *don't* want to transform
  786. -- case x of w { (p,q) -> f w }
  787. -- into
  788. -- case x of w { (p,q) -> f (p,q) }
  789. tag_case_bndr usage bndr
  790. = case lookupVarEnv usage bndr of
  791. Nothing -> (usage, setIdOccInfo bndr IAmDead)
  792. Just _ -> (usage `delVarEnv` bndr, setIdOccInfo bndr NoOccInfo)
  793. alt_env = mkAltEnv env scrut bndr
  794. occ_anal_alt = occAnalAlt alt_env bndr
  795. occ_anal_scrut (Var v) (alt1 : other_alts)
  796. | not (null other_alts) || not (isDefaultAlt alt1)
  797. = (mkOneOcc env v True, Var v) -- The 'True' says that the variable occurs
  798. -- in an interesting context; the case has
  799. -- at least one non-default alternative
  800. occ_anal_scrut scrut _alts
  801. = occAnal (vanillaCtxt env) scrut -- No need for rhsCtxt
  802. occAnal env (Let bind body)
  803. = case occAnal env_body body of { (body_usage, body') ->
  804. case occAnalBind env env_body bind body_usage of { (final_usage, new_binds) ->
  805. (final_usage, mkLets new_binds body') }}
  806. where
  807. env_body = trimOccEnv env (bindersOf bind)
  808. occAnalArgs :: OccEnv -> [CoreExpr] -> (UsageDetails, [CoreExpr])
  809. occAnalArgs env args
  810. = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
  811. (foldr (+++) emptyDetails arg_uds_s, args')}
  812. where
  813. arg_env = vanillaCtxt env
  814. \end{code}
  815. Applications are dealt with specially because we want
  816. the "build hack" to work.
  817. \begin{code}
  818. occAnalApp :: OccEnv
  819. -> (Expr CoreBndr, [Arg CoreBndr])
  820. -> (UsageDetails, Expr CoreBndr)
  821. occAnalApp env (Var fun, args)
  822. = case args_stuff of { (args_uds, args') ->
  823. let
  824. final_args_uds = markManyIf (isRhsEnv env && is_exp) args_uds
  825. -- We mark the free vars of the argument of a constructor or PAP
  826. -- as "many", if it is the RHS of a let(rec).
  827. -- This means that nothing gets inlined into a constructor argument
  828. -- position, which is what we want. Typically those constructor
  829. -- arguments are just variables, or trivial expressions.
  830. --
  831. -- This is the *whole point* of the isRhsEnv predicate
  832. in
  833. (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
  834. where
  835. fun_uniq = idUnique fun
  836. fun_uds = mkOneOcc env fun (valArgCount args > 0)
  837. is_exp = isExpandableApp fun (valArgCount args)
  838. -- See Note [CONLIKE pragma] in BasicTypes
  839. -- The definition of is_exp should match that in
  840. -- Simplify.prepareRhs
  841. -- Hack for build, fold, runST
  842. args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
  843. | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
  844. | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
  845. | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
  846. -- (foldr k z xs) may call k many times, but it never
  847. -- shares a partial application of k; hence [False,True]
  848. -- This means we can optimise
  849. -- foldr (\x -> let v = ...x... in \y -> ...v...) z xs
  850. -- by floating in the v
  851. | otherwise = occAnalArgs env args
  852. occAnalApp env (fun, args)
  853. = case occAnal (addAppCtxt env args) fun of { (fun_uds, fun') ->
  854. -- The addAppCtxt is a bit cunning. One iteration of the simplifier
  855. -- often leaves behind beta redexs like
  856. -- (\x y -> e) a1 a2
  857. -- Here we would like to mark x,y as one-shot, and treat the whole
  858. -- thing much like a let. We do this by pushing some True items
  859. -- onto the context stack.
  860. case occAnalArgs env args of { (args_uds, args') ->
  861. let
  862. final_uds = fun_uds +++ args_uds
  863. in
  864. (final_uds, mkApps fun' args') }}
  865. markManyIf :: Bool -- If this is true
  866. -> UsageDetails -- Then do markMany on this
  867. -> UsageDetails
  868. markManyIf True uds = mapVarEnv markMany uds
  869. markManyIf False uds = uds
  870. appSpecial :: OccEnv
  871. -> Int -> CtxtTy -- Argument number, and context to use for it
  872. -> [CoreExpr]
  873. -> (UsageDetails, [CoreExpr])
  874. appSpecial env n ctxt args
  875. = go n args
  876. where
  877. arg_env = vanillaCtxt env
  878. go _ [] = (emptyDetails, []) -- Too few args
  879. go 1 (arg:args) -- The magic arg
  880. = case occAnal (setCtxtTy arg_env ctxt) arg of { (arg_uds, arg') ->
  881. case occAnalArgs env args of { (args_uds, args') ->
  882. (arg_uds +++ args_uds, arg':args') }}
  883. go n (arg:args)
  884. = case occAnal arg_env arg of { (arg_uds, arg') ->
  885. case go (n-1) args of { (args_uds, args') ->
  886. (arg_uds +++ args_uds, arg':args') }}
  887. \end{code}
  888. Note [Binders in case alternatives]
  889. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  890. Consider
  891. case x of y { (a,b) -> f y }
  892. We treat 'a', 'b' as dead, because they don't physically occur in the
  893. case alternative. (Indeed, a variable is dead iff it doesn't occur in
  894. its scope in the output of OccAnal.) It really helps to know when
  895. binders are unused. See esp the call to isDeadBinder in
  896. Simplify.mkDupableAlt
  897. In this example, though, the Simplifier will bring 'a' and 'b' back to
  898. life, beause it binds 'y' to (a,b) (imagine got inlined and
  899. scrutinised y).
  900. \begin{code}
  901. occAnalAlt :: OccEnv
  902. -> CoreBndr
  903. -> CoreAlt
  904. -> (UsageDetails, Alt IdWithOccInfo)
  905. occAnalAlt env case_bndr (con, bndrs, rhs)
  906. = let
  907. env' = trimOccEnv env bndrs
  908. in
  909. case occAnal env' rhs of { (rhs_usage1, rhs1) ->
  910. let
  911. proxies = getProxies env' case_bndr
  912. (rhs_usage2, rhs2) = foldrBag wrapProxy (rhs_usage1, rhs1) proxies
  913. (alt_usg, tagged_bndrs) = tagLamBinders rhs_usage2 bndrs
  914. bndrs' = tagged_bndrs -- See Note [Binders in case alternatives]
  915. in
  916. (alt_usg, (con, bndrs', rhs2)) }
  917. wrapProxy :: ProxyBind -> (UsageDetails, CoreExpr) -> (UsageDetails, CoreExpr)
  918. wrapProxy (bndr, rhs_var, co) (body_usg, body)
  919. | not (bndr `usedIn` body_usg)
  920. = (body_usg, body)
  921. | otherwise
  922. = (body_usg' +++ rhs_usg, Let (NonRec tagged_bndr rhs) body)
  923. where
  924. (body_usg', tagged_bndr) = tagBinder body_usg bndr
  925. rhs_usg = unitVarEnv rhs_var NoOccInfo -- We don't need exact info
  926. rhs = mkCoerceI co (Var rhs_var)
  927. \end{code}
  928. %************************************************************************
  929. %* *
  930. OccEnv
  931. %* *
  932. %************************************************************************
  933. \begin{code}
  934. data OccEnv
  935. = OccEnv { occ_encl :: !OccEncl -- Enclosing context information
  936. , occ_ctxt :: !CtxtTy -- Tells about linearity
  937. , occ_proxy :: ProxyEnv
  938. , occ_rule_fvs :: ImpRuleUsage
  939. , occ_rule_act :: Maybe (Activation -> Bool) -- Nothing => Rules are inactive
  940. -- See Note [Finding rule RHS free vars]
  941. }
  942. -----------------------------
  943. -- OccEncl is used to control whether to inline into constructor arguments
  944. -- For example:
  945. -- x = (p,q) -- Don't inline p or q
  946. -- y = /\a -> (p a, q a) -- Still don't inline p or q
  947. -- z = f (p,q) -- Do inline p,q; it may make a rule fire
  948. -- So OccEncl tells enought about the context to know what to do when
  949. -- we encounter a contructor application or PAP.
  950. data OccEncl
  951. = OccRhs -- RHS of let(rec), albeit perhaps inside a type lambda
  952. -- Don't inline into constructor args here
  953. | OccVanilla -- Argument of function, body of lambda, scruintee of case etc.
  954. -- Do inline into constructor args here
  955. instance Outputable OccEncl where
  956. ppr OccRhs = ptext (sLit "occRhs")
  957. ppr OccVanilla = ptext (sLit "occVanilla")
  958. type CtxtTy = [Bool]
  959. -- [] No info
  960. --
  961. -- True:ctxt Analysing a function-valued expression that will be
  962. -- applied just once
  963. --
  964. -- False:ctxt Analysing a function-valued expression that may
  965. -- be applied many times; but when it is,
  966. -- the CtxtTy inside applies
  967. initOccEnv :: Maybe (Activation -> Bool) -> [CoreRule]
  968. -> OccEnv
  969. initOccEnv active_rule imp_rules
  970. = OccEnv { occ_encl = OccVanilla
  971. , occ_ctxt = []
  972. , occ_proxy = PE emptyVarEnv emptyVarSet
  973. , occ_rule_fvs = findImpRuleUsage active_rule imp_rules
  974. , occ_rule_act = active_rule }
  975. vanillaCtxt :: OccEnv -> OccEnv
  976. vanillaCtxt env = env { occ_encl = OccVanilla, occ_ctxt = [] }
  977. rhsCtxt :: OccEnv -> OccEnv
  978. rhsCtxt env = env { occ_encl = OccRhs, occ_ctxt = [] }
  979. setCtxtTy :: OccEnv -> CtxtTy -> OccEnv
  980. setCtxtTy env ctxt = env { occ_ctxt = ctxt }
  981. isRhsEnv :: OccEnv -> Bool
  982. isRhsEnv (OccEnv { occ_encl = OccRhs }) = True
  983. isRhsEnv (OccEnv { occ_encl = OccVanilla }) = False
  984. oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
  985. -- The result binders have one-shot-ness set that they might not have had originally.
  986. -- This happens in (build (\cn -> e)). Here the occurrence analyser
  987. -- linearity context knows that c,n are one-shot, and it records that fact in
  988. -- the binder. This is useful to guide subsequent float-in/float-out tranformations
  989. oneShotGroup (OccEnv { occ_ctxt = ctxt }) bndrs
  990. = go ctxt bndrs []
  991. where
  992. go _ [] rev_bndrs = reverse rev_bndrs
  993. go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
  994. | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
  995. where
  996. bndr' | lin_ctxt = setOneShotLambda bndr
  997. | otherwise = bndr
  998. go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
  999. addAppCtxt :: OccEnv -> [Arg CoreBndr] -> OccEnv
  1000. addAppCtxt env@(OccEnv { occ_ctxt = ctxt }) args
  1001. = env { occ_ctxt = replicate (valArgCount args) True ++ ctxt }
  1002. \end{code}
  1003. %************************************************************************
  1004. %* *
  1005. ImpRuleUsage
  1006. %* *
  1007. %************************************************************************
  1008. \begin{code}
  1009. type ImpRuleUsage = NameEnv UsageDetails
  1010. -- Maps an *imported* Id f to the UsageDetails for *local* Ids
  1011. -- used on the RHS for a *local* rule for f.
  1012. \end{code}
  1013. Note [ImpRuleUsage]
  1014. ~~~~~~~~~~~~~~~~
  1015. Consider this, where A.g is an imported Id
  1016. f x = A.g x
  1017. {-# RULE "foo" forall x. A.g x = f x #-}
  1018. Obviously there's a loop, but the danger is that the occurrence analyser
  1019. will say that 'f' is not a loop breaker. Then the simplifier will
  1020. optimise 'f' to
  1021. f x = f x
  1022. and then gaily inline 'f'. Result infinite loop. More realistically,
  1023. these kind of rules are generated when specialising imported INLINABLE Ids.
  1024. Solution: treat an occurrence of A.g as an occurrence of all the local Ids
  1025. that occur on the RULE's RHS. This mapping from imported Id to local Ids
  1026. is held in occ_rule_fvs.
  1027. \begin{code}
  1028. findImpRuleUsage :: Maybe (Activation -> Bool) -> [CoreRule] -> ImpRuleUsage
  1029. -- Find the *local* Ids that can be reached transitively,
  1030. -- via local rules, from each *imported* Id.
  1031. -- Sigh: this function seems more complicated than it is really worth
  1032. findImpRuleUsage Nothing _ = emptyNameEnv
  1033. findImpRuleUsage (Just is_active) rules
  1034. = mkNameEnv [ (f, mapUFM (\_ -> NoOccInfo) ls)
  1035. | f <- rule_names
  1036. , let ls = find_lcl_deps f
  1037. , not (isEmptyVarSet ls) ]
  1038. where
  1039. rule_names = map ru_fn rules
  1040. rule_name_set = mkNameSet rule_names
  1041. imp_deps :: NameEnv VarSet
  1042. -- (f,g) means imported Id 'g' appears in RHS of
  1043. -- rule for imported Id 'f', *or* does so transitively
  1044. imp_deps = foldr add_imp emptyNameEnv rules
  1045. add_imp rule acc
  1046. | is_active (ruleActivation rule)
  1047. = extendNameEnv_C unionVarSet acc (ru_fn rule)
  1048. (exprSomeFreeVars keep_imp (ru_rhs rule))
  1049. | otherwise = acc
  1050. keep_imp v = isId v && (idName v `elemNameSet` rule_name_set)
  1051. full_imp_deps = transClosureFV (ufmToList imp_deps)
  1052. lcl_deps :: NameEnv VarSet
  1053. -- (f, l) means localId 'l' appears immediately
  1054. -- in the RHS of a rule for imported Id 'f'
  1055. -- Remember, many rules might have the same ru_fn
  1056. -- so we do need to fold
  1057. lcl_deps = foldr add_lcl emptyNameEnv rules
  1058. add_lcl rule acc = extendNameEnv_C unionVarSet acc (ru_fn rule)
  1059. (exprFreeIds (ru_rhs rule))
  1060. find_lcl_deps :: Name -> VarSet
  1061. find_lcl_deps f

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