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