PageRenderTime 58ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/ghc-7.4.1/compiler/stranal/DmdAnal.lhs

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