[project @ 2001-08-24 13:22:25 by simonpj]
[ghc-hetmet.git] / ghc / compiler / basicTypes / IdInfo.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[IdInfo]{@IdInfos@: Non-essential information about @Ids@}
5
6 (And a pretty good illustration of quite a few things wrong with
7 Haskell. [WDP 94/11])
8
9 \begin{code}
10 module IdInfo (
11         GlobalIdDetails(..), notGlobalId,       -- Not abstract
12
13         IdInfo,         -- Abstract
14         vanillaIdInfo, noCafNoTyGenIdInfo,
15         seqIdInfo, megaSeqIdInfo,
16
17         -- Zapping
18         zapLamInfo, zapDemandInfo,
19         shortableIdInfo, copyIdInfo,
20
21         -- Arity
22         ArityInfo,
23         exactArity, unknownArity, hasArity,
24         arityInfo, setArityInfo, ppArityInfo, arityLowerBound,
25
26         -- New demand and strictness info
27         newStrictnessInfo, setNewStrictnessInfo, mkNewStrictnessInfo,
28         newDemandInfo, setNewDemandInfo, newDemand, oldDemand,
29
30         -- Strictness; imported from Demand
31         StrictnessInfo(..),
32         mkStrictnessInfo, noStrictnessInfo,
33         ppStrictnessInfo,isBottomingStrictness, 
34         strictnessInfo, setStrictnessInfo,      
35
36         -- Usage generalisation
37         TyGenInfo(..),
38         tyGenInfo, setTyGenInfo,
39         noTyGenInfo, isNoTyGenInfo, ppTyGenInfo, tyGenInfoString,
40
41         -- Worker
42         WorkerInfo(..), workerExists, wrapperArity, workerId,
43         workerInfo, setWorkerInfo, ppWorkerInfo,
44
45         -- Unfolding
46         unfoldingInfo, setUnfoldingInfo, 
47
48         -- DemandInfo
49         demandInfo, setDemandInfo, 
50
51         -- Inline prags
52         InlinePragInfo(..), 
53         inlinePragInfo, setInlinePragInfo, pprInlinePragInfo,
54         isNeverInlinePrag, neverInlinePrag,
55
56         -- Occurrence info
57         OccInfo(..), isFragileOcc, isDeadOcc, isLoopBreaker,
58         InsideLam, OneBranch, insideLam, notInsideLam, oneBranch, notOneBranch,
59         occInfo, setOccInfo, 
60
61         -- Specialisation
62         specInfo, setSpecInfo,
63
64         -- CG info
65         CgInfo(..), cgInfo, setCgInfo,  cgMayHaveCafRefs, pprCgInfo,
66         cgArity, cgCafInfo, vanillaCgInfo,
67         CgInfoEnv, lookupCgInfo,
68         setCgArity,
69
70         -- CAF info
71         CafInfo(..), ppCafInfo, setCafInfo, mayHaveCafRefs,
72
73         -- Constructed Product Result Info
74         CprInfo(..), cprInfo, setCprInfo, ppCprInfo, noCprInfo,
75
76         -- Lambda-bound variable info
77         LBVarInfo(..), lbvarInfo, setLBVarInfo, noLBVarInfo, hasNoLBVarInfo
78     ) where
79
80 #include "HsVersions.h"
81
82
83 import CoreSyn
84 import Type             ( Type, usOnce, eqUsage )
85 import PrimOp           ( PrimOp )
86 import NameEnv          ( NameEnv, lookupNameEnv )
87 import Name             ( Name )
88 import Var              ( Id )
89 import BasicTypes       ( OccInfo(..), isFragileOcc, isDeadOcc, seqOccInfo, isLoopBreaker,
90                           InsideLam, insideLam, notInsideLam, 
91                           OneBranch, oneBranch, notOneBranch,
92                           Arity
93                         )
94 import DataCon          ( DataCon )
95 import ForeignCall      ( ForeignCall )
96 import FieldLabel       ( FieldLabel )
97 import Type             ( usOnce, usMany )
98 import Demand           hiding( Demand )
99 import qualified Demand
100 import NewDemand        ( Demand(..), Keepity(..), Deferredness(..), DmdResult(..),
101                           lazyDmd, topDmd,
102                           StrictSig, mkStrictSig, mkTopDmdType
103                         )
104 import Outputable       
105 import Util             ( seqList )
106 import List             ( replicate )
107
108 infixl  1 `setDemandInfo`,
109           `setTyGenInfo`,
110           `setStrictnessInfo`,
111           `setSpecInfo`,
112           `setArityInfo`,
113           `setInlinePragInfo`,
114           `setUnfoldingInfo`,
115           `setCprInfo`,
116           `setWorkerInfo`,
117           `setLBVarInfo`,
118           `setOccInfo`,
119           `setCgInfo`,
120           `setCafInfo`,
121           `setCgArity`,
122           `setNewStrictnessInfo`,
123           `setNewDemandInfo`
124         -- infixl so you can say (id `set` a `set` b)
125 \end{code}
126
127 %************************************************************************
128 %*                                                                      *
129 \subsection{New strictness info}
130 %*                                                                      *
131 %************************************************************************
132
133 To be removed later
134
135 \begin{code}
136 mkNewStrictnessInfo :: Id -> Arity -> Demand.StrictnessInfo -> CprInfo -> StrictSig
137 mkNewStrictnessInfo id arity (Demand.StrictnessInfo ds res) cpr
138   | length ds <= arity
139         -- Sometimes the old strictness analyser has more
140         -- demands than the arity justifies
141   = mkStrictSig id arity $
142     mkTopDmdType (map newDemand ds) (newRes res cpr)
143
144 mkNewStrictnessInfo id arity other cpr
145   =     -- Either no strictness info, or arity is too small
146         -- In either case we can't say anything useful
147     mkStrictSig id arity $
148     mkTopDmdType (replicate arity lazyDmd) (newRes False cpr)
149
150 newRes True  _          = BotRes
151 newRes False ReturnsCPR = RetCPR
152 newRes False NoCPRInfo  = TopRes
153
154 newDemand :: Demand.Demand -> NewDemand.Demand
155 newDemand (WwLazy True)      = Abs
156 newDemand (WwLazy False)     = Lazy
157 newDemand WwStrict           = Eval
158 newDemand (WwUnpack unpk ds) = Seq Drop Now (map newDemand ds)
159 newDemand WwPrim             = Lazy
160 newDemand WwEnum             = Eval
161
162 oldDemand :: NewDemand.Demand -> Demand.Demand
163 oldDemand Abs          = WwLazy True
164 oldDemand Lazy         = WwLazy False
165 oldDemand Bot          = WwStrict
166 oldDemand Err          = WwStrict
167 oldDemand Eval         = WwStrict
168 oldDemand (Seq _ _ ds) = WwUnpack True (map oldDemand ds)
169 oldDemand (Call _)     = WwStrict
170 \end{code}
171
172
173 %************************************************************************
174 %*                                                                      *
175 \subsection{GlobalIdDetails
176 %*                                                                      *
177 %************************************************************************
178
179 This type is here (rather than in Id.lhs) mainly because there's 
180 an IdInfo.hi-boot, but no Id.hi-boot, and GlobalIdDetails is imported
181 (recursively) by Var.lhs.
182
183 \begin{code}
184 data GlobalIdDetails
185   = VanillaGlobal               -- Imported from elsewhere, a default method Id.
186
187   | RecordSelId FieldLabel      -- The Id for a record selector
188   | DataConId DataCon           -- The Id for a data constructor *worker*
189   | DataConWrapId DataCon       -- The Id for a data constructor *wrapper*
190                                 -- [the only reasons we need to know is so that
191                                 --  a) we can  suppress printing a definition in the interface file
192                                 --  b) when typechecking a pattern we can get from the
193                                 --     Id back to the data con]
194
195   | PrimOpId PrimOp             -- The Id for a primitive operator
196   | FCallId ForeignCall         -- The Id for a foreign call
197
198   | NotGlobalId                 -- Used as a convenient extra return value from globalIdDetails
199     
200 notGlobalId = NotGlobalId
201
202 instance Outputable GlobalIdDetails where
203     ppr NotGlobalId       = ptext SLIT("[***NotGlobalId***]")
204     ppr VanillaGlobal     = ptext SLIT("[GlobalId]")
205     ppr (DataConId _)     = ptext SLIT("[DataCon]")
206     ppr (DataConWrapId _) = ptext SLIT("[DataConWrapper]")
207     ppr (PrimOpId _)      = ptext SLIT("[PrimOp]")
208     ppr (FCallId _)       = ptext SLIT("[ForeignCall]")
209     ppr (RecordSelId _)   = ptext SLIT("[RecSel]")
210 \end{code}
211
212
213 %************************************************************************
214 %*                                                                      *
215 \subsection{The main IdInfo type}
216 %*                                                                      *
217 %************************************************************************
218
219 An @IdInfo@ gives {\em optional} information about an @Id@.  If
220 present it never lies, but it may not be present, in which case there
221 is always a conservative assumption which can be made.
222
223 Two @Id@s may have different info even though they have the same
224 @Unique@ (and are hence the same @Id@); for example, one might lack
225 the properties attached to the other.
226
227 The @IdInfo@ gives information about the value, or definition, of the
228 @Id@.  It does {\em not} contain information about the @Id@'s usage
229 (except for @DemandInfo@? ToDo). (@lbvarInfo@ is also a marginal
230 case.  KSW 1999-04).
231
232 \begin{code}
233 data IdInfo
234   = IdInfo {
235         arityInfo       :: ArityInfo,           -- Its arity
236         demandInfo      :: Demand.Demand,       -- Whether or not it is definitely demanded
237         specInfo        :: CoreRules,           -- Specialisations of this function which exist
238         tyGenInfo       :: TyGenInfo,           -- Restrictions on usage-generalisation of this Id
239         strictnessInfo  :: StrictnessInfo,      -- Strictness properties
240         workerInfo      :: WorkerInfo,          -- Pointer to Worker Function
241         unfoldingInfo   :: Unfolding,           -- Its unfolding
242         cgInfo          :: CgInfo,              -- Code generator info (arity, CAF info)
243         cprInfo         :: CprInfo,             -- Function always constructs a product result
244         lbvarInfo       :: LBVarInfo,           -- Info about a lambda-bound variable
245         inlinePragInfo  :: InlinePragInfo,      -- Inline pragma
246         occInfo         :: OccInfo,             -- How it occurs
247
248         newStrictnessInfo :: Maybe StrictSig,
249         newDemandInfo     :: Demand
250     }
251
252 seqIdInfo :: IdInfo -> ()
253 seqIdInfo (IdInfo {}) = ()
254
255 megaSeqIdInfo :: IdInfo -> ()
256 megaSeqIdInfo info
257   = seqArity (arityInfo info)                   `seq`
258     seqDemand (demandInfo info)                 `seq`
259     seqRules (specInfo info)                    `seq`
260     seqTyGenInfo (tyGenInfo info)               `seq`
261     seqStrictnessInfo (strictnessInfo info)     `seq`
262     seqWorker (workerInfo info)                 `seq`
263
264 --    seqUnfolding (unfoldingInfo info) `seq`
265 -- Omitting this improves runtimes a little, presumably because
266 -- some unfoldings are not calculated at all
267
268 -- CgInfo is involved in a loop, so we have to be careful not to seq it
269 -- too early.
270 --    seqCg (cgInfo info)                       `seq`
271     seqCpr (cprInfo info)               `seq`
272     seqLBVar (lbvarInfo info)           `seq`
273     seqOccInfo (occInfo info) 
274 \end{code}
275
276 Setters
277
278 \begin{code}
279 setWorkerInfo     info wk = wk `seq` info { workerInfo = wk }
280 setSpecInfo       info sp = PSEQ sp (info { specInfo = sp })
281 setTyGenInfo      info tg = tg `seq` info { tyGenInfo = tg }
282 setInlinePragInfo info pr = pr `seq` info { inlinePragInfo = pr }
283 setOccInfo        info oc = oc `seq` info { occInfo = oc }
284 setStrictnessInfo info st = st `seq` info { strictnessInfo = st }
285         -- Try to avoid spack leaks by seq'ing
286
287 setUnfoldingInfo  info uf 
288   | isEvaldUnfolding uf && isStrict (demandInfo info)
289         -- If the unfolding is a value, the demand info may
290         -- go pear-shaped, so we nuke it.  Example:
291         --      let x = (a,b) in
292         --      case x of (p,q) -> h p q x
293         -- Here x is certainly demanded. But after we've nuked
294         -- the case, we'll get just
295         --      let x = (a,b) in h a b x
296         -- and now x is not demanded (I'm assuming h is lazy)
297         -- This really happens.  The solution here is a bit ad hoc...
298   = info { unfoldingInfo = uf, demandInfo = wwLazy }
299
300   | otherwise
301         -- We do *not* seq on the unfolding info, For some reason, doing so 
302         -- actually increases residency significantly. 
303   = info { unfoldingInfo = uf }
304
305 setDemandInfo     info dd = info { demandInfo = dd }
306 setArityInfo      info ar = info { arityInfo = Just ar  }
307 setCgInfo         info cg = info { cgInfo = cg }
308 setCprInfo        info cp = info { cprInfo = cp }
309 setLBVarInfo      info lb = info { lbvarInfo = lb }
310
311 setNewDemandInfo     info dd = info { newDemandInfo = dd }
312 setNewStrictnessInfo info dd = info { newStrictnessInfo = dd }
313 \end{code}
314
315
316 \begin{code}
317 vanillaIdInfo :: IdInfo
318 vanillaIdInfo 
319   = IdInfo {
320             cgInfo              = noCgInfo,
321             arityInfo           = unknownArity,
322             demandInfo          = wwLazy,
323             specInfo            = emptyCoreRules,
324             tyGenInfo           = noTyGenInfo,
325             workerInfo          = NoWorker,
326             strictnessInfo      = NoStrictnessInfo,
327             unfoldingInfo       = noUnfolding,
328             cprInfo             = NoCPRInfo,
329             lbvarInfo           = NoLBVarInfo,
330             inlinePragInfo      = NoInlinePragInfo,
331             occInfo             = NoOccInfo,
332             newDemandInfo       = topDmd,
333             newStrictnessInfo   = Nothing
334            }
335
336 noCafNoTyGenIdInfo = vanillaIdInfo `setTyGenInfo` TyGenNever
337                                    `setCgInfo`    (CgInfo 0 NoCafRefs)
338         -- Used for built-in type Ids in MkId.
339         -- Many built-in things have fixed types, so we shouldn't
340         -- run around generalising them
341 \end{code}
342
343
344 %************************************************************************
345 %*                                                                      *
346 \subsection[arity-IdInfo]{Arity info about an @Id@}
347 %*                                                                      *
348 %************************************************************************
349
350 For locally-defined Ids, the code generator maintains its own notion
351 of their arities; so it should not be asking...  (but other things
352 besides the code-generator need arity info!)
353
354 \begin{code}
355 type ArityInfo = Maybe Arity
356         -- A partial application of this Id to up to n-1 value arguments
357         -- does essentially no work.  That is not necessarily the
358         -- same as saying that it has n leading lambdas, because coerces
359         -- may get in the way.
360
361         -- The arity might increase later in the compilation process, if
362         -- an extra lambda floats up to the binding site.
363
364 seqArity :: ArityInfo -> ()
365 seqArity a = arityLowerBound a `seq` ()
366
367 exactArity   = Just
368 unknownArity = Nothing
369
370 arityLowerBound :: ArityInfo -> Arity
371 arityLowerBound Nothing  = 0
372 arityLowerBound (Just n) = n
373
374 hasArity :: ArityInfo -> Bool
375 hasArity Nothing = False
376 hasArity other   = True
377
378 ppArityInfo Nothing      = empty
379 ppArityInfo (Just arity) = hsep [ptext SLIT("Arity"), int arity]
380 \end{code}
381
382 %************************************************************************
383 %*                                                                      *
384 \subsection{Inline-pragma information}
385 %*                                                                      *
386 %************************************************************************
387
388 \begin{code}
389 data InlinePragInfo
390   = NoInlinePragInfo
391   | IMustNotBeINLINEd Bool              -- True <=> came from an INLINE prag, False <=> came from a NOINLINE prag
392                       (Maybe Int)       -- Phase number from pragma, if any
393   deriving( Eq )
394         -- The True, Nothing case doesn't need to be recorded
395
396         -- SEE COMMENTS WITH CoreUnfold.blackListed on the
397         -- exact significance of the IMustNotBeINLINEd pragma
398
399 isNeverInlinePrag :: InlinePragInfo -> Bool
400 isNeverInlinePrag (IMustNotBeINLINEd _ Nothing) = True
401 isNeverInlinePrag other                         = False
402
403 neverInlinePrag :: InlinePragInfo
404 neverInlinePrag = IMustNotBeINLINEd True{-should be False? --SDM -} Nothing
405
406 instance Outputable InlinePragInfo where
407   -- This is now parsed in interface files
408   ppr NoInlinePragInfo = empty
409   ppr other_prag       = ptext SLIT("__U") <> pprInlinePragInfo other_prag
410
411 pprInlinePragInfo NoInlinePragInfo                   = empty
412 pprInlinePragInfo (IMustNotBeINLINEd True Nothing)   = empty
413 pprInlinePragInfo (IMustNotBeINLINEd True (Just n))  = brackets (int n)
414 pprInlinePragInfo (IMustNotBeINLINEd False Nothing)  = brackets (char '!')
415 pprInlinePragInfo (IMustNotBeINLINEd False (Just n)) = brackets (char '!' <> int n)
416                                                         
417 instance Show InlinePragInfo where
418   showsPrec p prag = showsPrecSDoc p (ppr prag)
419 \end{code}
420
421
422 %************************************************************************
423 %*                                                                    *
424 \subsection[TyGen-IdInfo]{Type generalisation info about an @Id@}
425 %*                                                                    *
426 %************************************************************************
427
428 Certain passes (notably usage inference) may change the type of an
429 identifier, modifying all in-scope uses of that identifier
430 appropriately to maintain type safety.
431
432 However, some identifiers must not have their types changed in this
433 way, because their types are conjured up in the front end of the
434 compiler rather than being read from the interface file.  Default
435 methods, dictionary functions, record selectors, and others are in
436 this category.  (see comment at TcClassDcl.tcClassSig).
437
438 To indicate this property, such identifiers are marked TyGenNever.
439
440 Furthermore, if the usage inference generates a usage-specialised
441 variant of a function, we must NOT re-infer a fully-generalised type
442 at the next inference.  This finer property is indicated by a
443 TyGenUInfo on the identifier.
444
445 \begin{code}
446 data TyGenInfo
447   = NoTyGenInfo              -- no restriction on type generalisation
448
449   | TyGenUInfo [Maybe Type]  -- restrict generalisation of this Id to
450                              -- preserve specified usage annotations
451
452   | TyGenNever               -- never generalise the type of this Id
453 \end{code}
454
455 For TyGenUInfo, the list has one entry for each usage annotation on
456 the type of the Id, in left-to-right pre-order (annotations come
457 before the type they annotate).  Nothing means no restriction; Just
458 usOnce or Just usMany forces that annotation to that value.  Other
459 usage annotations are illegal.
460
461 \begin{code}
462 seqTyGenInfo :: TyGenInfo -> ()
463 seqTyGenInfo  NoTyGenInfo    = ()
464 seqTyGenInfo (TyGenUInfo us) = seqList us ()
465 seqTyGenInfo  TyGenNever     = ()
466
467 noTyGenInfo :: TyGenInfo
468 noTyGenInfo = NoTyGenInfo
469
470 isNoTyGenInfo :: TyGenInfo -> Bool
471 isNoTyGenInfo NoTyGenInfo = True
472 isNoTyGenInfo _           = False
473
474 -- NB: There's probably no need to write this information out to the interface file.
475 -- Why?  Simply because imported identifiers never get their types re-inferred.
476 -- But it's definitely nice to see in dumps, it for debugging purposes.
477
478 ppTyGenInfo :: TyGenInfo -> SDoc
479 ppTyGenInfo  NoTyGenInfo    = empty
480 ppTyGenInfo (TyGenUInfo us) = ptext SLIT("__G") <+> text (tyGenInfoString us)
481 ppTyGenInfo  TyGenNever     = ptext SLIT("__G N")
482
483 tyGenInfoString us = map go us
484   where go  Nothing                      = 'x'  -- for legibility, choose
485         go (Just u) | u `eqUsage` usOnce = '1'  -- chars with identity
486                     | u `eqUsage` usMany = 'M'  -- Z-encoding.
487         go other = pprPanic "IdInfo.tyGenInfoString: unexpected annotation" (ppr other)
488
489 instance Outputable TyGenInfo where
490   ppr = ppTyGenInfo
491
492 instance Show TyGenInfo where
493   showsPrec p c = showsPrecSDoc p (ppr c)
494 \end{code}
495
496
497 %************************************************************************
498 %*                                                                      *
499 \subsection[worker-IdInfo]{Worker info about an @Id@}
500 %*                                                                      *
501 %************************************************************************
502
503 If this Id has a worker then we store a reference to it. Worker
504 functions are generated by the worker/wrapper pass.  This uses
505 information from the strictness and CPR analyses.
506
507 There might not be a worker, even for a strict function, because:
508 (a) the function might be small enough to inline, so no need 
509     for w/w split
510 (b) the strictness info might be "SSS" or something, so no w/w split.
511
512 Sometimes the arity of a wrapper changes from the original arity from
513 which it was generated, so we always emit the "original" arity into
514 the interface file, as part of the worker info.
515
516 How can this happen?  Sometimes we get
517         f = coerce t (\x y -> $wf x y)
518 at the moment of w/w split; but the eta reducer turns it into
519         f = coerce t $wf
520 which is perfectly fine except that the exposed arity so far as
521 the code generator is concerned (zero) differs from the arity
522 when we did the split (2).  
523
524 All this arises because we use 'arity' to mean "exactly how many
525 top level lambdas are there" in interface files; but during the
526 compilation of this module it means "how many things can I apply
527 this to".
528
529 \begin{code}
530
531 data WorkerInfo = NoWorker
532                 | HasWorker Id Arity
533         -- The Arity is the arity of the *wrapper* at the moment of the
534         -- w/w split. See comments in MkIface.ifaceId, with the 'Worker' code.
535
536 seqWorker :: WorkerInfo -> ()
537 seqWorker (HasWorker id _) = id `seq` ()
538 seqWorker NoWorker         = ()
539
540 ppWorkerInfo NoWorker            = empty
541 ppWorkerInfo (HasWorker wk_id _) = ptext SLIT("__P") <+> ppr wk_id
542
543 workerExists :: WorkerInfo -> Bool
544 workerExists NoWorker        = False
545 workerExists (HasWorker _ _) = True
546
547 workerId :: WorkerInfo -> Id
548 workerId (HasWorker id _) = id
549
550 wrapperArity :: WorkerInfo -> Arity
551 wrapperArity (HasWorker _ a) = a
552 \end{code}
553
554
555 %************************************************************************
556 %*                                                                      *
557 \subsection[CG-IdInfo]{Code generator-related information}
558 %*                                                                      *
559 %************************************************************************
560
561 CgInfo encapsulates calling-convention information produced by the code 
562 generator.  It is pasted into the IdInfo of each emitted Id by CoreTidy,
563 but only as a thunk --- the information is only actually produced further
564 downstream, by the code generator.
565
566 \begin{code}
567 data CgInfo = CgInfo 
568                 !Arity          -- Exact arity for calling purposes
569                 !CafInfo
570 #ifdef DEBUG
571             | NoCgInfo          -- In debug mode we don't want a black hole here
572                                 -- See Id.idCgInfo
573
574         -- noCgInfo is used for local Ids, which shouldn't need any CgInfo
575 noCgInfo = NoCgInfo
576 #else
577 noCgInfo = panic "NoCgInfo!"
578 #endif
579
580 cgArity   (CgInfo arity _)    = arity
581 cgCafInfo (CgInfo _ caf_info) = caf_info
582
583 setCafInfo info caf_info = 
584   case cgInfo info of { CgInfo arity _  -> 
585         info `setCgInfo` CgInfo arity caf_info }
586
587 setCgArity info arity = 
588   case cgInfo info of { CgInfo _ caf_info  -> 
589         info `setCgInfo` CgInfo arity caf_info }
590
591 cgMayHaveCafRefs (CgInfo _ caf_info) = mayHaveCafRefs caf_info
592
593 seqCg c = c `seq` ()  -- fields are strict anyhow
594
595 vanillaCgInfo = CgInfo 0 MayHaveCafRefs         -- Definitely safe
596
597 -- CafInfo is used to build Static Reference Tables (see simplStg/SRT.lhs).
598
599 data CafInfo 
600         = MayHaveCafRefs                -- either:
601                                         -- (1) A function or static constructor
602                                         --     that refers to one or more CAFs,
603                                         -- (2) A real live CAF
604
605         | NoCafRefs                     -- A function or static constructor
606                                         -- that refers to no CAFs.
607
608 mayHaveCafRefs  MayHaveCafRefs = True
609 mayHaveCafRefs _               = False
610
611 seqCaf c = c `seq` ()
612
613 pprCgInfo (CgInfo arity caf_info) = ppArity arity <+> ppCafInfo caf_info
614
615 ppArity 0 = empty
616 ppArity n = hsep [ptext SLIT("__A"), int n]
617
618 ppCafInfo NoCafRefs = ptext SLIT("__C")
619 ppCafInfo MayHaveCafRefs = empty
620 \end{code}
621
622 \begin{code}
623 type CgInfoEnv = NameEnv CgInfo
624
625 lookupCgInfo :: NameEnv CgInfo -> Name -> CgInfo
626 lookupCgInfo env n = case lookupNameEnv env n of
627                         Just info -> info
628                         Nothing   -> pprTrace "Urk! Not in CgInfo env" (ppr n) vanillaCgInfo
629 \end{code}
630
631
632 %************************************************************************
633 %*                                                                      *
634 \subsection[cpr-IdInfo]{Constructed Product Result info about an @Id@}
635 %*                                                                      *
636 %************************************************************************
637
638 If the @Id@ is a function then it may have CPR info. A CPR analysis
639 phase detects whether:
640
641 \begin{enumerate}
642 \item
643 The function's return value has a product type, i.e. an algebraic  type 
644 with a single constructor. Examples of such types are tuples and boxed
645 primitive values.
646 \item
647 The function always 'constructs' the value that it is returning.  It
648 must do this on every path through,  and it's OK if it calls another
649 function which constructs the result.
650 \end{enumerate}
651
652 If this is the case then we store a template which tells us the
653 function has the CPR property and which components of the result are
654 also CPRs.   
655
656 \begin{code}
657 data CprInfo
658   = NoCPRInfo
659   | ReturnsCPR  -- Yes, this function returns a constructed product
660                 -- Implicitly, this means "after the function has been applied
661                 -- to all its arguments", so the worker/wrapper builder in 
662                 -- WwLib.mkWWcpr checks that that it is indeed saturated before
663                 -- making use of the CPR info
664
665         -- We used to keep nested info about sub-components, but
666         -- we never used it so I threw it away
667 \end{code}
668
669 \begin{code}
670 seqCpr :: CprInfo -> ()
671 seqCpr ReturnsCPR = ()
672 seqCpr NoCPRInfo  = ()
673
674 noCprInfo       = NoCPRInfo
675
676 ppCprInfo NoCPRInfo  = empty
677 ppCprInfo ReturnsCPR = ptext SLIT("__M")
678
679 instance Outputable CprInfo where
680     ppr = ppCprInfo
681
682 instance Show CprInfo where
683     showsPrec p c = showsPrecSDoc p (ppr c)
684 \end{code}
685
686
687 %************************************************************************
688 %*                                                                      *
689 \subsection[lbvar-IdInfo]{Lambda-bound var info about an @Id@}
690 %*                                                                      *
691 %************************************************************************
692
693 If the @Id@ is a lambda-bound variable then it may have lambda-bound
694 var info.  The usage analysis (UsageSP) detects whether the lambda
695 binding this var is a ``one-shot'' lambda; that is, whether it is
696 applied at most once.
697
698 This information may be useful in optimisation, as computations may
699 safely be floated inside such a lambda without risk of duplicating
700 work.
701
702 \begin{code}
703 data LBVarInfo
704   = NoLBVarInfo
705
706   | LBVarInfo Type              -- The lambda that binds this Id has this usage
707                                 --   annotation (i.e., if ==usOnce, then the
708                                 --   lambda is applied at most once).
709                                 -- The annotation's kind must be `$'
710                                 -- HACK ALERT! placing this info here is a short-term hack,
711                                 --   but it minimises changes to the rest of the compiler.
712                                 --   Hack agreed by SLPJ/KSW 1999-04.
713
714 seqLBVar l = l `seq` ()
715 \end{code}
716
717 \begin{code}
718 hasNoLBVarInfo NoLBVarInfo = True
719 hasNoLBVarInfo other       = False
720
721 noLBVarInfo = NoLBVarInfo
722
723 -- not safe to print or parse LBVarInfo because it is not really a
724 -- property of the definition, but a property of the context.
725 pprLBVarInfo NoLBVarInfo     = empty
726 pprLBVarInfo (LBVarInfo u)   | u `eqUsage` usOnce
727                              = getPprStyle $ \ sty ->
728                                if ifaceStyle sty
729                                then empty
730                                else ptext SLIT("OneShot")
731                              | otherwise
732                              = empty
733
734 instance Outputable LBVarInfo where
735     ppr = pprLBVarInfo
736
737 instance Show LBVarInfo where
738     showsPrec p c = showsPrecSDoc p (ppr c)
739 \end{code}
740
741
742 %************************************************************************
743 %*                                                                      *
744 \subsection{Bulk operations on IdInfo}
745 %*                                                                      *
746 %************************************************************************
747
748 @zapLamInfo@ is used for lambda binders that turn out to to be
749 part of an unsaturated lambda
750
751 \begin{code}
752 zapLamInfo :: IdInfo -> Maybe IdInfo
753 zapLamInfo info@(IdInfo {occInfo = occ, demandInfo = demand})
754   | is_safe_occ && not (isStrict demand)
755   = Nothing
756   | otherwise
757   = Just (info {occInfo = safe_occ,
758                 demandInfo = wwLazy})
759   where
760         -- The "unsafe" occ info is the ones that say I'm not in a lambda
761         -- because that might not be true for an unsaturated lambda
762     is_safe_occ = case occ of
763                         OneOcc in_lam once -> in_lam
764                         other              -> True
765
766     safe_occ = case occ of
767                  OneOcc _ once -> OneOcc insideLam once
768                  other         -> occ
769 \end{code}
770
771 \begin{code}
772 zapDemandInfo :: IdInfo -> Maybe IdInfo
773 zapDemandInfo info@(IdInfo {demandInfo = demand})
774   | not (isStrict demand) = Nothing
775   | otherwise             = Just (info {demandInfo = wwLazy})
776 \end{code}
777
778
779 copyIdInfo is used when shorting out a top-level binding
780         f_local = BIG
781         f = f_local
782 where f is exported.  We are going to swizzle it around to
783         f = BIG
784         f_local = f
785
786 BUT (a) we must be careful about messing up rules
787     (b) we must ensure f's IdInfo ends up right
788
789 (a) Messing up the rules
790 ~~~~~~~~~~~~~~~~~~~~
791 The example that went bad on me was this one:
792         
793     iterate :: (a -> a) -> a -> [a]
794     iterate = iterateList
795     
796     iterateFB c f x = x `c` iterateFB c f (f x)
797     iterateList f x =  x : iterateList f (f x)
798     
799     {-# RULES
800     "iterate"   forall f x.     iterate f x = build (\c _n -> iterateFB c f x)
801     "iterateFB"                 iterateFB (:) = iterateList
802      #-}
803
804 This got shorted out to:
805
806     iterateList :: (a -> a) -> a -> [a]
807     iterateList = iterate
808     
809     iterateFB c f x = x `c` iterateFB c f (f x)
810     iterate f x =  x : iterate f (f x)
811     
812     {-# RULES
813     "iterate"   forall f x.     iterate f x = build (\c _n -> iterateFB c f x)
814     "iterateFB"                 iterateFB (:) = iterate
815      #-}
816
817 And now we get an infinite loop in the rule system 
818         iterate f x -> build (\cn -> iterateFB c f x)
819                     -> iterateFB (:) f x
820                     -> iterate f x
821
822 Tiresome solution: don't do shorting out if f has rewrite rules.
823 Hence shortableIdInfo.
824
825 (b) Keeping the IdInfo right
826 ~~~~~~~~~~~~~~~~~~~~~~~~
827 We want to move strictness/worker info from f_local to f, but keep the rest.
828 Hence copyIdInfo.
829
830 \begin{code}
831 shortableIdInfo :: IdInfo -> Bool
832 shortableIdInfo info = isEmptyCoreRules (specInfo info)
833
834 copyIdInfo :: IdInfo    -- f_local
835            -> IdInfo    -- f (the exported one)
836            -> IdInfo    -- New info for f
837 copyIdInfo f_local f = f { strictnessInfo = strictnessInfo f_local,
838                            workerInfo     = workerInfo     f_local,
839                            cprInfo        = cprInfo        f_local
840                           }
841 \end{code}