Demand.lhs 65.6 KB
Newer Older
1
%
Simon Marlow's avatar
Simon Marlow committed
2
% (c) The University of Glasgow 2006
3
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
%
5
\section[Demand]{@Demand@: A decoupled implementation of a demand domain}
6 7

\begin{code}
8
{-# LANGUAGE CPP, FlexibleInstances, TypeSynonymInstances #-}
9 10

module Demand (
11 12
        StrDmd, UseDmd(..), Count(..), 
        countOnce, countMany,   -- cardinality
13

14 15 16 17
        Demand, CleanDemand, 
        mkProdDmd, mkOnceUsedDmd, mkManyUsedDmd, mkHeadStrict, oneifyDmd,
        getUsage, toCleanDmd, 
        absDmd, topDmd, botDmd, seqDmd,
18
        lubDmd, bothDmd, apply1Dmd, apply2Dmd, 
19
        isTopDmd, isBotDmd, isAbsDmd, isSeqDmd, 
20
        peelUseCall, cleanUseDmd_maybe, strictenDmd, bothCleanDmd,
21

22
        DmdType(..), dmdTypeDepth, lubDmdType, bothDmdType,
23
        nopDmdType, botDmdType, mkDmdType,
24
        addDemand, removeDmdTyArgs,
25
        BothDmdArg, mkBothDmdArg, toBothDmdArg,
26 27

        DmdEnv, emptyDmdEnv,
28
        peelFV,
29

30
        DmdResult, CPRResult,
Joachim Breitner's avatar
Joachim Breitner committed
31
        isBotRes, isTopRes,
32
        topRes, botRes, cprProdRes, vanillaCprProdRes, cprSumRes,
33
        appIsBottom, isBottomingSig, pprIfaceStrictSig, 
Joachim Breitner's avatar
Joachim Breitner committed
34
        trimCPRInfo, returnsCPR_maybe,
35
        StrictSig(..), mkStrictSig, mkClosedStrictSig, nopSig, botSig, cprProdSig,
36
        isNopSig, splitStrictSig, increaseStrictSigArity,
37

38 39
        seqDemand, seqDemandList, seqDmdType, seqStrictSig, 

40 41
        evalDmd, cleanEvalDmd, cleanEvalProdDmd, isStrictDmd, 
        splitDmdTy, splitFVs,
42
        deferAfterIO,
43
        postProcessUnsat, postProcessDmdTypeM,
44

45
        splitProdDmd_maybe, peelCallDmd, mkCallDmd,
46 47
        dmdTransformSig, dmdTransformDataConSig, dmdTransformDictSelSig,
        argOneShots, argsOneShots,
48
        trimToType, TypeShape(..),
49

50
        isSingleUsed, reuseEnv, zapDemand, zapStrictSig,
51

52
        strictifyDictDmd
53

sof's avatar
sof committed
54 55
     ) where

56 57
#include "HsVersions.h"

58
import StaticFlags
59
import DynFlags
60
import Outputable
61
import Var ( Var )
62 63
import VarEnv
import UniqFM
Simon Marlow's avatar
Simon Marlow committed
64
import Util
65 66
import BasicTypes
import Binary
Joachim Breitner's avatar
Joachim Breitner committed
67
import Maybes           ( orElse )
68 69 70 71

import Type            ( Type )
import TyCon           ( isNewTyCon, isClassTyCon )
import DataCon         ( splitDataProductType_maybe )
72
import FastString
73 74
\end{code}

75
%************************************************************************
76 77 78
%*                                                                      *
\subsection{Strictness domain}
%*                                                                      *
79 80
%************************************************************************

81 82
        Lazy
         |
83
      HeadStr
84 85 86 87
      /     \
  SCall      SProd
      \      /
      HyperStr
88

89
\begin{code}
90

91 92 93 94
-- Vanilla strictness domain
data StrDmd
  = HyperStr             -- Hyper-strict 
                         -- Bottom of the lattice
95
                         -- Note [HyperStr and Use demands]
96 97 98 99

  | SCall StrDmd         -- Call demand
                         -- Used only for values of function type

100
  | SProd [MaybeStr]     -- Product
101 102
                         -- Used only for values of product type
                         -- Invariant: not all components are HyperStr (use HyperStr)
103
                         --            not all components are Lazy     (use HeadStr)
104

105
  | HeadStr              -- Head-Strict
106 107 108
                         -- A polymorphic demand: used for values of all types,
                         --                       including a type variable

109 110 111 112 113
  deriving ( Eq, Show )

data MaybeStr = Lazy            -- Lazy
                                -- Top of the lattice
              | Str StrDmd
114 115 116
  deriving ( Eq, Show )

-- Well-formedness preserving constructors for the Strictness domain
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
strBot, strTop :: MaybeStr
strBot = Str HyperStr
strTop = Lazy

mkSCall :: StrDmd -> StrDmd
mkSCall HyperStr = HyperStr
mkSCall s        = SCall s

mkSProd :: [MaybeStr] -> StrDmd
mkSProd sx
  | any isHyperStr sx = HyperStr
  | all isLazy     sx = HeadStr
  | otherwise         = SProd sx

isLazy :: MaybeStr -> Bool
isLazy Lazy    = True
isLazy (Str _) = False

isHyperStr :: MaybeStr -> Bool
isHyperStr (Str HyperStr) = True
isHyperStr _              = False
138 139 140 141 142

-- Pretty-printing
instance Outputable StrDmd where
  ppr HyperStr      = char 'B'
  ppr (SCall s)     = char 'C' <> parens (ppr s)
143
  ppr HeadStr       = char 'S'
144 145
  ppr (SProd sx)    = char 'S' <> parens (hcat (map ppr sx))

146 147 148 149 150 151 152 153 154
instance Outputable MaybeStr where
  ppr (Str s)       = ppr s
  ppr Lazy          = char 'L'

lubMaybeStr :: MaybeStr -> MaybeStr -> MaybeStr
lubMaybeStr Lazy     _        = Lazy
lubMaybeStr _        Lazy     = Lazy
lubMaybeStr (Str s1) (Str s2) = Str (s1 `lubStr` s2)

155 156 157
lubStr :: StrDmd -> StrDmd -> StrDmd
lubStr HyperStr s              = s
lubStr (SCall s1) HyperStr     = SCall s1
158
lubStr (SCall _)  HeadStr      = HeadStr
159
lubStr (SCall s1) (SCall s2)   = SCall (s1 `lubStr` s2)
160 161 162
lubStr (SCall _)  (SProd _)    = HeadStr
lubStr (SProd sx) HyperStr     = SProd sx
lubStr (SProd _)  HeadStr      = HeadStr
163
lubStr (SProd s1) (SProd s2)
164 165 166 167 168 169 170 171 172
    | length s1 == length s2   = mkSProd (zipWith lubMaybeStr s1 s2)
    | otherwise                = HeadStr
lubStr (SProd _) (SCall _)     = HeadStr
lubStr HeadStr   _             = HeadStr

bothMaybeStr :: MaybeStr -> MaybeStr -> MaybeStr
bothMaybeStr Lazy     s           = s
bothMaybeStr s        Lazy        = s 
bothMaybeStr (Str s1) (Str s2) = Str (s1 `bothStr` s2)
173 174 175

bothStr :: StrDmd -> StrDmd -> StrDmd
bothStr HyperStr _             = HyperStr
176
bothStr HeadStr s              = s
177
bothStr (SCall _)  HyperStr    = HyperStr
178
bothStr (SCall s1) HeadStr     = SCall s1
179 180 181 182
bothStr (SCall s1) (SCall s2)  = SCall (s1 `bothStr` s2)
bothStr (SCall _)  (SProd _)   = HyperStr  -- Weird

bothStr (SProd _)  HyperStr    = HyperStr
183
bothStr (SProd s1) HeadStr     = SProd s1
184
bothStr (SProd s1) (SProd s2) 
185
    | length s1 == length s2   = mkSProd (zipWith bothMaybeStr s1 s2)
186 187 188
    | otherwise                = HyperStr  -- Weird
bothStr (SProd _) (SCall _)    = HyperStr

189 190 191 192 193 194
-- utility functions to deal with memory leaks
seqStrDmd :: StrDmd -> ()
seqStrDmd (SProd ds)   = seqStrDmdList ds
seqStrDmd (SCall s)     = s `seq` () 
seqStrDmd _            = ()

195
seqStrDmdList :: [MaybeStr] -> ()
196
seqStrDmdList [] = ()
197 198 199 200 201
seqStrDmdList (d:ds) = seqMaybeStr d `seq` seqStrDmdList ds

seqMaybeStr :: MaybeStr -> ()
seqMaybeStr Lazy    = ()
seqMaybeStr (Str s) = seqStrDmd s
202 203

-- Splitting polymorphic demands
204 205 206 207 208 209 210
splitStrProdDmd :: Int -> StrDmd -> Maybe [MaybeStr]
splitStrProdDmd n HyperStr   = Just (replicate n strBot)
splitStrProdDmd n HeadStr    = Just (replicate n strTop)
splitStrProdDmd n (SProd ds) = ASSERT( ds `lengthIs` n) Just ds
splitStrProdDmd _ (SCall {}) = Nothing
      -- This can happen when the programmer uses unsafeCoerce,
      -- and we don't then want to crash the compiler (Trac #9208)
211 212 213 214 215 216 217 218
\end{code}

%************************************************************************
%*                                                                      *
\subsection{Absence domain}
%*                                                                      *
%************************************************************************

219 220 221 222 223 224 225
      Used
      /   \
  UCall   UProd
      \   /
      UHead
       |
      Abs
226 227 228

\begin{code}

229 230 231
-- Domain for genuine usage
data UseDmd
  = UCall Count UseDmd   -- Call demand for absence
232 233
                         -- Used only for values of function type

234
  | UProd [MaybeUsed]     -- Product 
235 236 237 238 239
                         -- Used only for values of product type
                         -- See Note [Don't optimise UProd(Used) to Used]
                         -- [Invariant] Not all components are Abs
                         --             (in that case, use UHead)

240 241 242 243 244 245 246 247
  | UHead                -- May be used; but its sub-components are 
                         -- definitely *not* used.  Roughly U(AAA)
                         -- Eg the usage of x in x `seq` e
                         -- A polymorphic demand: used for values of all types,
                         --                       including a type variable
                         -- Since (UCall _ Abs) is ill-typed, UHead doesn't
                         -- make sense for lambdas

248 249 250 251
  | Used                 -- May be used; and its sub-components may be used
                         -- Top of the lattice
  deriving ( Eq, Show )

252 253 254 255 256 257 258 259 260 261 262
-- Extended usage demand for absence and counting
data MaybeUsed
  = Abs                  -- Definitely unused
                         -- Bottom of the lattice

  | Use Count UseDmd     -- May be used with some cardinality 
  deriving ( Eq, Show )

-- Abstract counting of usages
data Count = One | Many
  deriving ( Eq, Show )     
263 264

-- Pretty-printing
265 266 267 268 269 270 271 272 273 274 275 276 277 278
instance Outputable MaybeUsed where
  ppr Abs           = char 'A'
  ppr (Use Many a)   = ppr a 
  ppr (Use One  a)   = char '1' <> char '*' <> ppr a

instance Outputable UseDmd where
  ppr Used           = char 'U'
  ppr (UCall c a)    = char 'C' <> ppr c <> parens (ppr a)
  ppr UHead          = char 'H'
  ppr (UProd as)     = char 'U' <> parens (hcat (punctuate (char ',') (map ppr as)))

instance Outputable Count where
  ppr One  = char '1'
  ppr Many = text ""
279 280

-- Well-formedness preserving constructors for the Absence domain
281 282 283 284 285 286 287 288 289 290 291 292 293 294
countOnce, countMany :: Count
countOnce = One
countMany = Many

useBot, useTop :: MaybeUsed
useBot     = Abs
useTop     = Use Many Used

mkUCall :: Count -> UseDmd -> UseDmd
--mkUCall c Used = Used c 
mkUCall c a  = UCall c a

mkUProd :: [MaybeUsed] -> UseDmd
mkUProd ux 
295 296 297
  | all (== Abs) ux    = UHead
  | otherwise          = UProd ux

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
lubCount :: Count -> Count -> Count
lubCount _ Many = Many
lubCount Many _ = Many
lubCount x _    = x 

lubMaybeUsed :: MaybeUsed -> MaybeUsed -> MaybeUsed
lubMaybeUsed Abs x                   = x
lubMaybeUsed x Abs                   = x
lubMaybeUsed (Use c1 a1) (Use c2 a2) = Use (lubCount c1 c2) (lubUse a1 a2)

lubUse :: UseDmd -> UseDmd -> UseDmd
lubUse UHead       u               = u
lubUse (UCall c u) UHead           = UCall c u
lubUse (UCall c1 u1) (UCall c2 u2) = UCall (lubCount c1 c2) (lubUse u1 u2)
lubUse (UCall _ _) _               = Used
lubUse (UProd ux) UHead            = UProd ux 
lubUse (UProd ux1) (UProd ux2)
     | length ux1 == length ux2    = UProd $ zipWith lubMaybeUsed ux1 ux2
     | otherwise                   = Used
lubUse (UProd {}) (UCall {})       = Used
-- lubUse (UProd {}) Used             = Used
lubUse (UProd ux) Used             = UProd (map (`lubMaybeUsed` useTop) ux)
lubUse Used       (UProd ux)       = UProd (map (`lubMaybeUsed` useTop) ux)
lubUse Used _                      = Used  -- Note [Used should win]

-- `both` is different from `lub` in its treatment of counting; if
-- `both` is computed for two used, the result always has
--  cardinality `Many` (except for the inner demands of UCall demand -- [TODO] explain).  
--  Also,  x `bothUse` x /= x (for anything but Abs).

bothMaybeUsed :: MaybeUsed -> MaybeUsed -> MaybeUsed
bothMaybeUsed Abs x                   = x
bothMaybeUsed x Abs                   = x
bothMaybeUsed (Use _ a1) (Use _ a2)   = Use Many (bothUse a1 a2)


bothUse :: UseDmd -> UseDmd -> UseDmd
bothUse UHead       u               = u
bothUse (UCall c u) UHead           = UCall c u

-- Exciting special treatment of inner demand for call demands: 
--    use `lubUse` instead of `bothUse`!
bothUse (UCall _ u1) (UCall _ u2)   = UCall Many (u1 `lubUse` u2)

bothUse (UCall {}) _                = Used
bothUse (UProd ux) UHead            = UProd ux 
bothUse (UProd ux1) (UProd ux2)
      | length ux1 == length ux2    = UProd $ zipWith bothMaybeUsed ux1 ux2
      | otherwise                   = Used
bothUse (UProd {}) (UCall {})       = Used
-- bothUse (UProd {}) Used             = Used  -- Note [Used should win]
bothUse Used (UProd ux)             = UProd (map (`bothMaybeUsed` useTop) ux)
bothUse (UProd ux) Used             = UProd (map (`bothMaybeUsed` useTop) ux)
bothUse Used _                      = Used  -- Note [Used should win]

peelUseCall :: UseDmd -> Maybe (Count, UseDmd)
peelUseCall (UCall c u)   = Just (c,u)
peelUseCall _             = Nothing
\end{code}
357

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
Note [Don't optimise UProd(Used) to Used]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
These two UseDmds:
   UProd [Used, Used]   and    Used
are semantically equivalent, but we do not turn the former into
the latter, for a regrettable-subtle reason.  Suppose we did.
then
  f (x,y) = (y,x)
would get 
  StrDmd = Str  = SProd [Lazy, Lazy]
  UseDmd = Used = UProd [Used, Used]
But with the joint demand of <Str, Used> doesn't convey any clue
that there is a product involved, and so the worthSplittingFun
will not fire.  (We'd need to use the type as well to make it fire.)
Moreover, consider
  g h p@(_,_) = h p
This too would get <Str, Used>, but this time there really isn't any
point in w/w since the components of the pair are not used at all.

So the solution is: don't aggressively collapse UProd [Used,Used] to
Used; intead leave it as-is. In effect we are using the UseDmd to do a
little bit of boxity analysis.  Not very nice.

Note [Used should win]
~~~~~~~~~~~~~~~~~~~~~~
Both in lubUse and bothUse we want (Used `both` UProd us) to be Used.
Why?  Because Used carries the implication the whole thing is used,
box and all, so we don't want to w/w it.  If we use it both boxed and
unboxed, then we are definitely using the box, and so we are quite 
likely to pay a reboxing cost.  So we make Used win here.

Example is in the Buffer argument of GHC.IO.Handle.Internals.writeCharBuffer

Baseline: (A) Not making Used win (UProd wins)
Compare with: (B) making Used win for lub and both

            Min          -0.3%     -5.6%    -10.7%    -11.0%    -33.3%
            Max          +0.3%    +45.6%    +11.5%    +11.5%     +6.9%
 Geometric Mean          -0.0%     +0.5%     +0.3%     +0.2%     -0.8%

Baseline: (B) Making Used win for both lub and both
Compare with: (C) making Used win for both, but UProd win for lub

            Min          -0.1%     -0.3%     -7.9%     -8.0%     -6.5%
            Max          +0.1%     +1.0%    +21.0%    +21.0%     +0.5%
 Geometric Mean          +0.0%     +0.0%     -0.0%     -0.1%     -0.1%


\begin{code}
407 408 409 410 411
-- If a demand is used multiple times (i.e. reused), than any use-once
-- mentioned there, that is not protected by a UCall, can happen many times.
markReusedDmd :: MaybeUsed -> MaybeUsed
markReusedDmd Abs         = Abs
markReusedDmd (Use _ a)   = Use Many (markReused a)
412

413 414 415 416
markReused :: UseDmd -> UseDmd
markReused (UCall _ u)      = UCall Many u   -- No need to recurse here
markReused (UProd ux)       = UProd (map markReusedDmd ux)
markReused u                = u
417 418

isUsedMU :: MaybeUsed -> Bool
419
-- True <=> markReusedDmd d = d
420 421 422 423 424
isUsedMU Abs          = True
isUsedMU (Use One _)  = False
isUsedMU (Use Many u) = isUsedU u

isUsedU :: UseDmd -> Bool
425
-- True <=> markReused d = d
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
isUsedU Used           = True
isUsedU UHead          = True
isUsedU (UProd us)     = all isUsedMU us
isUsedU (UCall One _)  = False
isUsedU (UCall Many _) = True  -- No need to recurse

-- Squashing usage demand demands
seqUseDmd :: UseDmd -> ()
seqUseDmd (UProd ds)   = seqMaybeUsedList ds
seqUseDmd (UCall c d)  = c `seq` seqUseDmd d
seqUseDmd _            = ()

seqMaybeUsedList :: [MaybeUsed] -> ()
seqMaybeUsedList []     = ()
seqMaybeUsedList (d:ds) = seqMaybeUsed d `seq` seqMaybeUsedList ds

seqMaybeUsed :: MaybeUsed -> ()
seqMaybeUsed (Use c u)  = c `seq` seqUseDmd u
seqMaybeUsed _          = ()

-- Splitting polymorphic Maybe-Used demands
447 448 449 450 451 452 453 454
splitUseProdDmd :: Int -> UseDmd -> Maybe [MaybeUsed]
splitUseProdDmd n Used        = Just (replicate n useTop)
splitUseProdDmd n UHead       = Just (replicate n Abs)
splitUseProdDmd n (UProd ds)  = ASSERT2( ds `lengthIs` n, text "splitUseProdDmd" $$ ppr n $$ ppr ds ) 
                                Just ds
splitUseProdDmd _ (UCall _ _) = Nothing
      -- This can happen when the programmer uses unsafeCoerce,
      -- and we don't then want to crash the compiler (Trac #9208)
455 456 457 458 459 460 461 462 463
\end{code}
%************************************************************************
%*                                                                      *
\subsection{Joint domain for Strictness and Absence}
%*                                                                      *
%************************************************************************

\begin{code}

464
data JointDmd = JD { strd :: MaybeStr, absd :: MaybeUsed } 
465 466 467 468 469 470 471
  deriving ( Eq, Show )

-- Pretty-printing
instance Outputable JointDmd where
  ppr (JD {strd = s, absd = a}) = angleBrackets (ppr s <> char ',' <> ppr a)

-- Well-formedness preserving constructors for the joint domain
472
mkJointDmd :: MaybeStr -> MaybeUsed -> JointDmd
473 474
mkJointDmd s a = JD { strd = s, absd = a }

475
mkJointDmds :: [MaybeStr] -> [MaybeUsed] -> [JointDmd]
476 477 478
mkJointDmds ss as = zipWithEqual "mkJointDmds" mkJointDmd ss as
     
absDmd :: JointDmd
479
absDmd = mkJointDmd Lazy Abs
480

481 482 483 484 485
apply1Dmd, apply2Dmd :: Demand
-- C1(U), C1(C1(U)) respectively
apply1Dmd = JD { strd = Lazy, absd = Use Many (UCall One Used) }
apply2Dmd = JD { strd = Lazy, absd = Use Many (UCall One (UCall One Used)) }

486
topDmd :: JointDmd
487 488 489 490
topDmd = mkJointDmd Lazy useTop

seqDmd :: JointDmd
seqDmd = mkJointDmd (Str HeadStr) (Use One UHead)
491 492

botDmd :: JointDmd
493
botDmd = mkJointDmd strBot useBot
494 495 496

lubDmd :: JointDmd -> JointDmd -> JointDmd
lubDmd (JD {strd = s1, absd = a1}) 
497
       (JD {strd = s2, absd = a2}) = mkJointDmd (s1 `lubMaybeStr` s2) (a1 `lubMaybeUsed` a2)
498 499 500

bothDmd :: JointDmd -> JointDmd -> JointDmd
bothDmd (JD {strd = s1, absd = a1}) 
501
        (JD {strd = s2, absd = a2}) = mkJointDmd (s1 `bothMaybeStr` s2) (a1 `bothMaybeUsed` a2)
502 503

isTopDmd :: JointDmd -> Bool
504 505
isTopDmd (JD {strd = Lazy, absd = Use Many Used}) = True
isTopDmd _                                        = False 
506 507

isBotDmd :: JointDmd -> Bool
508 509
isBotDmd (JD {strd = Str HyperStr, absd = Abs}) = True
isBotDmd _                                      = False 
510 511 512 513 514 515
  
isAbsDmd :: JointDmd -> Bool
isAbsDmd (JD {absd = Abs})  = True   -- The strictness part can be HyperStr 
isAbsDmd _                  = False  -- for a bottom demand

isSeqDmd :: JointDmd -> Bool
516 517
isSeqDmd (JD {strd=Str HeadStr, absd=Use _ UHead}) = True
isSeqDmd _                                         = False
518 519 520

-- More utility functions for strictness
seqDemand :: JointDmd -> ()
521
seqDemand (JD {strd = x, absd = y}) = seqMaybeStr x `seq` seqMaybeUsed y `seq` ()
522 523

seqDemandList :: [JointDmd] -> ()
524 525
seqDemandList [] = ()
seqDemandList (d:ds) = seqDemand d `seq` seqDemandList ds
526

527
isStrictDmd :: Demand -> Bool
528 529 530 531 532
-- See Note [Strict demands]
isStrictDmd (JD {absd = Abs})  = False
isStrictDmd (JD {strd = Lazy}) = False
isStrictDmd _                  = True

533 534
isWeakDmd :: Demand -> Bool
isWeakDmd (JD {strd = s, absd = a}) = isLazy s && isUsedMU a
535

536 537 538
cleanUseDmd_maybe :: JointDmd -> Maybe UseDmd
cleanUseDmd_maybe (JD { absd = Use _ ud }) = Just ud
cleanUseDmd_maybe _                        = Nothing
539

540 541 542 543 544 545 546 547 548 549 550
splitFVs :: Bool   -- Thunk
         -> DmdEnv -> (DmdEnv, DmdEnv)
splitFVs is_thunk rhs_fvs
  | is_thunk  = foldUFM_Directly add (emptyVarEnv, emptyVarEnv) rhs_fvs
  | otherwise = partitionVarEnv isWeakDmd rhs_fvs
  where
    add uniq dmd@(JD { strd = s, absd = u }) (lazy_fv, sig_fv)
      | Lazy <- s = (addToUFM_Directly lazy_fv uniq dmd, sig_fv)
      | otherwise = ( addToUFM_Directly lazy_fv uniq (JD { strd = Lazy, absd = u })
                    , addToUFM_Directly sig_fv  uniq (JD { strd = s,    absd = Abs }) )
\end{code}
551

552 553 554 555 556
%************************************************************************
%*                                                                      *
\subsection{Clean demand for Strictness and Usage}
%*                                                                      *
%************************************************************************
557

558 559
This domain differst from JointDemand in the sence that pure absence
is taken away, i.e., we deal *only* with non-absent demands.
560

561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
Note [Strict demands]
~~~~~~~~~~~~~~~~~~~~~
isStrictDmd returns true only of demands that are 
   both strict
   and  used
In particular, it is False for <HyperStr, Abs>, which can and does
arise in, say (Trac #7319)
   f x = raise# <some exception>
Then 'x' is not used, so f gets strictness <HyperStr,Abs> -> .
Now the w/w generates
   fx = let x <HyperStr,Abs> = absentError "unused"
        in raise <some exception>
At this point we really don't want to convert to
   fx = case absentError "unused" of x -> raise <some exception>
Since the program is going to diverge, this swaps one error for another,
but it's really a bad idea to *ever* evaluate an absent argument.
In Trac #7319 we get
   T7319.exe: Oops!  Entered absent arg w_s1Hd{v} [lid] [base:GHC.Base.String{tc 36u}]

580 581 582 583 584 585 586 587 588 589 590
Note [Dealing with call demands]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Call demands are constructed and deconstructed coherently for
strictness and absence. For instance, the strictness signature for the
following function

f :: (Int -> (Int, Int)) -> (Int, Bool)
f g = (snd (g 3), True)

should be: <L,C(U(AU))>m

591

592 593
\begin{code}

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
data CleanDemand = CD { sd :: StrDmd, ud :: UseDmd } 
  deriving ( Eq, Show )

instance Outputable CleanDemand where
  ppr (CD {sd = s, ud = a}) = angleBrackets (ppr s <> comma <> ppr a)

mkCleanDmd :: StrDmd -> UseDmd -> CleanDemand
mkCleanDmd s a = CD { sd = s, ud = a }

bothCleanDmd :: CleanDemand -> CleanDemand -> CleanDemand
bothCleanDmd (CD { sd = s1, ud = a1}) (CD { sd = s2, ud = a2}) 
  = CD { sd = s1 `bothStr` s2, ud = a1 `bothUse` a2 }

mkHeadStrict :: CleanDemand -> CleanDemand
mkHeadStrict (CD { ud = a }) = mkCleanDmd HeadStr a

oneifyDmd :: JointDmd -> JointDmd
oneifyDmd (JD { strd = s, absd = Use _ a }) = JD { strd = s, absd = Use One a }
oneifyDmd jd                                = jd

mkOnceUsedDmd, mkManyUsedDmd :: CleanDemand -> JointDmd
mkOnceUsedDmd (CD {sd = s,ud = a}) = mkJointDmd (Str s) (Use One a)
mkManyUsedDmd (CD {sd = s,ud = a}) = mkJointDmd (Str s) (Use Many a)

getUsage :: CleanDemand -> UseDmd
getUsage = ud

evalDmd :: JointDmd
-- Evaluated strictly, and used arbitrarily deeply
evalDmd = mkJointDmd (Str HeadStr) useTop

mkProdDmd :: [JointDmd] -> CleanDemand
mkProdDmd dx 
  = mkCleanDmd sp up 
  where
    sp = mkSProd $ map strd dx
    up = mkUProd $ map absd dx   

mkCallDmd :: CleanDemand -> CleanDemand
mkCallDmd (CD {sd = d, ud = u}) 
  = mkCleanDmd (mkSCall d) (mkUCall One u)

cleanEvalDmd :: CleanDemand
cleanEvalDmd = mkCleanDmd HeadStr Used

cleanEvalProdDmd :: Arity -> CleanDemand
cleanEvalProdDmd n = mkCleanDmd HeadStr (UProd (replicate n useTop))

isSingleUsed :: JointDmd -> Bool
isSingleUsed (JD {absd=a}) = is_used_once a
644
  where
645 646 647
    is_used_once Abs         = True
    is_used_once (Use One _) = True
    is_used_once _           = False
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684


data TypeShape = TsFun TypeShape
               | TsProd [TypeShape]
               | TsUnk

instance Outputable TypeShape where
  ppr TsUnk        = ptext (sLit "TsUnk")
  ppr (TsFun ts)   = ptext (sLit "TsFun") <> parens (ppr ts)
  ppr (TsProd tss) = parens (hsep $ punctuate comma $ map ppr tss)

trimToType :: JointDmd -> TypeShape -> JointDmd
-- See Note [Trimming a demand to a type]
trimToType (JD ms mu) ts
  = JD (go_ms ms ts) (go_mu mu ts)
  where
    go_ms :: MaybeStr -> TypeShape -> MaybeStr
    go_ms Lazy    _  = Lazy
    go_ms (Str s) ts = Str (go_s s ts)

    go_s :: StrDmd -> TypeShape -> StrDmd
    go_s HyperStr    _            = HyperStr
    go_s (SCall s)   (TsFun ts)   = SCall (go_s s ts)
    go_s (SProd mss) (TsProd tss)
      | equalLength mss tss       = SProd (zipWith go_ms mss tss)
    go_s _           _            = HeadStr

    go_mu :: MaybeUsed -> TypeShape -> MaybeUsed
    go_mu Abs _ = Abs
    go_mu (Use c u) ts = Use c (go_u u ts)

    go_u :: UseDmd -> TypeShape -> UseDmd
    go_u UHead       _          = UHead
    go_u (UCall c u) (TsFun ts) = UCall c (go_u u ts)
    go_u (UProd mus) (TsProd tss)
      | equalLength mus tss      = UProd (zipWith go_mu mus tss)
    go_u _           _           = Used
685 686
\end{code}

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
Note [Trimming a demand to a type]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this:

  f :: a -> Bool
  f x = case ... of
          A g1 -> case (x |> g1) of (p,q) -> ...
          B    -> error "urk"

where A,B are the constructors of a GADT.  We'll get a U(U,U) demand
on x from the A branch, but that's a stupid demand for x itself, which
has type 'a'. Indeed we get ASSERTs going off (notably in
splitUseProdDmd, Trac #8569).

Bottom line: we really don't want to have a binder whose demand is more
deeply-nested than its type.  There are various ways to tackle this.
When processing (x |> g1), we could "trim" the incoming demand U(U,U)
to match x's type.  But I'm currently doing so just at the moment when
we pin a demand on a binder, in DmdAnal.findBndrDmd.


708 709 710 711 712 713
Note [Threshold demands]
~~~~~~~~~~~~~~~~~~~~~~~~
Threshold usage demand is generated to figure out if
cardinality-instrumented demands of a binding's free variables should
be unleashed. See also [Aggregated demand for cardinality].

714 715 716 717 718 719 720 721 722 723 724 725 726
Note [Replicating polymorphic demands]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some demands can be considered as polymorphic. Generally, it is
applicable to such beasts as tops, bottoms as well as Head-Used adn
Head-stricts demands. For instance,

S ~ S(L, ..., L)

Also, when top or bottom is occurred as a result demand, it in fact
can be expanded to saturate a callee's arity. 


\begin{code}
727
splitProdDmd_maybe :: JointDmd -> Maybe [JointDmd]
728 729 730
-- Split a product into its components, iff there is any
-- useful information to be extracted thereby
-- The demand is not necessarily strict!
731 732
splitProdDmd_maybe (JD {strd = s, absd = u})
  = case (s,u) of
733 734 735 736 737 738
      (Str (SProd sx), Use _ u)          | Just ux <- splitUseProdDmd (length sx) u
                                         -> Just (mkJointDmds sx ux)
      (Str s,          Use _ (UProd ux)) | Just sx <- splitStrProdDmd (length ux) s
                                         -> Just (mkJointDmds sx ux)
      (Lazy,           Use _ (UProd ux)) -> Just (mkJointDmds (replicate (length ux) Lazy) ux)
      _ -> Nothing
739
\end{code}
740 741

%************************************************************************
742
%*                                                                      *
743
                   Demand results
744
%*                                                                      *
745 746
%************************************************************************

747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762

DmdResult:     Dunno CPRResult
               /
        Diverges


CPRResult:         NoCPR
                   /    \
            RetProd    RetSum ConTag


Product contructors return (Dunno (RetProd rs))
In a fixpoint iteration, start from Diverges
We have lubs, but not glbs; but that is ok.


763
\begin{code}
764 765 766 767
------------------------------------------------------------------------
-- Constructed Product Result                                             
------------------------------------------------------------------------

768 769
data Termination r = Diverges    -- Definitely diverges
                   | Dunno r     -- Might diverge or converge
770 771
               deriving( Eq, Show )

772 773 774 775 776
type DmdResult = Termination CPRResult

data CPRResult = NoCPR          -- Top of the lattice
               | RetProd        -- Returns a constructor from a product type
               | RetSum ConTag  -- Returns a constructor from a data type
777 778
               deriving( Eq, Show )

779 780
lubCPR :: CPRResult -> CPRResult -> CPRResult
lubCPR (RetSum t1) (RetSum t2) 
781
  | t1 == t2                       = RetSum t1
782 783
lubCPR RetProd     RetProd     = RetProd
lubCPR _ _                     = NoCPR
784 785 786 787 788

lubDmdResult :: DmdResult -> DmdResult -> DmdResult
lubDmdResult Diverges       r              = r
lubDmdResult (Dunno c1)     Diverges       = Dunno c1
lubDmdResult (Dunno c1)     (Dunno c2)     = Dunno (c1 `lubCPR` c2)
789
-- This needs to commute with defaultDmd, i.e.
790
-- defaultDmd (r1 `lubDmdResult` r2) = defaultDmd r1 `lubDmd` defaultDmd r2
791
-- (See Note [Default demand on free variables] for why)
792

793
bothDmdResult :: DmdResult -> Termination () -> DmdResult
794
-- See Note [Asymmetry of 'both' for DmdType and DmdResult]
795 796
bothDmdResult _              Diverges   = Diverges
bothDmdResult r              _          = r
797
-- This needs to commute with defaultDmd, i.e.
798
-- defaultDmd (r1 `bothDmdResult` r2) = defaultDmd r1 `bothDmd` defaultDmd r2
799
-- (See Note [Default demand on free variables] for why)
800

801
instance Outputable DmdResult where
802 803
  ppr Diverges      = char 'b'
  ppr (Dunno c)     = ppr c
804

805 806 807 808
instance Outputable CPRResult where
  ppr NoCPR        = empty
  ppr (RetSum n)   = char 'm' <> int n
  ppr RetProd      = char 'm'
809

810 811 812
seqDmdResult :: DmdResult -> ()
seqDmdResult Diverges = ()
seqDmdResult (Dunno c)     = seqCPRResult c
813

814 815 816 817
seqCPRResult :: CPRResult -> ()
seqCPRResult NoCPR        = ()
seqCPRResult (RetSum n)   = n `seq` ()
seqCPRResult RetProd      = ()
818

819 820 821 822

------------------------------------------------------------------------
-- Combined demand result                                             --
------------------------------------------------------------------------
823

824
-- [cprRes] lets us switch off CPR analysis
825 826
-- by making sure that everything uses TopRes
topRes, botRes :: DmdResult
827 828
topRes = Dunno NoCPR
botRes = Diverges
829

830 831 832
cprSumRes :: ConTag -> DmdResult
cprSumRes tag | opt_CprOff = topRes
              | otherwise  = Dunno $ RetSum tag
833

834
cprProdRes :: [DmdType] -> DmdResult
835
cprProdRes _arg_tys
836 837
  | opt_CprOff = topRes
  | otherwise  = Dunno $ RetProd
838

839
vanillaCprProdRes :: Arity -> DmdResult
840
vanillaCprProdRes _arity
841 842
  | opt_CprOff = topRes
  | otherwise  = Dunno $ RetProd
843

844
isTopRes :: DmdResult -> Bool
845 846
isTopRes (Dunno NoCPR) = True
isTopRes _             = False
847 848

isBotRes :: DmdResult -> Bool
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
isBotRes Diverges = True
isBotRes _        = False

trimCPRInfo :: Bool -> Bool -> DmdResult -> DmdResult
trimCPRInfo trim_all trim_sums res
  = trimR res
  where
    trimR (Dunno c)     = Dunno (trimC c)
    trimR Diverges      = Diverges

    trimC (RetSum n)   | trim_all || trim_sums = NoCPR
                       | otherwise             = RetSum n
    trimC RetProd      | trim_all  = NoCPR
                       | otherwise = RetProd
    trimC NoCPR = NoCPR
864

865
returnsCPR_maybe :: DmdResult -> Maybe ConTag
866 867 868 869 870 871 872
returnsCPR_maybe (Dunno c)     = retCPR_maybe c
returnsCPR_maybe Diverges      = Nothing

retCPR_maybe :: CPRResult -> Maybe ConTag
retCPR_maybe (RetSum t)  = Just t
retCPR_maybe RetProd     = Just fIRST_TAG
retCPR_maybe NoCPR       = Nothing
873

Gabor Greif's avatar
Gabor Greif committed
874
-- See Notes [Default demand on free variables]
Joachim Breitner's avatar
Joachim Breitner committed
875 876 877 878 879
-- and [defaultDmd vs. resTypeArgDmd]
defaultDmd :: Termination r -> JointDmd
defaultDmd Diverges = botDmd
defaultDmd _        = absDmd

880
resTypeArgDmd :: DmdResult -> JointDmd
881 882 883 884
-- TopRes and BotRes are polymorphic, so that
--      BotRes === Bot -> BotRes === ...
--      TopRes === Top -> TopRes === ...
-- This function makes that concrete
Joachim Breitner's avatar
Joachim Breitner committed
885
-- Also see Note [defaultDmd vs. resTypeArgDmd]
886 887
resTypeArgDmd r | isBotRes r = botDmd
resTypeArgDmd _              = topDmd
888 889
\end{code}

Joachim Breitner's avatar
Joachim Breitner committed
890 891 892 893
Note [defaultDmd and resTypeArgDmd]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

These functions are similar: They express the demand on something not
Gabor Greif's avatar
Gabor Greif committed
894
explicitly mentioned in the environment resp. the argument list. Yet they are
Joachim Breitner's avatar
Joachim Breitner committed
895 896 897 898 899
different:
 * Variables not mentioned in the free variables environment are definitely
   unused, so we can use absDmd there.
 * Further arguments *can* be used, of course. Hence topDmd is used.

900
Note [Worthy functions for Worker-Wrapper split]
901
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
For non-bottoming functions a worker-wrapper transformation takes into
account several possibilities to decide if the function is worthy for
splitting:

1. The result is of product type and the function is strict in some
(or even all) of its arguments. The check that the argument is used is
more of sanity nature, since strictness implies usage. Example:

f :: (Int, Int) -> Int
f p = (case p of (a,b) -> a) + 1

should be splitted to

f :: (Int, Int) -> Int
f p = case p of (a,b) -> $wf a

$wf :: Int -> Int
$wf a = a + 1

2. Sometimes it also makes sense to perform a WW split if the
strictness analysis cannot say for sure if the function is strict in
components of its argument. Then we reason according to the inferred
usage information: if the function uses its product argument's
components, the WW split can be beneficial. Example:

g :: Bool -> (Int, Int) -> Int
928
g c p = case p of (a,b) ->
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
          if c then a else b

The function g is strict in is argument p and lazy in its
components. However, both components are used in the RHS. The idea is
since some of the components (both in this case) are used in the
right-hand side, the product must presumable be taken apart.

Therefore, the WW transform splits the function g to

g :: Bool -> (Int, Int) -> Int
g c p = case p of (a,b) -> $wg c a b

$wg :: Bool -> Int -> Int -> Int
$wg c a b = if c then a else b

3. If an argument is absent, it would be silly to pass it to a
function, hence the worker with reduced arity is generated.


Note [Worker-wrapper for bottoming functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We used not to split if the result is bottom.
[Justification:  there's no efficiency to be gained.]

But it's sometimes bad not to make a wrapper.  Consider
        fw = \x# -> let x = I# x# in case e of
                                        p1 -> error_fn x
                                        p2 -> error_fn x
                                        p3 -> the real stuff
The re-boxing code won't go away unless error_fn gets a wrapper too.
[We don't do reboxing now, but in general it's better to pass an
unboxed thing to f, and have it reboxed in the error cases....]

962 963 964 965
However we *don't* want to do this when the argument is not actually
taken apart in the function at all.  Otherwise we risk decomposing a
masssive tuple which is barely used.  Example:

Simon Peyton Jones's avatar
Simon Peyton Jones committed
966 967
        f :: ((Int,Int) -> String) -> (Int,Int) -> a
        f g pr = error (g pr)
968

Simon Peyton Jones's avatar
Simon Peyton Jones committed
969
        main = print (f fst (1, error "no"))
970

971 972 973 974
Here, f does not take 'pr' apart, and it's stupid to do so.
Imagine that it had millions of fields. This actually happened
in GHC itself where the tuple was DynFlags

975 976 977 978 979 980 981 982 983

%************************************************************************
%*                                                                      *
\subsection{Demand environments and types}
%*                                                                      *
%************************************************************************

\begin{code}
type Demand = JointDmd
984

985
type DmdEnv = VarEnv Demand   -- See Note [Default demand on free variables]
986

987 988 989 990
data DmdType = DmdType 
                  DmdEnv        -- Demand on explicitly-mentioned 
                                --      free variables
                  [Demand]      -- Demand on arguments
991
                  DmdResult     -- See [Nature of result demand]
992 993 994 995
\end{code}

Note [Nature of result demand]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
A DmdResult contains information about termination (currently distinguishing
definite divergence and no information; it is possible to include definite
convergence here), and CPR information about the result.

The semantics of this depends on whether we are looking at a DmdType, i.e. the
demand put on by an expression _under a specific incoming demand_ on its
environment, or at a StrictSig describing a demand transformer.

For a
 * DmdType, the termination information is true given the demand it was
   generated with, while for
 * a StrictSig it is olds after applying enough arguments.

The CPR information, though, is valid after the number of arguments mentioned
in the type is given. Therefore, when forgetting the demand on arguments, as in
dmdAnalRhs, this needs to be considere (via removeDmdTyArgs).

Consider
  b2 x y = x `seq` y `seq` error (show x)
this has a strictness signature of
  <S><S>b
meaning that "b2 `seq` ()" and "b2 1 `seq` ()" might well terminate, but
for "b2 1 2 `seq` ()" we get definite divergence.

Gabor Greif's avatar
Gabor Greif committed
1020
For comparison,
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
  b1 x = x `seq` error (show x)
has a strictness signature of
  <S>b
and "b1 1 `seq` ()" is known to terminate.

Now consider a function h with signature "<C(S)>", and the expression
  e1 = h b1
now h puts a demand of <C(S)> onto its argument, and the demand transformer
turns it into
  <S>b
Now the DmdResult "b" does apply to us, even though "b1 `seq` ()" does not
diverge, and we do not anything being passed to b.
1033 1034 1035 1036 1037

Note [Asymmetry of 'both' for DmdType and DmdResult]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'both' for DmdTypes is *assymetrical*, because there is only one
result!  For example, given (e1 e2), we get a DmdType dt1 for e1, use
1038 1039 1040 1041 1042 1043
its arg demand to analyse e2 giving dt2, and then do (dt1 `bothType` dt2).
Similarly with 
  case e of { p -> rhs }
we get dt_scrut from the scrutinee and dt_rhs from the RHS, and then
compute (dt_rhs `bothType` dt_scrut).

1044 1045 1046 1047 1048 1049 1050
We
 1. combine the information on the free variables,
 2. take the demand on arguments from the first argument
 3. combine the termination results, but
 4. take CPR info from the first argument.

3 and 4 are implementd in bothDmdResult.
1051 1052 1053


\begin{code}
1054 1055 1056 1057
-- Equality needed for fixpoints in DmdAnal
instance Eq DmdType where
  (==) (DmdType fv1 ds1 res1)
       (DmdType fv2 ds2 res2) =  ufmToList fv1 == ufmToList fv2
1058 1059 1060
                              && ds1 == ds2 && res1 == res2

lubDmdType :: DmdType -> DmdType -> DmdType
1061 1062
lubDmdType d1 d2
  = DmdType lub_fv lub_ds lub_res
1063
  where
1064 1065 1066 1067
    n = max (dmdTypeDepth d1) (dmdTypeDepth d2)
    (DmdType fv1 ds1 r1) = ensureArgs n d1
    (DmdType fv2 ds2 r2) = ensureArgs n d2

1068
    lub_fv  = plusVarEnv_CD lubDmd fv1 (defaultDmd r1) fv2 (defaultDmd r2)
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    lub_ds  = zipWithEqual "lubDmdType" lubDmd ds1 ds2
    lub_res = lubDmdResult r1 r2
\end{code}

Note [The need for BothDmdArg]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Previously, the right argument to bothDmdType, as well as the return value of
dmdAnalStar via postProcessDmdTypeM, was a DmdType. But bothDmdType only needs
to know about the free variables and termination information, but nothing about
the demand put on arguments, nor cpr information. So we make that explicit by
only passing the relevant information.
1080

1081

1082
\begin{code}
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
type BothDmdArg = (DmdEnv, Termination ())

mkBothDmdArg :: DmdEnv -> BothDmdArg
mkBothDmdArg env = (env, Dunno ())

toBothDmdArg :: DmdType -> BothDmdArg
toBothDmdArg (DmdType fv _ r) = (fv, go r)
  where
  go (Dunno {})     = Dunno ()
  go Diverges       = Diverges

bothDmdType :: DmdType -> BothDmdArg -> DmdType
bothDmdType (DmdType fv1 ds1 r1) (fv2, t2)
1096 1097 1098
    -- See Note [Asymmetry of 'both' for DmdType and DmdResult]
    -- 'both' takes the argument/result info from its *first* arg,
    -- using its second arg just for its free-var info.
1099 1100
  = DmdType both_fv ds1 (r1 `bothDmdResult` t2)
  where both_fv = plusVarEnv_CD bothDmd fv1 (defaultDmd r1) fv2 (defaultDmd t2)
1101 1102 1103 1104

instance Outputable DmdType where
  ppr (DmdType fv ds res) 
    = hsep [text "DmdType",
1105 1106 1107
            hcat (map ppr ds) <> ppr res,
            if null fv_elts then empty
            else braces (fsep (map pp_elt fv_elts))]
1108 1109 1110 1111 1112 1113 1114
    where
      pp_elt (uniq, dmd) = ppr uniq <> text "->" <> ppr dmd
      fv_elts = ufmToList fv

emptyDmdEnv :: VarEnv Demand
emptyDmdEnv = emptyVarEnv

1115 1116 1117 1118 1119 1120
-- nopDmdType is the demand of doing nothing
-- (lazy, absent, no CPR information, no termination information).
-- Note that it is ''not'' the top of the lattice (which would be "may use everything"),
-- so it is (no longer) called topDmd
nopDmdType, botDmdType :: DmdType
nopDmdType = DmdType emptyDmdEnv [] topRes
1121
botDmdType = DmdType emptyDmdEnv [] botRes
1122

1123 1124 1125
cprProdDmdType :: Arity -> DmdType
cprProdDmdType _arity
  = DmdType emptyDmdEnv [] (Dunno RetProd)
1126

1127 1128
isNopDmdType :: DmdType -> Bool
isNopDmdType (DmdType env [] res)
1129
  | isTopRes res && isEmptyVarEnv env = True
1130
isNopDmdType _                        = False
1131 1132 1133 1134 1135 1136

mkDmdType :: DmdEnv -> [Demand] -> DmdResult -> DmdType
mkDmdType fv ds res = DmdType fv ds res

dmdTypeDepth :: DmdType -> Arity
dmdTypeDepth (DmdType _ ds _) = length ds
1137

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
-- Remove any demand on arguments. This is used in dmdAnalRhs on the body
removeDmdTyArgs :: DmdType -> DmdType
removeDmdTyArgs = ensureArgs 0

-- This makes sure we can use the demand type with n arguments,
-- It extends the argument list with the correct resTypeArgDmd
-- It also adjusts the DmdResult: Divergence survives additional arguments,
-- CPR information does not (and definite converge also would not).
ensureArgs :: Arity -> DmdType -> DmdType
ensureArgs n d | n == depth = d
               | otherwise  = DmdType fv ds' r'
  where depth = dmdTypeDepth d
        DmdType fv ds r = d

        ds' = take n (ds ++ repeat (resTypeArgDmd r))
        r' | Diverges <- r = r
           | otherwise     = topRes
                -- See [Nature of result demand]

1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
seqDmdType :: DmdType -> ()
seqDmdType (DmdType _env ds res) = 
  {- ??? env `seq` -} seqDemandList ds `seq` seqDmdResult res `seq` ()

splitDmdTy :: DmdType -> (Demand, DmdType)
-- Split off one function argument
-- We already have a suitable demand on all
-- free vars, so no need to add more!
splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
splitDmdTy ty@(DmdType _ [] res_ty)       = (resTypeArgDmd res_ty, ty)

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
-- When e is evaluated after executing an IO action, and d is e's demand, then
-- what of this demand should we consider, given that the IO action can cleanly
-- exit?
-- * We have to kill all strictness demands (i.e. lub with a lazy demand)
-- * We can keep demand information (i.e. lub with an absent deman)
-- * We have to kill definite divergence
-- * We can keep CPR information.
-- See Note [IO hack in the demand analyser]
deferAfterIO :: DmdType -> DmdType
deferAfterIO d@(DmdType _ _ res) =
1178
    case d `lubDmdType` nopDmdType of
1179 1180
        DmdType fv ds _ -> DmdType fv ds (defer_res res)
  where
1181 1182
  defer_res Diverges      = topRes
  defer_res r             = r
1183

1184 1185 1186 1187 1188 1189 1190 1191
strictenDmd :: JointDmd -> CleanDemand
strictenDmd (JD {strd = s, absd = u})
  = CD { sd = poke_s s, ud = poke_u u }
  where
    poke_s Lazy      = HeadStr
    poke_s (Str s)   = s
    poke_u Abs       = UHead
    poke_u (Use _ u) = u
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
\end{code}

Deferring and peeeling

\begin{code}
type DeferAndUse   -- Describes how to degrade a result type
   =( Bool        -- Lazify (defer) the type
    , Count)      -- Many => manify the type

type DeferAndUseM = Maybe DeferAndUse
  -- Nothing <=> absent-ify the result type; it will never be used
1203

1204
toCleanDmd :: Demand -> (CleanDemand, DeferAndUseM)
1205
-- See Note [Analyzing with lazy demand and lambdas]
1206
toCleanDmd (JD { strd = s, absd = u })
1207
  = case (s,u) of
1208 1209 1210 1211
      (Str s', Use c u') -> (CD { sd = s',      ud = u' },   Just (False, c))
      (Lazy,   Use c u') -> (CD { sd = HeadStr, ud = u' },   Just (True,  c))
      (_,      Abs)      -> (CD { sd = HeadStr, ud = Used }, Nothing)

1212 1213 1214
-- This is used in dmdAnalStar when post-processing
-- a function's argument demand. So we only care about what
-- does to free variables, and whether it terminates.
1215
-- see Note [The need for BothDmdArg]
1216 1217
postProcessDmdTypeM :: DeferAndUseM -> DmdType -> BothDmdArg
postProcessDmdTypeM Nothing   _  = (emptyDmdEnv, Dunno ())
1218 1219 1220
  -- Incoming demand was Absent, so just discard all usage information
  -- We only processed the thing at all to analyse the body
  -- See Note [Always analyse in virgin pass]
1221
postProcessDmdTypeM (Just du) (DmdType fv _ res_ty)
1222
    = (postProcessDmdEnv du fv, postProcessDmdResult du res_ty)
1223

1224 1225 1226 1227
postProcessDmdResult :: DeferAndUse -> DmdResult -> Termination ()
postProcessDmdResult (True,_)  _          = Dunno ()
postProcessDmdResult (False,_) (Dunno {}) = Dunno ()
postProcessDmdResult (False,_) Diverges   = Diverges
1228 1229 1230 1231 1232 1233 1234

postProcessDmdEnv :: DeferAndUse -> DmdEnv -> DmdEnv
postProcessDmdEnv (True,  Many) env = deferReuseEnv env
postProcessDmdEnv (False, Many) env = reuseEnv env
postProcessDmdEnv (True,  One)  env = deferEnv env
postProcessDmdEnv (False, One)  env = env

1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258

postProcessUnsat :: DeferAndUse -> DmdType -> DmdType
postProcessUnsat (True,  Many) ty = deferReuse ty
postProcessUnsat (False, Many) ty = reuseType ty
postProcessUnsat (True,  One)  ty = deferType ty
postProcessUnsat (False, One)  ty = ty

deferType, reuseType, deferReuse :: DmdType -> DmdType
deferType  (DmdType fv ds _)      = DmdType (deferEnv fv)      (map deferDmd ds)      topRes
reuseType  (DmdType fv ds res_ty) = DmdType (reuseEnv fv)      (map reuseDmd ds)      res_ty
deferReuse (DmdType fv ds _)      = DmdType (deferReuseEnv fv) (map deferReuseDmd ds) topRes

deferEnv, reuseEnv, deferReuseEnv :: DmdEnv -> DmdEnv
deferEnv      fv = mapVarEnv deferDmd fv
reuseEnv      fv = mapVarEnv reuseDmd fv
deferReuseEnv fv = mapVarEnv deferReuseDmd fv

deferDmd, reuseDmd, deferReuseDmd :: JointDmd -> JointDmd
deferDmd      (JD {strd=_, absd=a}) = mkJointDmd Lazy a
reuseDmd      (JD {strd=d, absd=a}) = mkJointDmd d    (markReusedDmd a)
deferReuseDmd (JD {strd=_, absd=a}) = mkJointDmd Lazy (markReusedDmd a)

-- Peels one call level from the demand, and also returns
-- whether it was unsaturated (separately for strictness and usage)
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
peelCallDmd :: CleanDemand -> (CleanDemand, DeferAndUse)
-- Exploiting the fact that
-- on the strictness side      C(B) = B
-- and on the usage side       C(U) = U
peelCallDmd (CD {sd = s, ud = u})
  = case (s, u) of
      (SCall s', UCall c u') -> (CD { sd = s',       ud = u' },   (False, c))
      (SCall s', _)          -> (CD { sd = s',       ud = Used }, (False, Many))
      (HyperStr, UCall c u') -> (CD { sd = HyperStr, ud = u' },   (False, c))
      (HyperStr, _)          -> (CD { sd = HyperStr, ud = Used }, (False, Many))
      (_,        UCall c u') -> (CD { sd = HeadStr,  ud = u' },   (True,  c))
      (_,        _)          -> (CD { sd = HeadStr,  ud = Used }, (True,  Many))
       -- The _ cases for usage includes UHead which seems a bit wrong
       -- because the body isn't used at all!
       -- c.f. the Abs case in toCleanDmd

Joachim Breitner's avatar
Joachim Breitner committed
1275 1276 1277 1278 1279 1280
-- Peels that multiple nestings of calls clean demand and also returns
-- whether it was unsaturated (separately for strictness and usage
-- see Note [Demands from unsaturated function calls]
peelManyCalls :: Int -> CleanDemand -> DeferAndUse
peelManyCalls n (CD { sd = str, ud = abs })
  = (go_str n str, go_abs n abs)
1281
  where
Joachim Breitner's avatar
Joachim Breitner committed
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
    go_str :: Int -> StrDmd -> Bool  -- True <=> unsaturated, defer
    go_str 0 _          = False
    go_str _ HyperStr   = False -- == go_str (n-1) HyperStr, as HyperStr = Call(HyperStr)
    go_str n (SCall d') = go_str (n-1) d'
    go_str _ _          = True

    go_abs :: Int -> UseDmd -> Count -- Many <=> unsaturated, or at least
    go_abs 0 _              = One    --          one UCall Many in the demand
    go_abs n (UCall One d') = go_abs (n-1) d'
    go_abs _ _              = Many
\end{code}
1293

Joachim Breitner's avatar
Joachim Breitner committed
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
Note [Demands from unsaturated function calls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Consider a demand transformer d1 -> d2 -> r for f.
If a sufficiently detailed demand is fed into this transformer,
e.g <C(C(S)), C1(C1(S))> arising from "f x1 x2" in a strict, use-once context,
then d1 and d2 is precisely the demand unleashed onto x1 and x2 (similar for
the free variable environment) and furthermore the result information r is the
one we want to use.

1304 1305 1306
An anonymous lambda is also an unsaturated function all (needs one argument,
none given), so this applies to that case as well.

Joachim Breitner's avatar
Joachim Breitner committed
1307 1308 1309 1310
But the demand fed into f might be less than <C(C(S)), C1(C1(S))>. There are a few cases:
 * Not enough demand on the strictness side:
   - In that case, we need to zap all strictness in the demand on arguments and
     free variables.
1311 1312 1313 1314 1315 1316 1317
   - Furthermore, we remove CPR information. It could be left, but given the incoming
     demand is not enough to evaluate so far we just do not bother.
   - And finally termination information: If r says that f diverges for sure,
     then this holds when the demand guarantees that two arguments are going to
     be passed. If the demand is lower, we may just as well converge.
     If we were tracking definite convegence, than that would still hold under
     a weaker demand than expected by the demand transformer.
Joachim Breitner's avatar
Joachim Breitner committed
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
 * Not enough demand from the usage side: The missing usage can be expanded
   using UCall Many, therefore this is subsumed by the third case:
 * At least one of the uses has a cardinality of Many.
   - Even if f puts a One demand on any of its argument or free variables, if
     we call f multiple times, we may evaluate this argument or free variable
     multiple times. So forget about any occurrence of "One" in the demand.

In dmdTransformSig, we call peelManyCalls to find out if we are in any of these
cases, and then call postProcessUnsat to reduce the demand appropriately.

Similarly, dmdTransformDictSelSig and dmdAnal, when analyzing a Lambda, use
peelCallDmd, which peels only one level, but also returns the demand put on the
body of the function.
1331

Joachim Breitner's avatar
Joachim Breitner committed
1332
\begin{code}
1333 1334 1335 1336 1337
peelFV :: DmdType -> Var -> (DmdType, Demand)
peelFV (DmdType fv ds res) id = -- pprTrace "rfv" (ppr id <+> ppr dmd $$ ppr fv)
                               (DmdType fv' ds res, dmd)
  where
  fv' = fv `delVarEnv` id
1338
  -- See Note [Default demand on free variables]