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