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