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