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