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