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