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