80d4622e7f3acd0e14724502b80df244e0012a26
[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         mkDictFunId, mkDefaultMethodId,
17         mkDictSelId, 
18
19         mkDataConId, mkDataConWrapId,
20         mkRecordSelId, 
21         mkPrimOpId, mkFCallId,
22
23         mkReboxingAlt, mkNewTypeBody,
24
25         -- And some particular Ids; see below for why they are wired in
26         wiredInIds, ghcPrimIds,
27         unsafeCoerceId, realWorldPrimId, voidArgId, nullAddrId, seqId,
28
29         mkRuntimeErrorApp,
30         rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID, rUNTIME_ERROR_ID,
31         nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
32         pAT_ERROR_ID
33     ) where
34
35 #include "HsVersions.h"
36
37
38 import BasicTypes       ( Arity, StrictnessMark(..), isMarkedUnboxed, isMarkedStrict )
39 import TysPrim          ( openAlphaTyVars, alphaTyVar, alphaTy, betaTyVar, betaTy,
40                           intPrimTy, realWorldStatePrimTy, addrPrimTy
41                         )
42 import TysWiredIn       ( charTy, mkListTy )
43 import PrelRules        ( primOpRules )
44 import Rules            ( addRule )
45 import TcType           ( Type, ThetaType, mkDictTy, mkPredTys, mkTyConApp,
46                           mkTyVarTys, mkClassPred, tcEqPred,
47                           mkFunTys, mkFunTy, mkSigmaTy, tcSplitSigmaTy, 
48                           isUnLiftedType, mkForAllTys, mkTyVarTy, tyVarsOfType,
49                           tcSplitFunTys, tcSplitForAllTys, mkPredTy
50                         )
51 import Module           ( Module )
52 import CoreUtils        ( exprType )
53 import CoreUnfold       ( mkTopUnfolding, mkCompulsoryUnfolding, mkOtherCon )
54 import Literal          ( Literal(..), nullAddrLit )
55 import TyCon            ( TyCon, isNewTyCon, tyConTyVars, tyConDataCons,
56                           tyConTheta, isProductTyCon, isDataTyCon, isRecursiveTyCon )
57 import Class            ( Class, classTyCon, classTyVars, classSelIds )
58 import Var              ( Id, TyVar, Var )
59 import VarSet           ( isEmptyVarSet )
60 import Name             ( mkWiredInName, mkFCallName, Name )
61 import OccName          ( mkVarOcc )
62 import PrimOp           ( PrimOp(DataToTagOp), primOpSig, mkPrimOpIdName )
63 import ForeignCall      ( ForeignCall )
64 import DataCon          ( DataCon, 
65                           dataConFieldLabels, dataConRepArity, dataConTyCon,
66                           dataConArgTys, dataConRepType, 
67                           dataConOrigArgTys,
68                           dataConName, dataConTheta,
69                           dataConSig, dataConStrictMarks, dataConWorkId,
70                           splitProductType
71                         )
72 import Id               ( idType, mkGlobalId, mkVanillaGlobal, mkSysLocal,
73                           mkTemplateLocals, mkTemplateLocalsNum,
74                           mkTemplateLocal, idNewStrictness, idName
75                         )
76 import IdInfo           ( IdInfo, noCafNoTyGenIdInfo,
77                           setUnfoldingInfo, 
78                           setArityInfo, setSpecInfo, setCafInfo,
79                           setAllStrictnessInfo,
80                           GlobalIdDetails(..), CafInfo(..)
81                         )
82 import NewDemand        ( mkStrictSig, strictSigResInfo, DmdResult(..),
83                           mkTopDmdType, topDmd, evalDmd, lazyDmd, retCPR,
84                           Demand(..), Demands(..) )
85 import FieldLabel       ( mkFieldLabel, fieldLabelName, 
86                           firstFieldLabelTag, allFieldLabelTags, fieldLabelType
87                         )
88 import DmdAnal          ( dmdAnalTopRhs )
89 import CoreSyn
90 import Unique           ( mkBuiltinUnique )
91 import Maybes
92 import PrelNames
93 import Maybe            ( isJust )
94 import Util             ( dropList, isSingleton )
95 import Outputable
96 import ListSetOps       ( assoc, assocMaybe )
97 import UnicodeUtil      ( stringToUtf8 )
98 import List             ( nubBy )
99 import Char             ( ord )
100 \end{code}              
101
102 %************************************************************************
103 %*                                                                      *
104 \subsection{Wired in Ids}
105 %*                                                                      *
106 %************************************************************************
107
108 \begin{code}
109 wiredInIds
110   = [   -- These error-y things are wired in because we don't yet have
111         -- a way to express in an interface file that the result type variable
112         -- is 'open'; that is can be unified with an unboxed type
113         -- 
114         -- [The interface file format now carry such information, but there's
115         -- no way yet of expressing at the definition site for these 
116         -- error-reporting functions that they have an 'open' 
117         -- result type. -- sof 1/99]
118
119     eRROR_ID,   -- This one isn't used anywhere else in the compiler
120                 -- But we still need it in wiredInIds so that when GHC
121                 -- compiles a program that mentions 'error' we don't
122                 -- import its type from the interface file; we just get
123                 -- the Id defined here.  Which has an 'open-tyvar' type.
124
125     rUNTIME_ERROR_ID,
126     iRREFUT_PAT_ERROR_ID,
127     nON_EXHAUSTIVE_GUARDS_ERROR_ID,
128     nO_METHOD_BINDING_ERROR_ID,
129     pAT_ERROR_ID,
130     rEC_CON_ERROR_ID
131     ] ++ ghcPrimIds
132
133 -- These Ids are exported from GHC.Prim
134 ghcPrimIds
135   = [   -- These can't be defined in Haskell, but they have
136         -- perfectly reasonable unfoldings in Core
137     realWorldPrimId,
138     unsafeCoerceId,
139     nullAddrId,
140     getTagId,
141     seqId
142     ]
143 \end{code}
144
145 %************************************************************************
146 %*                                                                      *
147 \subsection{Data constructors}
148 %*                                                                      *
149 %************************************************************************
150
151 \begin{code}
152 mkDataConId :: Name -> DataCon -> Id
153         -- Makes the *worker* for the data constructor; that is, the function
154         -- that takes the reprsentation arguments and builds the constructor.
155 mkDataConId work_name data_con
156   = mkGlobalId (DataConId data_con) work_name (dataConRepType data_con) info
157   where
158     info = noCafNoTyGenIdInfo
159            `setArityInfo`               arity
160            `setAllStrictnessInfo`       Just strict_sig
161
162     arity      = dataConRepArity data_con
163
164     strict_sig = mkStrictSig (mkTopDmdType (replicate arity topDmd) cpr_info)
165         -- Notice that we do *not* say the worker is strict
166         -- even if the data constructor is declared strict
167         --      e.g.    data T = MkT !(Int,Int)
168         -- Why?  Because the *wrapper* is strict (and its unfolding has case
169         -- expresssions that do the evals) but the *worker* itself is not.
170         -- If we pretend it is strict then when we see
171         --      case x of y -> $wMkT y
172         -- the simplifier thinks that y is "sure to be evaluated" (because
173         -- $wMkT is strict) and drops the case.  No, $wMkT is not strict.
174         --
175         -- When the simplifer sees a pattern 
176         --      case e of MkT x -> ...
177         -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
178         -- but that's fine... dataConRepStrictness comes from the data con
179         -- not from the worker Id.
180
181     tycon = dataConTyCon data_con
182     cpr_info | isProductTyCon tycon && 
183                isDataTyCon tycon    &&
184                arity > 0            &&
185                arity <= mAX_CPR_SIZE    = retCPR
186              | otherwise                = TopRes
187         -- RetCPR is only true for products that are real data types;
188         -- that is, not unboxed tuples or [non-recursive] newtypes
189
190 mAX_CPR_SIZE :: Arity
191 mAX_CPR_SIZE = 10
192 -- We do not treat very big tuples as CPR-ish:
193 --      a) for a start we get into trouble because there aren't 
194 --         "enough" unboxed tuple types (a tiresome restriction, 
195 --         but hard to fix), 
196 --      b) more importantly, big unboxed tuples get returned mainly
197 --         on the stack, and are often then allocated in the heap
198 --         by the caller.  So doing CPR for them may in fact make
199 --         things worse.
200 \end{code}
201
202 The wrapper for a constructor is an ordinary top-level binding that evaluates
203 any strict args, unboxes any args that are going to be flattened, and calls
204 the worker.
205
206 We're going to build a constructor that looks like:
207
208         data (Data a, C b) =>  T a b = T1 !a !Int b
209
210         T1 = /\ a b -> 
211              \d1::Data a, d2::C b ->
212              \p q r -> case p of { p ->
213                        case q of { q ->
214                        Con T1 [a,b] [p,q,r]}}
215
216 Notice that
217
218 * d2 is thrown away --- a context in a data decl is used to make sure
219   one *could* construct dictionaries at the site the constructor
220   is used, but the dictionary isn't actually used.
221
222 * We have to check that we can construct Data dictionaries for
223   the types a and Int.  Once we've done that we can throw d1 away too.
224
225 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
226   all that matters is that the arguments are evaluated.  "seq" is 
227   very careful to preserve evaluation order, which we don't need
228   to be here.
229
230   You might think that we could simply give constructors some strictness
231   info, like PrimOps, and let CoreToStg do the let-to-case transformation.
232   But we don't do that because in the case of primops and functions strictness
233   is a *property* not a *requirement*.  In the case of constructors we need to
234   do something active to evaluate the argument.
235
236   Making an explicit case expression allows the simplifier to eliminate
237   it in the (common) case where the constructor arg is already evaluated.
238
239 \begin{code}
240 mkDataConWrapId data_con
241   = mkGlobalId (DataConWrapId data_con) (dataConName data_con) wrap_ty info
242   where
243     work_id = dataConWorkId data_con
244
245     info = noCafNoTyGenIdInfo
246            `setUnfoldingInfo`   wrap_unf
247                 -- The NoCaf-ness is set by noCafNoTyGenIdInfo
248            `setArityInfo`       arity
249                 -- It's important to specify the arity, so that partial
250                 -- applications are treated as values
251            `setAllStrictnessInfo`       Just wrap_sig
252
253     wrap_sig = mkStrictSig (mkTopDmdType arg_dmds res_info)
254     res_info = strictSigResInfo (idNewStrictness work_id)
255     arg_dmds = map mk_dmd strict_marks
256     mk_dmd str | isMarkedStrict str = evalDmd
257                | otherwise          = lazyDmd
258         -- The Cpr info can be important inside INLINE rhss, where the
259         -- wrapper constructor isn't inlined.
260         -- And the argument strictness can be important too; we
261         -- may not inline a contructor when it is partially applied.
262         -- For example:
263         --      data W = C !Int !Int !Int
264         --      ...(let w = C x in ...(w p q)...)...
265         -- we want to see that w is strict in its two arguments
266
267     wrap_unf | isNewTyCon tycon
268              = ASSERT( null ex_tyvars && null ex_dict_args && isSingleton orig_arg_tys )
269                 -- No existentials on a newtype, but it can have a context
270                 -- e.g.         newtype Eq a => T a = MkT (...)
271                 mkTopUnfolding $ Note InlineMe $
272                 mkLams tyvars $ Lam id_arg1 $ 
273                 mkNewTypeBody tycon result_ty (Var id_arg1)
274
275              | not (any isMarkedStrict strict_marks)
276              = mkCompulsoryUnfolding (Var work_id)
277                         -- The common case.  Not only is this efficient,
278                         -- but it also ensures that the wrapper is replaced
279                         -- by the worker even when there are no args.
280                         --              f (:) x
281                         -- becomes 
282                         --              f $w: x
283                         -- This is really important in rule matching,
284                         -- (We could match on the wrappers,
285                         -- but that makes it less likely that rules will match
286                         -- when we bring bits of unfoldings together.)
287                 --
288                 -- NB:  because of this special case, (map (:) ys) turns into
289                 --      (map $w: ys).  The top-level defn for (:) is never used.
290                 --      This is somewhat of a bore, but I'm currently leaving it 
291                 --      as is, so that there still is a top level curried (:) for
292                 --      the interpreter to call.
293
294              | otherwise
295              = mkTopUnfolding $ Note InlineMe $
296                mkLams all_tyvars $ 
297                mkLams ex_dict_args $ mkLams id_args $
298                foldr mk_case con_app 
299                      (zip (ex_dict_args++id_args) strict_marks) i3 []
300
301     con_app i rep_ids = mkApps (Var work_id)
302                                (map varToCoreExpr (all_tyvars ++ reverse rep_ids))
303
304     (tyvars, _, ex_tyvars, ex_theta, orig_arg_tys, tycon) = dataConSig data_con
305     all_tyvars   = tyvars ++ ex_tyvars
306
307     ex_dict_tys  = mkPredTys ex_theta
308     all_arg_tys  = ex_dict_tys ++ orig_arg_tys
309     result_ty    = mkTyConApp tycon (mkTyVarTys tyvars)
310
311     wrap_ty = mkForAllTys all_tyvars (mkFunTys all_arg_tys result_ty)
312         -- We used to include the stupid theta in the wrapper's args
313         -- but now we don't.  Instead the type checker just injects these
314         -- extra constraints where necessary.
315
316     mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
317                    where
318                      n = length tys
319
320     (ex_dict_args,i2)  = mkLocals 1  ex_dict_tys
321     (id_args,i3)       = mkLocals i2 orig_arg_tys
322     arity              = i3-1
323     (id_arg1:_)   = id_args             -- Used for newtype only
324
325     strict_marks  = dataConStrictMarks data_con
326
327     mk_case 
328            :: (Id, StrictnessMark)      -- Arg, strictness
329            -> (Int -> [Id] -> CoreExpr) -- Body
330            -> Int                       -- Next rep arg id
331            -> [Id]                      -- Rep args so far, reversed
332            -> CoreExpr
333     mk_case (arg,strict) body i rep_args
334           = case strict of
335                 NotMarkedStrict -> body i (arg:rep_args)
336                 MarkedStrict 
337                    | isUnLiftedType (idType arg) -> body i (arg:rep_args)
338                    | otherwise ->
339                         Case (Var arg) arg [(DEFAULT,[], body i (arg:rep_args))]
340
341                 MarkedUnboxed
342                    -> case splitProductType "do_unbox" (idType arg) of
343                            (tycon, tycon_args, con, tys) ->
344                                    Case (Var arg) arg [(DataAlt con, con_args,
345                                         body i' (reverse con_args ++ rep_args))]
346                               where 
347                                 (con_args, i') = mkLocals i tys
348 \end{code}
349
350
351 %************************************************************************
352 %*                                                                      *
353 \subsection{Record selectors}
354 %*                                                                      *
355 %************************************************************************
356
357 We're going to build a record selector unfolding that looks like this:
358
359         data T a b c = T1 { ..., op :: a, ...}
360                      | T2 { ..., op :: a, ...}
361                      | T3
362
363         sel = /\ a b c -> \ d -> case d of
364                                     T1 ... x ... -> x
365                                     T2 ... x ... -> x
366                                     other        -> error "..."
367
368 Similarly for newtypes
369
370         newtype N a = MkN { unN :: a->a }
371
372         unN :: N a -> a -> a
373         unN n = coerce (a->a) n
374         
375 We need to take a little care if the field has a polymorphic type:
376
377         data R = R { f :: forall a. a->a }
378
379 Then we want
380
381         f :: forall a. R -> a -> a
382         f = /\ a \ r = case r of
383                           R f -> f a
384
385 (not f :: R -> forall a. a->a, which gives the type inference mechanism 
386 problems at call sites)
387
388 Similarly for newtypes
389
390         newtype N = MkN { unN :: forall a. a->a }
391
392         unN :: forall a. N -> a -> a
393         unN = /\a -> \n:N -> coerce (a->a) n
394
395 \begin{code}
396 mkRecordSelId tycon field_label
397         -- Assumes that all fields with the same field label have the same type
398         --
399         -- Annoyingly, we have to pass in the unpackCString# Id, because
400         -- we can't conjure it up out of thin air
401   = sel_id
402   where
403     sel_id     = mkGlobalId (RecordSelId field_label) (fieldLabelName field_label) selector_ty info
404     field_ty   = fieldLabelType field_label
405     data_cons  = tyConDataCons tycon
406     tyvars     = tyConTyVars tycon      -- These scope over the types in 
407                                         -- the FieldLabels of constructors of this type
408     data_ty   = mkTyConApp tycon tyvar_tys
409     tyvar_tys = mkTyVarTys tyvars
410
411         -- Very tiresomely, the selectors are (unnecessarily!) overloaded over
412         -- just the dictionaries in the types of the constructors that contain
413         -- the relevant field.  [The Report says that pattern matching on a
414         -- constructor gives the same constraints as applying it.]  Urgh.  
415         --
416         -- However, not all data cons have all constraints (because of
417         -- TcTyDecls.thinContext).  So we need to find all the data cons 
418         -- involved in the pattern match and take the union of their constraints.
419         --
420         -- NB: this code relies on the fact that DataCons are quantified over
421         -- the identical type variables as their parent TyCon
422     tycon_theta  = tyConTheta tycon     -- The context on the data decl
423                                         --   eg data (Eq a, Ord b) => T a b = ...
424     needed_preds = [pred | (DataAlt dc, _, _) <- the_alts, pred <- dataConTheta dc]
425     dict_tys     = map mkPredTy (nubBy tcEqPred needed_preds)
426     n_dict_tys   = length dict_tys
427
428     (field_tyvars,field_theta,field_tau) = tcSplitSigmaTy field_ty
429     field_dict_tys                       = map mkPredTy field_theta
430     n_field_dict_tys                     = length field_dict_tys
431         -- If the field has a universally quantified type we have to 
432         -- be a bit careful.  Suppose we have
433         --      data R = R { op :: forall a. Foo a => a -> a }
434         -- Then we can't give op the type
435         --      op :: R -> forall a. Foo a => a -> a
436         -- because the typechecker doesn't understand foralls to the
437         -- right of an arrow.  The "right" type to give it is
438         --      op :: forall a. Foo a => R -> a -> a
439         -- But then we must generate the right unfolding too:
440         --      op = /\a -> \dfoo -> \ r ->
441         --           case r of
442         --              R op -> op a dfoo
443         -- Note that this is exactly the type we'd infer from a user defn
444         --      op (R op) = op
445
446     selector_ty :: Type
447     selector_ty  = mkForAllTys tyvars $ mkForAllTys field_tyvars $
448                    mkFunTys dict_tys  $  mkFunTys field_dict_tys $
449                    mkFunTy data_ty field_tau
450       
451     arity = 1 + n_dict_tys + n_field_dict_tys
452
453     (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
454         -- Use the demand analyser to work out strictness.
455         -- With all this unpackery it's not easy!
456
457     info = noCafNoTyGenIdInfo
458            `setCafInfo`           caf_info
459            `setArityInfo`         arity
460            `setUnfoldingInfo`     mkTopUnfolding rhs_w_str
461            `setAllStrictnessInfo` Just strict_sig
462
463         -- Allocate Ids.  We do it a funny way round because field_dict_tys is
464         -- almost always empty.  Also note that we use length_tycon_theta
465         -- rather than n_dict_tys, because the latter gives an infinite loop:
466         -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
467         -- on arity, which depends on n_dict tys.  Sigh!  Mega sigh!
468     field_dict_base    = length tycon_theta + 1
469     dict_id_base       = field_dict_base + n_field_dict_tys
470     field_base         = dict_id_base + 1
471     dict_ids           = mkTemplateLocalsNum  1               dict_tys
472     field_dict_ids     = mkTemplateLocalsNum  field_dict_base field_dict_tys
473     data_id            = mkTemplateLocal      dict_id_base    data_ty
474
475     alts      = map mk_maybe_alt data_cons
476     the_alts  = catMaybes alts
477
478     no_default = all isJust alts        -- No default needed
479     default_alt | no_default = []
480                 | otherwise  = [(DEFAULT, [], error_expr)]
481
482         -- the default branch may have CAF refs, because it calls recSelError etc.
483     caf_info    | no_default = NoCafRefs
484                 | otherwise  = MayHaveCafRefs
485
486     sel_rhs = mkLams tyvars   $ mkLams field_tyvars $ 
487               mkLams dict_ids $ mkLams field_dict_ids $
488               Lam data_id     $ sel_body
489
490     sel_body | isNewTyCon tycon = mkNewTypeBody tycon field_tau (mk_result data_id)
491              | otherwise        = Case (Var data_id) data_id (default_alt ++ the_alts)
492
493     mk_result result_id = mkVarApps (mkVarApps (Var result_id) field_tyvars) field_dict_ids
494         -- We pull the field lambdas to the top, so we need to 
495         -- apply them in the body.  For example:
496         --      data T = MkT { foo :: forall a. a->a }
497         --
498         --      foo :: forall a. T -> a -> a
499         --      foo = /\a. \t:T. case t of { MkT f -> f a }
500
501     mk_maybe_alt data_con 
502         = case maybe_the_arg_id of
503                 Nothing         -> Nothing
504                 Just the_arg_id -> Just (mkReboxingAlt uniqs data_con arg_ids body)
505                                 where
506                                    body = mk_result the_arg_id
507         where
508             arg_ids = mkTemplateLocalsNum field_base (dataConOrigArgTys data_con)
509                         -- No need to instantiate; same tyvars in datacon as tycon
510
511             unpack_base = field_base + length arg_ids
512             uniqs = map mkBuiltinUnique [unpack_base..]
513
514                                 -- arity+1 avoids all shadowing
515             maybe_the_arg_id  = assocMaybe (field_lbls `zip` arg_ids) field_label
516             field_lbls        = dataConFieldLabels data_con
517
518     error_expr = mkRuntimeErrorApp rEC_SEL_ERROR_ID field_tau full_msg
519     full_msg   = showSDoc (sep [text "No match in record selector", ppr sel_id]) 
520
521
522 -- (mkReboxingAlt us con xs rhs) basically constructs the case
523 -- alternative  (con, xs, rhs)
524 -- but it does the reboxing necessary to construct the *source* 
525 -- arguments, xs, from the representation arguments ys.
526 -- For example:
527 --      data T = MkT !(Int,Int) Bool
528 --
529 -- mkReboxingAlt MkT [x,b] r 
530 --      = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
531 --
532 -- mkDataAlt should really be in DataCon, but it can't because
533 -- it manipulates CoreSyn.
534
535 mkReboxingAlt
536   :: [Unique]                   -- Uniques for the new Ids
537   -> DataCon
538   -> [Var]                      -- Source-level args
539   -> CoreExpr                   -- RHS
540   -> CoreAlt
541
542 mkReboxingAlt us con args rhs
543   | not (any isMarkedUnboxed stricts)
544   = (DataAlt con, args, rhs)
545
546   | otherwise
547   = let
548         (binds, args') = go args stricts us
549     in
550     (DataAlt con, args', mkLets binds rhs)
551
552   where
553     stricts = dataConStrictMarks con
554
555     go [] stricts us = ([], [])
556
557         -- Type variable case
558     go (arg:args) stricts us 
559       | isTyVar arg
560       = let (binds, args') = go args stricts us
561         in  (binds, arg:args')
562
563         -- Term variable case
564     go (arg:args) (str:stricts) us
565       | isMarkedUnboxed str
566       = let
567           (_, tycon_args, pack_con, con_arg_tys)
568                  = splitProductType "mkReboxingAlt" (idType arg)
569
570           unpacked_args  = zipWith (mkSysLocal FSLIT("rb")) us con_arg_tys
571           (binds, args') = go args stricts (dropList con_arg_tys us)
572           con_app        = mkConApp pack_con (map Type tycon_args ++ map Var unpacked_args)
573         in
574         (NonRec arg con_app : binds, unpacked_args ++ args')
575
576       | otherwise
577       = let (binds, args') = go args stricts us
578         in  (binds, arg:args')
579 \end{code}
580
581
582 %************************************************************************
583 %*                                                                      *
584 \subsection{Dictionary selectors}
585 %*                                                                      *
586 %************************************************************************
587
588 Selecting a field for a dictionary.  If there is just one field, then
589 there's nothing to do.  
590
591 ToDo: unify with mkRecordSelId.
592
593 \begin{code}
594 mkDictSelId :: Name -> Class -> Id
595 mkDictSelId name clas
596   = mkGlobalId (RecordSelId field_lbl) name sel_ty info
597   where
598     sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
599         -- We can't just say (exprType rhs), because that would give a type
600         --      C a -> C a
601         -- for a single-op class (after all, the selector is the identity)
602         -- But it's type must expose the representation of the dictionary
603         -- to gat (say)         C a -> (a -> a)
604
605     field_lbl = mkFieldLabel name tycon sel_ty tag
606     tag       = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` allFieldLabelTags) name
607
608     info      = noCafNoTyGenIdInfo
609                 `setArityInfo`          1
610                 `setUnfoldingInfo`      mkTopUnfolding rhs
611                 `setAllStrictnessInfo`  Just strict_sig
612
613         -- We no longer use 'must-inline' on record selectors.  They'll
614         -- inline like crazy if they scrutinise a constructor
615
616         -- The strictness signature is of the form U(AAAVAAAA) -> T
617         -- where the V depends on which item we are selecting
618         -- It's worth giving one, so that absence info etc is generated
619         -- even if the selector isn't inlined
620     strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
621     arg_dmd | isNewTyCon tycon = evalDmd
622             | otherwise        = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
623                                             | id <- arg_ids ])
624
625     tyvars  = classTyVars clas
626
627     tycon      = classTyCon clas
628     [data_con] = tyConDataCons tycon
629     tyvar_tys  = mkTyVarTys tyvars
630     arg_tys    = dataConArgTys data_con tyvar_tys
631     the_arg_id = arg_ids !! (tag - firstFieldLabelTag)
632
633     pred              = mkClassPred clas tyvar_tys
634     (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
635
636     rhs | isNewTyCon tycon = mkLams tyvars $ Lam dict_id $ 
637                              mkNewTypeBody tycon (head arg_tys) (Var dict_id)
638         | otherwise        = mkLams tyvars $ Lam dict_id $
639                              Case (Var dict_id) dict_id
640                                   [(DataAlt data_con, arg_ids, Var the_arg_id)]
641
642 mkNewTypeBody tycon result_ty result_expr
643         -- Adds a coerce where necessary
644         -- Used for both wrapping and unwrapping
645   | isRecursiveTyCon tycon      -- Recursive case; use a coerce
646   = Note (Coerce result_ty (exprType result_expr)) result_expr
647   | otherwise                   -- Normal case
648   = result_expr
649 \end{code}
650
651
652 %************************************************************************
653 %*                                                                      *
654 \subsection{Primitive operations
655 %*                                                                      *
656 %************************************************************************
657
658 \begin{code}
659 mkPrimOpId :: PrimOp -> Id
660 mkPrimOpId prim_op 
661   = id
662   where
663     (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
664     ty   = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
665     name = mkPrimOpIdName prim_op
666     id   = mkGlobalId (PrimOpId prim_op) name ty info
667                 
668     info = noCafNoTyGenIdInfo
669            `setSpecInfo`        rules
670            `setArityInfo`       arity
671            `setAllStrictnessInfo` Just strict_sig
672
673     rules = foldl (addRule id) emptyCoreRules (primOpRules prim_op)
674
675
676 -- For each ccall we manufacture a separate CCallOpId, giving it
677 -- a fresh unique, a type that is correct for this particular ccall,
678 -- and a CCall structure that gives the correct details about calling
679 -- convention etc.  
680 --
681 -- The *name* of this Id is a local name whose OccName gives the full
682 -- details of the ccall, type and all.  This means that the interface 
683 -- file reader can reconstruct a suitable Id
684
685 mkFCallId :: Unique -> ForeignCall -> Type -> Id
686 mkFCallId uniq fcall ty
687   = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
688         -- A CCallOpId should have no free type variables; 
689         -- when doing substitutions won't substitute over it
690     mkGlobalId (FCallId fcall) name ty info
691   where
692     occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
693         -- The "occurrence name" of a ccall is the full info about the
694         -- ccall; it is encoded, but may have embedded spaces etc!
695
696     name = mkFCallName uniq occ_str
697
698     info = noCafNoTyGenIdInfo
699            `setArityInfo`               arity
700            `setAllStrictnessInfo`       Just strict_sig
701
702     (_, tau)     = tcSplitForAllTys ty
703     (arg_tys, _) = tcSplitFunTys tau
704     arity        = length arg_tys
705     strict_sig   = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
706 \end{code}
707
708
709 %************************************************************************
710 %*                                                                      *
711 \subsection{DictFuns and default methods}
712 %*                                                                      *
713 %************************************************************************
714
715 Important notes about dict funs and default methods
716 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
717 Dict funs and default methods are *not* ImplicitIds.  Their definition
718 involves user-written code, so we can't figure out their strictness etc
719 based on fixed info, as we can for constructors and record selectors (say).
720
721 We build them as GlobalIds, but when in the module where they are
722 bound, we turn the Id at the *binding site* into an exported LocalId.
723 This ensures that they are taken to account by free-variable finding
724 and dependency analysis (e.g. CoreFVs.exprFreeVars).   The simplifier
725 will propagate the LocalId to all occurrence sites. 
726
727 Why shouldn't they be bound as GlobalIds?  Because, in particular, if
728 they are globals, the specialiser floats dict uses above their defns,
729 which prevents good simplifications happening.  Also the strictness
730 analyser treats a occurrence of a GlobalId as imported and assumes it
731 contains strictness in its IdInfo, which isn't true if the thing is
732 bound in the same module as the occurrence.
733
734 It's OK for dfuns to be LocalIds, because we form the instance-env to
735 pass on to the next module (md_insts) in CoreTidy, afer tidying
736 and globalising the top-level Ids.
737
738 BUT make sure they are *exported* LocalIds (setIdLocalExported) so 
739 that they aren't discarded by the occurrence analyser.
740
741 \begin{code}
742 mkDefaultMethodId dm_name ty = mkVanillaGlobal dm_name ty noCafNoTyGenIdInfo
743
744 mkDictFunId :: Name             -- Name to use for the dict fun;
745             -> Class 
746             -> [TyVar]
747             -> [Type]
748             -> ThetaType
749             -> Id
750
751 mkDictFunId dfun_name clas inst_tyvars inst_tys dfun_theta
752   = mkVanillaGlobal dfun_name dfun_ty noCafNoTyGenIdInfo
753   where
754     dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
755
756 {-  1 dec 99: disable the Mark Jones optimisation for the sake
757     of compatibility with Hugs.
758     See `types/InstEnv' for a discussion related to this.
759
760     (class_tyvars, sc_theta, _, _) = classBigSig clas
761     not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
762     sc_theta' = substClasses (mkTopTyVarSubst class_tyvars inst_tys) sc_theta
763     dfun_theta = case inst_decl_theta of
764                    []    -> []  -- If inst_decl_theta is empty, then we don't
765                                 -- want to have any dict arguments, so that we can
766                                 -- expose the constant methods.
767
768                    other -> nub (inst_decl_theta ++ filter not_const sc_theta')
769                                 -- Otherwise we pass the superclass dictionaries to
770                                 -- the dictionary function; the Mark Jones optimisation.
771                                 --
772                                 -- NOTE the "nub".  I got caught by this one:
773                                 --   class Monad m => MonadT t m where ...
774                                 --   instance Monad m => MonadT (EnvT env) m where ...
775                                 -- Here, the inst_decl_theta has (Monad m); but so
776                                 -- does the sc_theta'!
777                                 --
778                                 -- NOTE the "not_const".  I got caught by this one too:
779                                 --   class Foo a => Baz a b where ...
780                                 --   instance Wob b => Baz T b where..
781                                 -- Now sc_theta' has Foo T
782 -}
783 \end{code}
784
785
786 %************************************************************************
787 %*                                                                      *
788 \subsection{Un-definable}
789 %*                                                                      *
790 %************************************************************************
791
792 These Ids can't be defined in Haskell.  They could be defined in
793 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
794 ensure that they were definitely, definitely inlined, because there is
795 no curried identifier for them.  That's what mkCompulsoryUnfolding
796 does.  If we had a way to get a compulsory unfolding from an interface
797 file, we could do that, but we don't right now.
798
799 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
800 just gets expanded into a type coercion wherever it occurs.  Hence we
801 add it as a built-in Id with an unfolding here.
802
803 The type variables we use here are "open" type variables: this means
804 they can unify with both unlifted and lifted types.  Hence we provide
805 another gun with which to shoot yourself in the foot.
806
807 \begin{code}
808 -- unsafeCoerce# :: forall a b. a -> b
809 unsafeCoerceId
810   = pcMiscPrelId unsafeCoerceIdKey gHC_PRIM FSLIT("unsafeCoerce#") ty info
811   where
812     info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
813            
814
815     ty  = mkForAllTys [openAlphaTyVar,openBetaTyVar]
816                       (mkFunTy openAlphaTy openBetaTy)
817     [x] = mkTemplateLocals [openAlphaTy]
818     rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
819           Note (Coerce openBetaTy openAlphaTy) (Var x)
820
821 -- nullAddr# :: Addr#
822 -- The reason is is here is because we don't provide 
823 -- a way to write this literal in Haskell.
824 nullAddrId 
825   = pcMiscPrelId nullAddrIdKey gHC_PRIM FSLIT("nullAddr#") addrPrimTy info
826   where
827     info = noCafNoTyGenIdInfo `setUnfoldingInfo` 
828            mkCompulsoryUnfolding (Lit nullAddrLit)
829
830 seqId
831   = pcMiscPrelId seqIdKey gHC_PRIM FSLIT("seq") ty info
832   where
833     info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
834            
835
836     ty  = mkForAllTys [alphaTyVar,betaTyVar]
837                       (mkFunTy alphaTy (mkFunTy betaTy betaTy))
838     [x,y] = mkTemplateLocals [alphaTy, betaTy]
839     rhs = mkLams [alphaTyVar,betaTyVar,x,y] (Case (Var x) x [(DEFAULT, [], Var y)])
840 \end{code}
841
842 @getTag#@ is another function which can't be defined in Haskell.  It needs to
843 evaluate its argument and call the dataToTag# primitive.
844
845 \begin{code}
846 getTagId
847   = pcMiscPrelId getTagIdKey gHC_PRIM FSLIT("getTag#") ty info
848   where
849     info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
850         -- We don't provide a defn for this; you must inline it
851
852     ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy intPrimTy)
853     [x,y] = mkTemplateLocals [alphaTy,alphaTy]
854     rhs = mkLams [alphaTyVar,x] $
855           Case (Var x) y [ (DEFAULT, [], mkApps (Var dataToTagId) [Type alphaTy, Var y]) ]
856
857 dataToTagId = mkPrimOpId DataToTagOp
858 \end{code}
859
860 @realWorld#@ used to be a magic literal, \tr{void#}.  If things get
861 nasty as-is, change it back to a literal (@Literal@).
862
863 voidArgId is a Local Id used simply as an argument in functions
864 where we just want an arg to avoid having a thunk of unlifted type.
865 E.g.
866         x = \ void :: State# RealWorld -> (# p, q #)
867
868 This comes up in strictness analysis
869
870 \begin{code}
871 realWorldPrimId -- :: State# RealWorld
872   = pcMiscPrelId realWorldPrimIdKey gHC_PRIM FSLIT("realWorld#")
873                  realWorldStatePrimTy
874                  (noCafNoTyGenIdInfo `setUnfoldingInfo` mkOtherCon [])
875         -- The mkOtherCon makes it look that realWorld# is evaluated
876         -- which in turn makes Simplify.interestingArg return True,
877         -- which in turn makes INLINE things applied to realWorld# likely
878         -- to be inlined
879
880 voidArgId       -- :: State# RealWorld
881   = mkSysLocal FSLIT("void") voidArgIdKey realWorldStatePrimTy
882 \end{code}
883
884
885 %************************************************************************
886 %*                                                                      *
887 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
888 %*                                                                      *
889 %************************************************************************
890
891 GHC randomly injects these into the code.
892
893 @patError@ is just a version of @error@ for pattern-matching
894 failures.  It knows various ``codes'' which expand to longer
895 strings---this saves space!
896
897 @absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
898 well shouldn't be yanked on, but if one is, then you will get a
899 friendly message from @absentErr@ (rather than a totally random
900 crash).
901
902 @parError@ is a special version of @error@ which the compiler does
903 not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
904 templates, but we don't ever expect to generate code for it.
905
906 \begin{code}
907 mkRuntimeErrorApp 
908         :: Id           -- Should be of type (forall a. Addr# -> a)
909                         --      where Addr# points to a UTF8 encoded string
910         -> Type         -- The type to instantiate 'a'
911         -> String       -- The string to print
912         -> CoreExpr
913
914 mkRuntimeErrorApp err_id res_ty err_msg 
915   = mkApps (Var err_id) [Type res_ty, err_string]
916   where
917     err_string = Lit (MachStr (_PK_ (stringToUtf8 err_msg)))
918
919 rEC_SEL_ERROR_ID                = mkRuntimeErrorId recSelErrIdKey                FSLIT("recSelError")
920 rUNTIME_ERROR_ID                = mkRuntimeErrorId runtimeErrorIdKey             FSLIT("runtimeError")
921
922 iRREFUT_PAT_ERROR_ID            = mkRuntimeErrorId irrefutPatErrorIdKey          FSLIT("irrefutPatError")
923 rEC_CON_ERROR_ID                = mkRuntimeErrorId recConErrorIdKey              FSLIT("recConError")
924 nON_EXHAUSTIVE_GUARDS_ERROR_ID  = mkRuntimeErrorId nonExhaustiveGuardsErrorIdKey FSLIT("nonExhaustiveGuardsError")
925 pAT_ERROR_ID                    = mkRuntimeErrorId patErrorIdKey                 FSLIT("patError")
926 nO_METHOD_BINDING_ERROR_ID      = mkRuntimeErrorId noMethodBindingErrorIdKey     FSLIT("noMethodBindingError")
927
928 -- The runtime error Ids take a UTF8-encoded string as argument
929 mkRuntimeErrorId key name = pc_bottoming_Id key pREL_ERR name runtimeErrorTy
930 runtimeErrorTy            = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
931 \end{code}
932
933 \begin{code}
934 eRROR_ID = pc_bottoming_Id errorIdKey pREL_ERR FSLIT("error") errorTy
935
936 errorTy  :: Type
937 errorTy  = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
938     -- Notice the openAlphaTyVar.  It says that "error" can be applied
939     -- to unboxed as well as boxed types.  This is OK because it never
940     -- returns, so the return type is irrelevant.
941 \end{code}
942
943
944 %************************************************************************
945 %*                                                                      *
946 \subsection{Utilities}
947 %*                                                                      *
948 %************************************************************************
949
950 \begin{code}
951 pcMiscPrelId :: Unique{-IdKey-} -> Module -> FAST_STRING -> Type -> IdInfo -> Id
952 pcMiscPrelId key mod str ty info
953   = let
954         name = mkWiredInName mod (mkVarOcc str) key
955         imp  = mkVanillaGlobal name ty info -- the usual case...
956     in
957     imp
958     -- We lie and say the thing is imported; otherwise, we get into
959     -- a mess with dependency analysis; e.g., core2stg may heave in
960     -- random calls to GHCbase.unpackPS__.  If GHCbase is the module
961     -- being compiled, then it's just a matter of luck if the definition
962     -- will be in "the right place" to be in scope.
963
964 pc_bottoming_Id key mod name ty
965  = pcMiscPrelId key mod name ty bottoming_info
966  where
967     strict_sig     = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
968     bottoming_info = noCafNoTyGenIdInfo `setAllStrictnessInfo` Just strict_sig
969         -- these "bottom" out, no matter what their arguments
970
971 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
972 openAlphaTy  = mkTyVarTy openAlphaTyVar
973 openBetaTy   = mkTyVarTy openBetaTyVar
974 \end{code}
975