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