PageRenderTime 63ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/compiler/stranal/DmdAnal.lhs

https://bitbucket.org/carter/ghc
Haskell | 1317 lines | 825 code | 189 blank | 303 comment | 46 complexity | 249166ce8795e0f17dae8835ce333ee5 MD5 | raw file
  1. %
  2. % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
  3. %
  4. -----------------
  5. A demand analysis
  6. -----------------
  7. \begin{code}
  8. {-# OPTIONS -fno-warn-tabs #-}
  9. -- The above warning supression flag is a temporary kludge.
  10. -- While working on this module you are encouraged to remove it and
  11. -- detab the module (please do the detabbing in a separate patch). See
  12. -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
  13. -- for details
  14. module DmdAnal ( dmdAnalPgm, dmdAnalTopRhs,
  15. both {- needed by WwLib -}
  16. ) where
  17. #include "HsVersions.h"
  18. import DynFlags
  19. import Demand -- All of it
  20. import CoreSyn
  21. import PprCore
  22. import Coercion ( isCoVarType )
  23. import CoreUtils ( exprIsHNF, exprIsTrivial )
  24. import CoreArity ( exprArity )
  25. import DataCon ( dataConTyCon, dataConRepStrictness )
  26. import TyCon ( isProductTyCon, isRecursiveTyCon )
  27. import Id ( Id, idType, idInlineActivation,
  28. isDataConWorkId, isGlobalId, idArity,
  29. idStrictness,
  30. setIdStrictness, idDemandInfo, idUnfolding,
  31. idDemandInfo_maybe, setIdDemandInfo
  32. )
  33. import Var ( Var, isTyVar )
  34. import VarEnv
  35. import TysWiredIn ( unboxedPairDataCon )
  36. import TysPrim ( realWorldStatePrimTy )
  37. import UniqFM ( addToUFM_Directly, lookupUFM_Directly,
  38. minusUFM, filterUFM )
  39. import Type ( isUnLiftedType, eqType, tyConAppTyCon_maybe )
  40. import Coercion ( coercionKind )
  41. import Util
  42. import BasicTypes ( Arity, TopLevelFlag(..), isTopLevel, isNeverActive,
  43. RecFlag(..), isRec, isMarkedStrict )
  44. import Maybes ( orElse, expectJust )
  45. import Outputable
  46. import Pair
  47. import Data.List
  48. import FastString
  49. \end{code}
  50. To think about
  51. * set a noinline pragma on bottoming Ids
  52. * Consider f x = x+1 `fatbar` error (show x)
  53. We'd like to unbox x, even if that means reboxing it in the error case.
  54. %************************************************************************
  55. %* *
  56. \subsection{Top level stuff}
  57. %* *
  58. %************************************************************************
  59. \begin{code}
  60. dmdAnalPgm :: DynFlags -> CoreProgram -> IO CoreProgram
  61. dmdAnalPgm dflags binds
  62. = do {
  63. let { binds_plus_dmds = do_prog binds } ;
  64. return binds_plus_dmds
  65. }
  66. where
  67. do_prog :: CoreProgram -> CoreProgram
  68. do_prog binds = snd $ mapAccumL (dmdAnalTopBind dflags) emptySigEnv binds
  69. dmdAnalTopBind :: DynFlags
  70. -> SigEnv
  71. -> CoreBind
  72. -> (SigEnv, CoreBind)
  73. dmdAnalTopBind dflags sigs (NonRec id rhs)
  74. = (sigs2, NonRec id2 rhs2)
  75. where
  76. ( _, _, (_, rhs1)) = dmdAnalRhs dflags TopLevel NonRecursive (virgin sigs) (id, rhs)
  77. (sigs2, _, (id2, rhs2)) = dmdAnalRhs dflags TopLevel NonRecursive (nonVirgin sigs) (id, rhs1)
  78. -- Do two passes to improve CPR information
  79. -- See comments with ignore_cpr_info in mk_sig_ty
  80. -- and with extendSigsWithLam
  81. dmdAnalTopBind dflags sigs (Rec pairs)
  82. = (sigs', Rec pairs')
  83. where
  84. (sigs', _, pairs') = dmdFix dflags TopLevel (virgin sigs) pairs
  85. -- We get two iterations automatically
  86. -- c.f. the NonRec case above
  87. \end{code}
  88. \begin{code}
  89. dmdAnalTopRhs :: DynFlags -> CoreExpr -> (StrictSig, CoreExpr)
  90. -- Analyse the RHS and return
  91. -- a) appropriate strictness info
  92. -- b) the unfolding (decorated with strictness info)
  93. dmdAnalTopRhs dflags rhs
  94. = (sig, rhs2)
  95. where
  96. call_dmd = vanillaCall (exprArity rhs)
  97. (_, rhs1) = dmdAnal dflags (virgin emptySigEnv) call_dmd rhs
  98. (rhs_ty, rhs2) = dmdAnal dflags (nonVirgin emptySigEnv) call_dmd rhs1
  99. sig = mkTopSigTy dflags rhs rhs_ty
  100. -- Do two passes; see notes with extendSigsWithLam
  101. -- Otherwise we get bogus CPR info for constructors like
  102. -- newtype T a = MkT a
  103. -- The constructor looks like (\x::T a -> x), modulo the coerce
  104. -- extendSigsWithLam will optimistically give x a CPR tag the
  105. -- first time, which is wrong in the end.
  106. \end{code}
  107. %************************************************************************
  108. %* *
  109. \subsection{The analyser itself}
  110. %* *
  111. %************************************************************************
  112. \begin{code}
  113. dmdAnal :: DynFlags -> AnalEnv -> Demand -> CoreExpr -> (DmdType, CoreExpr)
  114. dmdAnal _ _ Abs e = (topDmdType, e)
  115. dmdAnal dflags env dmd e
  116. | not (isStrictDmd dmd)
  117. = let
  118. (res_ty, e') = dmdAnal dflags env evalDmd e
  119. in
  120. (deferType res_ty, e')
  121. -- It's important not to analyse e with a lazy demand because
  122. -- a) When we encounter case s of (a,b) ->
  123. -- we demand s with U(d1d2)... but if the overall demand is lazy
  124. -- that is wrong, and we'd need to reduce the demand on s,
  125. -- which is inconvenient
  126. -- b) More important, consider
  127. -- f (let x = R in x+x), where f is lazy
  128. -- We still want to mark x as demanded, because it will be when we
  129. -- enter the let. If we analyse f's arg with a Lazy demand, we'll
  130. -- just mark x as Lazy
  131. -- c) The application rule wouldn't be right either
  132. -- Evaluating (f x) in a L demand does *not* cause
  133. -- evaluation of f in a C(L) demand!
  134. dmdAnal _ _ _ (Lit lit) = (topDmdType, Lit lit)
  135. dmdAnal _ _ _ (Type ty) = (topDmdType, Type ty) -- Doesn't happen, in fact
  136. dmdAnal _ _ _ (Coercion co) = (topDmdType, Coercion co)
  137. dmdAnal _ env dmd (Var var)
  138. = (dmdTransform env var dmd, Var var)
  139. dmdAnal dflags env dmd (Cast e co)
  140. = (dmd_ty, Cast e' co)
  141. where
  142. (dmd_ty, e') = dmdAnal dflags env dmd' e
  143. to_co = pSnd (coercionKind co)
  144. dmd'
  145. | Just tc <- tyConAppTyCon_maybe to_co
  146. , isRecursiveTyCon tc = evalDmd
  147. | otherwise = dmd
  148. -- This coerce usually arises from a recursive
  149. -- newtype, and we don't want to look inside them
  150. -- for exactly the same reason that we don't look
  151. -- inside recursive products -- we might not reach
  152. -- a fixpoint. So revert to a vanilla Eval demand
  153. dmdAnal dflags env dmd (Tick t e)
  154. = (dmd_ty, Tick t e')
  155. where
  156. (dmd_ty, e') = dmdAnal dflags env dmd e
  157. dmdAnal dflags env dmd (App fun (Type ty))
  158. = (fun_ty, App fun' (Type ty))
  159. where
  160. (fun_ty, fun') = dmdAnal dflags env dmd fun
  161. dmdAnal dflags sigs dmd (App fun (Coercion co))
  162. = (fun_ty, App fun' (Coercion co))
  163. where
  164. (fun_ty, fun') = dmdAnal dflags sigs dmd fun
  165. -- Lots of the other code is there to make this
  166. -- beautiful, compositional, application rule :-)
  167. dmdAnal dflags env dmd (App fun arg) -- Non-type arguments
  168. = let -- [Type arg handled above]
  169. (fun_ty, fun') = dmdAnal dflags env (Call dmd) fun
  170. (arg_ty, arg') = dmdAnal dflags env arg_dmd arg
  171. (arg_dmd, res_ty) = splitDmdTy fun_ty
  172. in
  173. (res_ty `bothType` arg_ty, App fun' arg')
  174. dmdAnal dflags env dmd (Lam var body)
  175. | isTyVar var
  176. = let
  177. (body_ty, body') = dmdAnal dflags env dmd body
  178. in
  179. (body_ty, Lam var body')
  180. | Call body_dmd <- dmd -- A call demand: good!
  181. = let
  182. env' = extendSigsWithLam env var
  183. (body_ty, body') = dmdAnal dflags env' body_dmd body
  184. (lam_ty, var') = annotateLamIdBndr dflags env body_ty var
  185. in
  186. (lam_ty, Lam var' body')
  187. | otherwise -- Not enough demand on the lambda; but do the body
  188. = let -- anyway to annotate it and gather free var info
  189. (body_ty, body') = dmdAnal dflags env evalDmd body
  190. (lam_ty, var') = annotateLamIdBndr dflags env body_ty var
  191. in
  192. (deferType lam_ty, Lam var' body')
  193. dmdAnal dflags env dmd (Case scrut case_bndr ty [alt@(DataAlt dc, _, _)])
  194. | let tycon = dataConTyCon dc
  195. , isProductTyCon tycon
  196. , not (isRecursiveTyCon tycon)
  197. = let
  198. env_alt = extendAnalEnv NotTopLevel env case_bndr case_bndr_sig
  199. (alt_ty, alt') = dmdAnalAlt dflags env_alt dmd alt
  200. (alt_ty1, case_bndr') = annotateBndr alt_ty case_bndr
  201. (_, bndrs', _) = alt'
  202. case_bndr_sig = cprSig
  203. -- Inside the alternative, the case binder has the CPR property.
  204. -- Meaning that a case on it will successfully cancel.
  205. -- Example:
  206. -- f True x = case x of y { I# x' -> if x' ==# 3 then y else I# 8 }
  207. -- f False x = I# 3
  208. --
  209. -- We want f to have the CPR property:
  210. -- f b x = case fw b x of { r -> I# r }
  211. -- fw True x = case x of y { I# x' -> if x' ==# 3 then x' else 8 }
  212. -- fw False x = 3
  213. -- Figure out whether the demand on the case binder is used, and use
  214. -- that to set the scrut_dmd. This is utterly essential.
  215. -- Consider f x = case x of y { (a,b) -> k y a }
  216. -- If we just take scrut_demand = U(L,A), then we won't pass x to the
  217. -- worker, so the worker will rebuild
  218. -- x = (a, absent-error)
  219. -- and that'll crash.
  220. -- So at one stage I had:
  221. -- dead_case_bndr = isAbsentDmd (idDemandInfo case_bndr')
  222. -- keepity | dead_case_bndr = Drop
  223. -- | otherwise = Keep
  224. --
  225. -- But then consider
  226. -- case x of y { (a,b) -> h y + a }
  227. -- where h : U(LL) -> T
  228. -- The above code would compute a Keep for x, since y is not Abs, which is silly
  229. -- The insight is, of course, that a demand on y is a demand on the
  230. -- scrutinee, so we need to `both` it with the scrut demand
  231. alt_dmd = Eval (Prod [idDemandInfo b | b <- bndrs', isId b])
  232. scrut_dmd = alt_dmd `both`
  233. idDemandInfo case_bndr'
  234. (scrut_ty, scrut') = dmdAnal dflags env scrut_dmd scrut
  235. res_ty = alt_ty1 `bothType` scrut_ty
  236. in
  237. -- pprTrace "dmdAnal:Case1" (vcat [ text "scrut" <+> ppr scrut
  238. -- , text "scrut_ty" <+> ppr scrut_ty
  239. -- , text "alt_ty" <+> ppr alt_ty1
  240. -- , text "res_ty" <+> ppr res_ty ]) $
  241. (res_ty, Case scrut' case_bndr' ty [alt'])
  242. dmdAnal dflags env dmd (Case scrut case_bndr ty alts)
  243. = let
  244. (alt_tys, alts') = mapAndUnzip (dmdAnalAlt dflags env dmd) alts
  245. (scrut_ty, scrut') = dmdAnal dflags env evalDmd scrut
  246. (alt_ty, case_bndr') = annotateBndr (foldr lubType botDmdType alt_tys) case_bndr
  247. res_ty = alt_ty `bothType` scrut_ty
  248. in
  249. -- pprTrace "dmdAnal:Case2" (vcat [ text "scrut" <+> ppr scrut
  250. -- , text "scrut_ty" <+> ppr scrut_ty
  251. -- , text "alt_ty" <+> ppr alt_ty
  252. -- , text "res_ty" <+> ppr res_ty ]) $
  253. (res_ty, Case scrut' case_bndr' ty alts')
  254. dmdAnal dflags env dmd (Let (NonRec id rhs) body)
  255. = let
  256. (sigs', lazy_fv, (id1, rhs')) = dmdAnalRhs dflags NotTopLevel NonRecursive env (id, rhs)
  257. (body_ty, body') = dmdAnal dflags (updSigEnv env sigs') dmd body
  258. (body_ty1, id2) = annotateBndr body_ty id1
  259. body_ty2 = addLazyFVs body_ty1 lazy_fv
  260. in
  261. -- If the actual demand is better than the vanilla call
  262. -- demand, you might think that we might do better to re-analyse
  263. -- the RHS with the stronger demand.
  264. -- But (a) That seldom happens, because it means that *every* path in
  265. -- the body of the let has to use that stronger demand
  266. -- (b) It often happens temporarily in when fixpointing, because
  267. -- the recursive function at first seems to place a massive demand.
  268. -- But we don't want to go to extra work when the function will
  269. -- probably iterate to something less demanding.
  270. -- In practice, all the times the actual demand on id2 is more than
  271. -- the vanilla call demand seem to be due to (b). So we don't
  272. -- bother to re-analyse the RHS.
  273. (body_ty2, Let (NonRec id2 rhs') body')
  274. dmdAnal dflags env dmd (Let (Rec pairs) body)
  275. = let
  276. bndrs = map fst pairs
  277. (sigs', lazy_fv, pairs') = dmdFix dflags NotTopLevel env pairs
  278. (body_ty, body') = dmdAnal dflags (updSigEnv env sigs') dmd body
  279. body_ty1 = addLazyFVs body_ty lazy_fv
  280. in
  281. sigs' `seq` body_ty `seq`
  282. let
  283. (body_ty2, _) = annotateBndrs body_ty1 bndrs
  284. -- Don't bother to add demand info to recursive
  285. -- binders as annotateBndr does;
  286. -- being recursive, we can't treat them strictly.
  287. -- But we do need to remove the binders from the result demand env
  288. in
  289. (body_ty2, Let (Rec pairs') body')
  290. dmdAnalAlt :: DynFlags -> AnalEnv -> Demand -> Alt Var -> (DmdType, Alt Var)
  291. dmdAnalAlt dflags env dmd (con,bndrs,rhs)
  292. = let
  293. (rhs_ty, rhs') = dmdAnal dflags env dmd rhs
  294. rhs_ty' = addDataConPatDmds con bndrs rhs_ty
  295. (alt_ty, bndrs') = annotateBndrs rhs_ty' bndrs
  296. final_alt_ty | io_hack_reqd = alt_ty `lubType` topDmdType
  297. | otherwise = alt_ty
  298. -- There's a hack here for I/O operations. Consider
  299. -- case foo x s of { (# s, r #) -> y }
  300. -- Is this strict in 'y'. Normally yes, but what if 'foo' is an I/O
  301. -- operation that simply terminates the program (not in an erroneous way)?
  302. -- In that case we should not evaluate y before the call to 'foo'.
  303. -- Hackish solution: spot the IO-like situation and add a virtual branch,
  304. -- as if we had
  305. -- case foo x s of
  306. -- (# s, r #) -> y
  307. -- other -> return ()
  308. -- So the 'y' isn't necessarily going to be evaluated
  309. --
  310. -- A more complete example (Trac #148, #1592) where this shows up is:
  311. -- do { let len = <expensive> ;
  312. -- ; when (...) (exitWith ExitSuccess)
  313. -- ; print len }
  314. io_hack_reqd = con == DataAlt unboxedPairDataCon &&
  315. idType (head bndrs) `eqType` realWorldStatePrimTy
  316. in
  317. (final_alt_ty, (con, bndrs', rhs'))
  318. addDataConPatDmds :: AltCon -> [Var] -> DmdType -> DmdType
  319. -- See Note [Add demands for strict constructors]
  320. addDataConPatDmds DEFAULT _ dmd_ty = dmd_ty
  321. addDataConPatDmds (LitAlt _) _ dmd_ty = dmd_ty
  322. addDataConPatDmds (DataAlt con) bndrs dmd_ty
  323. = foldr add dmd_ty str_bndrs
  324. where
  325. add bndr dmd_ty = addVarDmd dmd_ty bndr seqDmd
  326. str_bndrs = [ b | (b,s) <- zipEqual "addDataConPatBndrs"
  327. (filter isId bndrs)
  328. (dataConRepStrictness con)
  329. , isMarkedStrict s ]
  330. \end{code}
  331. Note [Add demands for strict constructors]
  332. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  333. Consider this program (due to Roman):
  334. data X a = X !a
  335. foo :: X Int -> Int -> Int
  336. foo (X a) n = go 0
  337. where
  338. go i | i < n = a + go (i+1)
  339. | otherwise = 0
  340. We want the worker for 'foo' too look like this:
  341. $wfoo :: Int# -> Int# -> Int#
  342. with the first argument unboxed, so that it is not eval'd each time
  343. around the loop (which would otherwise happen, since 'foo' is not
  344. strict in 'a'. It is sound for the wrapper to pass an unboxed arg
  345. because X is strict, so its argument must be evaluated. And if we
  346. *don't* pass an unboxed argument, we can't even repair it by adding a
  347. `seq` thus:
  348. foo (X a) n = a `seq` go 0
  349. because the seq is discarded (very early) since X is strict!
  350. There is the usual danger of reboxing, which as usual we ignore. But
  351. if X is monomorphic, and has an UNPACK pragma, then this optimisation
  352. is even more important. We don't want the wrapper to rebox an unboxed
  353. argument, and pass an Int to $wfoo!
  354. %************************************************************************
  355. %* *
  356. Demand transformer
  357. %* *
  358. %************************************************************************
  359. \begin{code}
  360. dmdTransform :: AnalEnv -- The strictness environment
  361. -> Id -- The function
  362. -> Demand -- The demand on the function
  363. -> DmdType -- The demand type of the function in this context
  364. -- Returned DmdEnv includes the demand on
  365. -- this function plus demand on its free variables
  366. dmdTransform env var dmd
  367. ------ DATA CONSTRUCTOR
  368. | isDataConWorkId var -- Data constructor
  369. = let
  370. StrictSig dmd_ty = idStrictness var -- It must have a strictness sig
  371. DmdType _ _ con_res = dmd_ty
  372. arity = idArity var
  373. in
  374. if arity == call_depth then -- Saturated, so unleash the demand
  375. let
  376. -- Important! If we Keep the constructor application, then
  377. -- we need the demands the constructor places (always lazy)
  378. -- If not, we don't need to. For example:
  379. -- f p@(x,y) = (p,y) -- S(AL)
  380. -- g a b = f (a,b)
  381. -- It's vital that we don't calculate Absent for a!
  382. dmd_ds = case res_dmd of
  383. Box (Eval ds) -> mapDmds box ds
  384. Eval ds -> ds
  385. _ -> Poly Top
  386. -- ds can be empty, when we are just seq'ing the thing
  387. -- If so we must make up a suitable bunch of demands
  388. arg_ds = case dmd_ds of
  389. Poly d -> replicate arity d
  390. Prod ds -> ASSERT( ds `lengthIs` arity ) ds
  391. in
  392. mkDmdType emptyDmdEnv arg_ds con_res
  393. -- Must remember whether it's a product, hence con_res, not TopRes
  394. else
  395. topDmdType
  396. ------ IMPORTED FUNCTION
  397. | isGlobalId var, -- Imported function
  398. let StrictSig dmd_ty = idStrictness var
  399. = -- pprTrace "strict-sig" (ppr var $$ ppr dmd_ty) $
  400. if dmdTypeDepth dmd_ty <= call_depth then -- Saturated, so unleash the demand
  401. dmd_ty
  402. else
  403. topDmdType
  404. ------ LOCAL LET/REC BOUND THING
  405. | Just (StrictSig dmd_ty, top_lvl) <- lookupSigEnv env var
  406. = let
  407. fn_ty | dmdTypeDepth dmd_ty <= call_depth = dmd_ty
  408. | otherwise = deferType dmd_ty
  409. -- NB: it's important to use deferType, and not just return topDmdType
  410. -- Consider let { f x y = p + x } in f 1
  411. -- The application isn't saturated, but we must nevertheless propagate
  412. -- a lazy demand for p!
  413. in
  414. if isTopLevel top_lvl then fn_ty -- Don't record top level things
  415. else addVarDmd fn_ty var dmd
  416. ------ LOCAL NON-LET/REC BOUND THING
  417. | otherwise -- Default case
  418. = unitVarDmd var dmd
  419. where
  420. (call_depth, res_dmd) = splitCallDmd dmd
  421. \end{code}
  422. %************************************************************************
  423. %* *
  424. \subsection{Bindings}
  425. %* *
  426. %************************************************************************
  427. \begin{code}
  428. dmdFix :: DynFlags
  429. -> TopLevelFlag
  430. -> AnalEnv -- Does not include bindings for this binding
  431. -> [(Id,CoreExpr)]
  432. -> (SigEnv, DmdEnv,
  433. [(Id,CoreExpr)]) -- Binders annotated with stricness info
  434. dmdFix dflags top_lvl env orig_pairs
  435. = loop 1 initial_env orig_pairs
  436. where
  437. bndrs = map fst orig_pairs
  438. initial_env = addInitialSigs top_lvl env bndrs
  439. loop :: Int
  440. -> AnalEnv -- Already contains the current sigs
  441. -> [(Id,CoreExpr)]
  442. -> (SigEnv, DmdEnv, [(Id,CoreExpr)])
  443. loop n env pairs
  444. = -- pprTrace "dmd loop" (ppr n <+> ppr bndrs $$ ppr env) $
  445. loop' n env pairs
  446. loop' n env pairs
  447. | found_fixpoint
  448. = (sigs', lazy_fv, pairs')
  449. -- Note: return pairs', not pairs. pairs' is the result of
  450. -- processing the RHSs with sigs (= sigs'), whereas pairs
  451. -- is the result of processing the RHSs with the *previous*
  452. -- iteration of sigs.
  453. | n >= 10
  454. = pprTrace "dmdFix loop" (ppr n <+> (vcat
  455. [ text "Sigs:" <+> ppr [ (id,lookupVarEnv sigs id, lookupVarEnv sigs' id)
  456. | (id,_) <- pairs],
  457. text "env:" <+> ppr env,
  458. text "binds:" <+> pprCoreBinding (Rec pairs)]))
  459. (sigEnv env, lazy_fv, orig_pairs) -- Safe output
  460. -- The lazy_fv part is really important! orig_pairs has no strictness
  461. -- info, including nothing about free vars. But if we have
  462. -- letrec f = ....y..... in ...f...
  463. -- where 'y' is free in f, we must record that y is mentioned,
  464. -- otherwise y will get recorded as absent altogether
  465. | otherwise
  466. = loop (n+1) (nonVirgin sigs') pairs'
  467. where
  468. sigs = sigEnv env
  469. found_fixpoint = all (same_sig sigs sigs') bndrs
  470. ((sigs',lazy_fv), pairs') = mapAccumL my_downRhs (sigs, emptyDmdEnv) pairs
  471. -- mapAccumL: Use the new signature to do the next pair
  472. -- The occurrence analyser has arranged them in a good order
  473. -- so this can significantly reduce the number of iterations needed
  474. my_downRhs (sigs,lazy_fv) (id,rhs)
  475. = ((sigs', lazy_fv'), pair')
  476. where
  477. (sigs', lazy_fv1, pair') = dmdAnalRhs dflags top_lvl Recursive (updSigEnv env sigs) (id,rhs)
  478. lazy_fv' = plusVarEnv_C both lazy_fv lazy_fv1
  479. same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
  480. lookup sigs var = case lookupVarEnv sigs var of
  481. Just (sig,_) -> sig
  482. Nothing -> pprPanic "dmdFix" (ppr var)
  483. dmdAnalRhs :: DynFlags -> TopLevelFlag -> RecFlag
  484. -> AnalEnv -> (Id, CoreExpr)
  485. -> (SigEnv, DmdEnv, (Id, CoreExpr))
  486. -- Process the RHS of the binding, add the strictness signature
  487. -- to the Id, and augment the environment with the signature as well.
  488. dmdAnalRhs dflags top_lvl rec_flag env (id, rhs)
  489. = (sigs', lazy_fv, (id', rhs'))
  490. where
  491. arity = idArity id -- The idArity should be up to date
  492. -- The simplifier was run just beforehand
  493. (rhs_dmd_ty, rhs') = dmdAnal dflags env (vanillaCall arity) rhs
  494. (lazy_fv, sig_ty) = WARN( arity /= dmdTypeDepth rhs_dmd_ty && not (exprIsTrivial rhs), ppr id )
  495. -- The RHS can be eta-reduced to just a variable,
  496. -- in which case we should not complain.
  497. mkSigTy dflags top_lvl rec_flag id rhs rhs_dmd_ty
  498. id' = id `setIdStrictness` sig_ty
  499. sigs' = extendSigEnv top_lvl (sigEnv env) id sig_ty
  500. \end{code}
  501. %************************************************************************
  502. %* *
  503. \subsection{Strictness signatures and types}
  504. %* *
  505. %************************************************************************
  506. \begin{code}
  507. mkTopSigTy :: DynFlags -> CoreExpr -> DmdType -> StrictSig
  508. -- Take a DmdType and turn it into a StrictSig
  509. -- NB: not used for never-inline things; hence False
  510. mkTopSigTy dflags rhs dmd_ty = snd (mk_sig_ty dflags False False rhs dmd_ty)
  511. mkSigTy :: DynFlags -> TopLevelFlag -> RecFlag -> Id -> CoreExpr -> DmdType -> (DmdEnv, StrictSig)
  512. mkSigTy dflags top_lvl rec_flag id rhs dmd_ty
  513. = mk_sig_ty dflags never_inline thunk_cpr_ok rhs dmd_ty
  514. where
  515. never_inline = isNeverActive (idInlineActivation id)
  516. maybe_id_dmd = idDemandInfo_maybe id
  517. -- Is Nothing the first time round
  518. thunk_cpr_ok -- See Note [CPR for thunks]
  519. | isTopLevel top_lvl = False -- Top level things don't get
  520. -- their demandInfo set at all
  521. | isRec rec_flag = False -- Ditto recursive things
  522. | Just dmd <- maybe_id_dmd = isStrictDmd dmd
  523. | otherwise = True -- Optimistic, first time round
  524. -- See notes below
  525. \end{code}
  526. Note [CPR for thunks]
  527. ~~~~~~~~~~~~~~~~~~~~~
  528. If the rhs is a thunk, we usually forget the CPR info, because
  529. it is presumably shared (else it would have been inlined, and
  530. so we'd lose sharing if w/w'd it into a function). E.g.
  531. let r = case expensive of
  532. (a,b) -> (b,a)
  533. in ...
  534. If we marked r as having the CPR property, then we'd w/w into
  535. let $wr = \() -> case expensive of
  536. (a,b) -> (# b, a #)
  537. r = case $wr () of
  538. (# b,a #) -> (b,a)
  539. in ...
  540. But now r is a thunk, which won't be inlined, so we are no further ahead.
  541. But consider
  542. f x = let r = case expensive of (a,b) -> (b,a)
  543. in if foo r then r else (x,x)
  544. Does f have the CPR property? Well, no.
  545. However, if the strictness analyser has figured out (in a previous
  546. iteration) that it's strict, then we DON'T need to forget the CPR info.
  547. Instead we can retain the CPR info and do the thunk-splitting transform
  548. (see WorkWrap.splitThunk).
  549. This made a big difference to PrelBase.modInt, which had something like
  550. modInt = \ x -> let r = ... -> I# v in
  551. ...body strict in r...
  552. r's RHS isn't a value yet; but modInt returns r in various branches, so
  553. if r doesn't have the CPR property then neither does modInt
  554. Another case I found in practice (in Complex.magnitude), looks like this:
  555. let k = if ... then I# a else I# b
  556. in ... body strict in k ....
  557. (For this example, it doesn't matter whether k is returned as part of
  558. the overall result; but it does matter that k's RHS has the CPR property.)
  559. Left to itself, the simplifier will make a join point thus:
  560. let $j k = ...body strict in k...
  561. if ... then $j (I# a) else $j (I# b)
  562. With thunk-splitting, we get instead
  563. let $j x = let k = I#x in ...body strict in k...
  564. in if ... then $j a else $j b
  565. This is much better; there's a good chance the I# won't get allocated.
  566. The difficulty with this is that we need the strictness type to
  567. look at the body... but we now need the body to calculate the demand
  568. on the variable, so we can decide whether its strictness type should
  569. have a CPR in it or not. Simple solution:
  570. a) use strictness info from the previous iteration
  571. b) make sure we do at least 2 iterations, by doing a second
  572. round for top-level non-recs. Top level recs will get at
  573. least 2 iterations except for totally-bottom functions
  574. which aren't very interesting anyway.
  575. NB: strictly_demanded is never true of a top-level Id, or of a recursive Id.
  576. Note [Optimistic in the Nothing case]
  577. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  578. Demand info now has a 'Nothing' state, just like strictness info.
  579. The analysis works from 'dangerous' towards a 'safe' state; so we
  580. start with botSig for 'Nothing' strictness infos, and we start with
  581. "yes, it's demanded" for 'Nothing' in the demand info. The
  582. fixpoint iteration will sort it all out.
  583. We can't start with 'not-demanded' because then consider
  584. f x = let
  585. t = ... I# x
  586. in
  587. if ... then t else I# y else f x'
  588. In the first iteration we'd have no demand info for x, so assume
  589. not-demanded; then we'd get TopRes for f's CPR info. Next iteration
  590. we'd see that t was demanded, and so give it the CPR property, but by
  591. now f has TopRes, so it will stay TopRes. Instead, with the Nothing
  592. setting the first time round, we say 'yes t is demanded' the first
  593. time.
  594. However, this does mean that for non-recursive bindings we must
  595. iterate twice to be sure of not getting over-optimistic CPR info,
  596. in the case where t turns out to be not-demanded. This is handled
  597. by dmdAnalTopBind.
  598. Note [NOINLINE and strictness]
  599. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  600. The strictness analyser used to have a HACK which ensured that NOINLNE
  601. things were not strictness-analysed. The reason was unsafePerformIO.
  602. Left to itself, the strictness analyser would discover this strictness
  603. for unsafePerformIO:
  604. unsafePerformIO: C(U(AV))
  605. But then consider this sub-expression
  606. unsafePerformIO (\s -> let r = f x in
  607. case writeIORef v r s of (# s1, _ #) ->
  608. (# s1, r #)
  609. The strictness analyser will now find that r is sure to be eval'd,
  610. and may then hoist it out. This makes tests/lib/should_run/memo002
  611. deadlock.
  612. Solving this by making all NOINLINE things have no strictness info is overkill.
  613. In particular, it's overkill for runST, which is perfectly respectable.
  614. Consider
  615. f x = runST (return x)
  616. This should be strict in x.
  617. So the new plan is to define unsafePerformIO using the 'lazy' combinator:
  618. unsafePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
  619. Remember, 'lazy' is a wired-in identity-function Id, of type a->a, which is
  620. magically NON-STRICT, and is inlined after strictness analysis. So
  621. unsafePerformIO will look non-strict, and that's what we want.
  622. Now we don't need the hack in the strictness analyser. HOWEVER, this
  623. decision does mean that even a NOINLINE function is not entirely
  624. opaque: some aspect of its implementation leaks out, notably its
  625. strictness. For example, if you have a function implemented by an
  626. error stub, but which has RULES, you may want it not to be eliminated
  627. in favour of error!
  628. \begin{code}
  629. mk_sig_ty :: DynFlags -> Bool -> Bool -> CoreExpr
  630. -> DmdType -> (DmdEnv, StrictSig)
  631. mk_sig_ty dflags _never_inline thunk_cpr_ok rhs (DmdType fv dmds res)
  632. = (lazy_fv, mkStrictSig dmd_ty)
  633. -- Re unused never_inline, see Note [NOINLINE and strictness]
  634. where
  635. dmd_ty = DmdType strict_fv final_dmds res'
  636. lazy_fv = filterUFM (not . isStrictDmd) fv
  637. strict_fv = filterUFM isStrictDmd fv
  638. -- We put the strict FVs in the DmdType of the Id, so
  639. -- that at its call sites we unleash demands on its strict fvs.
  640. -- An example is 'roll' in imaginary/wheel-sieve2
  641. -- Something like this:
  642. -- roll x = letrec
  643. -- go y = if ... then roll (x-1) else x+1
  644. -- in
  645. -- go ms
  646. -- We want to see that roll is strict in x, which is because
  647. -- go is called. So we put the DmdEnv for x in go's DmdType.
  648. --
  649. -- Another example:
  650. -- f :: Int -> Int -> Int
  651. -- f x y = let t = x+1
  652. -- h z = if z==0 then t else
  653. -- if z==1 then x+1 else
  654. -- x + h (z-1)
  655. -- in
  656. -- h y
  657. -- Calling h does indeed evaluate x, but we can only see
  658. -- that if we unleash a demand on x at the call site for t.
  659. --
  660. -- Incidentally, here's a place where lambda-lifting h would
  661. -- lose the cigar --- we couldn't see the joint strictness in t/x
  662. --
  663. -- ON THE OTHER HAND
  664. -- We don't want to put *all* the fv's from the RHS into the
  665. -- DmdType, because that makes fixpointing very slow --- the
  666. -- DmdType gets full of lazy demands that are slow to converge.
  667. final_dmds = setUnpackStrategy dflags dmds
  668. -- Set the unpacking strategy
  669. res' = case res of
  670. RetCPR | ignore_cpr_info -> TopRes
  671. _ -> res
  672. ignore_cpr_info = not (exprIsHNF rhs || thunk_cpr_ok)
  673. \end{code}
  674. The unpack strategy determines whether we'll *really* unpack the argument,
  675. or whether we'll just remember its strictness. If unpacking would give
  676. rise to a *lot* of worker args, we may decide not to unpack after all.
  677. \begin{code}
  678. setUnpackStrategy :: DynFlags -> [Demand] -> [Demand]
  679. setUnpackStrategy dflags ds
  680. = snd (go (maxWorkerArgs dflags - nonAbsentArgs ds) ds)
  681. where
  682. go :: Int -- Max number of args available for sub-components of [Demand]
  683. -> [Demand]
  684. -> (Int, [Demand]) -- Args remaining after subcomponents of [Demand] are unpacked
  685. go n (Eval (Prod cs) : ds)
  686. | n' >= 0 = Eval (Prod cs') `cons` go n'' ds
  687. | otherwise = Box (Eval (Prod cs)) `cons` go n ds
  688. where
  689. (n'',cs') = go n' cs
  690. n' = n + 1 - non_abs_args
  691. -- Add one to the budget 'cos we drop the top-level arg
  692. non_abs_args = nonAbsentArgs cs
  693. -- Delete # of non-absent args to which we'll now be committed
  694. go n (d:ds) = d `cons` go n ds
  695. go n [] = (n,[])
  696. cons d (n,ds) = (n, d:ds)
  697. nonAbsentArgs :: [Demand] -> Int
  698. nonAbsentArgs [] = 0
  699. nonAbsentArgs (Abs : ds) = nonAbsentArgs ds
  700. nonAbsentArgs (_ : ds) = 1 + nonAbsentArgs ds
  701. \end{code}
  702. %************************************************************************
  703. %* *
  704. \subsection{Strictness signatures and types}
  705. %* *
  706. %************************************************************************
  707. \begin{code}
  708. unitVarDmd :: Var -> Demand -> DmdType
  709. unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes
  710. addVarDmd :: DmdType -> Var -> Demand -> DmdType
  711. addVarDmd (DmdType fv ds res) var dmd
  712. = DmdType (extendVarEnv_C both fv var dmd) ds res
  713. addLazyFVs :: DmdType -> DmdEnv -> DmdType
  714. addLazyFVs (DmdType fv ds res) lazy_fvs
  715. = DmdType both_fv1 ds res
  716. where
  717. both_fv = plusVarEnv_C both fv lazy_fvs
  718. both_fv1 = modifyEnv (isBotRes res) (`both` Bot) lazy_fvs fv both_fv
  719. -- This modifyEnv is vital. Consider
  720. -- let f = \x -> (x,y)
  721. -- in error (f 3)
  722. -- Here, y is treated as a lazy-fv of f, but we must `both` that L
  723. -- demand with the bottom coming up from 'error'
  724. --
  725. -- I got a loop in the fixpointer without this, due to an interaction
  726. -- with the lazy_fv filtering in mkSigTy. Roughly, it was
  727. -- letrec f n x
  728. -- = letrec g y = x `fatbar`
  729. -- letrec h z = z + ...g...
  730. -- in h (f (n-1) x)
  731. -- in ...
  732. -- In the initial iteration for f, f=Bot
  733. -- Suppose h is found to be strict in z, but the occurrence of g in its RHS
  734. -- is lazy. Now consider the fixpoint iteration for g, esp the demands it
  735. -- places on its free variables. Suppose it places none. Then the
  736. -- x `fatbar` ...call to h...
  737. -- will give a x->V demand for x. That turns into a L demand for x,
  738. -- which floats out of the defn for h. Without the modifyEnv, that
  739. -- L demand doesn't get both'd with the Bot coming up from the inner
  740. -- call to f. So we just get an L demand for x for g.
  741. --
  742. -- A better way to say this is that the lazy-fv filtering should give the
  743. -- same answer as putting the lazy fv demands in the function's type.
  744. annotateBndr :: DmdType -> Var -> (DmdType, Var)
  745. -- The returned env has the var deleted
  746. -- The returned var is annotated with demand info
  747. -- No effect on the argument demands
  748. annotateBndr dmd_ty@(DmdType fv ds res) var
  749. | isTyVar var = (dmd_ty, var)
  750. | otherwise = (DmdType fv' ds res, setIdDemandInfo var dmd)
  751. where
  752. (fv', dmd) = removeFV fv var res
  753. annotateBndrs :: DmdType -> [Var] -> (DmdType, [Var])
  754. annotateBndrs = mapAccumR annotateBndr
  755. annotateLamIdBndr :: DynFlags
  756. -> AnalEnv
  757. -> DmdType -- Demand type of body
  758. -> Id -- Lambda binder
  759. -> (DmdType, -- Demand type of lambda
  760. Id) -- and binder annotated with demand
  761. annotateLamIdBndr dflags env (DmdType fv ds res) id
  762. -- For lambdas we add the demand to the argument demands
  763. -- Only called for Ids
  764. = ASSERT( isId id )
  765. (final_ty, setIdDemandInfo id hacked_dmd)
  766. where
  767. -- Watch out! See note [Lambda-bound unfoldings]
  768. final_ty = case maybeUnfoldingTemplate (idUnfolding id) of
  769. Nothing -> main_ty
  770. Just unf -> main_ty `bothType` unf_ty
  771. where
  772. (unf_ty, _) = dmdAnal dflags env dmd unf
  773. main_ty = DmdType fv' (hacked_dmd:ds) res
  774. (fv', dmd) = removeFV fv id res
  775. hacked_dmd = argDemand dmd
  776. -- This call to argDemand is vital, because otherwise we label
  777. -- a lambda binder with demand 'B'. But in terms of calling
  778. -- conventions that's Abs, because we don't pass it. But
  779. -- when we do a w/w split we get
  780. -- fw x = (\x y:B -> ...) x (error "oops")
  781. -- And then the simplifier things the 'B' is a strict demand
  782. -- and evaluates the (error "oops"). Sigh
  783. removeFV :: DmdEnv -> Var -> DmdResult -> (DmdEnv, Demand)
  784. removeFV fv id res = (fv', zapUnlifted id dmd)
  785. where
  786. fv' = fv `delVarEnv` id
  787. dmd = lookupVarEnv fv id `orElse` deflt
  788. deflt | isBotRes res = Bot
  789. | otherwise = Abs
  790. zapUnlifted :: Id -> Demand -> Demand
  791. -- For unlifted-type variables, we are only
  792. -- interested in Bot/Abs/Box Abs
  793. zapUnlifted id dmd
  794. = case dmd of
  795. _ | isCoVarType ty -> lazyDmd -- For coercions, ignore str/abs totally
  796. Bot -> Bot
  797. Abs -> Abs
  798. _ | isUnLiftedType ty -> lazyDmd -- For unlifted types, ignore strictness
  799. | otherwise -> dmd
  800. where
  801. ty = idType id
  802. \end{code}
  803. Note [Lamba-bound unfoldings]
  804. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  805. We allow a lambda-bound variable to carry an unfolding, a facility that is used
  806. exclusively for join points; see Note [Case binders and join points]. If so,
  807. we must be careful to demand-analyse the RHS of the unfolding! Example
  808. \x. \y{=Just x}. <body>
  809. Then if <body> uses 'y', then transitively it uses 'x', and we must not
  810. forget that fact, otherwise we might make 'x' absent when it isn't.
  811. %************************************************************************
  812. %* *
  813. \subsection{Strictness signatures}
  814. %* *
  815. %************************************************************************
  816. \begin{code}
  817. data AnalEnv
  818. = AE { ae_sigs :: SigEnv
  819. , ae_virgin :: Bool } -- True on first iteration only
  820. -- See Note [Initialising strictness]
  821. -- We use the se_env to tell us whether to
  822. -- record info about a variable in the DmdEnv
  823. -- We do so if it's a LocalId, but not top-level
  824. --
  825. -- The DmdEnv gives the demand on the free vars of the function
  826. -- when it is given enough args to satisfy the strictness signature
  827. type SigEnv = VarEnv (StrictSig, TopLevelFlag)
  828. instance Outputable AnalEnv where
  829. ppr (AE { ae_sigs = env, ae_virgin = virgin })
  830. = ptext (sLit "AE") <+> braces (vcat
  831. [ ptext (sLit "ae_virgin =") <+> ppr virgin
  832. , ptext (sLit "ae_sigs =") <+> ppr env ])
  833. emptySigEnv :: SigEnv
  834. emptySigEnv = emptyVarEnv
  835. sigEnv :: AnalEnv -> SigEnv
  836. sigEnv = ae_sigs
  837. updSigEnv :: AnalEnv -> SigEnv -> AnalEnv
  838. updSigEnv env sigs = env { ae_sigs = sigs }
  839. extendAnalEnv :: TopLevelFlag -> AnalEnv -> Id -> StrictSig -> AnalEnv
  840. extendAnalEnv top_lvl env var sig
  841. = env { ae_sigs = extendSigEnv top_lvl (ae_sigs env) var sig }
  842. extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
  843. extendSigEnv top_lvl sigs var sig = extendVarEnv sigs var (sig, top_lvl)
  844. lookupSigEnv :: AnalEnv -> Id -> Maybe (StrictSig, TopLevelFlag)
  845. lookupSigEnv env id = lookupVarEnv (ae_sigs env) id
  846. addInitialSigs :: TopLevelFlag -> AnalEnv -> [Id] -> AnalEnv
  847. -- See Note [Initialising strictness]
  848. addInitialSigs top_lvl env@(AE { ae_sigs = sigs, ae_virgin = virgin }) ids
  849. = env { ae_sigs = extendVarEnvList sigs [ (id, (init_sig id, top_lvl))
  850. | id <- ids ] }
  851. where
  852. init_sig | virgin = \_ -> botSig
  853. | otherwise = idStrictness
  854. virgin, nonVirgin :: SigEnv -> AnalEnv
  855. virgin sigs = AE { ae_sigs = sigs, ae_virgin = True }
  856. nonVirgin sigs = AE { ae_sigs = sigs, ae_virgin = False }
  857. extendSigsWithLam :: AnalEnv -> Id -> AnalEnv
  858. -- Extend the AnalEnv when we meet a lambda binder
  859. -- If the binder is marked demanded with a product demand, then give it a CPR
  860. -- signature, because in the likely event that this is a lambda on a fn defn
  861. -- [we only use this when the lambda is being consumed with a call demand],
  862. -- it'll be w/w'd and so it will be CPR-ish. E.g.
  863. -- f = \x::(Int,Int). if ...strict in x... then
  864. -- x
  865. -- else
  866. -- (a,b)
  867. -- We want f to have the CPR property because x does, by the time f has been w/w'd
  868. --
  869. -- Also note that we only want to do this for something that
  870. -- definitely has product type, else we may get over-optimistic
  871. -- CPR results (e.g. from \x -> x!).
  872. extendSigsWithLam env id
  873. = case idDemandInfo_maybe id of
  874. Nothing -> extendAnalEnv NotTopLevel env id cprSig
  875. -- See Note [Optimistic in the Nothing case]
  876. Just (Eval (Prod _)) -> extendAnalEnv NotTopLevel env id cprSig
  877. _ -> env
  878. \end{code}
  879. Note [Initialising strictness]
  880. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  881. Our basic plan is to initialise the strictness of each Id in
  882. a recursive group to "bottom", and find a fixpoint from there.
  883. However, this group A might be inside an *enclosing* recursive
  884. group B, in which case we'll do the entire fixpoint shebang on A
  885. for each iteration of B.
  886. To speed things up, we initialise each iteration of B from the result
  887. of the last one, which is neatly recorded in each binder. That way we
  888. make use of earlier iterations of the fixpoint algorithm. (Cunning
  889. plan.)
  890. But on the *first* iteration we want to *ignore* the current strictness
  891. of the Id, and start from "bottom". Nowadays the Id can have a current
  892. strictness, because interface files record strictness for nested bindings.
  893. To know when we are in the first iteration, we look at the ae_virgin
  894. field of the AnalEnv.
  895. %************************************************************************
  896. %* *
  897. Demands
  898. %* *
  899. %************************************************************************
  900. \begin{code}
  901. splitDmdTy :: DmdType -> (Demand, DmdType)
  902. -- Split off one function argument
  903. -- We already have a suitable demand on all
  904. -- free vars, so no need to add more!
  905. splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
  906. splitDmdTy ty@(DmdType _ [] res_ty) = (resTypeArgDmd res_ty, ty)
  907. splitCallDmd :: Demand -> (Int, Demand)
  908. splitCallDmd (Call d) = case splitCallDmd d of
  909. (n, r) -> (n+1, r)
  910. splitCallDmd d = (0, d)
  911. vanillaCall :: Arity -> Demand
  912. vanillaCall 0 = evalDmd
  913. vanillaCall n = Call (vanillaCall (n-1))
  914. deferType :: DmdType -> DmdType
  915. deferType (DmdType fv _ _) = DmdType (deferEnv fv) [] TopRes
  916. -- Notice that we throw away info about both arguments and results
  917. -- For example, f = let ... in \x -> x
  918. -- We don't want to get a stricness type V->T for f.
  919. deferEnv :: DmdEnv -> DmdEnv
  920. deferEnv fv = mapVarEnv defer fv
  921. ----------------
  922. argDemand :: Demand -> Demand
  923. -- The 'Defer' demands are just Lazy at function boundaries
  924. -- Ugly! Ask John how to improve it.
  925. argDemand Top = lazyDmd
  926. argDemand (Defer _) = lazyDmd
  927. argDemand (Eval ds) = Eval (mapDmds argDemand ds)
  928. argDemand (Box Bot) = evalDmd
  929. argDemand (Box d) = box (argDemand d)
  930. argDemand Bot = Abs -- Don't pass args that are consumed (only) by bottom
  931. argDemand d = d
  932. \end{code}
  933. \begin{code}
  934. -------------------------
  935. lubType :: DmdType -> DmdType -> DmdType
  936. -- Consider (if x then y else []) with demand V
  937. -- Then the first branch gives {y->V} and the second
  938. -- *implicitly* has {y->A}. So we must put {y->(V `lub` A)}
  939. -- in the result env.
  940. lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
  941. = DmdType lub_fv2 (lub_ds ds1 ds2) (r1 `lubRes` r2)
  942. where
  943. lub_fv = plusVarEnv_C lub fv1 fv2
  944. lub_fv1 = modifyEnv (not (isBotRes r1)) absLub fv2 fv1 lub_fv
  945. lub_fv2 = modifyEnv (not (isBotRes r2)) absLub fv1 fv2 lub_fv1
  946. -- lub is the identity for Bot
  947. -- Extend the shorter argument list to match the longer
  948. lub_ds (d1:ds1) (d2:ds2) = lub d1 d2 : lub_ds ds1 ds2
  949. lub_ds [] [] = []
  950. lub_ds ds1 [] = map (`lub` resTypeArgDmd r2) ds1
  951. lub_ds [] ds2 = map (resTypeArgDmd r1 `lub`) ds2
  952. -----------------------------------
  953. bothType :: DmdType -> DmdType -> DmdType
  954. -- (t1 `bothType` t2) takes the argument/result info from t1,
  955. -- using t2 just for its free-var info
  956. -- NB: Don't forget about r2! It might be BotRes, which is
  957. -- a bottom demand on all the in-scope variables.
  958. -- Peter: can this be done more neatly?
  959. bothType (DmdType fv1 ds1 r1) (DmdType fv2 _ r2)
  960. = DmdType both_fv2 ds1 (r1 `bothRes` r2)
  961. where
  962. both_fv = plusVarEnv_C both fv1 fv2
  963. both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv
  964. both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1
  965. -- both is the identity for Abs
  966. \end{code}
  967. \begin{code}
  968. lubRes :: DmdResult -> DmdResult -> DmdResult
  969. lubRes BotRes r = r
  970. lubRes r BotRes = r
  971. lubRes RetCPR RetCPR = RetCPR
  972. lubRes _ _ = TopRes
  973. bothRes :: DmdResult -> DmdResult -> DmdResult
  974. -- If either diverges, the whole thing does
  975. -- Otherwise take CPR info from the first
  976. bothRes _ BotRes = BotRes
  977. bothRes r1 _ = r1
  978. \end{code}
  979. \begin{code}
  980. modifyEnv :: Bool -- No-op if False
  981. -> (Demand -> Demand) -- The zapper
  982. -> DmdEnv -> DmdEnv -- Env1 and Env2
  983. -> DmdEnv -> DmdEnv -- Transform this env
  984. -- Zap anything in Env1 but not in Env2
  985. -- Assume: dom(env) includes dom(Env1) and dom(Env2)
  986. modifyEnv need_to_modify zapper env1 env2 env
  987. | need_to_modify = foldr zap env (varEnvKeys (env1 `minusUFM` env2))
  988. | otherwise = env
  989. where
  990. zap uniq env = addToUFM_Directly env uniq (zapper current_val)
  991. where
  992. current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq)
  993. \end{code}
  994. %************************************************************************
  995. %* *
  996. \subsection{LUB and BOTH}
  997. %* *
  998. %************************************************************************
  999. \begin{code}
  1000. lub :: Demand -> Demand -> Demand
  1001. lub Bot d2 = d2
  1002. lub Abs d2 = absLub d2
  1003. lub Top _ = Top
  1004. lub (Defer ds1) d2 = defer (Eval ds1 `lub` d2)
  1005. lub (Call d1) (Call d2) = Call (d1 `lub` d2)
  1006. lub d1@(Call _) (Box d2) = d1 `lub` d2 -- Just strip the box
  1007. lub (Call _) d2@(Eval _) = d2 -- Presumably seq or vanilla eval
  1008. lub d1@(Call _) d2 = d2 `lub` d1 -- Bot, Abs, Top
  1009. -- For the Eval case, we use these approximation rules
  1010. -- Box Bot <= Eval (Box Bot ...)
  1011. -- Box Top <= Defer (Box Bot ...)
  1012. -- Box (Eval ds) <= Eval (map Box ds)
  1013. lub (Eval ds1) (Eval ds2) = Eval (ds1 `lubs` ds2)
  1014. lub (Eval ds1) (Box Bot) = Eval (mapDmds (`lub` Box Bot) ds1)
  1015. lub (Eval ds1) (Box (Eval ds2)) = Eval (ds1 `lubs` mapDmds box ds2)
  1016. lub (Eval ds1) (Box Abs) = deferEval (mapDmds (`lub` Box Bot) ds1)
  1017. lub d1@(Eval _) d2 = d2 `lub` d1 -- Bot,Abs,Top,Call,Defer
  1018. lub (Box d1) (Box d2) = box (d1 `lub` d2)
  1019. lub d1@(Box _) d2 = d2 `lub` d1
  1020. lubs :: Demands -> Demands -> Demands
  1021. lubs ds1 ds2 = zipWithDmds lub ds1 ds2
  1022. ---------------------
  1023. box :: Demand -> Demand
  1024. -- box is the smart constructor for Box
  1025. -- It computes <B,bot> & d
  1026. -- INVARIANT: (Box d) => d = Bot, Abs, Eval
  1027. -- Seems to be no point in allowing (Box (Call d))
  1028. box (Call d) = Call d -- The odd man out. Why?
  1029. box (Box d) = Box d
  1030. box (Defer _) = lazyDmd
  1031. box Top = lazyDmd -- Box Abs and Box Top
  1032. box Abs = lazyDmd -- are the same <B,L>
  1033. box d = Box d -- Bot, Eval
  1034. ---------------
  1035. defer :: Demand -> Demand
  1036. -- defer is the smart constructor for Defer
  1037. -- The idea is that (Defer ds) = <U(ds), L>
  1038. --
  1039. -- It specifies what happens at a lazy function argument
  1040. -- or a lambda; the L* operator
  1041. -- Set the strictness part to L, but leave
  1042. -- the boxity side unaffected
  1043. -- It also ensures that Defer (Eval [LLLL]) = L
  1044. defer Bot = Abs
  1045. defer Abs = Abs
  1046. defer Top = Top
  1047. defer (Call _) = lazyDmd -- Approximation here?
  1048. defer (Box _) = lazyDmd
  1049. defer (Defer ds) = Defer ds
  1050. defer (Eval ds) = deferEval ds
  1051. deferEval :: Demands -> Demand
  1052. -- deferEval ds = defer (Eval ds)
  1053. deferEval ds | allTop ds = Top
  1054. | otherwise = Defer ds
  1055. ---------------------
  1056. absLub :: Demand -> Demand
  1057. -- Computes (Abs `lub` d)
  1058. -- For the Bot case consider
  1059. -- f x y = if ... then x else error x
  1060. -- Then for y we get Abs `lub` Bot, and we really
  1061. -- want Abs overall
  1062. absLub Bot = Abs
  1063. absLub Abs = Abs
  1064. absLub Top = Top
  1065. absLub (Call _) = Top
  1066. absLub (Box _) = Top
  1067. absLub (Eval ds) = Defer (absLubs ds) -- Or (Defer ds)?
  1068. absLub (Defer ds) = Defer (absLubs ds) -- Or (Defer ds)?
  1069. absLubs :: Demands -> Demands
  1070. absLubs = mapDmds absLub
  1071. ---------------
  1072. both :: Demand -> Demand -> Demand
  1073. both Abs d2 = d2
  1074. -- Note [Bottom demands]
  1075. both Bot Bot = Bot
  1076. both Bot Abs = Bot
  1077. both Bot (Eval ds) = Eval (mapDmds (`both` Bot) ds)
  1078. both Bot (Defer ds) = Eval (mapDmds (`both` Bot) ds)
  1079. both Bot _ = errDmd
  1080. both Top Bot = errDmd
  1081. both Top Abs = Top
  1082. both Top Top = Top
  1083. both Top (Box d) = Box d
  1084. both Top (Call d) = Call d
  1085. both Top (Eval ds) = Eval (mapDmds (`both` Top) ds)
  1086. both Top (Defer ds) -- = defer (Top `both` Eval ds)
  1087. -- = defer (Eval (mapDmds (`both` Top) ds))
  1088. = deferEval (mapDmds (`both` Top) ds)
  1089. both (Box d1) (Box d2) = box (d1 `both` d2)
  1090. both (Box d1) d2@(Call _) = box (d1 `both` d2)
  1091. both (Box d1) d2@(Eval _) = box (d1 `both` d2)
  1092. both (Box d1) (Defer _) = Box d1
  1093. both d1@(Box _) d2 = d2 `both` d1
  1094. both (Call d1) (Call d2) = Call (d1 `both` d2)
  1095. both (Call d1) (Eval _) = Call d1 -- Could do better for (Poly Bot)?
  1096. both (Call d1) (Defer _) = Call d1 -- Ditto
  1097. both d1@(Call _) d2 = d2 `both` d1
  1098. both (Eval ds1) (Eval ds2) = Eval (ds1 `boths` ds2)
  1099. both (Eval ds1) (Defer ds2) = Eval (ds1 `boths` mapDmds defer ds2)
  1100. both d1@(Eval _) d2 = d2 `both` d1
  1101. both (Defer ds1) (Defer ds2) = deferEval (ds1 `boths` ds2)
  1102. both d1@(Defer _) d2 = d2 `both` d1
  1103. boths :: Demands -> Demands -> Demands
  1104. boths ds1 ds2 = zipWithDmds both ds1 ds2
  1105. \end{code}
  1106. Note [Bottom demands]
  1107. ~~~~~~~~~~~~~~~~~~~~~
  1108. Consider
  1109. f x = error x
  1110. From 'error' itself we get demand Bot on x
  1111. From the arg demand on x we get
  1112. x :-> evalDmd = Box (Eval (Poly Abs))
  1113. So we get Bot `both` Box (Eval (Poly Abs))
  1114. = Seq Keep (Poly Bot)
  1115. Consider also
  1116. f x = if ... then error (fst x) else fst x
  1117. Then we get (Eval (Box Bot, Bot) `lub` Eval (SA))
  1118. = Eval (SA)
  1119. which is what we want.
  1120. Consider also
  1121. f x = error [fst x]
  1122. Then we get
  1123. x :-> Bot `both` Defer [SA]
  1124. and we want the Bot demand to cancel out the Defer
  1125. so that we get Eval [SA]. Otherwise we'd have the odd
  1126. situation that
  1127. f x = error (fst x) -- Strictness U(SA)b
  1128. g x = error ('y':fst x) -- Strictness Tb