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