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