[project @ 1999-09-17 09:11:20 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         IdInfo,         -- Abstract
12
13         vanillaIdInfo, mkIdInfo, seqIdInfo, megaSeqIdInfo,
14
15         -- Flavour
16         IdFlavour(..), flavourInfo, 
17         setNoDiscardInfo, zapSpecPragInfo, copyIdInfo,
18         ppFlavourInfo,
19
20         -- Arity
21         ArityInfo(..),
22         exactArity, atLeastArity, unknownArity, hasArity,
23         arityInfo, setArityInfo, ppArityInfo, arityLowerBound,
24
25         -- Strictness
26         StrictnessInfo(..),                             -- Non-abstract
27         mkStrictnessInfo,
28         noStrictnessInfo, strictnessInfo,
29         ppStrictnessInfo, setStrictnessInfo, 
30         isBottomingStrictness, appIsBottom,
31
32         -- Worker
33         WorkerInfo, workerExists, 
34         workerInfo, setWorkerInfo, ppWorkerInfo,
35
36         -- Unfolding
37         unfoldingInfo, setUnfoldingInfo, 
38
39         -- DemandInfo
40         demandInfo, setDemandInfo, 
41
42         -- Inline prags
43         InlinePragInfo(..), OccInfo(..),
44         inlinePragInfo, setInlinePragInfo, notInsideLambda,
45
46         -- Specialisation
47         specInfo, setSpecInfo,
48
49         -- Update
50         UpdateInfo, UpdateSpec,
51         mkUpdateInfo, updateInfo, updateInfoMaybe, ppUpdateInfo, setUpdateInfo,
52
53         -- CAF info
54         CafInfo(..), cafInfo, setCafInfo, ppCafInfo,
55
56         -- Constructed Product Result Info
57         CprInfo(..), cprInfo, setCprInfo, ppCprInfo, noCprInfo,
58
59         -- Zapping
60         zapLamIdInfo, zapFragileIdInfo, zapIdInfoForStg,
61
62         -- Lambda-bound variable info
63         LBVarInfo(..), lbvarInfo, setLBVarInfo, noLBVarInfo
64     ) where
65
66 #include "HsVersions.h"
67
68
69 import {-# SOURCE #-} CoreUnfold ( Unfolding, noUnfolding, hasUnfolding, seqUnfolding )
70 import {-# SOURCE #-} CoreSyn    ( CoreExpr, CoreRules, emptyCoreRules, isEmptyCoreRules, seqRules )
71 import {-# SOURCE #-} Const      ( Con )
72
73 import Var              ( Id )
74 import FieldLabel       ( FieldLabel )
75 import Demand           ( Demand, isStrict, isLazy, wwLazy, pprDemands, seqDemand, seqDemands )
76 import Type             ( UsageAnn )
77 import Outputable       
78 import Maybe            ( isJust )
79
80 infixl  1 `setUpdateInfo`,
81           `setDemandInfo`,
82           `setStrictnessInfo`,
83           `setSpecInfo`,
84           `setArityInfo`,
85           `setInlinePragInfo`,
86           `setUnfoldingInfo`,
87           `setCprInfo`,
88           `setWorkerInfo`,
89           `setCafInfo`
90         -- infixl so you can say (id `set` a `set` b)
91 \end{code}
92
93 An @IdInfo@ gives {\em optional} information about an @Id@.  If
94 present it never lies, but it may not be present, in which case there
95 is always a conservative assumption which can be made.
96
97         There is one exception: the 'flavour' is *not* optional.
98         You must not discard it.
99         It used to be in Var.lhs, but that seems unclean.
100
101 Two @Id@s may have different info even though they have the same
102 @Unique@ (and are hence the same @Id@); for example, one might lack
103 the properties attached to the other.
104
105 The @IdInfo@ gives information about the value, or definition, of the
106 @Id@.  It does {\em not} contain information about the @Id@'s usage
107 (except for @DemandInfo@? ToDo). (@lbvarInfo@ is also a marginal
108 case.  KSW 1999-04).
109
110 \begin{code}
111 data IdInfo
112   = IdInfo {
113         flavourInfo     :: IdFlavour,           -- NOT OPTIONAL
114         arityInfo       :: ArityInfo,           -- Its arity
115         demandInfo      :: Demand,              -- Whether or not it is definitely demanded
116         specInfo        :: CoreRules,           -- Specialisations of this function which exist
117         strictnessInfo  :: StrictnessInfo,      -- Strictness properties
118         workerInfo      :: WorkerInfo,          -- Pointer to Worker Function
119         unfoldingInfo   :: Unfolding,           -- Its unfolding
120         updateInfo      :: UpdateInfo,          -- Which args should be updated
121         cafInfo         :: CafInfo,
122         cprInfo         :: CprInfo,             -- Function always constructs a product result
123         lbvarInfo       :: LBVarInfo,           -- Info about a lambda-bound variable
124         inlinePragInfo  :: InlinePragInfo       -- Inline pragmas
125     }
126
127 seqIdInfo :: IdInfo -> ()
128 seqIdInfo (IdInfo {}) = ()
129
130 megaSeqIdInfo :: IdInfo -> ()
131 megaSeqIdInfo info
132   = seqFlavour (flavourInfo info)       `seq`
133     seqArity (arityInfo info)           `seq`
134     seqDemand (demandInfo info)         `seq`
135     seqRules (specInfo info)            `seq`
136     seqStrictness (strictnessInfo info) `seq`
137     seqWorker (workerInfo info)         `seq`
138
139 --    seqUnfolding (unfoldingInfo info) `seq`
140 -- Omitting this improves runtimes a little, presumably because
141 -- some unfoldings are not calculated at all
142
143     seqCaf (cafInfo info)               `seq`
144     seqCpr (cprInfo info)               `seq`
145     seqLBVar (lbvarInfo info)           `seq`
146     seqInlinePrag (inlinePragInfo info) 
147 \end{code}
148
149 Setters
150
151 \begin{code}
152 setWorkerInfo     info wk = wk `seq` info { workerInfo = wk }
153 setSpecInfo       info sp = PSEQ sp (info { specInfo = sp })
154 setInlinePragInfo info pr = pr `seq` info { inlinePragInfo = pr }
155 setStrictnessInfo info st = st `seq` info { strictnessInfo = st }
156         -- Try to avoid spack leaks by seq'ing
157
158 setUnfoldingInfo  info uf = info { unfoldingInfo = uf }
159         -- We do *not* seq on the unfolding info, For some reason, doing so 
160         -- actually increases residency significantly. 
161
162 setUpdateInfo     info ud = info { updateInfo = ud }
163 setDemandInfo     info dd = info { demandInfo = dd }
164 setArityInfo      info ar = info { arityInfo = ar  }
165 setCafInfo        info cf = info { cafInfo = cf }
166 setCprInfo        info cp = info { cprInfo = cp }
167 setLBVarInfo      info lb = info { lbvarInfo = lb }
168
169 setNoDiscardInfo  info = case flavourInfo info of
170                                 VanillaId -> info { flavourInfo = NoDiscardId }
171                                 other     -> info
172 zapSpecPragInfo   info = case flavourInfo info of
173                                 SpecPragmaId -> info { flavourInfo = VanillaId }
174                                 other        -> info
175
176 copyIdInfo :: IdInfo    -- From
177            -> IdInfo    -- To
178            -> IdInfo    -- To, updated with stuff from From; except flavour unchanged
179 -- copyIdInfo is used when shorting out a top-level binding
180 --      f_local = BIG
181 --      f = f_local
182 -- where f is exported.  We are going to swizzle it around to
183 --      f = BIG
184 --      f_local = f
185 -- but we must be careful to combine their IdInfos right.
186 -- The fact that things can go wrong here is a bad sign, but I can't see
187 -- how to make it 'patently right', so copyIdInfo is derived (pretty much) by trial and error
188 --
189 -- Here 'from' is f_local, 'to' is f, and the result is attached to f
190
191 copyIdInfo from to = from { flavourInfo = flavourInfo to,
192                             specInfo = specInfo to,
193                             inlinePragInfo = inlinePragInfo to
194                           }
195         -- It's important to preserve the inline pragma on 'f'; e.g. consider
196         --      {-# NOINLINE f #-}
197         --      f = local
198         --
199         -- similarly, transformation rules may be attached to f
200         -- and we want to preserve them.  
201         --
202         -- On the other hand, we want the strictness info from f_local.
203 \end{code}
204
205
206 \begin{code}
207 vanillaIdInfo :: IdInfo
208 vanillaIdInfo = mkIdInfo VanillaId
209
210 mkIdInfo :: IdFlavour -> IdInfo
211 mkIdInfo flv = IdInfo {
212                     flavourInfo         = flv,
213                     arityInfo           = UnknownArity,
214                     demandInfo          = wwLazy,
215                     specInfo            = emptyCoreRules,
216                     workerInfo          = Nothing,
217                     strictnessInfo      = NoStrictnessInfo,
218                     unfoldingInfo       = noUnfolding,
219                     updateInfo          = NoUpdateInfo,
220                     cafInfo             = MayHaveCafRefs,
221                     cprInfo             = NoCPRInfo,
222                     lbvarInfo           = NoLBVarInfo,
223                     inlinePragInfo      = NoInlinePragInfo
224            }
225 \end{code}
226
227
228 %************************************************************************
229 %*                                                                      *
230 \subsection{Flavour}
231 %*                                                                      *
232 %************************************************************************
233
234 \begin{code}
235 data IdFlavour
236   = VanillaId                           -- Most Ids are like this
237   | ConstantId Con                      -- The Id for a constant (data constructor or primop)
238   | RecordSelId FieldLabel              -- The Id for a record selector
239   | SpecPragmaId                        -- Don't discard these
240   | NoDiscardId                         -- Don't discard these either
241
242 ppFlavourInfo :: IdFlavour -> SDoc
243 ppFlavourInfo VanillaId       = empty
244 ppFlavourInfo (ConstantId _)  = ptext SLIT("[Constr]")
245 ppFlavourInfo (RecordSelId _) = ptext SLIT("[RecSel]")
246 ppFlavourInfo SpecPragmaId    = ptext SLIT("[SpecPrag]")
247 ppFlavourInfo NoDiscardId     = ptext SLIT("[NoDiscard]")
248
249 seqFlavour :: IdFlavour -> ()
250 seqFlavour f = f `seq` ()
251 \end{code}
252
253 The @SpecPragmaId@ exists only to make Ids that are
254 on the *LHS* of bindings created by SPECIALISE pragmas; 
255 eg:             s = f Int d
256 The SpecPragmaId is never itself mentioned; it
257 exists solely so that the specialiser will find
258 the call to f, and make specialised version of it.
259 The SpecPragmaId binding is discarded by the specialiser
260 when it gathers up overloaded calls.
261 Meanwhile, it is not discarded as dead code.
262
263
264 %************************************************************************
265 %*                                                                      *
266 \subsection[arity-IdInfo]{Arity info about an @Id@}
267 %*                                                                      *
268 %************************************************************************
269
270 For locally-defined Ids, the code generator maintains its own notion
271 of their arities; so it should not be asking...  (but other things
272 besides the code-generator need arity info!)
273
274 \begin{code}
275 data ArityInfo
276   = UnknownArity        -- No idea
277
278   | ArityExactly Int    -- Arity is exactly this.  We use this when importing a
279                         -- function; it's already been compiled and we know its
280                         -- arity for sure.
281
282   | ArityAtLeast Int    -- Arity is this or greater.  We attach this arity to 
283                         -- functions in the module being compiled.  Their arity
284                         -- might increase later in the compilation process, if
285                         -- an extra lambda floats up to the binding site.
286
287 seqArity :: ArityInfo -> ()
288 seqArity a = arityLowerBound a `seq` ()
289
290 exactArity   = ArityExactly
291 atLeastArity = ArityAtLeast
292 unknownArity = UnknownArity
293
294 arityLowerBound :: ArityInfo -> Int
295 arityLowerBound UnknownArity     = 0
296 arityLowerBound (ArityAtLeast n) = n
297 arityLowerBound (ArityExactly n) = n
298
299 hasArity :: ArityInfo -> Bool
300 hasArity UnknownArity = False
301 hasArity other        = True
302
303 ppArityInfo UnknownArity         = empty
304 ppArityInfo (ArityExactly arity) = hsep [ptext SLIT("__A"), int arity]
305 ppArityInfo (ArityAtLeast arity) = hsep [ptext SLIT("__AL"), int arity]
306 \end{code}
307
308 %************************************************************************
309 %*                                                                      *
310 \subsection{Inline-pragma information}
311 %*                                                                      *
312 %************************************************************************
313
314 \begin{code}
315 data InlinePragInfo
316   = NoInlinePragInfo
317
318   | IMustNotBeINLINEd   -- User NOINLINE pragma
319
320   | IAmALoopBreaker     -- Used by the occurrence analyser to mark loop-breakers
321                         -- in a group of recursive definitions
322
323   | ICanSafelyBeINLINEd -- Used by the occurrence analyser to mark things
324                         -- that manifesly occur once, not inside SCCs, 
325                         -- not in constructor arguments
326
327         OccInfo         -- Says whether the occurrence is inside a lambda
328                         --      If so, must only substitute WHNFs
329
330         Bool            -- False <=> occurs in more than one case branch
331                         --      If so, there's a code-duplication issue
332
333   | IAmDead             -- Marks unused variables.  Sometimes useful for
334                         -- lambda and case-bound variables.
335
336   | IMustBeINLINEd      -- Absolutely must inline; used for PrimOps and
337                         -- constructors only.
338
339 seqInlinePrag :: InlinePragInfo -> ()
340 seqInlinePrag (ICanSafelyBeINLINEd occ alts) 
341   = occ `seq` alts `seq` ()
342 seqInlinePrag other
343   = ()
344
345 instance Outputable InlinePragInfo where
346   -- only used for debugging; never parsed.  KSW 1999-07
347   ppr NoInlinePragInfo          = empty
348   ppr IMustBeINLINEd            = ptext SLIT("__UU")
349   ppr IMustNotBeINLINEd         = ptext SLIT("__Unot")
350   ppr IAmALoopBreaker           = ptext SLIT("__Ux")
351   ppr IAmDead                   = ptext SLIT("__Ud")
352   ppr (ICanSafelyBeINLINEd InsideLam _) = ptext SLIT("__Ul")
353   ppr (ICanSafelyBeINLINEd NotInsideLam True)  = ptext SLIT("__Us")
354   ppr (ICanSafelyBeINLINEd NotInsideLam False) = ptext SLIT("__Us*")
355
356 instance Show InlinePragInfo where
357   showsPrec p prag = showsPrecSDoc p (ppr prag)
358 \end{code}
359
360 \begin{code}
361 data OccInfo
362   = NotInsideLam
363
364   | InsideLam           -- Inside a non-linear lambda (that is, a lambda which
365                         -- is sure to be instantiated only once).
366                         -- Substituting a redex for this occurrence is
367                         -- dangerous because it might duplicate work.
368
369 instance Outputable OccInfo where
370   ppr NotInsideLam = empty
371   ppr InsideLam    = text "l"
372
373
374 notInsideLambda :: OccInfo -> Bool
375 notInsideLambda NotInsideLam = True
376 notInsideLambda InsideLam    = False
377 \end{code}
378
379 %************************************************************************
380 %*                                                                      *
381 \subsection[strictness-IdInfo]{Strictness info about an @Id@}
382 %*                                                                      *
383 %************************************************************************
384
385 We specify the strictness of a function by giving information about
386 each of the ``wrapper's'' arguments (see the description about
387 worker/wrapper-style transformations in the PJ/Launchbury paper on
388 unboxed types).
389
390 The list of @Demands@ specifies: (a)~the strictness properties of a
391 function's arguments; and (b)~the type signature of that worker (if it
392 exists); i.e. its calling convention.
393
394 Note that the existence of a worker function is now denoted by the Id's
395 workerInfo field.
396
397 \begin{code}
398 data StrictnessInfo
399   = NoStrictnessInfo
400
401   | StrictnessInfo [Demand] 
402                    Bool         -- True <=> the function diverges regardless of its arguments
403                                 -- Useful for "error" and other disguised variants thereof.  
404                                 -- BUT NB: f = \x y. error "urk"
405                                 --         will have info  SI [SS] True
406                                 -- but still (f) and (f 2) are not bot; only (f 3 2) is bot
407
408 seqStrictness :: StrictnessInfo -> ()
409 seqStrictness (StrictnessInfo ds b) = b `seq` seqDemands ds
410 seqStrictness other                 = ()
411 \end{code}
412
413 \begin{code}
414 mkStrictnessInfo :: ([Demand], Bool) -> StrictnessInfo
415
416 mkStrictnessInfo (xs, is_bot)
417   | all isLazy xs && not is_bot = NoStrictnessInfo              -- Uninteresting
418   | otherwise                   = StrictnessInfo xs is_bot
419
420 noStrictnessInfo       = NoStrictnessInfo
421
422 isBottomingStrictness (StrictnessInfo _ bot) = bot
423 isBottomingStrictness NoStrictnessInfo       = False
424
425 -- appIsBottom returns true if an application to n args would diverge
426 appIsBottom (StrictnessInfo ds bot)   n = bot && (n >= length ds)
427 appIsBottom  NoStrictnessInfo         n = False
428
429 ppStrictnessInfo NoStrictnessInfo = empty
430 ppStrictnessInfo (StrictnessInfo wrapper_args bot)
431   = hsep [ptext SLIT("__S"), pprDemands wrapper_args bot]
432 \end{code}
433
434 %************************************************************************
435 %*                                                                      *
436 \subsection[worker-IdInfo]{Worker info about an @Id@}
437 %*                                                                      *
438 %************************************************************************
439
440 If this Id has a worker then we store a reference to it. Worker
441 functions are generated by the worker/wrapper pass.  This uses
442 information from the strictness and CPR analyses.
443
444 There might not be a worker, even for a strict function, because:
445 (a) the function might be small enough to inline, so no need 
446     for w/w split
447 (b) the strictness info might be "SSS" or something, so no w/w split.
448
449 \begin{code}
450
451 type WorkerInfo = Maybe Id
452
453 {- UNUSED:
454 mkWorkerInfo :: Id -> WorkerInfo
455 mkWorkerInfo wk_id = Just wk_id
456 -}
457
458 seqWorker :: WorkerInfo -> ()
459 seqWorker (Just id) = id `seq` ()
460 seqWorker Nothing   = ()
461
462 ppWorkerInfo Nothing      = empty
463 ppWorkerInfo (Just wk_id) = ptext SLIT("__P") <+> ppr wk_id
464
465 noWorkerInfo = Nothing
466
467 workerExists :: WorkerInfo -> Bool
468 workerExists = isJust
469 \end{code}
470
471
472 %************************************************************************
473 %*                                                                      *
474 \subsection[update-IdInfo]{Update-analysis info about an @Id@}
475 %*                                                                      *
476 %************************************************************************
477
478 \begin{code}
479 data UpdateInfo
480   = NoUpdateInfo
481   | SomeUpdateInfo UpdateSpec
482   deriving (Eq, Ord)
483       -- we need Eq/Ord to cross-chk update infos in interfaces
484
485 -- the form in which we pass update-analysis info between modules:
486 type UpdateSpec = [Int]
487 \end{code}
488
489 \begin{code}
490 mkUpdateInfo = SomeUpdateInfo
491
492 updateInfoMaybe NoUpdateInfo        = Nothing
493 updateInfoMaybe (SomeUpdateInfo []) = Nothing
494 updateInfoMaybe (SomeUpdateInfo  u) = Just u
495 \end{code}
496
497 Text instance so that the update annotations can be read in.
498
499 \begin{code}
500 ppUpdateInfo NoUpdateInfo          = empty
501 ppUpdateInfo (SomeUpdateInfo [])   = empty
502 ppUpdateInfo (SomeUpdateInfo spec) = (<>) (ptext SLIT("__UA ")) (hcat (map int spec))
503   -- was "__U "; changed to avoid conflict with unfoldings.  KSW 1999-07.
504 \end{code}
505
506 %************************************************************************
507 %*                                                                      *
508 \subsection[CAF-IdInfo]{CAF-related information}
509 %*                                                                      *
510 %************************************************************************
511
512 This information is used to build Static Reference Tables (see
513 simplStg/ComputeSRT.lhs).
514
515 \begin{code}
516 data CafInfo 
517         = MayHaveCafRefs                -- either:
518                                         -- (1) A function or static constructor
519                                         --     that refers to one or more CAFs,
520                                         -- (2) A real live CAF
521
522         | NoCafRefs                     -- A function or static constructor
523                                         -- that refers to no CAFs.
524
525 -- LATER: not sure how easy this is...
526 --      | OneCafRef Id
527
528
529 seqCaf c = c `seq` ()
530
531 ppCafInfo NoCafRefs = ptext SLIT("__C")
532 ppCafInfo MayHaveCafRefs = empty
533 \end{code}
534
535
536 %************************************************************************
537 %*                                                                      *
538 \subsection[CAF-IdInfo]{CAF-related information}
539 %*                                                                      *
540 %************************************************************************
541
542 zapFragileIdInfo is used when cloning binders, mainly in the
543 simplifier.  We must forget about used-once information because that
544 isn't necessarily correct in the transformed program.
545 Also forget specialisations and unfoldings because they would need
546 substitution to be correct.  (They get pinned back on separately.)
547
548 \begin{code}
549 zapFragileIdInfo :: IdInfo -> Maybe IdInfo
550 zapFragileIdInfo info@(IdInfo {inlinePragInfo   = inline_prag, 
551                                workerInfo       = wrkr,
552                                specInfo         = rules, 
553                                unfoldingInfo    = unfolding})
554   |  not is_fragile_inline_prag 
555         -- We must forget about whether it was marked safe-to-inline,
556         -- because that isn't necessarily true in the simplified expression.
557         -- This is important because expressions may  be re-simplified
558
559   && isEmptyCoreRules rules
560         -- Specialisations would need substituting.  They get pinned
561         -- back on separately.
562
563   && not (workerExists wrkr)
564
565   && not (hasUnfolding unfolding)
566         -- This is very important; occasionally a let-bound binder is used
567         -- as a binder in some lambda, in which case its unfolding is utterly
568         -- bogus.  Also the unfolding uses old binders so if we left it we'd
569         -- have to substitute it. Much better simply to give the Id a new
570         -- unfolding each time, which is what the simplifier does.
571   = Nothing
572
573   | otherwise
574   = Just (info {inlinePragInfo  = safe_inline_prag, 
575                 workerInfo      = noWorkerInfo,
576                 specInfo        = emptyCoreRules,
577                 unfoldingInfo   = noUnfolding})
578
579   where
580     is_fragile_inline_prag = case inline_prag of
581                                 ICanSafelyBeINLINEd _ _ -> True
582
583 -- We used to say the dead-ness was fragile, but I don't
584 -- see why it is.  Furthermore, deadness is a pain to lose;
585 -- see Simplify.mkDupableCont (Select ...)
586 --                              IAmDead                 -> True
587
588                                 other                   -> False
589
590         -- Be careful not to destroy real 'pragma' info
591     safe_inline_prag | is_fragile_inline_prag = NoInlinePragInfo
592                      | otherwise              = inline_prag
593 \end{code}
594
595
596 @zapLamIdInfo@ is used for lambda binders that turn out to to be
597 part of an unsaturated lambda
598
599 \begin{code}
600 zapLamIdInfo :: IdInfo -> Maybe IdInfo
601 zapLamIdInfo info@(IdInfo {inlinePragInfo = inline_prag, demandInfo = demand})
602   | is_safe_inline_prag && not (isStrict demand)
603   = Nothing
604   | otherwise
605   = Just (info {inlinePragInfo = safe_inline_prag,
606                 demandInfo = wwLazy})
607   where
608         -- The "unsafe" prags are the ones that say I'm not in a lambda
609         -- because that might not be true for an unsaturated lambda
610     is_safe_inline_prag = case inline_prag of
611                                 ICanSafelyBeINLINEd NotInsideLam nalts -> False
612                                 other                                  -> True
613
614     safe_inline_prag    = case inline_prag of
615                                 ICanSafelyBeINLINEd _ nalts
616                                       -> ICanSafelyBeINLINEd InsideLam nalts
617                                 other -> inline_prag
618 \end{code}
619
620 \begin{code}
621 zapIdInfoForStg :: IdInfo -> IdInfo
622         -- Return only the info needed for STG stuff
623         -- Namely, nothing, I think
624 zapIdInfoForStg info = vanillaIdInfo    
625 \end{code}
626
627
628 %************************************************************************
629 %*                                                                      *
630 \subsection[cpr-IdInfo]{Constructed Product Result info about an @Id@}
631 %*                                                                      *
632 %************************************************************************
633
634 If the @Id@ is a function then it may have CPR info. A CPR analysis
635 phase detects whether:
636
637 \begin{enumerate}
638 \item
639 The function's return value has a product type, i.e. an algebraic  type 
640 with a single constructor. Examples of such types are tuples and boxed
641 primitive values.
642 \item
643 The function always 'constructs' the value that it is returning.  It
644 must do this on every path through,  and it's OK if it calls another
645 function which constructs the result.
646 \end{enumerate}
647
648 If this is the case then we store a template which tells us the
649 function has the CPR property and which components of the result are
650 also CPRs.   
651
652 \begin{code}
653 data CprInfo
654   = NoCPRInfo
655
656   | CPRInfo [CprInfo] 
657
658 -- e.g. const 5 == CPRInfo [NoCPRInfo]
659 --              == __M(-)
660 --      \x -> (5,
661 --              (x,
662 --               5,
663 --               x)
664 --            ) 
665 --            CPRInfo [CPRInfo [NoCPRInfo], 
666 --                     CPRInfo [NoCprInfo,
667 --                              CPRInfo [NoCPRInfo],
668 --                              NoCPRInfo]
669 --                    ]
670 --            __M((-)(-(-)-)-)
671 \end{code}
672
673 \begin{code}
674 seqCpr :: CprInfo -> ()
675 seqCpr (CPRInfo cs) = seqCprs cs
676 seqCpr NoCPRInfo    = ()
677
678 seqCprs [] = ()
679 seqCprs (c:cs) = seqCpr c `seq` seqCprs cs
680
681
682 noCprInfo       = NoCPRInfo
683
684 ppCprInfo NoCPRInfo = empty
685 ppCprInfo c@(CPRInfo _)
686   = hsep [ptext SLIT("__M"), ppCprInfo' c]
687     where
688     ppCprInfo' NoCPRInfo      = char '-'
689     ppCprInfo' (CPRInfo args) = parens (hcat (map ppCprInfo' args))
690
691 instance Outputable CprInfo where
692     ppr = ppCprInfo
693
694 instance Show CprInfo where
695     showsPrec p c = showsPrecSDoc p (ppr c)
696 \end{code}
697
698
699 %************************************************************************
700 %*                                                                      *
701 \subsection[lbvar-IdInfo]{Lambda-bound var info about an @Id@}
702 %*                                                                      *
703 %************************************************************************
704
705 If the @Id@ is a lambda-bound variable then it may have lambda-bound
706 var info.  The usage analysis (UsageSP) detects whether the lambda
707 binding this var is a ``one-shot'' lambda; that is, whether it is
708 applied at most once.
709
710 This information may be useful in optimisation, as computations may
711 safely be floated inside such a lambda without risk of duplicating
712 work.
713
714 \begin{code}
715 data LBVarInfo
716   = NoLBVarInfo
717
718   | IsOneShotLambda             -- The lambda that binds this Id is applied
719                                 --   at most once
720                                 -- HACK ALERT! placing this info here is a short-term hack,
721                                 --   but it minimises changes to the rest of the compiler.
722                                 --   Hack agreed by SLPJ/KSW 1999-04.
723
724 seqLBVar l = l `seq` ()
725 \end{code}
726
727 \begin{code}
728 noLBVarInfo = NoLBVarInfo
729
730 -- not safe to print or parse LBVarInfo because it is not really a
731 -- property of the definition, but a property of the context.
732 pprLBVarInfo NoLBVarInfo     = empty
733 pprLBVarInfo IsOneShotLambda = getPprStyle $ \ sty ->
734                                if ifaceStyle sty then empty
735                                                  else ptext SLIT("OneShot")
736
737 instance Outputable LBVarInfo where
738     ppr = pprLBVarInfo
739
740 instance Show LBVarInfo where
741     showsPrec p c = showsPrecSDoc p (ppr c)
742 \end{code}