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