[project @ 2001-09-26 15:12:33 by simonpj]
[ghc-hetmet.git] / ghc / compiler / basicTypes / MkId.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1998
3 %
4 \section[StdIdInfo]{Standard unfoldings}
5
6 This module contains definitions for the IdInfo for things that
7 have a standard form, namely:
8
9         * data constructors
10         * record selectors
11         * method and superclass selectors
12         * primitive operations
13
14 \begin{code}
15 module MkId (
16         mkDictFunId, mkDefaultMethodId,
17         mkDictSelId,
18
19         mkDataConId, mkDataConWrapId,
20         mkRecordSelId, rebuildConArgs,
21         mkPrimOpId, mkFCallId,
22
23         -- And some particular Ids; see below for why they are wired in
24         wiredInIds,
25         unsafeCoerceId, realWorldPrimId,
26         eRROR_ID, eRROR_CSTRING_ID, rEC_SEL_ERROR_ID, pAT_ERROR_ID, rEC_CON_ERROR_ID,
27         rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID, nON_EXHAUSTIVE_GUARDS_ERROR_ID,
28         nO_METHOD_BINDING_ERROR_ID, aBSENT_ERROR_ID, pAR_ERROR_ID
29     ) where
30
31 #include "HsVersions.h"
32
33
34 import BasicTypes       ( Arity, StrictnessMark(..), isMarkedUnboxed, isMarkedStrict )
35 import TysPrim          ( openAlphaTyVars, alphaTyVar, alphaTy, betaTyVar, betaTy,
36                           intPrimTy, realWorldStatePrimTy, addrPrimTy
37                         )
38 import TysWiredIn       ( charTy, mkListTy )
39 import PrelRules        ( primOpRules )
40 import Rules            ( addRule )
41 import TcType           ( Type, ThetaType, mkDictTy, mkPredTys, mkTyConApp,
42                           mkTyVarTys, mkClassPred, tcEqPred,
43                           mkFunTys, mkFunTy, mkSigmaTy, tcSplitSigmaTy, 
44                           isUnLiftedType, mkForAllTys, mkTyVarTy, tyVarsOfType,
45                           tcSplitFunTys, tcSplitForAllTys, mkPredTy
46                         )
47 import Module           ( Module )
48 import CoreUtils        ( mkInlineMe )
49 import CoreUnfold       ( mkTopUnfolding, mkCompulsoryUnfolding, mkOtherCon )
50 import Literal          ( Literal(..) )
51 import TyCon            ( TyCon, isNewTyCon, tyConTyVars, tyConDataCons,
52                           tyConTheta, isProductTyCon, isDataTyCon, isRecursiveTyCon )
53 import Class            ( Class, classTyCon, classTyVars, classSelIds )
54 import Var              ( Id, TyVar )
55 import VarSet           ( isEmptyVarSet )
56 import Name             ( mkWiredInName, mkFCallName, Name )
57 import OccName          ( mkVarOcc )
58 import PrimOp           ( PrimOp(DataToTagOp), primOpSig, mkPrimOpIdName )
59 import ForeignCall      ( ForeignCall )
60 import DataCon          ( DataCon, 
61                           dataConFieldLabels, dataConRepArity, dataConTyCon,
62                           dataConArgTys, dataConRepType, 
63                           dataConInstOrigArgTys,
64                           dataConName, dataConTheta,
65                           dataConSig, dataConStrictMarks, dataConId,
66                           splitProductType
67                         )
68 import Id               ( idType, mkGlobalId, mkVanillaGlobal, mkSysLocal,
69                           mkTemplateLocals, mkTemplateLocalsNum,
70                           mkTemplateLocal, idNewStrictness, idName
71                         )
72 import IdInfo           ( IdInfo, noCafNoTyGenIdInfo,
73                           setUnfoldingInfo, 
74                           setArityInfo, setSpecInfo,  setCgInfo,
75                           mkNewStrictnessInfo, setNewStrictnessInfo,
76                           GlobalIdDetails(..), CafInfo(..), CprInfo(..), 
77                           CgInfo(..), setCgArity
78                         )
79 import NewDemand        ( mkStrictSig, strictSigResInfo, DmdResult(..),
80                           mkTopDmdType, topDmd, evalDmd, Demand(..), Keepity(..) )
81 import FieldLabel       ( mkFieldLabel, fieldLabelName, 
82                           firstFieldLabelTag, allFieldLabelTags, fieldLabelType
83                         )
84 import DmdAnal          ( dmdAnalTopRhs )
85 import CoreSyn
86 import Unique           ( mkBuiltinUnique )
87 import Maybes
88 import PrelNames
89 import Maybe            ( isJust )
90 import Outputable
91 import ListSetOps       ( assoc, assocMaybe )
92 import UnicodeUtil      ( stringToUtf8 )
93 import Char             ( ord )
94 \end{code}              
95
96 %************************************************************************
97 %*                                                                      *
98 \subsection{Wired in Ids}
99 %*                                                                      *
100 %************************************************************************
101
102 \begin{code}
103 wiredInIds
104   = [   -- These error-y things are wired in because we don't yet have
105         -- a way to express in an interface file that the result type variable
106         -- is 'open'; that is can be unified with an unboxed type
107         -- 
108         -- [The interface file format now carry such information, but there's
109         -- no way yet of expressing at the definition site for these 
110         -- error-reporting
111         -- functions that they have an 'open' result type. -- sof 1/99]
112
113       aBSENT_ERROR_ID
114     , eRROR_ID
115     , eRROR_CSTRING_ID
116     , iRREFUT_PAT_ERROR_ID
117     , nON_EXHAUSTIVE_GUARDS_ERROR_ID
118     , nO_METHOD_BINDING_ERROR_ID
119     , pAR_ERROR_ID
120     , pAT_ERROR_ID
121     , rEC_CON_ERROR_ID
122     , rEC_UPD_ERROR_ID
123
124         -- These three can't be defined in Haskell
125     , realWorldPrimId
126     , unsafeCoerceId
127     , getTagId
128     , seqId
129     ]
130 \end{code}
131
132 %************************************************************************
133 %*                                                                      *
134 \subsection{Data constructors}
135 %*                                                                      *
136 %************************************************************************
137
138 \begin{code}
139 mkDataConId :: Name -> DataCon -> Id
140         -- Makes the *worker* for the data constructor; that is, the function
141         -- that takes the reprsentation arguments and builds the constructor.
142 mkDataConId work_name data_con
143   = mkGlobalId (DataConId data_con) work_name (dataConRepType data_con) info
144   where
145     info = noCafNoTyGenIdInfo
146            `setCgArity`                 arity
147            `setArityInfo`               arity
148            `setNewStrictnessInfo`       Just strict_sig
149
150     arity      = dataConRepArity data_con
151
152     strict_sig = mkStrictSig (mkTopDmdType (replicate arity topDmd) cpr_info)
153         -- Notice that we do *not* say the worker is strict
154         -- even if the data constructor is declared strict
155         --      e.g.    data T = MkT !(Int,Int)
156         -- Why?  Because the *wrapper* is strict (and its unfolding has case
157         -- expresssions that do the evals) but the *worker* itself is not.
158         -- If we pretend it is strict then when we see
159         --      case x of y -> $wMkT y
160         -- the simplifier thinks that y is "sure to be evaluated" (because
161         -- $wMkT is strict) and drops the case.  No, $wMkT is not strict.
162         --
163         -- When the simplifer sees a pattern 
164         --      case e of MkT x -> ...
165         -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
166         -- but that's fine... dataConRepStrictness comes from the data con
167         -- not from the worker Id.
168
169     tycon = dataConTyCon data_con
170     cpr_info | isProductTyCon tycon && 
171                isDataTyCon tycon    &&
172                arity > 0            &&
173                arity <= mAX_CPR_SIZE    = RetCPR
174              | otherwise                = TopRes
175         -- RetCPR is only true for products that are real data types;
176         -- that is, not unboxed tuples or [non-recursive] newtypes
177
178 mAX_CPR_SIZE :: Arity
179 mAX_CPR_SIZE = 10
180 -- We do not treat very big tuples as CPR-ish:
181 --      a) for a start we get into trouble because there aren't 
182 --         "enough" unboxed tuple types (a tiresome restriction, 
183 --         but hard to fix), 
184 --      b) more importantly, big unboxed tuples get returned mainly
185 --         on the stack, and are often then allocated in the heap
186 --         by the caller.  So doing CPR for them may in fact make
187 --         things worse.
188 \end{code}
189
190 The wrapper for a constructor is an ordinary top-level binding that evaluates
191 any strict args, unboxes any args that are going to be flattened, and calls
192 the worker.
193
194 We're going to build a constructor that looks like:
195
196         data (Data a, C b) =>  T a b = T1 !a !Int b
197
198         T1 = /\ a b -> 
199              \d1::Data a, d2::C b ->
200              \p q r -> case p of { p ->
201                        case q of { q ->
202                        Con T1 [a,b] [p,q,r]}}
203
204 Notice that
205
206 * d2 is thrown away --- a context in a data decl is used to make sure
207   one *could* construct dictionaries at the site the constructor
208   is used, but the dictionary isn't actually used.
209
210 * We have to check that we can construct Data dictionaries for
211   the types a and Int.  Once we've done that we can throw d1 away too.
212
213 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
214   all that matters is that the arguments are evaluated.  "seq" is 
215   very careful to preserve evaluation order, which we don't need
216   to be here.
217
218   You might think that we could simply give constructors some strictness
219   info, like PrimOps, and let CoreToStg do the let-to-case transformation.
220   But we don't do that because in the case of primops and functions strictness
221   is a *property* not a *requirement*.  In the case of constructors we need to
222   do something active to evaluate the argument.
223
224   Making an explicit case expression allows the simplifier to eliminate
225   it in the (common) case where the constructor arg is already evaluated.
226
227 \begin{code}
228 mkDataConWrapId data_con
229   = mkGlobalId (DataConWrapId data_con) (dataConName data_con) wrap_ty info
230   where
231     work_id = dataConId data_con
232
233     info = noCafNoTyGenIdInfo
234            `setUnfoldingInfo`   mkTopUnfolding (mkInlineMe wrap_rhs)
235            `setCgArity`         arity
236                 -- The NoCaf-ness is set by noCafNoTyGenIdInfo
237            `setArityInfo`       arity
238                 -- It's important to specify the arity, so that partial
239                 -- applications are treated as values
240            `setNewStrictnessInfo`       Just wrap_sig
241
242     wrap_ty = mkForAllTys all_tyvars (mkFunTys all_arg_tys result_ty)
243
244     res_info = strictSigResInfo (idNewStrictness work_id)
245     wrap_sig = mkStrictSig (mkTopDmdType (replicate arity topDmd) res_info)
246         -- The Cpr info can be important inside INLINE rhss, where the
247         -- wrapper constructor isn't inlined
248         -- But we are sloppy about the argument demands, because we expect 
249         -- to inline the constructor very vigorously.
250
251     wrap_rhs | isNewTyCon tycon
252              = ASSERT( null ex_tyvars && null ex_dict_args && length orig_arg_tys == 1 )
253                 -- No existentials on a newtype, but it can have a context
254                 -- e.g.         newtype Eq a => T a = MkT (...)
255                 mkLams tyvars $ mkLams dict_args $ Lam id_arg1 $ 
256                 mkNewTypeBody tycon result_ty id_arg1
257
258              | null dict_args && not (any isMarkedStrict strict_marks)
259              = Var work_id      -- The common case.  Not only is this efficient,
260                                 -- but it also ensures that the wrapper is replaced
261                                 -- by the worker even when there are no args.
262                                 --              f (:) x
263                                 -- becomes 
264                                 --              f $w: x
265                                 -- This is really important in rule matching,
266                                 -- (We could match on the wrappers,
267                                 -- but that makes it less likely that rules will match
268                                 -- when we bring bits of unfoldings together.)
269                 --
270                 -- NB:  because of this special case, (map (:) ys) turns into
271                 --      (map $w: ys), and thence into (map (\x xs. $w: x xs) ys)
272                 --      in core-to-stg.  The top-level defn for (:) is never used.
273                 --      This is somewhat of a bore, but I'm currently leaving it 
274                 --      as is, so that there still is a top level curried (:) for
275                 --      the interpreter to call.
276
277              | otherwise
278              = mkLams all_tyvars $ mkLams dict_args $ 
279                mkLams ex_dict_args $ mkLams id_args $
280                foldr mk_case con_app 
281                      (zip (ex_dict_args++id_args) strict_marks) i3 []
282
283     con_app i rep_ids = mkApps (Var work_id)
284                                (map varToCoreExpr (all_tyvars ++ reverse rep_ids))
285
286     (tyvars, theta, ex_tyvars, ex_theta, orig_arg_tys, tycon) = dataConSig data_con
287     all_tyvars   = tyvars ++ ex_tyvars
288
289     dict_tys     = mkPredTys theta
290     ex_dict_tys  = mkPredTys ex_theta
291     all_arg_tys  = dict_tys ++ ex_dict_tys ++ orig_arg_tys
292     result_ty    = mkTyConApp tycon (mkTyVarTys tyvars)
293
294     mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
295                    where
296                      n = length tys
297
298     (dict_args, i1)    = mkLocals 1  dict_tys
299     (ex_dict_args,i2)  = mkLocals i1 ex_dict_tys
300     (id_args,i3)       = mkLocals i2 orig_arg_tys
301     arity              = i3-1
302     (id_arg1:_)   = id_args             -- Used for newtype only
303
304     strict_marks  = dataConStrictMarks data_con
305
306     mk_case 
307            :: (Id, StrictnessMark)      -- Arg, strictness
308            -> (Int -> [Id] -> CoreExpr) -- Body
309            -> Int                       -- Next rep arg id
310            -> [Id]                      -- Rep args so far, reversed
311            -> CoreExpr
312     mk_case (arg,strict) body i rep_args
313           = case strict of
314                 NotMarkedStrict -> body i (arg:rep_args)
315                 MarkedStrict 
316                    | isUnLiftedType (idType arg) -> body i (arg:rep_args)
317                    | otherwise ->
318                         Case (Var arg) arg [(DEFAULT,[], body i (arg:rep_args))]
319
320                 MarkedUnboxed
321                    -> case splitProductType "do_unbox" (idType arg) of
322                            (tycon, tycon_args, con, tys) ->
323                                    Case (Var arg) arg [(DataAlt con, con_args,
324                                         body i' (reverse con_args ++ rep_args))]
325                               where 
326                                 (con_args, i') = mkLocals i tys
327 \end{code}
328
329
330 %************************************************************************
331 %*                                                                      *
332 \subsection{Record selectors}
333 %*                                                                      *
334 %************************************************************************
335
336 We're going to build a record selector unfolding that looks like this:
337
338         data T a b c = T1 { ..., op :: a, ...}
339                      | T2 { ..., op :: a, ...}
340                      | T3
341
342         sel = /\ a b c -> \ d -> case d of
343                                     T1 ... x ... -> x
344                                     T2 ... x ... -> x
345                                     other        -> error "..."
346
347 Similarly for newtypes
348
349         newtype N a = MkN { unN :: a->a }
350
351         unN :: N a -> a -> a
352         unN n = coerce (a->a) n
353         
354 We need to take a little care if the field has a polymorphic type:
355
356         data R = R { f :: forall a. a->a }
357
358 Then we want
359
360         f :: forall a. R -> a -> a
361         f = /\ a \ r = case r of
362                           R f -> f a
363
364 (not f :: R -> forall a. a->a, which gives the type inference mechanism 
365 problems at call sites)
366
367 Similarly for newtypes
368
369         newtype N = MkN { unN :: forall a. a->a }
370
371         unN :: forall a. N -> a -> a
372         unN = /\a -> \n:N -> coerce (a->a) n
373
374 \begin{code}
375 mkRecordSelId tycon field_label unpack_id unpackUtf8_id
376         -- Assumes that all fields with the same field label have the same type
377         --
378         -- Annoyingly, we have to pass in the unpackCString# Id, because
379         -- we can't conjure it up out of thin air
380   = sel_id
381   where
382     sel_id     = mkGlobalId (RecordSelId field_label) (fieldLabelName field_label) selector_ty info
383     field_ty   = fieldLabelType field_label
384     data_cons  = tyConDataCons tycon
385     tyvars     = tyConTyVars tycon      -- These scope over the types in 
386                                         -- the FieldLabels of constructors of this type
387     data_ty   = mkTyConApp tycon tyvar_tys
388     tyvar_tys = mkTyVarTys tyvars
389
390     tycon_theta = tyConTheta tycon      -- The context on the data decl
391                                         --   eg data (Eq a, Ord b) => T a b = ...
392     dict_tys  = [mkPredTy pred | pred <- tycon_theta, 
393                                  needed_dict pred]
394     needed_dict pred = or [ tcEqPred pred p
395                           | (DataAlt dc, _, _) <- the_alts, p <- dataConTheta dc]
396     n_dict_tys = length dict_tys
397
398     (field_tyvars,field_theta,field_tau) = tcSplitSigmaTy field_ty
399     field_dict_tys                       = map mkPredTy field_theta
400     n_field_dict_tys                     = length field_dict_tys
401         -- If the field has a universally quantified type we have to 
402         -- be a bit careful.  Suppose we have
403         --      data R = R { op :: forall a. Foo a => a -> a }
404         -- Then we can't give op the type
405         --      op :: R -> forall a. Foo a => a -> a
406         -- because the typechecker doesn't understand foralls to the
407         -- right of an arrow.  The "right" type to give it is
408         --      op :: forall a. Foo a => R -> a -> a
409         -- But then we must generate the right unfolding too:
410         --      op = /\a -> \dfoo -> \ r ->
411         --           case r of
412         --              R op -> op a dfoo
413         -- Note that this is exactly the type we'd infer from a user defn
414         --      op (R op) = op
415
416         -- Very tiresomely, the selectors are (unnecessarily!) overloaded over
417         -- just the dictionaries in the types of the constructors that contain
418         -- the relevant field.  Urgh.  
419         -- NB: this code relies on the fact that DataCons are quantified over
420         -- the identical type variables as their parent TyCon
421
422     selector_ty :: Type
423     selector_ty  = mkForAllTys tyvars $ mkForAllTys field_tyvars $
424                    mkFunTys dict_tys  $  mkFunTys field_dict_tys $
425                    mkFunTy data_ty field_tau
426       
427     arity = 1 + n_dict_tys + n_field_dict_tys
428
429     (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
430         -- Use the demand analyser to work out strictness.
431         -- With all this unpackery it's not easy!
432
433     info = noCafNoTyGenIdInfo
434            `setCgInfo`            CgInfo arity caf_info
435            `setArityInfo`         arity
436            `setUnfoldingInfo`     mkTopUnfolding rhs_w_str
437            `setNewStrictnessInfo` Just strict_sig
438
439         -- Allocate Ids.  We do it a funny way round because field_dict_tys is
440         -- almost always empty.  Also note that we use length_tycon_theta
441         -- rather than n_dict_tys, because the latter gives an infinite loop:
442         -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
443         -- on arity, which depends on n_dict tys.  Sigh!  Mega sigh!
444     field_dict_base    = length tycon_theta + 1
445     dict_id_base       = field_dict_base + n_field_dict_tys
446     field_base         = dict_id_base + 1
447     dict_ids           = mkTemplateLocalsNum  1               dict_tys
448     field_dict_ids     = mkTemplateLocalsNum  field_dict_base field_dict_tys
449     data_id            = mkTemplateLocal      dict_id_base    data_ty
450
451     alts      = map mk_maybe_alt data_cons
452     the_alts  = catMaybes alts
453
454     no_default = all isJust alts        -- No default needed
455     default_alt | no_default = []
456                 | otherwise  = [(DEFAULT, [], error_expr)]
457
458         -- the default branch may have CAF refs, because it calls recSelError etc.
459     caf_info    | no_default = NoCafRefs
460                 | otherwise  = MayHaveCafRefs
461
462     sel_rhs = mkLams tyvars   $ mkLams field_tyvars $ 
463               mkLams dict_ids $ mkLams field_dict_ids $
464               Lam data_id     $ sel_body
465
466     sel_body | isNewTyCon tycon = mkNewTypeBody tycon field_tau data_id
467              | otherwise        = Case (Var data_id) data_id (default_alt ++ the_alts)
468
469     mk_maybe_alt data_con 
470           = case maybe_the_arg_id of
471                 Nothing         -> Nothing
472                 Just the_arg_id -> Just (DataAlt data_con, real_args, mkLets binds body)
473                   where
474                     body               = mkVarApps (mkVarApps (Var the_arg_id) field_tyvars) field_dict_ids
475                     strict_marks       = dataConStrictMarks data_con
476                     (binds, real_args) = rebuildConArgs arg_ids strict_marks
477                                                         (map mkBuiltinUnique [unpack_base..])
478         where
479             arg_ids = mkTemplateLocalsNum field_base (dataConInstOrigArgTys data_con tyvar_tys)
480
481             unpack_base = field_base + length arg_ids
482
483                                 -- arity+1 avoids all shadowing
484             maybe_the_arg_id  = assocMaybe (field_lbls `zip` arg_ids) field_label
485             field_lbls        = dataConFieldLabels data_con
486
487     error_expr = mkApps (Var rEC_SEL_ERROR_ID) [Type field_tau, err_string]
488     err_string
489         | all safeChar full_msg
490             = App (Var unpack_id) (Lit (MachStr (_PK_ full_msg)))
491         | otherwise
492             = App (Var unpackUtf8_id) (Lit (MachStr (_PK_ (stringToUtf8 (map ord full_msg)))))
493         where
494         safeChar c = c >= '\1' && c <= '\xFF'
495         -- TODO: Putting this Unicode stuff here is ugly. Find a better
496         -- generic place to make string literals. This logic is repeated
497         -- in DsUtils.
498     full_msg   = showSDoc (sep [text "No match in record selector", ppr sel_id]) 
499
500
501 -- This rather ugly function converts the unpacked data con 
502 -- arguments back into their packed form.
503
504 rebuildConArgs
505   :: [Id]                       -- Source-level args
506   -> [StrictnessMark]           -- Strictness annotations (per-arg)
507   -> [Unique]                   -- Uniques for the new Ids
508   -> ([CoreBind], [Id])         -- A binding for each source-level arg, plus
509                                 -- a list of the representation-level arguments 
510 -- e.g.   data T = MkT Int !Int
511 --
512 -- rebuild [x::Int, y::Int] [Not, Unbox]
513 --  = ([ y = I# t ], [x,t])
514
515 rebuildConArgs []         stricts us = ([], [])
516
517 -- Type variable case
518 rebuildConArgs (arg:args) stricts us 
519   | isTyVar arg
520   = let (binds, args') = rebuildConArgs args stricts us
521     in  (binds, arg:args')
522
523 -- Term variable case
524 rebuildConArgs (arg:args) (str:stricts) us
525   | isMarkedUnboxed str
526   = let
527         arg_ty  = idType arg
528
529         (_, tycon_args, pack_con, con_arg_tys)
530                  = splitProductType "rebuildConArgs" arg_ty
531
532         unpacked_args  = zipWith (mkSysLocal SLIT("rb")) us con_arg_tys
533         (binds, args') = rebuildConArgs args stricts (drop (length con_arg_tys) us)
534         con_app        = mkConApp pack_con (map Type tycon_args ++ map Var unpacked_args)
535     in
536     (NonRec arg con_app : binds, unpacked_args ++ args')
537
538   | otherwise
539   = let (binds, args') = rebuildConArgs args stricts us
540     in  (binds, arg:args')
541 \end{code}
542
543
544 %************************************************************************
545 %*                                                                      *
546 \subsection{Dictionary selectors}
547 %*                                                                      *
548 %************************************************************************
549
550 Selecting a field for a dictionary.  If there is just one field, then
551 there's nothing to do.  
552
553 ToDo: unify with mkRecordSelId.
554
555 \begin{code}
556 mkDictSelId :: Name -> Class -> Id
557 mkDictSelId name clas
558   = mkGlobalId (RecordSelId field_lbl) name sel_ty info
559   where
560     sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
561         -- We can't just say (exprType rhs), because that would give a type
562         --      C a -> C a
563         -- for a single-op class (after all, the selector is the identity)
564         -- But it's type must expose the representation of the dictionary
565         -- to gat (say)         C a -> (a -> a)
566
567     field_lbl = mkFieldLabel name tycon sel_ty tag
568     tag       = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` allFieldLabelTags) name
569
570     info      = noCafNoTyGenIdInfo
571                 `setCgArity`            1
572                 `setArityInfo`          1
573                 `setUnfoldingInfo`      mkTopUnfolding rhs
574                 `setNewStrictnessInfo`  Just strict_sig
575
576         -- We no longer use 'must-inline' on record selectors.  They'll
577         -- inline like crazy if they scrutinise a constructor
578
579         -- The strictness signature is of the form U(AAAVAAAA) -> T
580         -- where the V depends on which item we are selecting
581         -- It's worth giving one, so that absence info etc is generated
582         -- even if the selector isn't inlined
583     strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
584     arg_dmd | isNewTyCon tycon = Eval
585             | otherwise        = Seq Drop [ if the_arg_id == id then Eval else Abs
586                                           | id <- arg_ids ]
587
588     tyvars  = classTyVars clas
589
590     tycon      = classTyCon clas
591     [data_con] = tyConDataCons tycon
592     tyvar_tys  = mkTyVarTys tyvars
593     arg_tys    = dataConArgTys data_con tyvar_tys
594     the_arg_id = arg_ids !! (tag - firstFieldLabelTag)
595
596     pred              = mkClassPred clas tyvar_tys
597     (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
598
599     rhs | isNewTyCon tycon = mkLams tyvars $ Lam dict_id $ 
600                              mkNewTypeBody tycon (head arg_tys) dict_id
601         | otherwise        = mkLams tyvars $ Lam dict_id $
602                              Case (Var dict_id) dict_id
603                                   [(DataAlt data_con, arg_ids, Var the_arg_id)]
604
605 mkNewTypeBody tycon result_ty result_id
606   | isRecursiveTyCon tycon      -- Recursive case; use a coerce
607   = Note (Coerce result_ty (idType result_id)) (Var result_id)
608   | otherwise                   -- Normal case
609   = Var result_id
610 \end{code}
611
612
613 %************************************************************************
614 %*                                                                      *
615 \subsection{Primitive operations
616 %*                                                                      *
617 %************************************************************************
618
619 \begin{code}
620 mkPrimOpId :: PrimOp -> Id
621 mkPrimOpId prim_op 
622   = id
623   where
624     (tyvars,arg_tys,res_ty, arity, strict_info) = primOpSig prim_op
625     ty   = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
626     name = mkPrimOpIdName prim_op
627     id   = mkGlobalId (PrimOpId prim_op) name ty info
628                 
629     info = noCafNoTyGenIdInfo
630            `setSpecInfo`        rules
631            `setCgArity`         arity
632            `setArityInfo`       arity
633            `setNewStrictnessInfo`       Just (mkNewStrictnessInfo id arity strict_info NoCPRInfo)
634         -- Until we modify the primop generation code
635
636     rules = foldl (addRule id) emptyCoreRules (primOpRules prim_op)
637
638
639 -- For each ccall we manufacture a separate CCallOpId, giving it
640 -- a fresh unique, a type that is correct for this particular ccall,
641 -- and a CCall structure that gives the correct details about calling
642 -- convention etc.  
643 --
644 -- The *name* of this Id is a local name whose OccName gives the full
645 -- details of the ccall, type and all.  This means that the interface 
646 -- file reader can reconstruct a suitable Id
647
648 mkFCallId :: Unique -> ForeignCall -> Type -> Id
649 mkFCallId uniq fcall ty
650   = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
651         -- A CCallOpId should have no free type variables; 
652         -- when doing substitutions won't substitute over it
653     mkGlobalId (FCallId fcall) name ty info
654   where
655     occ_str = showSDocIface (braces (ppr fcall <+> ppr ty))
656         -- The "occurrence name" of a ccall is the full info about the
657         -- ccall; it is encoded, but may have embedded spaces etc!
658
659     name = mkFCallName uniq occ_str
660
661     info = noCafNoTyGenIdInfo
662            `setCgArity`                 arity
663            `setArityInfo`               arity
664            `setNewStrictnessInfo`       Just strict_sig
665
666     (_, tau)     = tcSplitForAllTys ty
667     (arg_tys, _) = tcSplitFunTys tau
668     arity        = length arg_tys
669     strict_sig   = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
670 \end{code}
671
672
673 %************************************************************************
674 %*                                                                      *
675 \subsection{DictFuns and default methods}
676 %*                                                                      *
677 %************************************************************************
678
679 Important notes about dict funs and default methods
680 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
681 Dict funs and default methods are *not* ImplicitIds.  Their definition
682 involves user-written code, so we can't figure out their strictness etc
683 based on fixed info, as we can for constructors and record selectors (say).
684
685 We build them as GlobalIds, but when in the module where they are
686 bound, we turn the Id at the *binding site* into an exported LocalId.
687 This ensures that they are taken to account by free-variable finding
688 and dependency analysis (e.g. CoreFVs.exprFreeVars).   The simplifier
689 will propagate the LocalId to all occurrence sites. 
690
691 Why shouldn't they be bound as GlobalIds?  Because, in particular, if
692 they are globals, the specialiser floats dict uses above their defns,
693 which prevents good simplifications happening.  Also the strictness
694 analyser treats a occurrence of a GlobalId as imported and assumes it
695 contains strictness in its IdInfo, which isn't true if the thing is
696 bound in the same module as the occurrence.
697
698 It's OK for dfuns to be LocalIds, because we form the instance-env to
699 pass on to the next module (md_insts) in CoreTidy, afer tidying
700 and globalising the top-level Ids.
701
702 BUT make sure they are *exported* LocalIds (setIdLocalExported) so 
703 that they aren't discarded by the occurrence analyser.
704
705 \begin{code}
706 mkDefaultMethodId dm_name ty = mkVanillaGlobal dm_name ty noCafNoTyGenIdInfo
707
708 mkDictFunId :: Name             -- Name to use for the dict fun;
709             -> Class 
710             -> [TyVar]
711             -> [Type]
712             -> ThetaType
713             -> Id
714
715 mkDictFunId dfun_name clas inst_tyvars inst_tys dfun_theta
716   = mkVanillaGlobal dfun_name dfun_ty noCafNoTyGenIdInfo
717   where
718     dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
719
720 {-  1 dec 99: disable the Mark Jones optimisation for the sake
721     of compatibility with Hugs.
722     See `types/InstEnv' for a discussion related to this.
723
724     (class_tyvars, sc_theta, _, _) = classBigSig clas
725     not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
726     sc_theta' = substClasses (mkTopTyVarSubst class_tyvars inst_tys) sc_theta
727     dfun_theta = case inst_decl_theta of
728                    []    -> []  -- If inst_decl_theta is empty, then we don't
729                                 -- want to have any dict arguments, so that we can
730                                 -- expose the constant methods.
731
732                    other -> nub (inst_decl_theta ++ filter not_const sc_theta')
733                                 -- Otherwise we pass the superclass dictionaries to
734                                 -- the dictionary function; the Mark Jones optimisation.
735                                 --
736                                 -- NOTE the "nub".  I got caught by this one:
737                                 --   class Monad m => MonadT t m where ...
738                                 --   instance Monad m => MonadT (EnvT env) m where ...
739                                 -- Here, the inst_decl_theta has (Monad m); but so
740                                 -- does the sc_theta'!
741                                 --
742                                 -- NOTE the "not_const".  I got caught by this one too:
743                                 --   class Foo a => Baz a b where ...
744                                 --   instance Wob b => Baz T b where..
745                                 -- Now sc_theta' has Foo T
746 -}
747 \end{code}
748
749
750 %************************************************************************
751 %*                                                                      *
752 \subsection{Un-definable}
753 %*                                                                      *
754 %************************************************************************
755
756 These Ids can't be defined in Haskell.  They could be defined in 
757 unfoldings in PrelGHC.hi-boot, but we'd have to ensure that they
758 were definitely, definitely inlined, because there is no curried
759 identifier for them.  Thats what mkCompulsoryUnfolding does.
760 If we had a way to get a compulsory unfolding from an interface file,
761 we could do that, but we don't right now.
762
763 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
764 just gets expanded into a type coercion wherever it occurs.  Hence we
765 add it as a built-in Id with an unfolding here.
766
767 The type variables we use here are "open" type variables: this means
768 they can unify with both unlifted and lifted types.  Hence we provide
769 another gun with which to shoot yourself in the foot.
770
771 \begin{code}
772 unsafeCoerceId
773   = pcMiscPrelId unsafeCoerceIdKey pREL_GHC SLIT("unsafeCoerce#") ty info
774   where
775     info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
776            
777
778     ty  = mkForAllTys [openAlphaTyVar,openBetaTyVar]
779                       (mkFunTy openAlphaTy openBetaTy)
780     [x] = mkTemplateLocals [openAlphaTy]
781     rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
782           Note (Coerce openBetaTy openAlphaTy) (Var x)
783
784 seqId
785   = pcMiscPrelId seqIdKey pREL_GHC SLIT("seq") ty info
786   where
787     info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
788            
789
790     ty  = mkForAllTys [alphaTyVar,betaTyVar]
791                       (mkFunTy alphaTy (mkFunTy betaTy betaTy))
792     [x,y] = mkTemplateLocals [alphaTy, betaTy]
793     rhs = mkLams [alphaTyVar,betaTyVar,x,y] (Case (Var x) x [(DEFAULT, [], Var y)])
794 \end{code}
795
796 @getTag#@ is another function which can't be defined in Haskell.  It needs to
797 evaluate its argument and call the dataToTag# primitive.
798
799 \begin{code}
800 getTagId
801   = pcMiscPrelId getTagIdKey pREL_GHC SLIT("getTag#") ty info
802   where
803     info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
804         -- We don't provide a defn for this; you must inline it
805
806     ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy intPrimTy)
807     [x,y] = mkTemplateLocals [alphaTy,alphaTy]
808     rhs = mkLams [alphaTyVar,x] $
809           Case (Var x) y [ (DEFAULT, [], mkApps (Var dataToTagId) [Type alphaTy, Var y]) ]
810
811 dataToTagId = mkPrimOpId DataToTagOp
812 \end{code}
813
814 @realWorld#@ used to be a magic literal, \tr{void#}.  If things get
815 nasty as-is, change it back to a literal (@Literal@).
816
817 \begin{code}
818 realWorldPrimId -- :: State# RealWorld
819   = pcMiscPrelId realWorldPrimIdKey pREL_GHC SLIT("realWorld#")
820                  realWorldStatePrimTy
821                  (noCafNoTyGenIdInfo `setUnfoldingInfo` mkOtherCon [])
822         -- The mkOtherCon makes it look that realWorld# is evaluated
823         -- which in turn makes Simplify.interestingArg return True,
824         -- which in turn makes INLINE things applied to realWorld# likely
825         -- to be inlined
826 \end{code}
827
828
829 %************************************************************************
830 %*                                                                      *
831 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
832 %*                                                                      *
833 %************************************************************************
834
835 GHC randomly injects these into the code.
836
837 @patError@ is just a version of @error@ for pattern-matching
838 failures.  It knows various ``codes'' which expand to longer
839 strings---this saves space!
840
841 @absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
842 well shouldn't be yanked on, but if one is, then you will get a
843 friendly message from @absentErr@ (rather than a totally random
844 crash).
845
846 @parError@ is a special version of @error@ which the compiler does
847 not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
848 templates, but we don't ever expect to generate code for it.
849
850 \begin{code}
851 eRROR_ID
852   = pc_bottoming_Id errorIdKey pREL_ERR SLIT("error") errorTy
853 eRROR_CSTRING_ID
854   = pc_bottoming_Id errorCStringIdKey pREL_ERR SLIT("errorCString") 
855                     (mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy))
856 pAT_ERROR_ID
857   = generic_ERROR_ID patErrorIdKey SLIT("patError")
858 rEC_SEL_ERROR_ID
859   = generic_ERROR_ID recSelErrIdKey SLIT("recSelError")
860 rEC_CON_ERROR_ID
861   = generic_ERROR_ID recConErrorIdKey SLIT("recConError")
862 rEC_UPD_ERROR_ID
863   = generic_ERROR_ID recUpdErrorIdKey SLIT("recUpdError")
864 iRREFUT_PAT_ERROR_ID
865   = generic_ERROR_ID irrefutPatErrorIdKey SLIT("irrefutPatError")
866 nON_EXHAUSTIVE_GUARDS_ERROR_ID
867   = generic_ERROR_ID nonExhaustiveGuardsErrorIdKey SLIT("nonExhaustiveGuardsError")
868 nO_METHOD_BINDING_ERROR_ID
869   = generic_ERROR_ID noMethodBindingErrorIdKey SLIT("noMethodBindingError")
870
871 aBSENT_ERROR_ID
872   = pc_bottoming_Id absentErrorIdKey pREL_ERR SLIT("absentErr")
873         (mkSigmaTy [openAlphaTyVar] [] openAlphaTy)
874
875 pAR_ERROR_ID
876   = pcMiscPrelId parErrorIdKey pREL_ERR SLIT("parError")
877     (mkSigmaTy [openAlphaTyVar] [] openAlphaTy) noCafNoTyGenIdInfo
878 \end{code}
879
880
881 %************************************************************************
882 %*                                                                      *
883 \subsection{Utilities}
884 %*                                                                      *
885 %************************************************************************
886
887 \begin{code}
888 pcMiscPrelId :: Unique{-IdKey-} -> Module -> FAST_STRING -> Type -> IdInfo -> Id
889 pcMiscPrelId key mod str ty info
890   = let
891         name = mkWiredInName mod (mkVarOcc str) key
892         imp  = mkVanillaGlobal name ty info -- the usual case...
893     in
894     imp
895     -- We lie and say the thing is imported; otherwise, we get into
896     -- a mess with dependency analysis; e.g., core2stg may heave in
897     -- random calls to GHCbase.unpackPS__.  If GHCbase is the module
898     -- being compiled, then it's just a matter of luck if the definition
899     -- will be in "the right place" to be in scope.
900
901 pc_bottoming_Id key mod name ty
902  = pcMiscPrelId key mod name ty bottoming_info
903  where
904     strict_sig     = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
905     bottoming_info = noCafNoTyGenIdInfo `setNewStrictnessInfo` Just strict_sig
906         -- these "bottom" out, no matter what their arguments
907
908 generic_ERROR_ID u n = pc_bottoming_Id u pREL_ERR n errorTy
909
910 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
911 openAlphaTy  = mkTyVarTy openAlphaTyVar
912 openBetaTy   = mkTyVarTy openBetaTyVar
913
914 errorTy  :: Type
915 errorTy  = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] 
916                                                    openAlphaTy)
917     -- Notice the openAlphaTyVar.  It says that "error" can be applied
918     -- to unboxed as well as boxed types.  This is OK because it never
919     -- returns, so the return type is irrelevant.
920 \end{code}
921