69c2cc32b0a6ef476bf9ee486654233c04693ad3
[ghc.git] / compiler / basicTypes / Id.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5 \section[Id]{@Ids@: Value and constructor identifiers}
6 -}
7
8 {-# LANGUAGE CPP #-}
9
10 -- |
11 -- #name_types#
12 -- GHC uses several kinds of name internally:
13 --
14 -- * 'OccName.OccName': see "OccName#name_types"
15 --
16 -- * 'RdrName.RdrName': see "RdrName#name_types"
17 --
18 -- * 'Name.Name': see "Name#name_types"
19 --
20 -- * 'Id.Id' represents names that not only have a 'Name.Name' but also a 'TyCoRep.Type' and some additional
21 -- details (a 'IdInfo.IdInfo' and one of 'Var.LocalIdDetails' or 'IdInfo.GlobalIdDetails') that
22 -- are added, modified and inspected by various compiler passes. These 'Var.Var' names may either
23 -- be global or local, see "Var#globalvslocal"
24 --
25 -- * 'Var.Var': see "Var#name_types"
26
27 module Id (
28 -- * The main types
29 Var, Id, isId,
30
31 -- * In and Out variants
32 InVar, InId,
33 OutVar, OutId,
34
35 -- ** Simple construction
36 mkGlobalId, mkVanillaGlobal, mkVanillaGlobalWithInfo,
37 mkLocalId, mkLocalCoVar, mkLocalIdOrCoVar,
38 mkLocalIdOrCoVarWithInfo,
39 mkLocalIdWithInfo, mkExportedLocalId, mkExportedVanillaId,
40 mkSysLocal, mkSysLocalM, mkSysLocalOrCoVar, mkSysLocalOrCoVarM,
41 mkUserLocal, mkUserLocalOrCoVar,
42 mkTemplateLocals, mkTemplateLocalsNum, mkTemplateLocal,
43 mkWorkerId,
44
45 -- ** Taking an Id apart
46 idName, idType, idUnique, idInfo, idDetails,
47 recordSelectorTyCon,
48
49 -- ** Modifying an Id
50 setIdName, setIdUnique, Id.setIdType,
51 setIdExported, setIdNotExported,
52 globaliseId, localiseId,
53 setIdInfo, lazySetIdInfo, modifyIdInfo, maybeModifyIdInfo,
54 zapLamIdInfo, zapIdDemandInfo, zapIdUsageInfo, zapIdUsageEnvInfo,
55 zapIdUsedOnceInfo, zapIdTailCallInfo,
56 zapFragileIdInfo, zapIdStrictness,
57 transferPolyIdInfo,
58
59 -- ** Predicates on Ids
60 isImplicitId, isDeadBinder,
61 isStrictId,
62 isExportedId, isLocalId, isGlobalId,
63 isRecordSelector, isNaughtyRecordSelector,
64 isPatSynRecordSelector,
65 isDataConRecordSelector,
66 isClassOpId_maybe, isDFunId,
67 isPrimOpId, isPrimOpId_maybe,
68 isFCallId, isFCallId_maybe,
69 isDataConWorkId, isDataConWorkId_maybe, isDataConId_maybe, idDataCon,
70 isConLikeId, isBottomingId, idIsFrom,
71 hasNoBinding,
72
73 -- ** Evidence variables
74 DictId, isDictId, isEvVar,
75
76 -- ** Join variables
77 JoinId, isJoinId, isJoinId_maybe, idJoinArity,
78 asJoinId, asJoinId_maybe, zapJoinId,
79
80 -- ** Inline pragma stuff
81 idInlinePragma, setInlinePragma, modifyInlinePragma,
82 idInlineActivation, setInlineActivation, idRuleMatchInfo,
83
84 -- ** One-shot lambdas
85 isOneShotBndr, isProbablyOneShotLambda,
86 setOneShotLambda, clearOneShotLambda,
87 updOneShotInfo, setIdOneShotInfo,
88 isStateHackType, stateHackOneShot, typeOneShot,
89
90 -- ** Reading 'IdInfo' fields
91 idArity,
92 idCallArity, idFunRepArity,
93 idUnfolding, realIdUnfolding,
94 idSpecialisation, idCoreRules, idHasRules,
95 idCafInfo,
96 idOneShotInfo, idStateHackOneShotInfo,
97 idOccInfo,
98 isNeverLevPolyId,
99
100 -- ** Writing 'IdInfo' fields
101 setIdUnfolding, setCaseBndrEvald,
102 setIdArity,
103 setIdCallArity,
104
105 setIdSpecialisation,
106 setIdCafInfo,
107 setIdOccInfo, zapIdOccInfo,
108
109 setIdDemandInfo,
110 setIdStrictness,
111
112 idDemandInfo,
113 idStrictness,
114
115 ) where
116
117 #include "HsVersions.h"
118
119 import DynFlags
120 import CoreSyn ( CoreRule, evaldUnfolding, Unfolding( NoUnfolding ) )
121
122 import IdInfo
123 import BasicTypes
124
125 -- Imported and re-exported
126 import Var( Id, CoVar, DictId, JoinId,
127 InId, InVar,
128 OutId, OutVar,
129 idInfo, idDetails, setIdDetails, globaliseId, varType,
130 isId, isLocalId, isGlobalId, isExportedId,
131 isJoinId, isJoinId_maybe )
132 import qualified Var
133
134 import Type
135 import RepType
136 import TysPrim
137 import DataCon
138 import Demand
139 import Name
140 import Module
141 import Class
142 import {-# SOURCE #-} PrimOp (PrimOp)
143 import ForeignCall
144 import Maybes
145 import SrcLoc
146 import Outputable
147 import Unique
148 import UniqSupply
149 import FastString
150 import Util
151
152 -- infixl so you can say (id `set` a `set` b)
153 infixl 1 `setIdUnfolding`,
154 `setIdArity`,
155 `setIdCallArity`,
156 `setIdOccInfo`,
157 `setIdOneShotInfo`,
158
159 `setIdSpecialisation`,
160 `setInlinePragma`,
161 `setInlineActivation`,
162 `idCafInfo`,
163
164 `setIdDemandInfo`,
165 `setIdStrictness`,
166
167 `asJoinId`,
168 `asJoinId_maybe`
169
170 {-
171 ************************************************************************
172 * *
173 \subsection{Basic Id manipulation}
174 * *
175 ************************************************************************
176 -}
177
178 idName :: Id -> Name
179 idName = Var.varName
180
181 idUnique :: Id -> Unique
182 idUnique = Var.varUnique
183
184 idType :: Id -> Kind
185 idType = Var.varType
186
187 setIdName :: Id -> Name -> Id
188 setIdName = Var.setVarName
189
190 setIdUnique :: Id -> Unique -> Id
191 setIdUnique = Var.setVarUnique
192
193 -- | Not only does this set the 'Id' 'Type', it also evaluates the type to try and
194 -- reduce space usage
195 setIdType :: Id -> Type -> Id
196 setIdType id ty = seqType ty `seq` Var.setVarType id ty
197
198 setIdExported :: Id -> Id
199 setIdExported = Var.setIdExported
200
201 setIdNotExported :: Id -> Id
202 setIdNotExported = Var.setIdNotExported
203
204 localiseId :: Id -> Id
205 -- Make an with the same unique and type as the
206 -- incoming Id, but with an *Internal* Name and *LocalId* flavour
207 localiseId id
208 | ASSERT( isId id ) isLocalId id && isInternalName name
209 = id
210 | otherwise
211 = Var.mkLocalVar (idDetails id) (localiseName name) (idType id) (idInfo id)
212 where
213 name = idName id
214
215 lazySetIdInfo :: Id -> IdInfo -> Id
216 lazySetIdInfo = Var.lazySetIdInfo
217
218 setIdInfo :: Id -> IdInfo -> Id
219 setIdInfo id info = info `seq` (lazySetIdInfo id info)
220 -- Try to avoid spack leaks by seq'ing
221
222 modifyIdInfo :: (IdInfo -> IdInfo) -> Id -> Id
223 modifyIdInfo fn id = setIdInfo id (fn (idInfo id))
224
225 -- maybeModifyIdInfo tries to avoid unnecessary thrashing
226 maybeModifyIdInfo :: Maybe IdInfo -> Id -> Id
227 maybeModifyIdInfo (Just new_info) id = lazySetIdInfo id new_info
228 maybeModifyIdInfo Nothing id = id
229
230 {-
231 ************************************************************************
232 * *
233 \subsection{Simple Id construction}
234 * *
235 ************************************************************************
236
237 Absolutely all Ids are made by mkId. It is just like Var.mkId,
238 but in addition it pins free-tyvar-info onto the Id's type,
239 where it can easily be found.
240
241 Note [Free type variables]
242 ~~~~~~~~~~~~~~~~~~~~~~~~~~
243 At one time we cached the free type variables of the type of an Id
244 at the root of the type in a TyNote. The idea was to avoid repeating
245 the free-type-variable calculation. But it turned out to slow down
246 the compiler overall. I don't quite know why; perhaps finding free
247 type variables of an Id isn't all that common whereas applying a
248 substitution (which changes the free type variables) is more common.
249 Anyway, we removed it in March 2008.
250 -}
251
252 -- | For an explanation of global vs. local 'Id's, see "Var#globalvslocal"
253 mkGlobalId :: IdDetails -> Name -> Type -> IdInfo -> Id
254 mkGlobalId = Var.mkGlobalVar
255
256 -- | Make a global 'Id' without any extra information at all
257 mkVanillaGlobal :: Name -> Type -> Id
258 mkVanillaGlobal name ty = mkVanillaGlobalWithInfo name ty vanillaIdInfo
259
260 -- | Make a global 'Id' with no global information but some generic 'IdInfo'
261 mkVanillaGlobalWithInfo :: Name -> Type -> IdInfo -> Id
262 mkVanillaGlobalWithInfo = mkGlobalId VanillaId
263
264
265 -- | For an explanation of global vs. local 'Id's, see "Var#globalvslocal"
266 mkLocalId :: Name -> Type -> Id
267 mkLocalId name ty = mkLocalIdWithInfo name ty vanillaIdInfo
268 -- It's tempting to ASSERT( not (isCoercionType ty) ), but don't. Sometimes,
269 -- the type is a panic. (Search invented_id)
270
271 -- | Make a local CoVar
272 mkLocalCoVar :: Name -> Type -> CoVar
273 mkLocalCoVar name ty
274 = ASSERT( isCoercionType ty )
275 Var.mkLocalVar CoVarId name ty vanillaIdInfo
276
277 -- | Like 'mkLocalId', but checks the type to see if it should make a covar
278 mkLocalIdOrCoVar :: Name -> Type -> Id
279 mkLocalIdOrCoVar name ty
280 | isCoercionType ty = mkLocalCoVar name ty
281 | otherwise = mkLocalId name ty
282
283 -- | Make a local id, with the IdDetails set to CoVarId if the type indicates
284 -- so.
285 mkLocalIdOrCoVarWithInfo :: Name -> Type -> IdInfo -> Id
286 mkLocalIdOrCoVarWithInfo name ty info
287 = Var.mkLocalVar details name ty info
288 where
289 details | isCoercionType ty = CoVarId
290 | otherwise = VanillaId
291
292 -- proper ids only; no covars!
293 mkLocalIdWithInfo :: Name -> Type -> IdInfo -> Id
294 mkLocalIdWithInfo name ty info = Var.mkLocalVar VanillaId name ty info
295 -- Note [Free type variables]
296
297 -- | Create a local 'Id' that is marked as exported.
298 -- This prevents things attached to it from being removed as dead code.
299 -- See Note [Exported LocalIds]
300 mkExportedLocalId :: IdDetails -> Name -> Type -> Id
301 mkExportedLocalId details name ty = Var.mkExportedLocalVar details name ty vanillaIdInfo
302 -- Note [Free type variables]
303
304 mkExportedVanillaId :: Name -> Type -> Id
305 mkExportedVanillaId name ty = Var.mkExportedLocalVar VanillaId name ty vanillaIdInfo
306 -- Note [Free type variables]
307
308
309 -- | Create a system local 'Id'. These are local 'Id's (see "Var#globalvslocal")
310 -- that are created by the compiler out of thin air
311 mkSysLocal :: FastString -> Unique -> Type -> Id
312 mkSysLocal fs uniq ty = ASSERT( not (isCoercionType ty) )
313 mkLocalId (mkSystemVarName uniq fs) ty
314
315 -- | Like 'mkSysLocal', but checks to see if we have a covar type
316 mkSysLocalOrCoVar :: FastString -> Unique -> Type -> Id
317 mkSysLocalOrCoVar fs uniq ty
318 = mkLocalIdOrCoVar (mkSystemVarName uniq fs) ty
319
320 mkSysLocalM :: MonadUnique m => FastString -> Type -> m Id
321 mkSysLocalM fs ty = getUniqueM >>= (\uniq -> return (mkSysLocal fs uniq ty))
322
323 mkSysLocalOrCoVarM :: MonadUnique m => FastString -> Type -> m Id
324 mkSysLocalOrCoVarM fs ty
325 = getUniqueM >>= (\uniq -> return (mkSysLocalOrCoVar fs uniq ty))
326
327 -- | Create a user local 'Id'. These are local 'Id's (see "Var#globalvslocal") with a name and location that the user might recognize
328 mkUserLocal :: OccName -> Unique -> Type -> SrcSpan -> Id
329 mkUserLocal occ uniq ty loc = ASSERT( not (isCoercionType ty) )
330 mkLocalId (mkInternalName uniq occ loc) ty
331
332 -- | Like 'mkUserLocal', but checks if we have a coercion type
333 mkUserLocalOrCoVar :: OccName -> Unique -> Type -> SrcSpan -> Id
334 mkUserLocalOrCoVar occ uniq ty loc
335 = mkLocalIdOrCoVar (mkInternalName uniq occ loc) ty
336
337 {-
338 Make some local @Ids@ for a template @CoreExpr@. These have bogus
339 @Uniques@, but that's OK because the templates are supposed to be
340 instantiated before use.
341 -}
342
343 -- | Workers get local names. "CoreTidy" will externalise these if necessary
344 mkWorkerId :: Unique -> Id -> Type -> Id
345 mkWorkerId uniq unwrkr ty
346 = mkLocalIdOrCoVar (mkDerivedInternalName mkWorkerOcc uniq (getName unwrkr)) ty
347
348 -- | Create a /template local/: a family of system local 'Id's in bijection with @Int@s, typically used in unfoldings
349 mkTemplateLocal :: Int -> Type -> Id
350 mkTemplateLocal i ty = mkSysLocalOrCoVar (fsLit "v") (mkBuiltinUnique i) ty
351
352 -- | Create a template local for a series of types
353 mkTemplateLocals :: [Type] -> [Id]
354 mkTemplateLocals = mkTemplateLocalsNum 1
355
356 -- | Create a template local for a series of type, but start from a specified template local
357 mkTemplateLocalsNum :: Int -> [Type] -> [Id]
358 mkTemplateLocalsNum n tys = zipWith mkTemplateLocal [n..] tys
359
360 {- Note [Exported LocalIds]
361 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
362 We use mkExportedLocalId for things like
363 - Dictionary functions (DFunId)
364 - Wrapper and matcher Ids for pattern synonyms
365 - Default methods for classes
366 - Pattern-synonym matcher and builder Ids
367 - etc
368
369 They marked as "exported" in the sense that they should be kept alive
370 even if apparently unused in other bindings, and not dropped as dead
371 code by the occurrence analyser. (But "exported" here does not mean
372 "brought into lexical scope by an import declaration". Indeed these
373 things are always internal Ids that the user never sees.)
374
375 It's very important that they are *LocalIds*, not GlobalIds, for lots
376 of reasons:
377
378 * We want to treat them as free variables for the purpose of
379 dependency analysis (e.g. CoreFVs.exprFreeVars).
380
381 * Look them up in the current substitution when we come across
382 occurrences of them (in Subst.lookupIdSubst). Lacking this we
383 can get an out-of-date unfolding, which can in turn make the
384 simplifier go into an infinite loop (Trac #9857)
385
386 * Ensure that for dfuns that the specialiser does not float dict uses
387 above their defns, which would prevent good simplifications happening.
388
389 * The strictness analyser treats a occurrence of a GlobalId as
390 imported and assumes it contains strictness in its IdInfo, which
391 isn't true if the thing is bound in the same module as the
392 occurrence.
393
394 In CoreTidy we must make all these LocalIds into GlobalIds, so that in
395 importing modules (in --make mode) we treat them as properly global.
396 That is what is happening in, say tidy_insts in TidyPgm.
397
398 ************************************************************************
399 * *
400 \subsection{Special Ids}
401 * *
402 ************************************************************************
403 -}
404
405 -- | If the 'Id' is that for a record selector, extract the 'sel_tycon'. Panic otherwise.
406 recordSelectorTyCon :: Id -> RecSelParent
407 recordSelectorTyCon id
408 = case Var.idDetails id of
409 RecSelId { sel_tycon = parent } -> parent
410 _ -> panic "recordSelectorTyCon"
411
412
413 isRecordSelector :: Id -> Bool
414 isNaughtyRecordSelector :: Id -> Bool
415 isPatSynRecordSelector :: Id -> Bool
416 isDataConRecordSelector :: Id -> Bool
417 isPrimOpId :: Id -> Bool
418 isFCallId :: Id -> Bool
419 isDataConWorkId :: Id -> Bool
420 isDFunId :: Id -> Bool
421
422 isClassOpId_maybe :: Id -> Maybe Class
423 isPrimOpId_maybe :: Id -> Maybe PrimOp
424 isFCallId_maybe :: Id -> Maybe ForeignCall
425 isDataConWorkId_maybe :: Id -> Maybe DataCon
426
427 isRecordSelector id = case Var.idDetails id of
428 RecSelId {} -> True
429 _ -> False
430
431 isDataConRecordSelector id = case Var.idDetails id of
432 RecSelId {sel_tycon = RecSelData _} -> True
433 _ -> False
434
435 isPatSynRecordSelector id = case Var.idDetails id of
436 RecSelId {sel_tycon = RecSelPatSyn _} -> True
437 _ -> False
438
439 isNaughtyRecordSelector id = case Var.idDetails id of
440 RecSelId { sel_naughty = n } -> n
441 _ -> False
442
443 isClassOpId_maybe id = case Var.idDetails id of
444 ClassOpId cls -> Just cls
445 _other -> Nothing
446
447 isPrimOpId id = case Var.idDetails id of
448 PrimOpId _ -> True
449 _ -> False
450
451 isDFunId id = case Var.idDetails id of
452 DFunId {} -> True
453 _ -> False
454
455 isPrimOpId_maybe id = case Var.idDetails id of
456 PrimOpId op -> Just op
457 _ -> Nothing
458
459 isFCallId id = case Var.idDetails id of
460 FCallId _ -> True
461 _ -> False
462
463 isFCallId_maybe id = case Var.idDetails id of
464 FCallId call -> Just call
465 _ -> Nothing
466
467 isDataConWorkId id = case Var.idDetails id of
468 DataConWorkId _ -> True
469 _ -> False
470
471 isDataConWorkId_maybe id = case Var.idDetails id of
472 DataConWorkId con -> Just con
473 _ -> Nothing
474
475 isDataConId_maybe :: Id -> Maybe DataCon
476 isDataConId_maybe id = case Var.idDetails id of
477 DataConWorkId con -> Just con
478 DataConWrapId con -> Just con
479 _ -> Nothing
480
481 idDataCon :: Id -> DataCon
482 -- ^ Get from either the worker or the wrapper 'Id' to the 'DataCon'. Currently used only in the desugarer.
483 --
484 -- INVARIANT: @idDataCon (dataConWrapId d) = d@: remember, 'dataConWrapId' can return either the wrapper or the worker
485 idDataCon id = isDataConId_maybe id `orElse` pprPanic "idDataCon" (ppr id)
486
487 hasNoBinding :: Id -> Bool
488 -- ^ Returns @True@ of an 'Id' which may not have a
489 -- binding, even though it is defined in this module.
490
491 -- Data constructor workers used to be things of this kind, but
492 -- they aren't any more. Instead, we inject a binding for
493 -- them at the CorePrep stage.
494 -- EXCEPT: unboxed tuples, which definitely have no binding
495 hasNoBinding id = case Var.idDetails id of
496 PrimOpId _ -> True -- See Note [Primop wrappers]
497 FCallId _ -> True
498 DataConWorkId dc -> isUnboxedTupleCon dc || isUnboxedSumCon dc
499 _ -> False
500
501 isImplicitId :: Id -> Bool
502 -- ^ 'isImplicitId' tells whether an 'Id's info is implied by other
503 -- declarations, so we don't need to put its signature in an interface
504 -- file, even if it's mentioned in some other interface unfolding.
505 isImplicitId id
506 = case Var.idDetails id of
507 FCallId {} -> True
508 ClassOpId {} -> True
509 PrimOpId {} -> True
510 DataConWorkId {} -> True
511 DataConWrapId {} -> True
512 -- These are implied by their type or class decl;
513 -- remember that all type and class decls appear in the interface file.
514 -- The dfun id is not an implicit Id; it must *not* be omitted, because
515 -- it carries version info for the instance decl
516 _ -> False
517
518 idIsFrom :: Module -> Id -> Bool
519 idIsFrom mod id = nameIsLocalOrFrom mod (idName id)
520
521 {-
522 Note [Primop wrappers]
523 ~~~~~~~~~~~~~~~~~~~~~~
524 Currently hasNoBinding claims that PrimOpIds don't have a curried
525 function definition. But actually they do, in GHC.PrimopWrappers,
526 which is auto-generated from prelude/primops.txt.pp. So actually, hasNoBinding
527 could return 'False' for PrimOpIds.
528
529 But we'd need to add something in CoreToStg to swizzle any unsaturated
530 applications of GHC.Prim.plusInt# to GHC.PrimopWrappers.plusInt#.
531
532 Nota Bene: GHC.PrimopWrappers is needed *regardless*, because it's
533 used by GHCi, which does not implement primops direct at all.
534 -}
535
536 isDeadBinder :: Id -> Bool
537 isDeadBinder bndr | isId bndr = isDeadOcc (idOccInfo bndr)
538 | otherwise = False -- TyVars count as not dead
539
540 {-
541 ************************************************************************
542 * *
543 Evidence variables
544 * *
545 ************************************************************************
546 -}
547
548 isEvVar :: Var -> Bool
549 isEvVar var = isPredTy (varType var)
550
551 isDictId :: Id -> Bool
552 isDictId id = isDictTy (idType id)
553
554 {-
555 ************************************************************************
556 * *
557 Join variables
558 * *
559 ************************************************************************
560 -}
561
562 idJoinArity :: JoinId -> JoinArity
563 idJoinArity id = isJoinId_maybe id `orElse` pprPanic "idJoinArity" (ppr id)
564
565 asJoinId :: Id -> JoinArity -> JoinId
566 asJoinId id arity = WARN(not (isLocalId id),
567 text "global id being marked as join var:" <+> ppr id)
568 WARN(not (is_vanilla_or_join id),
569 ppr id <+> pprIdDetails (idDetails id))
570 id `setIdDetails` JoinId arity
571 where
572 is_vanilla_or_join id = case Var.idDetails id of
573 VanillaId -> True
574 JoinId {} -> True
575 _ -> False
576
577 zapJoinId :: Id -> Id
578 -- May be a regular id already
579 zapJoinId jid | isJoinId jid = zapIdTailCallInfo (jid `setIdDetails` VanillaId)
580 -- Core Lint may complain if still marked
581 -- as AlwaysTailCalled
582 | otherwise = jid
583
584 asJoinId_maybe :: Id -> Maybe JoinArity -> Id
585 asJoinId_maybe id (Just arity) = asJoinId id arity
586 asJoinId_maybe id Nothing = zapJoinId id
587
588 {-
589 ************************************************************************
590 * *
591 \subsection{IdInfo stuff}
592 * *
593 ************************************************************************
594 -}
595
596 ---------------------------------
597 -- ARITY
598 idArity :: Id -> Arity
599 idArity id = arityInfo (idInfo id)
600
601 setIdArity :: Id -> Arity -> Id
602 setIdArity id arity = modifyIdInfo (`setArityInfo` arity) id
603
604 idCallArity :: Id -> Arity
605 idCallArity id = callArityInfo (idInfo id)
606
607 setIdCallArity :: Id -> Arity -> Id
608 setIdCallArity id arity = modifyIdInfo (`setCallArityInfo` arity) id
609
610 idFunRepArity :: Id -> RepArity
611 idFunRepArity x = countFunRepArgs (idArity x) (idType x)
612
613 -- | Returns true if an application to n args would diverge
614 isBottomingId :: Id -> Bool
615 isBottomingId id = isBottomingSig (idStrictness id)
616
617 idStrictness :: Id -> StrictSig
618 idStrictness id = strictnessInfo (idInfo id)
619
620 setIdStrictness :: Id -> StrictSig -> Id
621 setIdStrictness id sig = modifyIdInfo (`setStrictnessInfo` sig) id
622
623 zapIdStrictness :: Id -> Id
624 zapIdStrictness id = modifyIdInfo (`setStrictnessInfo` nopSig) id
625
626 -- | This predicate says whether the 'Id' has a strict demand placed on it or
627 -- has a type such that it can always be evaluated strictly (i.e an
628 -- unlifted type, as of GHC 7.6). We need to
629 -- check separately whether the 'Id' has a so-called \"strict type\" because if
630 -- the demand for the given @id@ hasn't been computed yet but @id@ has a strict
631 -- type, we still want @isStrictId id@ to be @True@.
632 isStrictId :: Id -> Bool
633 isStrictId id
634 = ASSERT2( isId id, text "isStrictId: not an id: " <+> ppr id )
635 not (isJoinId id) && (
636 (isStrictType (idType id)) ||
637 -- Take the best of both strictnesses - old and new
638 (isStrictDmd (idDemandInfo id))
639 )
640
641 ---------------------------------
642 -- UNFOLDING
643 idUnfolding :: Id -> Unfolding
644 -- Do not expose the unfolding of a loop breaker!
645 idUnfolding id
646 | isStrongLoopBreaker (occInfo info) = NoUnfolding
647 | otherwise = unfoldingInfo info
648 where
649 info = idInfo id
650
651 realIdUnfolding :: Id -> Unfolding
652 -- Expose the unfolding if there is one, including for loop breakers
653 realIdUnfolding id = unfoldingInfo (idInfo id)
654
655 setIdUnfolding :: Id -> Unfolding -> Id
656 setIdUnfolding id unfolding = modifyIdInfo (`setUnfoldingInfo` unfolding) id
657
658 idDemandInfo :: Id -> Demand
659 idDemandInfo id = demandInfo (idInfo id)
660
661 setIdDemandInfo :: Id -> Demand -> Id
662 setIdDemandInfo id dmd = modifyIdInfo (`setDemandInfo` dmd) id
663
664 setCaseBndrEvald :: StrictnessMark -> Id -> Id
665 -- Used for variables bound by a case expressions, both the case-binder
666 -- itself, and any pattern-bound variables that are argument of a
667 -- strict constructor. It just marks the variable as already-evaluated,
668 -- so that (for example) a subsequent 'seq' can be dropped
669 setCaseBndrEvald str id
670 | isMarkedStrict str = id `setIdUnfolding` evaldUnfolding
671 | otherwise = id
672
673 ---------------------------------
674 -- SPECIALISATION
675
676 -- See Note [Specialisations and RULES in IdInfo] in IdInfo.hs
677
678 idSpecialisation :: Id -> RuleInfo
679 idSpecialisation id = ruleInfo (idInfo id)
680
681 idCoreRules :: Id -> [CoreRule]
682 idCoreRules id = ruleInfoRules (idSpecialisation id)
683
684 idHasRules :: Id -> Bool
685 idHasRules id = not (isEmptyRuleInfo (idSpecialisation id))
686
687 setIdSpecialisation :: Id -> RuleInfo -> Id
688 setIdSpecialisation id spec_info = modifyIdInfo (`setRuleInfo` spec_info) id
689
690 ---------------------------------
691 -- CAF INFO
692 idCafInfo :: Id -> CafInfo
693 idCafInfo id = cafInfo (idInfo id)
694
695 setIdCafInfo :: Id -> CafInfo -> Id
696 setIdCafInfo id caf_info = modifyIdInfo (`setCafInfo` caf_info) id
697
698 ---------------------------------
699 -- Occcurrence INFO
700 idOccInfo :: Id -> OccInfo
701 idOccInfo id = occInfo (idInfo id)
702
703 setIdOccInfo :: Id -> OccInfo -> Id
704 setIdOccInfo id occ_info = modifyIdInfo (`setOccInfo` occ_info) id
705
706 zapIdOccInfo :: Id -> Id
707 zapIdOccInfo b = b `setIdOccInfo` noOccInfo
708
709 {-
710 ---------------------------------
711 -- INLINING
712 The inline pragma tells us to be very keen to inline this Id, but it's still
713 OK not to if optimisation is switched off.
714 -}
715
716 idInlinePragma :: Id -> InlinePragma
717 idInlinePragma id = inlinePragInfo (idInfo id)
718
719 setInlinePragma :: Id -> InlinePragma -> Id
720 setInlinePragma id prag = modifyIdInfo (`setInlinePragInfo` prag) id
721
722 modifyInlinePragma :: Id -> (InlinePragma -> InlinePragma) -> Id
723 modifyInlinePragma id fn = modifyIdInfo (\info -> info `setInlinePragInfo` (fn (inlinePragInfo info))) id
724
725 idInlineActivation :: Id -> Activation
726 idInlineActivation id = inlinePragmaActivation (idInlinePragma id)
727
728 setInlineActivation :: Id -> Activation -> Id
729 setInlineActivation id act = modifyInlinePragma id (\prag -> setInlinePragmaActivation prag act)
730
731 idRuleMatchInfo :: Id -> RuleMatchInfo
732 idRuleMatchInfo id = inlinePragmaRuleMatchInfo (idInlinePragma id)
733
734 isConLikeId :: Id -> Bool
735 isConLikeId id = isDataConWorkId id || isConLike (idRuleMatchInfo id)
736
737 {-
738 ---------------------------------
739 -- ONE-SHOT LAMBDAS
740 -}
741
742 idOneShotInfo :: Id -> OneShotInfo
743 idOneShotInfo id = oneShotInfo (idInfo id)
744
745 -- | Like 'idOneShotInfo', but taking the Horrible State Hack in to account
746 -- See Note [The state-transformer hack] in CoreArity
747 idStateHackOneShotInfo :: Id -> OneShotInfo
748 idStateHackOneShotInfo id
749 | isStateHackType (idType id) = stateHackOneShot
750 | otherwise = idOneShotInfo id
751
752 -- | Returns whether the lambda associated with the 'Id' is certainly applied at most once
753 -- This one is the "business end", called externally.
754 -- It works on type variables as well as Ids, returning True
755 -- Its main purpose is to encapsulate the Horrible State Hack
756 -- See Note [The state-transformer hack] in CoreArity
757 isOneShotBndr :: Var -> Bool
758 isOneShotBndr var
759 | isTyVar var = True
760 | OneShotLam <- idStateHackOneShotInfo var = True
761 | otherwise = False
762
763 -- | Should we apply the state hack to values of this 'Type'?
764 stateHackOneShot :: OneShotInfo
765 stateHackOneShot = OneShotLam
766
767 typeOneShot :: Type -> OneShotInfo
768 typeOneShot ty
769 | isStateHackType ty = stateHackOneShot
770 | otherwise = NoOneShotInfo
771
772 isStateHackType :: Type -> Bool
773 isStateHackType ty
774 | hasNoStateHack unsafeGlobalDynFlags
775 = False
776 | otherwise
777 = case tyConAppTyCon_maybe ty of
778 Just tycon -> tycon == statePrimTyCon
779 _ -> False
780 -- This is a gross hack. It claims that
781 -- every function over realWorldStatePrimTy is a one-shot
782 -- function. This is pretty true in practice, and makes a big
783 -- difference. For example, consider
784 -- a `thenST` \ r -> ...E...
785 -- The early full laziness pass, if it doesn't know that r is one-shot
786 -- will pull out E (let's say it doesn't mention r) to give
787 -- let lvl = E in a `thenST` \ r -> ...lvl...
788 -- When `thenST` gets inlined, we end up with
789 -- let lvl = E in \s -> case a s of (r, s') -> ...lvl...
790 -- and we don't re-inline E.
791 --
792 -- It would be better to spot that r was one-shot to start with, but
793 -- I don't want to rely on that.
794 --
795 -- Another good example is in fill_in in PrelPack.hs. We should be able to
796 -- spot that fill_in has arity 2 (and when Keith is done, we will) but we can't yet.
797
798 isProbablyOneShotLambda :: Id -> Bool
799 isProbablyOneShotLambda id = case idStateHackOneShotInfo id of
800 OneShotLam -> True
801 NoOneShotInfo -> False
802
803 setOneShotLambda :: Id -> Id
804 setOneShotLambda id = modifyIdInfo (`setOneShotInfo` OneShotLam) id
805
806 clearOneShotLambda :: Id -> Id
807 clearOneShotLambda id = modifyIdInfo (`setOneShotInfo` NoOneShotInfo) id
808
809 setIdOneShotInfo :: Id -> OneShotInfo -> Id
810 setIdOneShotInfo id one_shot = modifyIdInfo (`setOneShotInfo` one_shot) id
811
812 updOneShotInfo :: Id -> OneShotInfo -> Id
813 -- Combine the info in the Id with new info
814 updOneShotInfo id one_shot
815 | do_upd = setIdOneShotInfo id one_shot
816 | otherwise = id
817 where
818 do_upd = case (idOneShotInfo id, one_shot) of
819 (NoOneShotInfo, _) -> True
820 (OneShotLam, _) -> False
821
822 -- The OneShotLambda functions simply fiddle with the IdInfo flag
823 -- But watch out: this may change the type of something else
824 -- f = \x -> e
825 -- If we change the one-shot-ness of x, f's type changes
826
827 zapInfo :: (IdInfo -> Maybe IdInfo) -> Id -> Id
828 zapInfo zapper id = maybeModifyIdInfo (zapper (idInfo id)) id
829
830 zapLamIdInfo :: Id -> Id
831 zapLamIdInfo = zapInfo zapLamInfo
832
833 zapFragileIdInfo :: Id -> Id
834 zapFragileIdInfo = zapInfo zapFragileInfo
835
836 zapIdDemandInfo :: Id -> Id
837 zapIdDemandInfo = zapInfo zapDemandInfo
838
839 zapIdUsageInfo :: Id -> Id
840 zapIdUsageInfo = zapInfo zapUsageInfo
841
842 zapIdUsageEnvInfo :: Id -> Id
843 zapIdUsageEnvInfo = zapInfo zapUsageEnvInfo
844
845 zapIdUsedOnceInfo :: Id -> Id
846 zapIdUsedOnceInfo = zapInfo zapUsedOnceInfo
847
848 zapIdTailCallInfo :: Id -> Id
849 zapIdTailCallInfo = zapInfo zapTailCallInfo
850
851 {-
852 Note [transferPolyIdInfo]
853 ~~~~~~~~~~~~~~~~~~~~~~~~~
854 This transfer is used in two places:
855 FloatOut (long-distance let-floating)
856 SimplUtils.abstractFloats (short-distance let-floating)
857
858 Consider the short-distance let-floating:
859
860 f = /\a. let g = rhs in ...
861
862 Then if we float thus
863
864 g' = /\a. rhs
865 f = /\a. ...[g' a/g]....
866
867 we *do not* want to lose g's
868 * strictness information
869 * arity
870 * inline pragma (though that is bit more debatable)
871 * occurrence info
872
873 Mostly this is just an optimisation, but it's *vital* to
874 transfer the occurrence info. Consider
875
876 NonRec { f = /\a. let Rec { g* = ..g.. } in ... }
877
878 where the '*' means 'LoopBreaker'. Then if we float we must get
879
880 Rec { g'* = /\a. ...(g' a)... }
881 NonRec { f = /\a. ...[g' a/g]....}
882
883 where g' is also marked as LoopBreaker. If not, terrible things
884 can happen if we re-simplify the binding (and the Simplifier does
885 sometimes simplify a term twice); see Trac #4345.
886
887 It's not so simple to retain
888 * worker info
889 * rules
890 so we simply discard those. Sooner or later this may bite us.
891
892 If we abstract wrt one or more *value* binders, we must modify the
893 arity and strictness info before transferring it. E.g.
894 f = \x. e
895 -->
896 g' = \y. \x. e
897 + substitute (g' y) for g
898 Notice that g' has an arity one more than the original g
899 -}
900
901 transferPolyIdInfo :: Id -- Original Id
902 -> [Var] -- Abstract wrt these variables
903 -> Id -- New Id
904 -> Id
905 transferPolyIdInfo old_id abstract_wrt new_id
906 = modifyIdInfo transfer new_id
907 where
908 arity_increase = count isId abstract_wrt -- Arity increases by the
909 -- number of value binders
910
911 old_info = idInfo old_id
912 old_arity = arityInfo old_info
913 old_inline_prag = inlinePragInfo old_info
914 old_occ_info = occInfo old_info
915 new_arity = old_arity + arity_increase
916 new_occ_info = zapOccTailCallInfo old_occ_info
917
918 old_strictness = strictnessInfo old_info
919 new_strictness = increaseStrictSigArity arity_increase old_strictness
920
921 transfer new_info = new_info `setArityInfo` new_arity
922 `setInlinePragInfo` old_inline_prag
923 `setOccInfo` new_occ_info
924 `setStrictnessInfo` new_strictness
925
926 isNeverLevPolyId :: Id -> Bool
927 isNeverLevPolyId = isNeverLevPolyIdInfo . idInfo