Add a note about primop wrappers (cf Trac #1509)
[ghc-hetmet.git] / compiler / basicTypes / Id.lhs
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 \begin{code}
8 {-# OPTIONS -w #-}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
13 -- for details
14
15 module Id (
16         Id, DictId,
17
18         -- Simple construction
19         mkGlobalId, mkLocalId, mkLocalIdWithInfo, 
20         mkSysLocal, mkUserLocal, mkVanillaGlobal,
21         mkTemplateLocals, mkTemplateLocalsNum, mkWildId, mkTemplateLocal,
22         mkWorkerId, mkExportedLocalId,
23
24         -- Taking an Id apart
25         idName, idType, idUnique, idInfo,
26         isId, globalIdDetails, idPrimRep,
27         recordSelectorFieldLabel,
28
29         -- Modifying an Id
30         setIdName, setIdUnique, Id.setIdType, setIdExported, setIdNotExported, 
31         setIdInfo, lazySetIdInfo, modifyIdInfo, maybeModifyIdInfo,
32         zapLamIdInfo, zapDemandIdInfo, zapFragileIdInfo,
33
34         -- Predicates
35         isImplicitId, isDeadBinder, isDictId, isStrictId,
36         isExportedId, isLocalId, isGlobalId,
37         isRecordSelector, isNaughtyRecordSelector,
38         isClassOpId_maybe,
39         isPrimOpId, isPrimOpId_maybe, 
40         isFCallId, isFCallId_maybe,
41         isDataConWorkId, isDataConWorkId_maybe, isDataConId_maybe, idDataCon,
42         isBottomingId, idIsFrom,
43         isTickBoxOp, isTickBoxOp_maybe,
44         hasNoBinding, 
45
46         -- Inline pragma stuff
47         idInlinePragma, setInlinePragma, modifyInlinePragma, 
48
49
50         -- One shot lambda stuff
51         isOneShotBndr, isOneShotLambda, isStateHackType,
52         setOneShotLambda, clearOneShotLambda,
53
54         -- IdInfo stuff
55         setIdUnfolding,
56         setIdArity,
57         setIdNewDemandInfo, 
58         setIdNewStrictness, zapIdNewStrictness,
59         setIdWorkerInfo,
60         setIdSpecialisation,
61         setIdCafInfo,
62         setIdOccInfo,
63
64 #ifdef OLD_STRICTNESS
65         idDemandInfo, 
66         idStrictness, 
67         idCprInfo,
68         setIdStrictness, 
69         setIdDemandInfo, 
70         setIdCprInfo,
71 #endif
72
73         idArity, 
74         idNewDemandInfo, idNewDemandInfo_maybe,
75         idNewStrictness, idNewStrictness_maybe, 
76         idWorkerInfo,
77         idUnfolding,
78         idSpecialisation, idCoreRules, idHasRules,
79         idCafInfo,
80         idLBVarInfo,
81         idOccInfo,
82
83 #ifdef OLD_STRICTNESS
84         newStrictnessFromOld    -- Temporary
85 #endif
86
87     ) where
88
89 #include "HsVersions.h"
90
91 import CoreSyn
92 import BasicTypes
93 import qualified Var
94 import Var hiding (mkLocalId, mkGlobalId, mkExportedLocalId)
95 import TyCon
96 import Type
97 import TcType
98 import TysPrim
99 import IdInfo 
100 #ifdef OLD_STRICTNESS
101 import qualified Demand
102 #endif
103 import DataCon
104 import NewDemand
105 import Name
106 import Module
107 import OccName
108 import Maybes
109 import SrcLoc
110 import Outputable
111 import Unique
112 import FastString
113 import StaticFlags
114
115 -- infixl so you can say (id `set` a `set` b)
116 infixl  1 `setIdUnfolding`,
117           `setIdArity`,
118           `setIdNewDemandInfo`,
119           `setIdNewStrictness`,
120           `setIdWorkerInfo`,
121           `setIdSpecialisation`,
122           `setInlinePragma`,
123           `idCafInfo`
124 #ifdef OLD_STRICTNESS
125           ,`idCprInfo`
126           ,`setIdStrictness`
127           ,`setIdDemandInfo`
128 #endif
129 \end{code}
130
131
132
133 %************************************************************************
134 %*                                                                      *
135 \subsection{Simple Id construction}
136 %*                                                                      *
137 %************************************************************************
138
139 Absolutely all Ids are made by mkId.  It is just like Var.mkId,
140 but in addition it pins free-tyvar-info onto the Id's type, 
141 where it can easily be found.
142
143 \begin{code}
144 mkLocalIdWithInfo :: Name -> Type -> IdInfo -> Id
145 mkLocalIdWithInfo name ty info = Var.mkLocalId name (addFreeTyVars ty) info
146
147 mkExportedLocalId :: Name -> Type -> Id
148 mkExportedLocalId name ty = Var.mkExportedLocalId name (addFreeTyVars ty) vanillaIdInfo
149
150 mkGlobalId :: GlobalIdDetails -> Name -> Type -> IdInfo -> Id
151 mkGlobalId details name ty info = Var.mkGlobalId details name (addFreeTyVars ty) info
152 \end{code}
153
154 \begin{code}
155 mkLocalId :: Name -> Type -> Id
156 mkLocalId name ty = mkLocalIdWithInfo name ty vanillaIdInfo
157
158 -- SysLocal: for an Id being created by the compiler out of thin air...
159 mkSysLocal :: FastString -> Unique -> Type -> Id
160 mkSysLocal fs uniq ty = mkLocalId (mkSystemVarName uniq fs) ty
161
162
163 -- UserLocal: an Id with a name the user might recognize...
164 mkUserLocal :: OccName -> Unique -> Type -> SrcSpan -> Id
165 mkVanillaGlobal :: Name -> Type -> IdInfo -> Id
166
167 mkUserLocal occ uniq ty loc = mkLocalId (mkInternalName    uniq occ loc) ty
168 mkVanillaGlobal             = mkGlobalId VanillaGlobal
169 \end{code}
170
171 Make some local @Ids@ for a template @CoreExpr@.  These have bogus
172 @Uniques@, but that's OK because the templates are supposed to be
173 instantiated before use.
174  
175 \begin{code}
176 -- "Wild Id" typically used when you need a binder that you don't expect to use
177 mkWildId :: Type -> Id
178 mkWildId ty = mkSysLocal FSLIT("wild") (mkBuiltinUnique 1) ty
179
180 mkWorkerId :: Unique -> Id -> Type -> Id
181 -- A worker gets a local name.  CoreTidy will externalise it if necessary.
182 mkWorkerId uniq unwrkr ty
183   = mkLocalId wkr_name ty
184   where
185     wkr_name = mkInternalName uniq (mkWorkerOcc (getOccName unwrkr)) (getSrcSpan unwrkr)
186
187 -- "Template locals" typically used in unfoldings
188 mkTemplateLocals :: [Type] -> [Id]
189 mkTemplateLocals tys = zipWith mkTemplateLocal [1..] tys
190
191 mkTemplateLocalsNum :: Int -> [Type] -> [Id]
192 -- The Int gives the starting point for unique allocation
193 mkTemplateLocalsNum n tys = zipWith mkTemplateLocal [n..] tys
194
195 mkTemplateLocal :: Int -> Type -> Id
196 mkTemplateLocal i ty = mkSysLocal FSLIT("tpl") (mkBuiltinUnique i) ty
197 \end{code}
198
199
200 %************************************************************************
201 %*                                                                      *
202 \subsection[Id-general-funs]{General @Id@-related functions}
203 %*                                                                      *
204 %************************************************************************
205
206 \begin{code}
207 setIdType :: Id -> Type -> Id
208         -- Add free tyvar info to the type
209 setIdType id ty = seqType ty `seq` Var.setIdType id (addFreeTyVars ty)
210
211 idPrimRep :: Id -> PrimRep
212 idPrimRep id = typePrimRep (idType id)
213 \end{code}
214
215
216 %************************************************************************
217 %*                                                                      *
218 \subsection{Special Ids}
219 %*                                                                      *
220 %************************************************************************
221
222 \begin{code}
223 recordSelectorFieldLabel :: Id -> (TyCon, FieldLabel)
224 recordSelectorFieldLabel id
225   = case globalIdDetails id of
226         RecordSelId { sel_tycon = tycon, sel_label = lbl } -> (tycon,lbl)
227         other -> panic "recordSelectorFieldLabel"
228
229 isRecordSelector id = case globalIdDetails id of
230                         RecordSelId {}  -> True
231                         other           -> False
232
233 isNaughtyRecordSelector id = case globalIdDetails id of
234                         RecordSelId { sel_naughty = n } -> n
235                         other                           -> False
236
237 isClassOpId_maybe id = case globalIdDetails id of
238                         ClassOpId cls -> Just cls
239                         _other        -> Nothing
240
241 isPrimOpId id = case globalIdDetails id of
242                     PrimOpId op -> True
243                     other       -> False
244
245 isPrimOpId_maybe id = case globalIdDetails id of
246                             PrimOpId op -> Just op
247                             other       -> Nothing
248
249 isFCallId id = case globalIdDetails id of
250                     FCallId call -> True
251                     other        -> False
252
253 isFCallId_maybe id = case globalIdDetails id of
254                             FCallId call -> Just call
255                             other        -> Nothing
256
257 isDataConWorkId id = case globalIdDetails id of
258                         DataConWorkId _ -> True
259                         other           -> False
260
261 isDataConWorkId_maybe id = case globalIdDetails id of
262                           DataConWorkId con -> Just con
263                           other             -> Nothing
264
265 isDataConId_maybe :: Id -> Maybe DataCon
266 isDataConId_maybe id = case globalIdDetails id of
267                          DataConWorkId con -> Just con
268                          DataConWrapId con -> Just con
269                          other              -> Nothing
270
271 idDataCon :: Id -> DataCon
272 -- Get from either the worker or the wrapper to the DataCon
273 -- Currently used only in the desugarer
274 --       INVARIANT: idDataCon (dataConWrapId d) = d
275 -- (Remember, dataConWrapId can return either the wrapper or the worker.)
276 idDataCon id = case globalIdDetails id of
277                   DataConWorkId con -> con
278                   DataConWrapId con -> con
279                   other             -> pprPanic "idDataCon" (ppr id)
280
281
282 isDictId :: Id -> Bool
283 isDictId id = isDictTy (idType id)
284
285 -- hasNoBinding returns True of an Id which may not have a
286 -- binding, even though it is defined in this module.  
287 -- Data constructor workers used to be things of this kind, but
288 -- they aren't any more.  Instead, we inject a binding for 
289 -- them at the CorePrep stage. 
290 -- EXCEPT: unboxed tuples, which definitely have no binding
291 hasNoBinding id = case globalIdDetails id of
292                         PrimOpId _       -> True        -- See Note [Primop wrappers]
293                         FCallId _        -> True
294                         DataConWorkId dc -> isUnboxedTupleCon dc
295                         other            -> False
296
297 isImplicitId :: Id -> Bool
298         -- isImplicitId tells whether an Id's info is implied by other
299         -- declarations, so we don't need to put its signature in an interface
300         -- file, even if it's mentioned in some other interface unfolding.
301 isImplicitId id
302   = case globalIdDetails id of
303         RecordSelId {}  -> True
304         FCallId _       -> True
305         PrimOpId _      -> True
306         ClassOpId _     -> True
307         DataConWorkId _ -> True
308         DataConWrapId _ -> True
309                 -- These are are implied by their type or class decl;
310                 -- remember that all type and class decls appear in the interface file.
311                 -- The dfun id is not an implicit Id; it must *not* be omitted, because 
312                 -- it carries version info for the instance decl
313         other           -> False
314
315 idIsFrom :: Module -> Id -> Bool
316 idIsFrom mod id = nameIsLocalOrFrom mod (idName id)
317 \end{code}
318
319 Note [Primop wrappers]
320 ~~~~~~~~~~~~~~~~~~~~~~
321 Currently hasNoBinding claims that PrimOpIds don't have a curried
322 function definition.  But actually they do, in GHC.PrimopWrappers,
323 which is auto-generated from prelude/primops.txt.pp.  So actually, hasNoBinding
324 could return 'False' for PrimOpIds.
325
326 But we'd need to add something in CoreToStg to swizzle any unsaturated
327 applications of GHC.Prim.plusInt# to GHC.PrimopWrappers.plusInt#.
328
329 Nota Bene: GHC.PrimopWrappers is needed *regardless*, because it's
330 used by GHCi, which does not implement primops direct at all.
331
332
333
334 \begin{code}
335 isDeadBinder :: Id -> Bool
336 isDeadBinder bndr | isId bndr = isDeadOcc (idOccInfo bndr)
337                   | otherwise = False   -- TyVars count as not dead
338 \end{code}
339
340 \begin{code}
341 isTickBoxOp :: Id -> Bool
342 isTickBoxOp id = 
343   case globalIdDetails id of
344     TickBoxOpId tick -> True
345     _                -> False
346
347 isTickBoxOp_maybe :: Id -> Maybe TickBoxOp
348 isTickBoxOp_maybe id = 
349   case globalIdDetails id of
350     TickBoxOpId tick -> Just tick
351     _                -> Nothing
352 \end{code}
353
354 %************************************************************************
355 %*                                                                      *
356 \subsection{IdInfo stuff}
357 %*                                                                      *
358 %************************************************************************
359
360 \begin{code}
361         ---------------------------------
362         -- ARITY
363 idArity :: Id -> Arity
364 idArity id = arityInfo (idInfo id)
365
366 setIdArity :: Id -> Arity -> Id
367 setIdArity id arity = modifyIdInfo (`setArityInfo` arity) id
368
369 #ifdef OLD_STRICTNESS
370         ---------------------------------
371         -- (OLD) STRICTNESS 
372 idStrictness :: Id -> StrictnessInfo
373 idStrictness id = strictnessInfo (idInfo id)
374
375 setIdStrictness :: Id -> StrictnessInfo -> Id
376 setIdStrictness id strict_info = modifyIdInfo (`setStrictnessInfo` strict_info) id
377 #endif
378
379 -- isBottomingId returns true if an application to n args would diverge
380 isBottomingId :: Id -> Bool
381 isBottomingId id = isBottomingSig (idNewStrictness id)
382
383 idNewStrictness_maybe :: Id -> Maybe StrictSig
384 idNewStrictness :: Id -> StrictSig
385
386 idNewStrictness_maybe id = newStrictnessInfo (idInfo id)
387 idNewStrictness       id = idNewStrictness_maybe id `orElse` topSig
388
389 setIdNewStrictness :: Id -> StrictSig -> Id
390 setIdNewStrictness id sig = modifyIdInfo (`setNewStrictnessInfo` Just sig) id
391
392 zapIdNewStrictness :: Id -> Id
393 zapIdNewStrictness id = modifyIdInfo (`setNewStrictnessInfo` Nothing) id
394 \end{code}
395
396 This predicate says whether the id has a strict demand placed on it or
397 has a type such that it can always be evaluated strictly (e.g., an
398 unlifted type, but see the comment for isStrictType).  We need to
399 check separately whether <id> has a so-called "strict type" because if
400 the demand for <id> hasn't been computed yet but <id> has a strict
401 type, we still want (isStrictId <id>) to be True.
402 \begin{code}
403 isStrictId :: Id -> Bool
404 isStrictId id
405   = ASSERT2( isId id, text "isStrictId: not an id: " <+> ppr id )
406            (isStrictDmd (idNewDemandInfo id)) || 
407            (isStrictType (idType id))
408
409         ---------------------------------
410         -- WORKER ID
411 idWorkerInfo :: Id -> WorkerInfo
412 idWorkerInfo id = workerInfo (idInfo id)
413
414 setIdWorkerInfo :: Id -> WorkerInfo -> Id
415 setIdWorkerInfo id work_info = modifyIdInfo (`setWorkerInfo` work_info) id
416
417         ---------------------------------
418         -- UNFOLDING
419 idUnfolding :: Id -> Unfolding
420 idUnfolding id = unfoldingInfo (idInfo id)
421
422 setIdUnfolding :: Id -> Unfolding -> Id
423 setIdUnfolding id unfolding = modifyIdInfo (`setUnfoldingInfo` unfolding) id
424
425 #ifdef OLD_STRICTNESS
426         ---------------------------------
427         -- (OLD) DEMAND
428 idDemandInfo :: Id -> Demand.Demand
429 idDemandInfo id = demandInfo (idInfo id)
430
431 setIdDemandInfo :: Id -> Demand.Demand -> Id
432 setIdDemandInfo id demand_info = modifyIdInfo (`setDemandInfo` demand_info) id
433 #endif
434
435 idNewDemandInfo_maybe :: Id -> Maybe NewDemand.Demand
436 idNewDemandInfo       :: Id -> NewDemand.Demand
437
438 idNewDemandInfo_maybe id = newDemandInfo (idInfo id)
439 idNewDemandInfo       id = newDemandInfo (idInfo id) `orElse` NewDemand.topDmd
440
441 setIdNewDemandInfo :: Id -> NewDemand.Demand -> Id
442 setIdNewDemandInfo id dmd = modifyIdInfo (`setNewDemandInfo` Just dmd) id
443
444         ---------------------------------
445         -- SPECIALISATION
446 idSpecialisation :: Id -> SpecInfo
447 idSpecialisation id = specInfo (idInfo id)
448
449 idCoreRules :: Id -> [CoreRule]
450 idCoreRules id = specInfoRules (idSpecialisation id)
451
452 idHasRules :: Id -> Bool
453 idHasRules id = not (isEmptySpecInfo (idSpecialisation id))
454
455 setIdSpecialisation :: Id -> SpecInfo -> Id
456 setIdSpecialisation id spec_info = modifyIdInfo (`setSpecInfo` spec_info) id
457
458         ---------------------------------
459         -- CAF INFO
460 idCafInfo :: Id -> CafInfo
461 #ifdef OLD_STRICTNESS
462 idCafInfo id = case cgInfo (idInfo id) of
463                   NoCgInfo -> pprPanic "idCafInfo" (ppr id)
464                   info     -> cgCafInfo info
465 #else
466 idCafInfo id = cafInfo (idInfo id)
467 #endif
468
469 setIdCafInfo :: Id -> CafInfo -> Id
470 setIdCafInfo id caf_info = modifyIdInfo (`setCafInfo` caf_info) id
471
472         ---------------------------------
473         -- CPR INFO
474 #ifdef OLD_STRICTNESS
475 idCprInfo :: Id -> CprInfo
476 idCprInfo id = cprInfo (idInfo id)
477
478 setIdCprInfo :: Id -> CprInfo -> Id
479 setIdCprInfo id cpr_info = modifyIdInfo (`setCprInfo` cpr_info) id
480 #endif
481
482         ---------------------------------
483         -- Occcurrence INFO
484 idOccInfo :: Id -> OccInfo
485 idOccInfo id = occInfo (idInfo id)
486
487 setIdOccInfo :: Id -> OccInfo -> Id
488 setIdOccInfo id occ_info = modifyIdInfo (`setOccInfo` occ_info) id
489 \end{code}
490
491
492         ---------------------------------
493         -- INLINING
494 The inline pragma tells us to be very keen to inline this Id, but it's still
495 OK not to if optimisation is switched off.
496
497 \begin{code}
498 idInlinePragma :: Id -> InlinePragInfo
499 idInlinePragma id = inlinePragInfo (idInfo id)
500
501 setInlinePragma :: Id -> InlinePragInfo -> Id
502 setInlinePragma id prag = modifyIdInfo (`setInlinePragInfo` prag) id
503
504 modifyInlinePragma :: Id -> (InlinePragInfo -> InlinePragInfo) -> Id
505 modifyInlinePragma id fn = modifyIdInfo (\info -> info `setInlinePragInfo` (fn (inlinePragInfo info))) id
506 \end{code}
507
508
509         ---------------------------------
510         -- ONE-SHOT LAMBDAS
511 \begin{code}
512 idLBVarInfo :: Id -> LBVarInfo
513 idLBVarInfo id = lbvarInfo (idInfo id)
514
515 isOneShotBndr :: Id -> Bool
516 -- This one is the "business end", called externally.
517 -- Its main purpose is to encapsulate the Horrible State Hack
518 isOneShotBndr id = isOneShotLambda id || isStateHackType (idType id)
519
520 isStateHackType :: Type -> Bool
521 isStateHackType ty
522   | opt_NoStateHack 
523   = False
524   | otherwise
525   = case splitTyConApp_maybe ty of
526         Just (tycon,_) -> tycon == statePrimTyCon
527         other          -> False
528         -- This is a gross hack.  It claims that 
529         -- every function over realWorldStatePrimTy is a one-shot
530         -- function.  This is pretty true in practice, and makes a big
531         -- difference.  For example, consider
532         --      a `thenST` \ r -> ...E...
533         -- The early full laziness pass, if it doesn't know that r is one-shot
534         -- will pull out E (let's say it doesn't mention r) to give
535         --      let lvl = E in a `thenST` \ r -> ...lvl...
536         -- When `thenST` gets inlined, we end up with
537         --      let lvl = E in \s -> case a s of (r, s') -> ...lvl...
538         -- and we don't re-inline E.
539         --
540         -- It would be better to spot that r was one-shot to start with, but
541         -- I don't want to rely on that.
542         --
543         -- Another good example is in fill_in in PrelPack.lhs.  We should be able to
544         -- spot that fill_in has arity 2 (and when Keith is done, we will) but we can't yet.
545
546
547 -- The OneShotLambda functions simply fiddle with the IdInfo flag
548 isOneShotLambda :: Id -> Bool
549 isOneShotLambda id = case idLBVarInfo id of
550                        IsOneShotLambda  -> True
551                        NoLBVarInfo      -> False
552
553 setOneShotLambda :: Id -> Id
554 setOneShotLambda id = modifyIdInfo (`setLBVarInfo` IsOneShotLambda) id
555
556 clearOneShotLambda :: Id -> Id
557 clearOneShotLambda id 
558   | isOneShotLambda id = modifyIdInfo (`setLBVarInfo` NoLBVarInfo) id
559   | otherwise          = id                     
560
561 -- But watch out: this may change the type of something else
562 --      f = \x -> e
563 -- If we change the one-shot-ness of x, f's type changes
564 \end{code}
565
566 \begin{code}
567 zapInfo :: (IdInfo -> Maybe IdInfo) -> Id -> Id
568 zapInfo zapper id = maybeModifyIdInfo (zapper (idInfo id)) id
569
570 zapLamIdInfo :: Id -> Id
571 zapLamIdInfo = zapInfo zapLamInfo
572
573 zapDemandIdInfo = zapInfo zapDemandInfo
574
575 zapFragileIdInfo :: Id -> Id
576 zapFragileIdInfo = zapInfo zapFragileInfo 
577 \end{code}
578