2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[IdInfo]{@IdInfos@: Non-essential information about @Ids@}
6 (And a pretty good illustration of quite a few things wrong with
11 GlobalIdDetails(..), notGlobalId, -- Not abstract
14 vanillaIdInfo, noTyGenIdInfo, noCafOrTyGenIdInfo, noCafIdInfo,
15 seqIdInfo, megaSeqIdInfo,
18 zapLamInfo, zapDemandInfo,
19 shortableIdInfo, copyIdInfo,
23 exactArity, atLeastArity, unknownArity, hasArity,
24 arityInfo, setArityInfo, ppArityInfo, arityLowerBound,
26 -- Strictness; imported from Demand
28 mkStrictnessInfo, noStrictnessInfo,
29 ppStrictnessInfo,isBottomingStrictness,
30 strictnessInfo, setStrictnessInfo,
32 -- Usage generalisation
34 tyGenInfo, setTyGenInfo,
35 noTyGenInfo, isNoTyGenInfo, ppTyGenInfo, tyGenInfoString,
38 WorkerInfo(..), workerExists, wrapperArity, workerId,
39 workerInfo, setWorkerInfo, ppWorkerInfo,
42 unfoldingInfo, setUnfoldingInfo,
45 demandInfo, setDemandInfo,
49 inlinePragInfo, setInlinePragInfo, pprInlinePragInfo,
50 isNeverInlinePrag, neverInlinePrag,
53 OccInfo(..), isFragileOcc, isDeadOcc, isLoopBreaker,
54 InsideLam, OneBranch, insideLam, notInsideLam, oneBranch, notOneBranch,
58 specInfo, setSpecInfo,
61 CafInfo(..), cafInfo, setCafInfo, mayHaveCafRefs, ppCafInfo,
63 -- Constructed Product Result Info
64 CprInfo(..), cprInfo, setCprInfo, ppCprInfo, noCprInfo,
66 -- Lambda-bound variable info
67 LBVarInfo(..), lbvarInfo, setLBVarInfo, noLBVarInfo, hasNoLBVarInfo
70 #include "HsVersions.h"
74 import Type ( Type, usOnce )
75 import PrimOp ( PrimOp )
77 import BasicTypes ( OccInfo(..), isFragileOcc, isDeadOcc, seqOccInfo, isLoopBreaker,
78 InsideLam, insideLam, notInsideLam,
79 OneBranch, oneBranch, notOneBranch,
82 import DataCon ( DataCon )
83 import FieldLabel ( FieldLabel )
84 import Type ( usOnce, usMany )
85 import Demand -- Lots of stuff
87 import Util ( seqList )
89 infixl 1 `setDemandInfo`,
101 -- infixl so you can say (id `set` a `set` b)
104 %************************************************************************
106 \subsection{GlobalIdDetails
108 %************************************************************************
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.
116 = VanillaGlobal -- Imported from elsewhere, a default method Id.
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]
126 | PrimOpId PrimOp -- The Id for a primitive operator
128 | NotGlobalId -- Used as a convenient extra return value from globalIdDetails
130 notGlobalId = NotGlobalId
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]")
142 %************************************************************************
144 \subsection{The main IdInfo type}
146 %************************************************************************
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.
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.
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
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
178 seqIdInfo :: IdInfo -> ()
179 seqIdInfo (IdInfo {}) = ()
181 megaSeqIdInfo :: IdInfo -> ()
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`
190 -- seqUnfolding (unfoldingInfo info) `seq`
191 -- Omitting this improves runtimes a little, presumably because
192 -- some unfoldings are not calculated at all
194 seqCaf (cafInfo info) `seq`
195 seqCpr (cprInfo info) `seq`
196 seqLBVar (lbvarInfo info) `seq`
197 seqOccInfo (occInfo info)
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
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:
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 }
225 -- We do *not* seq on the unfolding info, For some reason, doing so
226 -- actually increases residency significantly.
227 = info { unfoldingInfo = uf }
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 }
238 vanillaIdInfo :: IdInfo
241 cafInfo = MayHaveCafRefs, -- Safe!
242 arityInfo = UnknownArity,
244 specInfo = emptyCoreRules,
245 tyGenInfo = noTyGenInfo,
246 workerInfo = NoWorker,
247 strictnessInfo = NoStrictnessInfo,
248 unfoldingInfo = noUnfolding,
250 lbvarInfo = NoLBVarInfo,
251 inlinePragInfo = NoInlinePragInfo,
255 noTyGenIdInfo = vanillaIdInfo `setTyGenInfo` TyGenNever
256 -- Many built-in things have fixed types, so we shouldn't
257 -- run around generalising them
259 noCafIdInfo = vanillaIdInfo `setCafInfo` NoCafRefs
260 -- Local things don't refer to Cafs
262 noCafOrTyGenIdInfo = noTyGenIdInfo `setCafInfo` NoCafRefs
263 -- Most also guarantee not to refer to CAFs
267 %************************************************************************
269 \subsection[arity-IdInfo]{Arity info about an @Id@}
271 %************************************************************************
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!)
279 = UnknownArity -- No idea
281 | ArityExactly Arity -- Arity is exactly this. We use this when importing a
282 -- function; it's already been compiled and we know its
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.
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.
295 seqArity :: ArityInfo -> ()
296 seqArity a = arityLowerBound a `seq` ()
298 exactArity = ArityExactly
299 atLeastArity = ArityAtLeast
300 unknownArity = UnknownArity
302 arityLowerBound :: ArityInfo -> Arity
303 arityLowerBound UnknownArity = 0
304 arityLowerBound (ArityAtLeast n) = n
305 arityLowerBound (ArityExactly n) = n
307 hasArity :: ArityInfo -> Bool
308 hasArity UnknownArity = False
309 hasArity other = True
311 ppArityInfo UnknownArity = empty
312 ppArityInfo (ArityExactly arity) = hsep [ptext SLIT("__A"), int arity]
313 ppArityInfo (ArityAtLeast arity) = hsep [ptext SLIT("__AL"), int arity]
316 %************************************************************************
318 \subsection{Inline-pragma information}
320 %************************************************************************
325 | IMustNotBeINLINEd Bool -- True <=> came from an INLINE prag, False <=> came from a NOINLINE prag
326 (Maybe Int) -- Phase number from pragma, if any
328 -- The True, Nothing case doesn't need to be recorded
330 -- SEE COMMENTS WITH CoreUnfold.blackListed on the
331 -- exact significance of the IMustNotBeINLINEd pragma
333 isNeverInlinePrag :: InlinePragInfo -> Bool
334 isNeverInlinePrag (IMustNotBeINLINEd _ Nothing) = True
335 isNeverInlinePrag other = False
337 neverInlinePrag :: InlinePragInfo
338 neverInlinePrag = IMustNotBeINLINEd True{-should be False? --SDM -} Nothing
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
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)
351 instance Show InlinePragInfo where
352 showsPrec p prag = showsPrecSDoc p (ppr prag)
356 %************************************************************************
358 \subsection[TyGen-IdInfo]{Type generalisation info about an @Id@}
360 %************************************************************************
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.
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).
372 To indicate this property, such identifiers are marked TyGenNever.
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.
381 = NoTyGenInfo -- no restriction on type generalisation
383 | TyGenUInfo [Maybe Type] -- restrict generalisation of this Id to
384 -- preserve specified usage annotations
386 | TyGenNever -- never generalise the type of this Id
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.
398 seqTyGenInfo :: TyGenInfo -> ()
399 seqTyGenInfo NoTyGenInfo = ()
400 seqTyGenInfo (TyGenUInfo us) = seqList us ()
401 seqTyGenInfo TyGenNever = ()
403 noTyGenInfo :: TyGenInfo
404 noTyGenInfo = NoTyGenInfo
406 isNoTyGenInfo :: TyGenInfo -> Bool
407 isNoTyGenInfo NoTyGenInfo = True
408 isNoTyGenInfo _ = False
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.
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")
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)
425 instance Outputable TyGenInfo where
428 instance Show TyGenInfo where
429 showsPrec p c = showsPrecSDoc p (ppr c)
433 %************************************************************************
435 \subsection[worker-IdInfo]{Worker info about an @Id@}
437 %************************************************************************
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.
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
446 (b) the strictness info might be "SSS" or something, so no w/w split.
450 data WorkerInfo = NoWorker
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.
455 seqWorker :: WorkerInfo -> ()
456 seqWorker (HasWorker id _) = id `seq` ()
457 seqWorker NoWorker = ()
459 ppWorkerInfo NoWorker = empty
460 ppWorkerInfo (HasWorker wk_id _) = ptext SLIT("__P") <+> ppr wk_id
462 workerExists :: WorkerInfo -> Bool
463 workerExists NoWorker = False
464 workerExists (HasWorker _ _) = True
466 workerId :: WorkerInfo -> Id
467 workerId (HasWorker id _) = id
469 wrapperArity :: WorkerInfo -> Arity
470 wrapperArity (HasWorker _ a) = a
474 %************************************************************************
476 \subsection[CAF-IdInfo]{CAF-related information}
478 %************************************************************************
480 This information is used to build Static Reference Tables (see
481 simplStg/ComputeSRT.lhs).
485 = MayHaveCafRefs -- either:
486 -- (1) A function or static constructor
487 -- that refers to one or more CAFs,
488 -- (2) A real live CAF
490 | NoCafRefs -- A function or static constructor
491 -- that refers to no CAFs.
493 -- LATER: not sure how easy this is...
497 mayHaveCafRefs MayHaveCafRefs = True
498 mayHaveCafRefs _ = False
500 seqCaf c = c `seq` ()
502 ppCafInfo NoCafRefs = ptext SLIT("__C")
503 ppCafInfo MayHaveCafRefs = empty
507 %************************************************************************
509 \subsection[cpr-IdInfo]{Constructed Product Result info about an @Id@}
511 %************************************************************************
513 If the @Id@ is a function then it may have CPR info. A CPR analysis
514 phase detects whether:
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
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.
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
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
540 -- We used to keep nested info about sub-components, but
541 -- we never used it so I threw it away
545 seqCpr :: CprInfo -> ()
546 seqCpr ReturnsCPR = ()
547 seqCpr NoCPRInfo = ()
549 noCprInfo = NoCPRInfo
551 ppCprInfo NoCPRInfo = empty
552 ppCprInfo ReturnsCPR = ptext SLIT("__M")
554 instance Outputable CprInfo where
557 instance Show CprInfo where
558 showsPrec p c = showsPrecSDoc p (ppr c)
562 %************************************************************************
564 \subsection[lbvar-IdInfo]{Lambda-bound var info about an @Id@}
566 %************************************************************************
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.
573 This information may be useful in optimisation, as computations may
574 safely be floated inside such a lambda without risk of duplicating
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.
589 seqLBVar l = l `seq` ()
593 hasNoLBVarInfo NoLBVarInfo = True
594 hasNoLBVarInfo other = False
596 noLBVarInfo = NoLBVarInfo
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 ->
605 else ptext SLIT("OneShot")
609 instance Outputable LBVarInfo where
612 instance Show LBVarInfo where
613 showsPrec p c = showsPrecSDoc p (ppr c)
617 %************************************************************************
619 \subsection{Bulk operations on IdInfo}
621 %************************************************************************
623 @zapLamInfo@ is used for lambda binders that turn out to to be
624 part of an unsaturated lambda
627 zapLamInfo :: IdInfo -> Maybe IdInfo
628 zapLamInfo info@(IdInfo {occInfo = occ, demandInfo = demand})
629 | is_safe_occ && not (isStrict demand)
632 = Just (info {occInfo = safe_occ,
633 demandInfo = wwLazy})
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
641 safe_occ = case occ of
642 OneOcc _ once -> OneOcc insideLam once
647 zapDemandInfo :: IdInfo -> Maybe IdInfo
648 zapDemandInfo info@(IdInfo {demandInfo = demand})
649 | not (isStrict demand) = Nothing
650 | otherwise = Just (info {demandInfo = wwLazy})
654 copyIdInfo is used when shorting out a top-level binding
657 where f is exported. We are going to swizzle it around to
661 BUT (a) we must be careful about messing up rules
662 (b) we must ensure f's IdInfo ends up right
664 (a) Messing up the rules
666 The example that went bad on me was this one:
668 iterate :: (a -> a) -> a -> [a]
669 iterate = iterateList
671 iterateFB c f x = x `c` iterateFB c f (f x)
672 iterateList f x = x : iterateList f (f x)
675 "iterate" forall f x. iterate f x = build (\c _n -> iterateFB c f x)
676 "iterateFB" iterateFB (:) = iterateList
679 This got shorted out to:
681 iterateList :: (a -> a) -> a -> [a]
682 iterateList = iterate
684 iterateFB c f x = x `c` iterateFB c f (f x)
685 iterate f x = x : iterate f (f x)
688 "iterate" forall f x. iterate f x = build (\c _n -> iterateFB c f x)
689 "iterateFB" iterateFB (:) = iterate
692 And now we get an infinite loop in the rule system
693 iterate f x -> build (\cn -> iterateFB c f x
697 Tiresome solution: don't do shorting out if f has rewrite rules.
698 Hence shortableIdInfo.
700 (b) Keeping the IdInfo right
701 ~~~~~~~~~~~~~~~~~~~~~~~~
702 We want to move strictness/worker info from f_local to f, but keep the rest.
706 shortableIdInfo :: IdInfo -> Bool
707 shortableIdInfo info = isEmptyCoreRules (specInfo info)
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