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, noCafIdInfo, hasCafIdInfo,
15 seqIdInfo, megaSeqIdInfo,
18 zapLamInfo, zapDemandInfo,
19 shortableIdInfo, copyIdInfo,
24 arityInfo, setArityInfo, ppArityInfo,
26 -- New demand and strictness info
27 newStrictnessInfo, setNewStrictnessInfo,
28 newDemandInfo, setNewDemandInfo, pprNewStrictness,
30 -- Strictness; imported from Demand
32 mkStrictnessInfo, noStrictnessInfo,
33 ppStrictnessInfo,isBottomingStrictness,
37 WorkerInfo(..), workerExists, wrapperArity, workerId,
38 workerInfo, setWorkerInfo, ppWorkerInfo,
41 unfoldingInfo, setUnfoldingInfo,
44 -- Old DemandInfo and StrictnessInfo
45 demandInfo, setDemandInfo,
46 strictnessInfo, setStrictnessInfo,
47 cprInfoFromNewStrictness,
48 oldStrictnessFromNew, newStrictnessFromOld,
51 -- Constructed Product Result Info
52 CprInfo(..), cprInfo, setCprInfo, ppCprInfo, noCprInfo,
57 inlinePragInfo, setInlinePragInfo,
60 OccInfo(..), isFragileOcc, isDeadOcc, isLoopBreaker,
61 InsideLam, OneBranch, insideLam, notInsideLam, oneBranch, notOneBranch,
65 specInfo, setSpecInfo,
68 CgInfo(..), cgInfo, setCgInfo, pprCgInfo,
69 cgCafInfo, vanillaCgInfo,
70 CgInfoEnv, lookupCgInfo,
73 CafInfo(..), ppCafInfo, setCafInfo, mayHaveCafRefs,
75 -- Lambda-bound variable info
76 LBVarInfo(..), lbvarInfo, setLBVarInfo, noLBVarInfo, hasNoLBVarInfo
79 #include "HsVersions.h"
83 import Type ( Type, usOnce, eqUsage )
84 import PrimOp ( PrimOp )
85 import NameEnv ( NameEnv, lookupNameEnv )
88 import BasicTypes ( OccInfo(..), isFragileOcc, isDeadOcc, seqOccInfo, isLoopBreaker,
89 InsideLam, insideLam, notInsideLam,
90 OneBranch, oneBranch, notOneBranch,
94 import DataCon ( DataCon )
95 import ForeignCall ( ForeignCall )
96 import FieldLabel ( FieldLabel )
97 import Type ( usOnce )
98 import Demand hiding( Demand, seqDemand )
99 import qualified Demand
102 import Util ( listLengthCmp )
103 import Maybe ( isJust )
104 import List ( replicate )
106 -- infixl so you can say (id `set` a `set` b)
107 infixl 1 `setSpecInfo`,
116 `setNewStrictnessInfo`,
117 `setAllStrictnessInfo`,
119 #ifdef OLD_STRICTNESS
122 , `setStrictnessInfo`
126 %************************************************************************
128 \subsection{New strictness info}
130 %************************************************************************
135 -- setAllStrictnessInfo :: IdInfo -> Maybe StrictSig -> IdInfo
136 -- Set old and new strictness info
137 setAllStrictnessInfo info Nothing
138 = info { newStrictnessInfo = Nothing
139 #ifdef OLD_STRICTNESS
140 , strictnessInfo = NoStrictnessInfo
141 , cprInfo = NoCPRInfo
145 setAllStrictnessInfo info (Just sig)
146 = info { newStrictnessInfo = Just sig
147 #ifdef OLD_STRICTNESS
148 , strictnessInfo = oldStrictnessFromNew sig
149 , cprInfo = cprInfoFromNewStrictness sig
153 seqNewStrictnessInfo Nothing = ()
154 seqNewStrictnessInfo (Just ty) = seqStrictSig ty
156 pprNewStrictness Nothing = empty
157 pprNewStrictness (Just sig) = ftext FSLIT("Str:") <+> ppr sig
159 #ifdef OLD_STRICTNESS
160 oldStrictnessFromNew :: StrictSig -> Demand.StrictnessInfo
161 oldStrictnessFromNew sig = mkStrictnessInfo (map oldDemand dmds, isBotRes res_info)
163 (dmds, res_info) = splitStrictSig sig
165 cprInfoFromNewStrictness :: StrictSig -> CprInfo
166 cprInfoFromNewStrictness sig = case strictSigResInfo sig of
170 newStrictnessFromOld :: Name -> Arity -> Demand.StrictnessInfo -> CprInfo -> StrictSig
171 newStrictnessFromOld name arity (Demand.StrictnessInfo ds res) cpr
172 | listLengthCmp ds arity /= GT -- length ds <= arity
173 -- Sometimes the old strictness analyser has more
174 -- demands than the arity justifies
175 = mk_strict_sig name arity $
176 mkTopDmdType (map newDemand ds) (newRes res cpr)
178 newStrictnessFromOld name arity other cpr
179 = -- Either no strictness info, or arity is too small
180 -- In either case we can't say anything useful
181 mk_strict_sig name arity $
182 mkTopDmdType (replicate arity lazyDmd) (newRes False cpr)
184 mk_strict_sig name arity dmd_ty
185 = WARN( arity /= dmdTypeDepth dmd_ty, ppr name <+> (ppr arity $$ ppr dmd_ty) )
188 newRes True _ = BotRes
189 newRes False ReturnsCPR = retCPR
190 newRes False NoCPRInfo = TopRes
192 newDemand :: Demand.Demand -> NewDemand.Demand
193 newDemand (WwLazy True) = Abs
194 newDemand (WwLazy False) = lazyDmd
195 newDemand WwStrict = evalDmd
196 newDemand (WwUnpack unpk ds) = Eval (Prod (map newDemand ds))
197 newDemand WwPrim = lazyDmd
198 newDemand WwEnum = evalDmd
200 oldDemand :: NewDemand.Demand -> Demand.Demand
201 oldDemand Abs = WwLazy True
202 oldDemand Top = WwLazy False
203 oldDemand Bot = WwStrict
204 oldDemand (Box Bot) = WwStrict
205 oldDemand (Box Abs) = WwLazy False
206 oldDemand (Box (Eval _)) = WwStrict -- Pass box only
207 oldDemand (Defer d) = WwLazy False
208 oldDemand (Eval (Prod ds)) = WwUnpack True (map oldDemand ds)
209 oldDemand (Eval (Poly _)) = WwStrict
210 oldDemand (Call _) = WwStrict
212 #endif /* OLD_STRICTNESS */
217 seqNewDemandInfo Nothing = ()
218 seqNewDemandInfo (Just dmd) = seqDemand dmd
222 %************************************************************************
224 \subsection{GlobalIdDetails
226 %************************************************************************
228 This type is here (rather than in Id.lhs) mainly because there's
229 an IdInfo.hi-boot, but no Id.hi-boot, and GlobalIdDetails is imported
230 (recursively) by Var.lhs.
234 = VanillaGlobal -- Imported from elsewhere, a default method Id.
236 | RecordSelId FieldLabel -- The Id for a record selector
237 | DataConId DataCon -- The Id for a data constructor *worker*
238 | DataConWrapId DataCon -- The Id for a data constructor *wrapper*
239 -- [the only reasons we need to know is so that
240 -- a) we can suppress printing a definition in the interface file
241 -- b) when typechecking a pattern we can get from the
242 -- Id back to the data con]
244 | PrimOpId PrimOp -- The Id for a primitive operator
245 | FCallId ForeignCall -- The Id for a foreign call
247 | NotGlobalId -- Used as a convenient extra return value from globalIdDetails
249 notGlobalId = NotGlobalId
251 instance Outputable GlobalIdDetails where
252 ppr NotGlobalId = ptext SLIT("[***NotGlobalId***]")
253 ppr VanillaGlobal = ptext SLIT("[GlobalId]")
254 ppr (DataConId _) = ptext SLIT("[DataCon]")
255 ppr (DataConWrapId _) = ptext SLIT("[DataConWrapper]")
256 ppr (PrimOpId _) = ptext SLIT("[PrimOp]")
257 ppr (FCallId _) = ptext SLIT("[ForeignCall]")
258 ppr (RecordSelId _) = ptext SLIT("[RecSel]")
262 %************************************************************************
264 \subsection{The main IdInfo type}
266 %************************************************************************
268 An @IdInfo@ gives {\em optional} information about an @Id@. If
269 present it never lies, but it may not be present, in which case there
270 is always a conservative assumption which can be made.
272 Two @Id@s may have different info even though they have the same
273 @Unique@ (and are hence the same @Id@); for example, one might lack
274 the properties attached to the other.
276 The @IdInfo@ gives information about the value, or definition, of the
277 @Id@. It does {\em not} contain information about the @Id@'s usage
278 (except for @DemandInfo@? ToDo). (@lbvarInfo@ is also a marginal
284 arityInfo :: !ArityInfo, -- Its arity
285 specInfo :: CoreRules, -- Specialisations of this function which exist
286 #ifdef OLD_STRICTNESS
287 cprInfo :: CprInfo, -- Function always constructs a product result
288 demandInfo :: Demand.Demand, -- Whether or not it is definitely demanded
289 strictnessInfo :: StrictnessInfo, -- Strictness properties
291 workerInfo :: WorkerInfo, -- Pointer to Worker Function
292 unfoldingInfo :: Unfolding, -- Its unfolding
293 cgInfo :: CgInfo, -- Code generator info (arity, CAF info)
294 lbvarInfo :: LBVarInfo, -- Info about a lambda-bound variable
295 inlinePragInfo :: InlinePragInfo, -- Inline pragma
296 occInfo :: OccInfo, -- How it occurs
298 newStrictnessInfo :: Maybe StrictSig, -- Reason for Maybe: the DmdAnal phase needs to
299 -- know whether whether this is the first visit,
300 -- so it can assign botSig. Other customers want
301 -- topSig. So Nothing is good.
303 newDemandInfo :: Maybe Demand -- Similarly we want to know if there's no
304 -- known demand yet, for when we are looking for
308 seqIdInfo :: IdInfo -> ()
309 seqIdInfo (IdInfo {}) = ()
311 megaSeqIdInfo :: IdInfo -> ()
313 = seqRules (specInfo info) `seq`
314 seqWorker (workerInfo info) `seq`
316 -- Omitting this improves runtimes a little, presumably because
317 -- some unfoldings are not calculated at all
318 -- seqUnfolding (unfoldingInfo info) `seq`
320 seqNewDemandInfo (newDemandInfo info) `seq`
321 seqNewStrictnessInfo (newStrictnessInfo info) `seq`
323 #ifdef OLD_STRICTNESS
324 Demand.seqDemand (demandInfo info) `seq`
325 seqStrictnessInfo (strictnessInfo info) `seq`
326 seqCpr (cprInfo info) `seq`
329 -- CgInfo is involved in a loop, so we have to be careful not to seq it
331 -- seqCg (cgInfo info) `seq`
332 seqLBVar (lbvarInfo info) `seq`
333 seqOccInfo (occInfo info)
339 setWorkerInfo info wk = wk `seq` info { workerInfo = wk }
340 setSpecInfo info sp = sp `seq` info { specInfo = sp }
341 setInlinePragInfo info pr = pr `seq` info { inlinePragInfo = pr }
342 setOccInfo info oc = oc `seq` info { occInfo = oc }
343 #ifdef OLD_STRICTNESS
344 setStrictnessInfo info st = st `seq` info { strictnessInfo = st }
346 -- Try to avoid spack leaks by seq'ing
348 setUnfoldingInfo info uf
349 | isEvaldUnfolding uf
350 -- If the unfolding is a value, the demand info may
351 -- go pear-shaped, so we nuke it. Example:
353 -- case x of (p,q) -> h p q x
354 -- Here x is certainly demanded. But after we've nuked
355 -- the case, we'll get just
356 -- let x = (a,b) in h a b x
357 -- and now x is not demanded (I'm assuming h is lazy)
358 -- This really happens. The solution here is a bit ad hoc...
359 = info { unfoldingInfo = uf, newDemandInfo = Nothing }
362 -- We do *not* seq on the unfolding info, For some reason, doing so
363 -- actually increases residency significantly.
364 = info { unfoldingInfo = uf }
366 #ifdef OLD_STRICTNESS
367 setDemandInfo info dd = info { demandInfo = dd }
368 setCprInfo info cp = info { cprInfo = cp }
371 setArityInfo info ar = info { arityInfo = ar }
372 setCgInfo info cg = info { cgInfo = cg }
374 setLBVarInfo info lb = {-lb `seq`-} info { lbvarInfo = lb }
376 setNewDemandInfo info dd = dd `seq` info { newDemandInfo = dd }
377 setNewStrictnessInfo info dd = dd `seq` info { newStrictnessInfo = dd }
382 vanillaIdInfo :: IdInfo
386 arityInfo = unknownArity,
387 #ifdef OLD_STRICTNESS
390 strictnessInfo = NoStrictnessInfo,
392 specInfo = emptyCoreRules,
393 workerInfo = NoWorker,
394 unfoldingInfo = noUnfolding,
395 lbvarInfo = NoLBVarInfo,
396 inlinePragInfo = AlwaysActive,
398 newDemandInfo = Nothing,
399 newStrictnessInfo = Nothing
402 hasCafIdInfo = vanillaIdInfo `setCgInfo` CgInfo MayHaveCafRefs
403 noCafIdInfo = vanillaIdInfo `setCgInfo` CgInfo NoCafRefs
404 -- Used for built-in type Ids in MkId.
405 -- These must have a valid CgInfo set, so you can't
406 -- use vanillaIdInfo!
410 %************************************************************************
412 \subsection[arity-IdInfo]{Arity info about an @Id@}
414 %************************************************************************
416 For locally-defined Ids, the code generator maintains its own notion
417 of their arities; so it should not be asking... (but other things
418 besides the code-generator need arity info!)
421 type ArityInfo = Arity
422 -- A partial application of this Id to up to n-1 value arguments
423 -- does essentially no work. That is not necessarily the
424 -- same as saying that it has n leading lambdas, because coerces
425 -- may get in the way.
427 -- The arity might increase later in the compilation process, if
428 -- an extra lambda floats up to the binding site.
430 unknownArity = 0 :: Arity
432 ppArityInfo 0 = empty
433 ppArityInfo n = hsep [ptext SLIT("Arity"), int n]
436 %************************************************************************
438 \subsection{Inline-pragma information}
440 %************************************************************************
443 type InlinePragInfo = Activation
444 -- Tells when the inlining is active
445 -- When it is active the thing may be inlined, depending on how
448 -- If there was an INLINE pragma, then as a separate matter, the
449 -- RHS will have been made to look small with a CoreSyn Inline Note
453 %************************************************************************
455 \subsection[worker-IdInfo]{Worker info about an @Id@}
457 %************************************************************************
459 If this Id has a worker then we store a reference to it. Worker
460 functions are generated by the worker/wrapper pass. This uses
461 information from strictness analysis.
463 There might not be a worker, even for a strict function, because:
464 (a) the function might be small enough to inline, so no need
466 (b) the strictness info might be "SSS" or something, so no w/w split.
468 Sometimes the arity of a wrapper changes from the original arity from
469 which it was generated, so we always emit the "original" arity into
470 the interface file, as part of the worker info.
472 How can this happen? Sometimes we get
473 f = coerce t (\x y -> $wf x y)
474 at the moment of w/w split; but the eta reducer turns it into
476 which is perfectly fine except that the exposed arity so far as
477 the code generator is concerned (zero) differs from the arity
478 when we did the split (2).
480 All this arises because we use 'arity' to mean "exactly how many
481 top level lambdas are there" in interface files; but during the
482 compilation of this module it means "how many things can I apply
487 data WorkerInfo = NoWorker
489 -- The Arity is the arity of the *wrapper* at the moment of the
490 -- w/w split. See comments in MkIface.ifaceId, with the 'Worker' code.
492 seqWorker :: WorkerInfo -> ()
493 seqWorker (HasWorker id a) = id `seq` a `seq` ()
494 seqWorker NoWorker = ()
496 ppWorkerInfo NoWorker = empty
497 ppWorkerInfo (HasWorker wk_id _) = ptext SLIT("__P") <+> ppr wk_id
499 workerExists :: WorkerInfo -> Bool
500 workerExists NoWorker = False
501 workerExists (HasWorker _ _) = True
503 workerId :: WorkerInfo -> Id
504 workerId (HasWorker id _) = id
506 wrapperArity :: WorkerInfo -> Arity
507 wrapperArity (HasWorker _ a) = a
511 %************************************************************************
513 \subsection[CG-IdInfo]{Code generator-related information}
515 %************************************************************************
517 CgInfo encapsulates calling-convention information produced by the code
518 generator. It is pasted into the IdInfo of each emitted Id by CoreTidy,
519 but only as a thunk --- the information is only actually produced further
520 downstream, by the code generator.
523 #ifndef OLD_STRICTNESS
524 newtype CgInfo = CgInfo CafInfo -- We are back to only having CafRefs in CgInfo
525 noCgInfo = panic "NoCgInfo!"
527 data CgInfo = CgInfo CafInfo
528 | NoCgInfo -- In debug mode we don't want a black hole here
530 -- noCgInfo is used for local Ids, which shouldn't need any CgInfo
534 cgCafInfo (CgInfo caf_info) = caf_info
536 setCafInfo info caf_info = info `setCgInfo` CgInfo caf_info
538 seqCg c = c `seq` () -- fields are strict anyhow
540 vanillaCgInfo = CgInfo MayHaveCafRefs -- Definitely safe
542 -- CafInfo is used to build Static Reference Tables (see simplStg/SRT.lhs).
545 = MayHaveCafRefs -- either:
546 -- (1) A function or static constructor
547 -- that refers to one or more CAFs,
548 -- (2) A real live CAF
550 | NoCafRefs -- A function or static constructor
551 -- that refers to no CAFs.
553 mayHaveCafRefs MayHaveCafRefs = True
554 mayHaveCafRefs _ = False
556 seqCaf c = c `seq` ()
558 pprCgInfo (CgInfo caf_info) = ppCafInfo caf_info
561 ppArity n = hsep [ptext SLIT("__A"), int n]
563 ppCafInfo NoCafRefs = ptext SLIT("__C")
564 ppCafInfo MayHaveCafRefs = empty
568 type CgInfoEnv = NameEnv CgInfo
570 lookupCgInfo :: NameEnv CgInfo -> Name -> CgInfo
571 lookupCgInfo env n = case lookupNameEnv env n of
573 Nothing -> pprTrace "Urk! Not in CgInfo env" (ppr n) vanillaCgInfo
577 %************************************************************************
579 \subsection[cpr-IdInfo]{Constructed Product Result info about an @Id@}
581 %************************************************************************
583 If the @Id@ is a function then it may have CPR info. A CPR analysis
584 phase detects whether:
588 The function's return value has a product type, i.e. an algebraic type
589 with a single constructor. Examples of such types are tuples and boxed
592 The function always 'constructs' the value that it is returning. It
593 must do this on every path through, and it's OK if it calls another
594 function which constructs the result.
597 If this is the case then we store a template which tells us the
598 function has the CPR property and which components of the result are
602 #ifdef OLD_STRICTNESS
605 | ReturnsCPR -- Yes, this function returns a constructed product
606 -- Implicitly, this means "after the function has been applied
607 -- to all its arguments", so the worker/wrapper builder in
608 -- WwLib.mkWWcpr checks that that it is indeed saturated before
609 -- making use of the CPR info
611 -- We used to keep nested info about sub-components, but
612 -- we never used it so I threw it away
614 seqCpr :: CprInfo -> ()
615 seqCpr ReturnsCPR = ()
616 seqCpr NoCPRInfo = ()
618 noCprInfo = NoCPRInfo
620 ppCprInfo NoCPRInfo = empty
621 ppCprInfo ReturnsCPR = ptext SLIT("__M")
623 instance Outputable CprInfo where
626 instance Show CprInfo where
627 showsPrec p c = showsPrecSDoc p (ppr c)
632 %************************************************************************
634 \subsection[lbvar-IdInfo]{Lambda-bound var info about an @Id@}
636 %************************************************************************
638 If the @Id@ is a lambda-bound variable then it may have lambda-bound
639 var info. The usage analysis (UsageSP) detects whether the lambda
640 binding this var is a ``one-shot'' lambda; that is, whether it is
641 applied at most once.
643 This information may be useful in optimisation, as computations may
644 safely be floated inside such a lambda without risk of duplicating
651 | LBVarInfo Type -- The lambda that binds this Id has this usage
652 -- annotation (i.e., if ==usOnce, then the
653 -- lambda is applied at most once).
654 -- The annotation's kind must be `$'
655 -- HACK ALERT! placing this info here is a short-term hack,
656 -- but it minimises changes to the rest of the compiler.
657 -- Hack agreed by SLPJ/KSW 1999-04.
659 seqLBVar l = l `seq` ()
663 hasNoLBVarInfo NoLBVarInfo = True
664 hasNoLBVarInfo other = False
666 noLBVarInfo = NoLBVarInfo
668 -- not safe to print or parse LBVarInfo because it is not really a
669 -- property of the definition, but a property of the context.
670 pprLBVarInfo NoLBVarInfo = empty
671 pprLBVarInfo (LBVarInfo u) | u `eqUsage` usOnce
672 = ptext SLIT("OneShot")
676 instance Outputable LBVarInfo where
679 instance Show LBVarInfo where
680 showsPrec p c = showsPrecSDoc p (ppr c)
684 %************************************************************************
686 \subsection{Bulk operations on IdInfo}
688 %************************************************************************
690 @zapLamInfo@ is used for lambda binders that turn out to to be
691 part of an unsaturated lambda
694 zapLamInfo :: IdInfo -> Maybe IdInfo
695 zapLamInfo info@(IdInfo {occInfo = occ, newDemandInfo = demand})
696 | is_safe_occ occ && is_safe_dmd demand
699 = Just (info {occInfo = safe_occ, newDemandInfo = Nothing})
701 -- The "unsafe" occ info is the ones that say I'm not in a lambda
702 -- because that might not be true for an unsaturated lambda
703 is_safe_occ (OneOcc in_lam once) = in_lam
704 is_safe_occ other = True
706 safe_occ = case occ of
707 OneOcc _ once -> OneOcc insideLam once
710 is_safe_dmd Nothing = True
711 is_safe_dmd (Just dmd) = not (isStrictDmd dmd)
715 zapDemandInfo :: IdInfo -> Maybe IdInfo
716 zapDemandInfo info@(IdInfo {newDemandInfo = dmd})
717 | isJust dmd = Just (info {newDemandInfo = Nothing})
718 | otherwise = Nothing
722 copyIdInfo is used when shorting out a top-level binding
725 where f is exported. We are going to swizzle it around to
729 BUT (a) we must be careful about messing up rules
730 (b) we must ensure f's IdInfo ends up right
732 (a) Messing up the rules
734 The example that went bad on me was this one:
736 iterate :: (a -> a) -> a -> [a]
737 iterate = iterateList
739 iterateFB c f x = x `c` iterateFB c f (f x)
740 iterateList f x = x : iterateList f (f x)
743 "iterate" forall f x. iterate f x = build (\c _n -> iterateFB c f x)
744 "iterateFB" iterateFB (:) = iterateList
747 This got shorted out to:
749 iterateList :: (a -> a) -> a -> [a]
750 iterateList = iterate
752 iterateFB c f x = x `c` iterateFB c f (f x)
753 iterate f x = x : iterate f (f x)
756 "iterate" forall f x. iterate f x = build (\c _n -> iterateFB c f x)
757 "iterateFB" iterateFB (:) = iterate
760 And now we get an infinite loop in the rule system
761 iterate f x -> build (\cn -> iterateFB c f x)
765 Tiresome solution: don't do shorting out if f has rewrite rules.
766 Hence shortableIdInfo.
768 (b) Keeping the IdInfo right
769 ~~~~~~~~~~~~~~~~~~~~~~~~
770 We want to move strictness/worker info from f_local to f, but keep the rest.
774 shortableIdInfo :: IdInfo -> Bool
775 shortableIdInfo info = isEmptyCoreRules (specInfo info)
777 copyIdInfo :: IdInfo -- f_local
778 -> IdInfo -- f (the exported one)
779 -> IdInfo -- New info for f
780 copyIdInfo f_local f = f { newStrictnessInfo = newStrictnessInfo f_local,
781 #ifdef OLD_STRICTNESS
782 strictnessInfo = strictnessInfo f_local,
783 cprInfo = cprInfo f_local,
785 workerInfo = workerInfo f_local