2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 \section[Id]{@Ids@: Value and constructor identifiers}
10 -- GHC uses several kinds of name internally:
12 -- * 'OccName.OccName': see "OccName#name_types"
14 -- * 'RdrName.RdrName': see "RdrName#name_types"
16 -- * 'Name.Name': see "Name#name_types"
18 -- * 'Id.Id' represents names that not only have a 'Name.Name' but also a 'TypeRep.Type' and some additional
19 -- details (a 'IdInfo.IdInfo' and one of 'Var.LocalIdDetails' or 'IdInfo.GlobalIdDetails') that
20 -- are added, modified and inspected by various compiler passes. These 'Var.Var' names may either
21 -- be global or local, see "Var#globalvslocal"
23 -- * 'Var.Var': see "Var#name_types"
28 -- ** Simple construction
29 mkGlobalId, mkVanillaGlobal, mkVanillaGlobalWithInfo,
30 mkLocalId, mkLocalIdWithInfo, mkExportedLocalId,
31 mkSysLocal, mkSysLocalM, mkUserLocal, mkUserLocalM,
32 mkTemplateLocals, mkTemplateLocalsNum, mkTemplateLocal,
33 mkWorkerId, mkWiredInIdName,
35 -- ** Taking an Id apart
36 idName, idType, idUnique, idInfo, idDetails,
38 recordSelectorFieldLabel,
41 setIdName, setIdUnique, Id.setIdType,
42 setIdExported, setIdNotExported,
43 globaliseId, localiseId,
44 setIdInfo, lazySetIdInfo, modifyIdInfo, maybeModifyIdInfo,
45 zapLamIdInfo, zapDemandIdInfo, zapFragileIdInfo, transferPolyIdInfo,
48 -- ** Predicates on Ids
49 isImplicitId, isDeadBinder, isDictId, isStrictId,
50 isExportedId, isLocalId, isGlobalId,
51 isRecordSelector, isNaughtyRecordSelector,
52 isClassOpId_maybe, isDFunId,
53 isPrimOpId, isPrimOpId_maybe,
54 isFCallId, isFCallId_maybe,
55 isDataConWorkId, isDataConWorkId_maybe, isDataConId_maybe, idDataCon,
56 isConLikeId, isBottomingId, idIsFrom,
57 isTickBoxOp, isTickBoxOp_maybe,
60 -- ** Inline pragma stuff
61 idInlinePragma, setInlinePragma, modifyInlinePragma,
62 idInlineActivation, setInlineActivation, idRuleMatchInfo,
64 -- ** One-shot lambdas
65 isOneShotBndr, isOneShotLambda, isStateHackType,
66 setOneShotLambda, clearOneShotLambda,
68 -- ** Reading 'IdInfo' fields
70 idDemandInfo, idDemandInfo_maybe,
71 idStrictness, idStrictness_maybe,
72 idUnfolding, realIdUnfolding,
73 idSpecialisation, idCoreRules, idHasRules,
78 -- ** Writing 'IdInfo' fields
82 setIdStrictness, zapIdStrictness,
85 setIdOccInfo, zapIdOccInfo,
89 #include "HsVersions.h"
91 import CoreSyn ( CoreRule, Unfolding( NoUnfolding ) )
96 -- Imported and re-exported
97 import Var( Var, Id, DictId,
98 idInfo, idDetails, globaliseId,
99 isId, isLocalId, isGlobalId, isExportedId )
121 -- infixl so you can say (id `set` a `set` b)
122 infixl 1 `setIdUnfolding`,
127 `setIdSpecialisation`,
129 `setInlineActivation`,
133 %************************************************************************
135 \subsection{Basic Id manipulation}
137 %************************************************************************
143 idUnique :: Id -> Unique
144 idUnique = Var.varUnique
149 idPrimRep :: Id -> PrimRep
150 idPrimRep id = typePrimRep (idType id)
152 setIdName :: Id -> Name -> Id
153 setIdName = Var.setVarName
155 setIdUnique :: Id -> Unique -> Id
156 setIdUnique = Var.setVarUnique
158 -- | Not only does this set the 'Id' 'Type', it also evaluates the type to try and
159 -- reduce space usage
160 setIdType :: Id -> Type -> Id
161 setIdType id ty = seqType ty `seq` Var.setVarType id ty
163 setIdExported :: Id -> Id
164 setIdExported = Var.setIdExported
166 setIdNotExported :: Id -> Id
167 setIdNotExported = Var.setIdNotExported
169 localiseId :: Id -> Id
170 -- Make an with the same unique and type as the
171 -- incoming Id, but with an *Internal* Name and *LocalId* flavour
173 | isLocalId id && isInternalName name
176 = mkLocalIdWithInfo (localiseName name) (idType id) (idInfo id)
180 lazySetIdInfo :: Id -> IdInfo -> Id
181 lazySetIdInfo = Var.lazySetIdInfo
183 setIdInfo :: Id -> IdInfo -> Id
184 setIdInfo id info = seqIdInfo info `seq` (lazySetIdInfo id info)
185 -- Try to avoid spack leaks by seq'ing
187 modifyIdInfo :: (IdInfo -> IdInfo) -> Id -> Id
188 modifyIdInfo fn id = setIdInfo id (fn (idInfo id))
190 -- maybeModifyIdInfo tries to avoid unnecesary thrashing
191 maybeModifyIdInfo :: Maybe IdInfo -> Id -> Id
192 maybeModifyIdInfo (Just new_info) id = lazySetIdInfo id new_info
193 maybeModifyIdInfo Nothing id = id
196 %************************************************************************
198 \subsection{Simple Id construction}
200 %************************************************************************
202 Absolutely all Ids are made by mkId. It is just like Var.mkId,
203 but in addition it pins free-tyvar-info onto the Id's type,
204 where it can easily be found.
206 Note [Free type variables]
207 ~~~~~~~~~~~~~~~~~~~~~~~~~~
208 At one time we cached the free type variables of the type of an Id
209 at the root of the type in a TyNote. The idea was to avoid repeating
210 the free-type-variable calculation. But it turned out to slow down
211 the compiler overall. I don't quite know why; perhaps finding free
212 type variables of an Id isn't all that common whereas applying a
213 substitution (which changes the free type variables) is more common.
214 Anyway, we removed it in March 2008.
217 -- | For an explanation of global vs. local 'Id's, see "Var#globalvslocal"
218 mkGlobalId :: IdDetails -> Name -> Type -> IdInfo -> Id
219 mkGlobalId = Var.mkGlobalVar
221 -- | Make a global 'Id' without any extra information at all
222 mkVanillaGlobal :: Name -> Type -> Id
223 mkVanillaGlobal name ty = mkVanillaGlobalWithInfo name ty vanillaIdInfo
225 -- | Make a global 'Id' with no global information but some generic 'IdInfo'
226 mkVanillaGlobalWithInfo :: Name -> Type -> IdInfo -> Id
227 mkVanillaGlobalWithInfo = mkGlobalId VanillaId
230 -- | For an explanation of global vs. local 'Id's, see "Var#globalvslocal"
231 mkLocalId :: Name -> Type -> Id
232 mkLocalId name ty = mkLocalIdWithInfo name ty vanillaIdInfo
234 mkLocalIdWithInfo :: Name -> Type -> IdInfo -> Id
235 mkLocalIdWithInfo name ty info = Var.mkLocalVar VanillaId name ty info
236 -- Note [Free type variables]
238 -- | Create a local 'Id' that is marked as exported.
239 -- This prevents things attached to it from being removed as dead code.
240 mkExportedLocalId :: Name -> Type -> Id
241 mkExportedLocalId name ty = Var.mkExportedLocalVar VanillaId name ty vanillaIdInfo
242 -- Note [Free type variables]
245 -- | Create a system local 'Id'. These are local 'Id's (see "Var#globalvslocal")
246 -- that are created by the compiler out of thin air
247 mkSysLocal :: FastString -> Unique -> Type -> Id
248 mkSysLocal fs uniq ty = mkLocalId (mkSystemVarName uniq fs) ty
250 mkSysLocalM :: MonadUnique m => FastString -> Type -> m Id
251 mkSysLocalM fs ty = getUniqueM >>= (\uniq -> return (mkSysLocal fs uniq ty))
254 -- | Create a user local 'Id'. These are local 'Id's (see "Var#globalvslocal") with a name and location that the user might recognize
255 mkUserLocal :: OccName -> Unique -> Type -> SrcSpan -> Id
256 mkUserLocal occ uniq ty loc = mkLocalId (mkInternalName uniq occ loc) ty
258 mkUserLocalM :: MonadUnique m => OccName -> Type -> SrcSpan -> m Id
259 mkUserLocalM occ ty loc = getUniqueM >>= (\uniq -> return (mkUserLocal occ uniq ty loc))
261 mkWiredInIdName :: Module -> FastString -> Unique -> Id -> Name
262 mkWiredInIdName mod fs uniq id
263 = mkWiredInName mod (mkOccNameFS varName fs) uniq (AnId id) UserSyntax
266 Make some local @Ids@ for a template @CoreExpr@. These have bogus
267 @Uniques@, but that's OK because the templates are supposed to be
268 instantiated before use.
271 -- | Workers get local names. "CoreTidy" will externalise these if necessary
272 mkWorkerId :: Unique -> Id -> Type -> Id
273 mkWorkerId uniq unwrkr ty
274 = mkLocalId (mkDerivedInternalName mkWorkerOcc uniq (getName unwrkr)) ty
276 -- | Create a /template local/: a family of system local 'Id's in bijection with @Int@s, typically used in unfoldings
277 mkTemplateLocal :: Int -> Type -> Id
278 mkTemplateLocal i ty = mkSysLocal (fsLit "tpl") (mkBuiltinUnique i) ty
280 -- | Create a template local for a series of types
281 mkTemplateLocals :: [Type] -> [Id]
282 mkTemplateLocals = mkTemplateLocalsNum 1
284 -- | Create a template local for a series of type, but start from a specified template local
285 mkTemplateLocalsNum :: Int -> [Type] -> [Id]
286 mkTemplateLocalsNum n tys = zipWith mkTemplateLocal [n..] tys
290 %************************************************************************
292 \subsection{Special Ids}
294 %************************************************************************
297 -- | If the 'Id' is that for a record selector, extract the 'sel_tycon' and label. Panic otherwise
298 recordSelectorFieldLabel :: Id -> (TyCon, FieldLabel)
299 recordSelectorFieldLabel id
300 = case Var.idDetails id of
301 RecSelId { sel_tycon = tycon } -> (tycon, idName id)
302 _ -> panic "recordSelectorFieldLabel"
304 isRecordSelector :: Id -> Bool
305 isNaughtyRecordSelector :: Id -> Bool
306 isPrimOpId :: Id -> Bool
307 isFCallId :: Id -> Bool
308 isDataConWorkId :: Id -> Bool
309 isDFunId :: Id -> Bool
311 isClassOpId_maybe :: Id -> Maybe Class
312 isPrimOpId_maybe :: Id -> Maybe PrimOp
313 isFCallId_maybe :: Id -> Maybe ForeignCall
314 isDataConWorkId_maybe :: Id -> Maybe DataCon
316 isRecordSelector id = case Var.idDetails id of
320 isNaughtyRecordSelector id = case Var.idDetails id of
321 RecSelId { sel_naughty = n } -> n
324 isClassOpId_maybe id = case Var.idDetails id of
325 ClassOpId cls -> Just cls
328 isPrimOpId id = case Var.idDetails id of
332 isDFunId id = case Var.idDetails id of
336 isPrimOpId_maybe id = case Var.idDetails id of
337 PrimOpId op -> Just op
340 isFCallId id = case Var.idDetails id of
344 isFCallId_maybe id = case Var.idDetails id of
345 FCallId call -> Just call
348 isDataConWorkId id = case Var.idDetails id of
349 DataConWorkId _ -> True
352 isDataConWorkId_maybe id = case Var.idDetails id of
353 DataConWorkId con -> Just con
356 isDataConId_maybe :: Id -> Maybe DataCon
357 isDataConId_maybe id = case Var.idDetails id of
358 DataConWorkId con -> Just con
359 DataConWrapId con -> Just con
362 idDataCon :: Id -> DataCon
363 -- ^ Get from either the worker or the wrapper 'Id' to the 'DataCon'. Currently used only in the desugarer.
365 -- INVARIANT: @idDataCon (dataConWrapId d) = d@: remember, 'dataConWrapId' can return either the wrapper or the worker
366 idDataCon id = isDataConId_maybe id `orElse` pprPanic "idDataCon" (ppr id)
369 isDictId :: Id -> Bool
370 isDictId id = isDictTy (idType id)
372 hasNoBinding :: Id -> Bool
373 -- ^ Returns @True@ of an 'Id' which may not have a
374 -- binding, even though it is defined in this module.
376 -- Data constructor workers used to be things of this kind, but
377 -- they aren't any more. Instead, we inject a binding for
378 -- them at the CorePrep stage.
379 -- EXCEPT: unboxed tuples, which definitely have no binding
380 hasNoBinding id = case Var.idDetails id of
381 PrimOpId _ -> True -- See Note [Primop wrappers]
383 DataConWorkId dc -> isUnboxedTupleCon dc
386 isImplicitId :: Id -> Bool
387 -- ^ 'isImplicitId' tells whether an 'Id's info is implied by other
388 -- declarations, so we don't need to put its signature in an interface
389 -- file, even if it's mentioned in some other interface unfolding.
391 = case Var.idDetails id of
395 DataConWorkId {} -> True
396 DataConWrapId {} -> True
397 -- These are are implied by their type or class decl;
398 -- remember that all type and class decls appear in the interface file.
399 -- The dfun id is not an implicit Id; it must *not* be omitted, because
400 -- it carries version info for the instance decl
403 idIsFrom :: Module -> Id -> Bool
404 idIsFrom mod id = nameIsLocalOrFrom mod (idName id)
407 Note [Primop wrappers]
408 ~~~~~~~~~~~~~~~~~~~~~~
409 Currently hasNoBinding claims that PrimOpIds don't have a curried
410 function definition. But actually they do, in GHC.PrimopWrappers,
411 which is auto-generated from prelude/primops.txt.pp. So actually, hasNoBinding
412 could return 'False' for PrimOpIds.
414 But we'd need to add something in CoreToStg to swizzle any unsaturated
415 applications of GHC.Prim.plusInt# to GHC.PrimopWrappers.plusInt#.
417 Nota Bene: GHC.PrimopWrappers is needed *regardless*, because it's
418 used by GHCi, which does not implement primops direct at all.
423 isDeadBinder :: Id -> Bool
424 isDeadBinder bndr | isId bndr = isDeadOcc (idOccInfo bndr)
425 | otherwise = False -- TyVars count as not dead
429 isTickBoxOp :: Id -> Bool
431 case Var.idDetails id of
432 TickBoxOpId _ -> True
435 isTickBoxOp_maybe :: Id -> Maybe TickBoxOp
436 isTickBoxOp_maybe id =
437 case Var.idDetails id of
438 TickBoxOpId tick -> Just tick
442 %************************************************************************
444 \subsection{IdInfo stuff}
446 %************************************************************************
449 ---------------------------------
451 idArity :: Id -> Arity
452 idArity id = arityInfo (idInfo id)
454 setIdArity :: Id -> Arity -> Id
455 setIdArity id arity = modifyIdInfo (`setArityInfo` arity) id
457 -- | Returns true if an application to n args would diverge
458 isBottomingId :: Id -> Bool
459 isBottomingId id = isBottomingSig (idStrictness id)
461 idStrictness_maybe :: Id -> Maybe StrictSig
462 idStrictness :: Id -> StrictSig
464 idStrictness_maybe id = strictnessInfo (idInfo id)
465 idStrictness id = idStrictness_maybe id `orElse` topSig
467 setIdStrictness :: Id -> StrictSig -> Id
468 setIdStrictness id sig = modifyIdInfo (`setStrictnessInfo` Just sig) id
470 zapIdStrictness :: Id -> Id
471 zapIdStrictness id = modifyIdInfo (`setStrictnessInfo` Nothing) id
473 -- | This predicate says whether the 'Id' has a strict demand placed on it or
474 -- has a type such that it can always be evaluated strictly (e.g., an
475 -- unlifted type, but see the comment for 'isStrictType'). We need to
476 -- check separately whether the 'Id' has a so-called \"strict type\" because if
477 -- the demand for the given @id@ hasn't been computed yet but @id@ has a strict
478 -- type, we still want @isStrictId id@ to be @True@.
479 isStrictId :: Id -> Bool
481 = ASSERT2( isId id, text "isStrictId: not an id: " <+> ppr id )
482 (isStrictDmd (idDemandInfo id)) ||
483 (isStrictType (idType id))
485 ---------------------------------
487 idUnfolding :: Id -> Unfolding
488 -- Do not expose the unfolding of a loop breaker!
490 | isNonRuleLoopBreaker (occInfo info) = NoUnfolding
491 | otherwise = unfoldingInfo info
495 realIdUnfolding :: Id -> Unfolding
496 -- Expose the unfolding if there is one, including for loop breakers
497 realIdUnfolding id = unfoldingInfo (idInfo id)
499 setIdUnfolding :: Id -> Unfolding -> Id
500 setIdUnfolding id unfolding = modifyIdInfo (`setUnfoldingInfo` unfolding) id
502 idDemandInfo_maybe :: Id -> Maybe Demand
503 idDemandInfo :: Id -> Demand
505 idDemandInfo_maybe id = demandInfo (idInfo id)
506 idDemandInfo id = demandInfo (idInfo id) `orElse` topDmd
508 setIdDemandInfo :: Id -> Demand -> Id
509 setIdDemandInfo id dmd = modifyIdInfo (`setDemandInfo` Just dmd) id
511 ---------------------------------
514 -- See Note [Specialisations and RULES in IdInfo] in IdInfo.lhs
516 idSpecialisation :: Id -> SpecInfo
517 idSpecialisation id = specInfo (idInfo id)
519 idCoreRules :: Id -> [CoreRule]
520 idCoreRules id = specInfoRules (idSpecialisation id)
522 idHasRules :: Id -> Bool
523 idHasRules id = not (isEmptySpecInfo (idSpecialisation id))
525 setIdSpecialisation :: Id -> SpecInfo -> Id
526 setIdSpecialisation id spec_info = modifyIdInfo (`setSpecInfo` spec_info) id
528 ---------------------------------
530 idCafInfo :: Id -> CafInfo
531 idCafInfo id = cafInfo (idInfo id)
533 setIdCafInfo :: Id -> CafInfo -> Id
534 setIdCafInfo id caf_info = modifyIdInfo (`setCafInfo` caf_info) id
536 ---------------------------------
538 idOccInfo :: Id -> OccInfo
539 idOccInfo id = occInfo (idInfo id)
541 setIdOccInfo :: Id -> OccInfo -> Id
542 setIdOccInfo id occ_info = modifyIdInfo (`setOccInfo` occ_info) id
544 zapIdOccInfo :: Id -> Id
545 zapIdOccInfo b = b `setIdOccInfo` NoOccInfo
549 ---------------------------------
551 The inline pragma tells us to be very keen to inline this Id, but it's still
552 OK not to if optimisation is switched off.
555 idInlinePragma :: Id -> InlinePragma
556 idInlinePragma id = inlinePragInfo (idInfo id)
558 setInlinePragma :: Id -> InlinePragma -> Id
559 setInlinePragma id prag = modifyIdInfo (`setInlinePragInfo` prag) id
561 modifyInlinePragma :: Id -> (InlinePragma -> InlinePragma) -> Id
562 modifyInlinePragma id fn = modifyIdInfo (\info -> info `setInlinePragInfo` (fn (inlinePragInfo info))) id
564 idInlineActivation :: Id -> Activation
565 idInlineActivation id = inlinePragmaActivation (idInlinePragma id)
567 setInlineActivation :: Id -> Activation -> Id
568 setInlineActivation id act = modifyInlinePragma id (\prag -> setInlinePragmaActivation prag act)
570 idRuleMatchInfo :: Id -> RuleMatchInfo
571 idRuleMatchInfo id = inlinePragmaRuleMatchInfo (idInlinePragma id)
573 isConLikeId :: Id -> Bool
574 isConLikeId id = isDataConWorkId id || isConLike (idRuleMatchInfo id)
578 ---------------------------------
581 idLBVarInfo :: Id -> LBVarInfo
582 idLBVarInfo id = lbvarInfo (idInfo id)
584 -- | Returns whether the lambda associated with the 'Id' is certainly applied at most once
585 -- OR we are applying the \"state hack\" which makes it appear as if theis is the case for
586 -- lambdas used in @IO@. You should prefer using this over 'isOneShotLambda'
587 isOneShotBndr :: Id -> Bool
588 -- This one is the "business end", called externally.
589 -- Its main purpose is to encapsulate the Horrible State Hack
590 isOneShotBndr id = isOneShotLambda id || isStateHackType (idType id)
592 -- | Should we apply the state hack to values of this 'Type'?
593 isStateHackType :: Type -> Bool
598 = case splitTyConApp_maybe ty of
599 Just (tycon,_) -> tycon == statePrimTyCon
601 -- This is a gross hack. It claims that
602 -- every function over realWorldStatePrimTy is a one-shot
603 -- function. This is pretty true in practice, and makes a big
604 -- difference. For example, consider
605 -- a `thenST` \ r -> ...E...
606 -- The early full laziness pass, if it doesn't know that r is one-shot
607 -- will pull out E (let's say it doesn't mention r) to give
608 -- let lvl = E in a `thenST` \ r -> ...lvl...
609 -- When `thenST` gets inlined, we end up with
610 -- let lvl = E in \s -> case a s of (r, s') -> ...lvl...
611 -- and we don't re-inline E.
613 -- It would be better to spot that r was one-shot to start with, but
614 -- I don't want to rely on that.
616 -- Another good example is in fill_in in PrelPack.lhs. We should be able to
617 -- spot that fill_in has arity 2 (and when Keith is done, we will) but we can't yet.
620 -- | Returns whether the lambda associated with the 'Id' is certainly applied at most once.
621 -- You probably want to use 'isOneShotBndr' instead
622 isOneShotLambda :: Id -> Bool
623 isOneShotLambda id = case idLBVarInfo id of
624 IsOneShotLambda -> True
627 setOneShotLambda :: Id -> Id
628 setOneShotLambda id = modifyIdInfo (`setLBVarInfo` IsOneShotLambda) id
630 clearOneShotLambda :: Id -> Id
631 clearOneShotLambda id
632 | isOneShotLambda id = modifyIdInfo (`setLBVarInfo` NoLBVarInfo) id
635 -- The OneShotLambda functions simply fiddle with the IdInfo flag
636 -- But watch out: this may change the type of something else
638 -- If we change the one-shot-ness of x, f's type changes
642 zapInfo :: (IdInfo -> Maybe IdInfo) -> Id -> Id
643 zapInfo zapper id = maybeModifyIdInfo (zapper (idInfo id)) id
645 zapLamIdInfo :: Id -> Id
646 zapLamIdInfo = zapInfo zapLamInfo
648 zapDemandIdInfo :: Id -> Id
649 zapDemandIdInfo = zapInfo zapDemandInfo
651 zapFragileIdInfo :: Id -> Id
652 zapFragileIdInfo = zapInfo zapFragileInfo
655 Note [transferPolyIdInfo]
656 ~~~~~~~~~~~~~~~~~~~~~~~~~
659 f = /\a. let g = rhs in ...
661 where g has interesting strictness information. Then if we float thus
666 we *do not* want to lose g's
667 * strictness information
669 * inline pragma (though that is bit more debatable)
671 It's simple to retain strictness and arity, but not so simple to retain
674 so we simply discard those. Sooner or later this may bite us.
676 This transfer is used in two places:
677 FloatOut (long-distance let-floating)
678 SimplUtils.abstractFloats (short-distance let-floating)
680 If we abstract wrt one or more *value* binders, we must modify the
681 arity and strictness info before transferring it. E.g.
685 + substitute (g' y) for g
686 Notice that g' has an arity one more than the original g
689 transferPolyIdInfo :: Id -- Original Id
690 -> [Var] -- Abstract wrt these variables
693 transferPolyIdInfo old_id abstract_wrt new_id
694 = modifyIdInfo transfer new_id
696 arity_increase = count isId abstract_wrt -- Arity increases by the
697 -- number of value binders
699 old_info = idInfo old_id
700 old_arity = arityInfo old_info
701 old_inline_prag = inlinePragInfo old_info
702 new_arity = old_arity + arity_increase
703 old_strictness = strictnessInfo old_info
704 new_strictness = fmap (increaseStrictSigArity arity_increase) old_strictness
706 transfer new_info = new_info `setStrictnessInfo` new_strictness
707 `setArityInfo` new_arity
708 `setInlinePragInfo` old_inline_prag