Fixes to data type families
[ghc-hetmet.git] / compiler / basicTypes / MkId.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1998
4 %
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         mkDataConIds,
20         mkRecordSelId, 
21         mkPrimOpId, mkFCallId, mkTickBoxOpId, mkBreakPointOpId,
22
23         mkReboxingAlt, wrapNewTypeBody, unwrapNewTypeBody,
24         mkUnpackCase, mkProductBox,
25
26         -- And some particular Ids; see below for why they are wired in
27         wiredInIds, ghcPrimIds,
28         unsafeCoerceId, realWorldPrimId, voidArgId, nullAddrId, seqId,
29         lazyId, lazyIdUnfolding, lazyIdKey, 
30
31         mkRuntimeErrorApp,
32         rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID, rUNTIME_ERROR_ID,
33         nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
34         pAT_ERROR_ID, eRROR_ID,
35
36         unsafeCoerceName
37     ) where
38
39 #include "HsVersions.h"
40
41 import Rules
42 import TysPrim
43 import TysWiredIn
44 import PrelRules
45 import Type
46 import TcGadt
47 import Coercion
48 import TcType
49 import CoreUtils
50 import CoreUnfold
51 import Literal
52 import TyCon
53 import Class
54 import VarSet
55 import Name
56 import OccName
57 import PrimOp
58 import ForeignCall
59 import DataCon
60 import Id
61 import Var              ( Var, TyVar)
62 import IdInfo
63 import NewDemand
64 import DmdAnal
65 import CoreSyn
66 import Unique
67 import Maybes
68 import PrelNames
69 import BasicTypes       hiding ( SuccessFlag(..) )
70 import Util
71 import Outputable
72 import FastString
73 import ListSetOps
74 import Module
75 \end{code}              
76
77 %************************************************************************
78 %*                                                                      *
79 \subsection{Wired in Ids}
80 %*                                                                      *
81 %************************************************************************
82
83 \begin{code}
84 wiredInIds
85   = [   -- These error-y things are wired in because we don't yet have
86         -- a way to express in an interface file that the result type variable
87         -- is 'open'; that is can be unified with an unboxed type
88         -- 
89         -- [The interface file format now carry such information, but there's
90         -- no way yet of expressing at the definition site for these 
91         -- error-reporting functions that they have an 'open' 
92         -- result type. -- sof 1/99]
93
94     eRROR_ID,   -- This one isn't used anywhere else in the compiler
95                 -- But we still need it in wiredInIds so that when GHC
96                 -- compiles a program that mentions 'error' we don't
97                 -- import its type from the interface file; we just get
98                 -- the Id defined here.  Which has an 'open-tyvar' type.
99
100     rUNTIME_ERROR_ID,
101     iRREFUT_PAT_ERROR_ID,
102     nON_EXHAUSTIVE_GUARDS_ERROR_ID,
103     nO_METHOD_BINDING_ERROR_ID,
104     pAT_ERROR_ID,
105     rEC_CON_ERROR_ID,
106
107     lazyId
108     ] ++ ghcPrimIds
109
110 -- These Ids are exported from GHC.Prim
111 ghcPrimIds
112   = [   -- These can't be defined in Haskell, but they have
113         -- perfectly reasonable unfoldings in Core
114     realWorldPrimId,
115     unsafeCoerceId,
116     nullAddrId,
117     seqId
118     ]
119 \end{code}
120
121 %************************************************************************
122 %*                                                                      *
123 \subsection{Data constructors}
124 %*                                                                      *
125 %************************************************************************
126
127 The wrapper for a constructor is an ordinary top-level binding that evaluates
128 any strict args, unboxes any args that are going to be flattened, and calls
129 the worker.
130
131 We're going to build a constructor that looks like:
132
133         data (Data a, C b) =>  T a b = T1 !a !Int b
134
135         T1 = /\ a b -> 
136              \d1::Data a, d2::C b ->
137              \p q r -> case p of { p ->
138                        case q of { q ->
139                        Con T1 [a,b] [p,q,r]}}
140
141 Notice that
142
143 * d2 is thrown away --- a context in a data decl is used to make sure
144   one *could* construct dictionaries at the site the constructor
145   is used, but the dictionary isn't actually used.
146
147 * We have to check that we can construct Data dictionaries for
148   the types a and Int.  Once we've done that we can throw d1 away too.
149
150 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
151   all that matters is that the arguments are evaluated.  "seq" is 
152   very careful to preserve evaluation order, which we don't need
153   to be here.
154
155   You might think that we could simply give constructors some strictness
156   info, like PrimOps, and let CoreToStg do the let-to-case transformation.
157   But we don't do that because in the case of primops and functions strictness
158   is a *property* not a *requirement*.  In the case of constructors we need to
159   do something active to evaluate the argument.
160
161   Making an explicit case expression allows the simplifier to eliminate
162   it in the (common) case where the constructor arg is already evaluated.
163
164 Note [Wrappers for data instance tycons]
165 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
166 In the case of data instances, the wrapper also applies the coercion turning
167 the representation type into the family instance type to cast the result of
168 the wrapper.  For example, consider the declarations
169
170   data family Map k :: * -> *
171   data instance Map (a, b) v = MapPair (Map a (Pair b v))
172
173 The tycon to which the datacon MapPair belongs gets a unique internal
174 name of the form :R123Map, and we call it the representation tycon.
175 In contrast, Map is the family tycon (accessible via
176 tyConFamInst_maybe). A coercion allows you to move between
177 representation and family type.  It is accessible from :R123Map via
178 tyConFamilyCoercion_maybe and has kind
179
180   Co123Map a b v :: {Map (a, b) v :=: :R123Map a b v}
181
182 The wrapper and worker of MapPair get the types
183
184         -- Wrapper
185   $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
186   $WMapPair a b v = MapPair a b v `cast` sym (Co123Map a b v)
187
188         -- Worker
189   MapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
190
191 This coercion is conditionally applied by wrapFamInstBody.
192
193 It's a bit more complicated if the data instance is a GADT as well!
194
195    data instance T [a] where
196         T1 :: forall b. b -> T [Maybe b]
197 Hence
198    Co7T a :: T [a] ~ :R7T a
199
200 Now we want
201
202         -- Wrapper
203   $WT1 :: forall b. b -> T [Maybe b]
204   $WT1 b v = T1 (Maybe b) b (Maybe b) v
205                         `cast` sym (Co7T (Maybe b))
206
207         -- Worker
208   T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c
209
210 \begin{code}
211 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
212 mkDataConIds wrap_name wkr_name data_con
213   | isNewTyCon tycon                    -- Newtype, only has a worker
214   , not (isFamInstTyCon tycon)          -- unless it's a family instancex
215   = DCIds Nothing nt_work_id                 
216
217   | any isMarkedStrict all_strict_marks      -- Algebraic, needs wrapper
218     || not (null eq_spec)                    -- NB: LoadIface.ifaceDeclSubBndrs
219     || isFamInstTyCon tycon                  --     depends on this test
220   = DCIds (Just alg_wrap_id) wrk_id
221
222   | otherwise                                -- Algebraic, no wrapper
223   = DCIds Nothing wrk_id
224   where
225     (univ_tvs, ex_tvs, eq_spec, 
226      theta, orig_arg_tys, res_ty) = dataConFullSig data_con
227     tycon = dataConTyCon data_con       -- The representation TyCon (not family)
228
229         ----------- Worker (algebraic data types only) --------------
230         -- The *worker* for the data constructor is the function that
231         -- takes the representation arguments and builds the constructor.
232     wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
233                         (dataConRepType data_con) wkr_info
234
235     wkr_arity = dataConRepArity data_con
236     wkr_info  = noCafIdInfo
237                 `setArityInfo`          wkr_arity
238                 `setAllStrictnessInfo`  Just wkr_sig
239                 `setUnfoldingInfo`      evaldUnfolding  -- Record that it's evaluated,
240                                                         -- even if arity = 0
241
242     wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
243         --      Note [Data-con worker strictness]
244         -- Notice that we do *not* say the worker is strict
245         -- even if the data constructor is declared strict
246         --      e.g.    data T = MkT !(Int,Int)
247         -- Why?  Because the *wrapper* is strict (and its unfolding has case
248         -- expresssions that do the evals) but the *worker* itself is not.
249         -- If we pretend it is strict then when we see
250         --      case x of y -> $wMkT y
251         -- the simplifier thinks that y is "sure to be evaluated" (because
252         --  $wMkT is strict) and drops the case.  No, $wMkT is not strict.
253         --
254         -- When the simplifer sees a pattern 
255         --      case e of MkT x -> ...
256         -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
257         -- but that's fine... dataConRepStrictness comes from the data con
258         -- not from the worker Id.
259
260     cpr_info | isProductTyCon tycon && 
261                isDataTyCon tycon    &&
262                wkr_arity > 0        &&
263                wkr_arity <= mAX_CPR_SIZE        = retCPR
264              | otherwise                        = TopRes
265         -- RetCPR is only true for products that are real data types;
266         -- that is, not unboxed tuples or [non-recursive] newtypes
267
268         ----------- Workers for newtypes --------------
269     nt_work_id   = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
270     nt_work_info = noCafIdInfo          -- The NoCaf-ness is set by noCafIdInfo
271                   `setArityInfo` 1      -- Arity 1
272                   `setUnfoldingInfo`     newtype_unf
273     newtype_unf  = ASSERT( isVanillaDataCon data_con &&
274                            isSingleton orig_arg_tys )
275                    -- No existentials on a newtype, but it can have a context
276                    -- e.g.      newtype Eq a => T a = MkT (...)
277                    mkCompulsoryUnfolding $ 
278                    mkLams wrap_tvs $ Lam id_arg1 $ 
279                    wrapNewTypeBody tycon res_ty_args
280                        (Var id_arg1)
281
282     id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
283
284         ----------- Wrapper --------------
285         -- We used to include the stupid theta in the wrapper's args
286         -- but now we don't.  Instead the type checker just injects these
287         -- extra constraints where necessary.
288     wrap_tvs    = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
289     res_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
290     dict_tys = mkPredTys theta
291     wrap_ty  = mkForAllTys wrap_tvs $ mkFunTys dict_tys $
292                mkFunTys orig_arg_tys $ res_ty
293         -- NB: watch out here if you allow user-written equality 
294         --     constraints in data constructor signatures
295
296         ----------- Wrappers for algebraic data types -------------- 
297     alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
298     alg_wrap_info = noCafIdInfo         -- The NoCaf-ness is set by noCafIdInfo
299                     `setArityInfo`         wrap_arity
300                         -- It's important to specify the arity, so that partial
301                         -- applications are treated as values
302                     `setUnfoldingInfo`     wrap_unf
303                     `setAllStrictnessInfo` Just wrap_sig
304
305     all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
306     wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
307     arg_dmds = map mk_dmd all_strict_marks
308     mk_dmd str | isMarkedStrict str = evalDmd
309                | otherwise          = lazyDmd
310         -- The Cpr info can be important inside INLINE rhss, where the
311         -- wrapper constructor isn't inlined.
312         -- And the argument strictness can be important too; we
313         -- may not inline a contructor when it is partially applied.
314         -- For example:
315         --      data W = C !Int !Int !Int
316         --      ...(let w = C x in ...(w p q)...)...
317         -- we want to see that w is strict in its two arguments
318
319     wrap_unf = mkTopUnfolding $ Note InlineMe $
320               mkLams wrap_tvs $ 
321               mkLams dict_args $ mkLams id_args $
322               foldr mk_case con_app 
323                     (zip (dict_args ++ id_args) all_strict_marks)
324                     i3 []
325
326     con_app _ rep_ids = wrapFamInstBody tycon res_ty_args $
327                           Var wrk_id `mkTyApps`  res_ty_args
328                                      `mkVarApps` ex_tvs                 
329                                      `mkTyApps`  map snd eq_spec        -- Equality evidence 
330                                      `mkVarApps` reverse rep_ids
331
332     (dict_args,i2) = mkLocals 1  dict_tys
333     (id_args,i3)   = mkLocals i2 orig_arg_tys
334     wrap_arity     = i3-1
335
336     mk_case 
337            :: (Id, StrictnessMark)      -- Arg, strictness
338            -> (Int -> [Id] -> CoreExpr) -- Body
339            -> Int                       -- Next rep arg id
340            -> [Id]                      -- Rep args so far, reversed
341            -> CoreExpr
342     mk_case (arg,strict) body i rep_args
343           = case strict of
344                 NotMarkedStrict -> body i (arg:rep_args)
345                 MarkedStrict 
346                    | isUnLiftedType (idType arg) -> body i (arg:rep_args)
347                    | otherwise ->
348                         Case (Var arg) arg res_ty [(DEFAULT,[], body i (arg:rep_args))]
349
350                 MarkedUnboxed
351                    -> unboxProduct i (Var arg) (idType arg) the_body 
352                       where
353                         the_body i con_args = body i (reverse con_args ++ rep_args)
354
355 mAX_CPR_SIZE :: Arity
356 mAX_CPR_SIZE = 10
357 -- We do not treat very big tuples as CPR-ish:
358 --      a) for a start we get into trouble because there aren't 
359 --         "enough" unboxed tuple types (a tiresome restriction, 
360 --         but hard to fix), 
361 --      b) more importantly, big unboxed tuples get returned mainly
362 --         on the stack, and are often then allocated in the heap
363 --         by the caller.  So doing CPR for them may in fact make
364 --         things worse.
365
366 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
367                where
368                  n = length tys
369 \end{code}
370
371
372 %************************************************************************
373 %*                                                                      *
374 \subsection{Record selectors}
375 %*                                                                      *
376 %************************************************************************
377
378 We're going to build a record selector unfolding that looks like this:
379
380         data T a b c = T1 { ..., op :: a, ...}
381                      | T2 { ..., op :: a, ...}
382                      | T3
383
384         sel = /\ a b c -> \ d -> case d of
385                                     T1 ... x ... -> x
386                                     T2 ... x ... -> x
387                                     other        -> error "..."
388
389 Similarly for newtypes
390
391         newtype N a = MkN { unN :: a->a }
392
393         unN :: N a -> a -> a
394         unN n = coerce (a->a) n
395         
396 We need to take a little care if the field has a polymorphic type:
397
398         data R = R { f :: forall a. a->a }
399
400 Then we want
401
402         f :: forall a. R -> a -> a
403         f = /\ a \ r = case r of
404                           R f -> f a
405
406 (not f :: R -> forall a. a->a, which gives the type inference mechanism 
407 problems at call sites)
408
409 Similarly for (recursive) newtypes
410
411         newtype N = MkN { unN :: forall a. a->a }
412
413         unN :: forall b. N -> b -> b
414         unN = /\b -> \n:N -> (coerce (forall a. a->a) n)
415
416
417 Note [Naughty record selectors]
418 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
419 A "naughty" field is one for which we can't define a record 
420 selector, because an existential type variable would escape.  For example:
421         data T = forall a. MkT { x,y::a }
422 We obviously can't define       
423         x (MkT v _) = v
424 Nevertheless we *do* put a RecordSelId into the type environment
425 so that if the user tries to use 'x' as a selector we can bleat
426 helpfully, rather than saying unhelpfully that 'x' is not in scope.
427 Hence the sel_naughty flag, to identify record selectors that don't really exist.
428
429 In general, a field is naughty if its type mentions a type variable that
430 isn't in the result type of the constructor.
431
432 Note [GADT record selectors]
433 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
434 For GADTs, we require that all constructors with a common field 'f' have the same
435 result type (modulo alpha conversion).  [Checked in TcTyClsDecls.checkValidTyCon]
436 E.g. 
437         data T where
438           T1 { f :: a } :: T [a]
439           T2 { f :: a, y :: b  } :: T [a]
440 and now the selector takes that type as its argument:
441         f :: forall a. T [a] -> a
442         f t = case t of
443                 T1 { f = v } -> v
444                 T2 { f = v } -> v
445 Note the forall'd tyvars of the selector are just the free tyvars
446 of the result type; there may be other tyvars in the constructor's
447 type (e.g. 'b' in T2).
448
449 Note [Selector running example]
450 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
451 It's OK to combine GADTs and type families.  Here's a running example:
452
453         data instance T [a] where 
454           T1 { fld :: b } :: T [Maybe b]
455
456 The representation type looks like this
457         data :R7T a where
458           T1 { fld :: b } :: :R7T (Maybe b)
459
460 and there's coercion from the family type to the representation type
461         :CoR7T a :: T [a] ~ :R7T a
462
463 The selector we want for fld looks like this:
464
465         fld :: forall b. T [Maybe b] -> b
466         fld = /\b. \(d::T [Maybe b]).
467               case d `cast` :CoR7T (Maybe b) of 
468                 T1 (x::b) -> x
469
470 The scrutinee of the case has type :R7T (Maybe b), which can be
471 gotten by appying the eq_spec to the univ_tvs of the data con.
472
473 \begin{code}
474 mkRecordSelId :: TyCon -> FieldLabel -> Id
475 mkRecordSelId tycon field_label
476         -- Assumes that all fields with the same field label have the same type
477   | is_naughty = naughty_id
478   | otherwise  = sel_id
479   where
480     is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tv_set)
481     sel_id_details = RecordSelId tycon field_label is_naughty
482
483     -- Escapist case here for naughty constructors
484     -- We give it no IdInfo, and a type of forall a.a (never looked at)
485     naughty_id = mkGlobalId sel_id_details field_label forall_a_a noCafIdInfo
486     forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
487
488     -- Normal case starts here
489     sel_id = mkGlobalId sel_id_details field_label selector_ty info
490     data_cons         = tyConDataCons tycon     
491     data_cons_w_field = filter has_field data_cons      -- Can't be empty!
492     has_field con     = field_label `elem` dataConFieldLabels con
493
494     con1        = head data_cons_w_field
495     (univ_tvs, _, eq_spec, _, _, data_ty) = dataConFullSig con1
496     data_tv_set = tyVarsOfType data_ty
497     data_tvs    = varSetElems data_tv_set
498     field_ty    = dataConFieldType con1 field_label
499     
500         -- *Very* tiresomely, the selectors are (unnecessarily!) overloaded over
501         -- just the dictionaries in the types of the constructors that contain
502         -- the relevant field.  [The Report says that pattern matching on a
503         -- constructor gives the same constraints as applying it.]  Urgh.  
504         --
505         -- However, not all data cons have all constraints (because of
506         -- BuildTyCl.mkDataConStupidTheta).  So we need to find all the data cons 
507         -- involved in the pattern match and take the union of their constraints.
508     stupid_dict_tys = mkPredTys (dataConsStupidTheta data_cons_w_field)
509     n_stupid_dicts  = length stupid_dict_tys
510
511     (field_tyvars,pre_field_theta,field_tau) = tcSplitSigmaTy field_ty
512     field_theta       = filter (not . isEqPred) pre_field_theta
513     field_dict_tys    = mkPredTys field_theta
514     n_field_dict_tys  = length field_dict_tys
515         -- If the field has a universally quantified type we have to 
516         -- be a bit careful.  Suppose we have
517         --      data R = R { op :: forall a. Foo a => a -> a }
518         -- Then we can't give op the type
519         --      op :: R -> forall a. Foo a => a -> a
520         -- because the typechecker doesn't understand foralls to the
521         -- right of an arrow.  The "right" type to give it is
522         --      op :: forall a. Foo a => R -> a -> a
523         -- But then we must generate the right unfolding too:
524         --      op = /\a -> \dfoo -> \ r ->
525         --           case r of
526         --              R op -> op a dfoo
527         -- Note that this is exactly the type we'd infer from a user defn
528         --      op (R op) = op
529
530     selector_ty :: Type
531     selector_ty  = mkForAllTys data_tvs $ mkForAllTys field_tyvars $
532                    mkFunTys stupid_dict_tys  $  mkFunTys field_dict_tys $
533                    mkFunTy data_ty field_tau
534       
535     arity = 1 + n_stupid_dicts + n_field_dict_tys
536
537     (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
538         -- Use the demand analyser to work out strictness.
539         -- With all this unpackery it's not easy!
540
541     info = noCafIdInfo
542            `setCafInfo`           caf_info
543            `setArityInfo`         arity
544            `setUnfoldingInfo`     mkTopUnfolding rhs_w_str
545            `setAllStrictnessInfo` Just strict_sig
546
547         -- Allocate Ids.  We do it a funny way round because field_dict_tys is
548         -- almost always empty.  Also note that we use max_dict_tys
549         -- rather than n_dict_tys, because the latter gives an infinite loop:
550         -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
551         -- on arity, which depends on n_dict tys.  Sigh!  Mega sigh!
552     stupid_dict_ids  = mkTemplateLocalsNum 1 stupid_dict_tys
553     max_stupid_dicts = length (tyConStupidTheta tycon)
554     field_dict_base  = max_stupid_dicts + 1
555     field_dict_ids   = mkTemplateLocalsNum field_dict_base field_dict_tys
556     dict_id_base     = field_dict_base + n_field_dict_tys
557     data_id          = mkTemplateLocal dict_id_base data_ty
558     scrut_id         = mkTemplateLocal (dict_id_base+1) scrut_ty
559     arg_base         = dict_id_base + 2
560
561     the_alts :: [CoreAlt]
562     the_alts   = map mk_alt data_cons_w_field   -- Already sorted by data-con
563     no_default = length data_cons == length data_cons_w_field   -- No default needed
564
565     default_alt | no_default = []
566                 | otherwise  = [(DEFAULT, [], error_expr)]
567
568         -- The default branch may have CAF refs, because it calls recSelError etc.
569     caf_info    | no_default = NoCafRefs
570                 | otherwise  = MayHaveCafRefs
571
572     sel_rhs = mkLams data_tvs $ mkLams field_tyvars $ 
573               mkLams stupid_dict_ids $ mkLams field_dict_ids $
574               Lam data_id $ mk_result sel_body
575
576     scrut_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
577     scrut_ty      = mkTyConApp tycon scrut_ty_args
578     scrut = unwrapFamInstScrut tycon scrut_ty_args (Var data_id)
579         -- First coerce from the type family to the representation type
580
581         -- NB: A newtype always has a vanilla DataCon; no existentials etc
582         --     data_tys will simply be the dataConUnivTyVars
583     sel_body | isNewTyCon tycon = unwrapNewTypeBody tycon scrut_ty_args scrut
584              | otherwise        = Case scrut scrut_id field_ty (default_alt ++ the_alts)
585
586     mk_result poly_result = mkVarApps (mkVarApps poly_result field_tyvars) field_dict_ids
587         -- We pull the field lambdas to the top, so we need to 
588         -- apply them in the body.  For example:
589         --      data T = MkT { foo :: forall a. a->a }
590         --
591         --      foo :: forall a. T -> a -> a
592         --      foo = /\a. \t:T. case t of { MkT f -> f a }
593
594     mk_alt data_con 
595       =   ASSERT2( data_ty `tcEqType` field_ty, ppr data_con $$ ppr data_ty $$ ppr field_ty )
596           mkReboxingAlt rebox_uniqs data_con (ex_tvs ++ co_tvs ++ arg_vs) rhs
597       where
598            -- get pattern binders with types appropriately instantiated
599         arg_uniqs = map mkBuiltinUnique [arg_base..]
600         (ex_tvs, co_tvs, arg_vs) = dataConOrigInstPat arg_uniqs data_con scrut_ty_args
601
602         rebox_base  = arg_base + length ex_tvs + length co_tvs + length arg_vs
603         rebox_uniqs = map mkBuiltinUnique [rebox_base..]
604
605         -- data T :: *->* where T1 { fld :: Maybe b } -> T [b]
606         --      Hence T1 :: forall a b. (a=[b]) => b -> T a
607         -- fld :: forall b. T [b] -> Maybe b
608         -- fld = /\b.\(t:T[b]). case t of 
609         --              T1 b' (c : [b]=[b']) (x:Maybe b') 
610         --                      -> x `cast` Maybe (sym (right c))
611
612
613                 -- Generate the refinement for b'=b, 
614                 -- and apply to (Maybe b'), to get (Maybe b)
615         Succeeded refinement = gadtRefine emptyRefinement ex_tvs co_tvs
616         the_arg_id_ty = idType the_arg_id
617         (rhs, data_ty) = case refineType refinement the_arg_id_ty of
618                           Just (co, data_ty) -> (Cast (Var the_arg_id) co, data_ty)
619                           Nothing            -> (Var the_arg_id, the_arg_id_ty)
620
621         field_vs    = filter (not . isPredTy . idType) arg_vs 
622         the_arg_id  = assoc "mkRecordSelId:mk_alt" (field_lbls `zip` field_vs) field_label
623         field_lbls  = dataConFieldLabels data_con
624
625     error_expr = mkRuntimeErrorApp rEC_SEL_ERROR_ID field_ty full_msg
626     full_msg   = showSDoc (sep [text "No match in record selector", ppr sel_id])
627
628 -- unbox a product type...
629 -- we will recurse into newtypes, casting along the way, and unbox at the
630 -- first product data constructor we find. e.g.
631 --  
632 --   data PairInt = PairInt Int Int
633 --   newtype S = MkS PairInt
634 --   newtype T = MkT S
635 --
636 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
637 -- ids, we get (modulo int passing)
638 --
639 --   case (e `cast` CoT) `cast` CoS of
640 --     PairInt a b -> body [a,b]
641 --
642 -- The Ints passed around are just for creating fresh locals
643 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
644 unboxProduct i arg arg_ty body
645   = result
646   where 
647     result = mkUnpackCase the_id arg con_args boxing_con rhs
648     (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
649     ([the_id], i') = mkLocals i [arg_ty]
650     (con_args, i'') = mkLocals i' tys
651     rhs = body i'' con_args
652
653 mkUnpackCase ::  Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
654 -- (mkUnpackCase x e args Con body)
655 --      returns
656 -- case (e `cast` ...) of bndr { Con args -> body }
657 -- 
658 -- the type of the bndr passed in is irrelevent
659 mkUnpackCase bndr arg unpk_args boxing_con body
660   = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
661   where
662   (cast_arg, bndr_ty) = go (idType bndr) arg
663   go ty arg 
664     | (tycon, tycon_args, _, _)  <- splitProductType "mkUnpackCase" ty
665     , isNewTyCon tycon && not (isRecursiveTyCon tycon)
666     = go (newTyConInstRhs tycon tycon_args) 
667          (unwrapNewTypeBody tycon tycon_args arg)
668     | otherwise = (arg, ty)
669
670 -- ...and the dual
671 reboxProduct :: [Unique]     -- uniques to create new local binders
672              -> Type         -- type of product to box
673              -> ([Unique],   -- remaining uniques
674                  CoreExpr,   -- boxed product
675                  [Id])       -- Ids being boxed into product
676 reboxProduct us ty
677   = let 
678         (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
679  
680         us' = dropList con_arg_tys us
681
682         arg_ids  = zipWith (mkSysLocal FSLIT("rb")) us con_arg_tys
683
684         bind_rhs = mkProductBox arg_ids ty
685
686     in
687       (us', bind_rhs, arg_ids)
688
689 mkProductBox :: [Id] -> Type -> CoreExpr
690 mkProductBox arg_ids ty 
691   = result_expr
692   where 
693     (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
694
695     result_expr
696       | isNewTyCon tycon && not (isRecursiveTyCon tycon) 
697       = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
698       | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
699
700     wrap expr = wrapNewTypeBody tycon tycon_args expr
701
702
703 -- (mkReboxingAlt us con xs rhs) basically constructs the case
704 -- alternative  (con, xs, rhs)
705 -- but it does the reboxing necessary to construct the *source* 
706 -- arguments, xs, from the representation arguments ys.
707 -- For example:
708 --      data T = MkT !(Int,Int) Bool
709 --
710 -- mkReboxingAlt MkT [x,b] r 
711 --      = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
712 --
713 -- mkDataAlt should really be in DataCon, but it can't because
714 -- it manipulates CoreSyn.
715
716 mkReboxingAlt
717   :: [Unique]           -- Uniques for the new Ids
718   -> DataCon
719   -> [Var]              -- Source-level args, including existential dicts
720   -> CoreExpr           -- RHS
721   -> CoreAlt
722
723 mkReboxingAlt us con args rhs
724   | not (any isMarkedUnboxed stricts)
725   = (DataAlt con, args, rhs)
726
727   | otherwise
728   = let
729         (binds, args') = go args stricts us
730     in
731     (DataAlt con, args', mkLets binds rhs)
732
733   where
734     stricts = dataConExStricts con ++ dataConStrictMarks con
735
736     go [] _stricts _us = ([], [])
737
738         -- Type variable case
739     go (arg:args) stricts us 
740       | isTyVar arg
741       = let (binds, args') = go args stricts us
742         in  (binds, arg:args')
743
744         -- Term variable case
745     go (arg:args) (str:stricts) us
746       | isMarkedUnboxed str
747       = 
748         let (binds, unpacked_args')        = go args stricts us'
749             (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
750         in
751             (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
752       | otherwise
753       = let (binds, args') = go args stricts us
754         in  (binds, arg:args')
755 \end{code}
756
757
758 %************************************************************************
759 %*                                                                      *
760 \subsection{Dictionary selectors}
761 %*                                                                      *
762 %************************************************************************
763
764 Selecting a field for a dictionary.  If there is just one field, then
765 there's nothing to do.  
766
767 Dictionary selectors may get nested forall-types.  Thus:
768
769         class Foo a where
770           op :: forall b. Ord b => a -> b -> b
771
772 Then the top-level type for op is
773
774         op :: forall a. Foo a => 
775               forall b. Ord b => 
776               a -> b -> b
777
778 This is unlike ordinary record selectors, which have all the for-alls
779 at the outside.  When dealing with classes it's very convenient to
780 recover the original type signature from the class op selector.
781
782 \begin{code}
783 mkDictSelId :: Name -> Class -> Id
784 mkDictSelId name clas
785   = mkGlobalId (ClassOpId clas) name sel_ty info
786   where
787     sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
788         -- We can't just say (exprType rhs), because that would give a type
789         --      C a -> C a
790         -- for a single-op class (after all, the selector is the identity)
791         -- But it's type must expose the representation of the dictionary
792         -- to gat (say)         C a -> (a -> a)
793
794     info = noCafIdInfo
795                 `setArityInfo`          1
796                 `setUnfoldingInfo`      mkTopUnfolding rhs
797                 `setAllStrictnessInfo`  Just strict_sig
798
799         -- We no longer use 'must-inline' on record selectors.  They'll
800         -- inline like crazy if they scrutinise a constructor
801
802         -- The strictness signature is of the form U(AAAVAAAA) -> T
803         -- where the V depends on which item we are selecting
804         -- It's worth giving one, so that absence info etc is generated
805         -- even if the selector isn't inlined
806     strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
807     arg_dmd | isNewTyCon tycon = evalDmd
808             | otherwise        = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
809                                             | id <- arg_ids ])
810
811     tycon      = classTyCon clas
812     [data_con] = tyConDataCons tycon
813     tyvars     = dataConUnivTyVars data_con
814     arg_tys    = ASSERT( isVanillaDataCon data_con ) dataConRepArgTys data_con
815     the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
816
817     pred              = mkClassPred clas (mkTyVarTys tyvars)
818     (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
819
820     rhs = mkLams tyvars (Lam dict_id rhs_body)
821     rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
822              | otherwise        = Case (Var dict_id) dict_id (idType the_arg_id)
823                                        [(DataAlt data_con, arg_ids, Var the_arg_id)]
824 \end{code}
825
826
827 %************************************************************************
828 %*                                                                      *
829         Wrapping and unwrapping newtypes and type families
830 %*                                                                      *
831 %************************************************************************
832
833 \begin{code}
834 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
835 -- The wrapper for the data constructor for a newtype looks like this:
836 --      newtype T a = MkT (a,Int)
837 --      MkT :: forall a. (a,Int) -> T a
838 --      MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
839 -- where CoT is the coercion TyCon assoicated with the newtype
840 --
841 -- The call (wrapNewTypeBody T [a] e) returns the
842 -- body of the wrapper, namely
843 --      e `cast` (CoT [a])
844 --
845 -- If a coercion constructor is provided in the newtype, then we use
846 -- it, otherwise the wrap/unwrap are both no-ops 
847 --
848 -- If the we are dealing with a newtype *instance*, we have a second coercion
849 -- identifying the family instance with the constructor of the newtype
850 -- instance.  This coercion is applied in any case (ie, composed with the
851 -- coercion constructor of the newtype or applied by itself).
852
853 wrapNewTypeBody tycon args result_expr
854   = wrapFamInstBody tycon args inner
855   where
856     inner
857       | Just co_con <- newTyConCo_maybe tycon
858       = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
859       | otherwise
860       = result_expr
861
862 -- When unwrapping, we do *not* apply any family coercion, because this will
863 -- be done via a CoPat by the type checker.  We have to do it this way as
864 -- computing the right type arguments for the coercion requires more than just
865 -- a spliting operation (cf, TcPat.tcConPat).
866
867 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
868 unwrapNewTypeBody tycon args result_expr
869   | Just co_con <- newTyConCo_maybe tycon
870   = mkCoerce (mkTyConApp co_con args) result_expr
871   | otherwise
872   = result_expr
873
874 -- If the type constructor is a representation type of a data instance, wrap
875 -- the expression into a cast adjusting the expression type, which is an
876 -- instance of the representation type, to the corresponding instance of the
877 -- family instance type.
878 -- See Note [Wrappers for data instance tycons]
879 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
880 wrapFamInstBody tycon args body
881   | Just co_con <- tyConFamilyCoercion_maybe tycon
882   = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) body
883   | otherwise
884   = body
885
886 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
887 unwrapFamInstScrut tycon args scrut
888   | Just co_con <- tyConFamilyCoercion_maybe tycon
889   = mkCoerce (mkTyConApp co_con args) scrut
890   | otherwise
891   = scrut
892 \end{code}
893
894
895 %************************************************************************
896 %*                                                                      *
897 \subsection{Primitive operations
898 %*                                                                      *
899 %************************************************************************
900
901 \begin{code}
902 mkPrimOpId :: PrimOp -> Id
903 mkPrimOpId prim_op 
904   = id
905   where
906     (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
907     ty   = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
908     name = mkWiredInName gHC_PRIM (primOpOcc prim_op) 
909                          (mkPrimOpIdUnique (primOpTag prim_op))
910                          (AnId id) UserSyntax
911     id   = mkGlobalId (PrimOpId prim_op) name ty info
912                 
913     info = noCafIdInfo
914            `setSpecInfo`          mkSpecInfo (primOpRules prim_op name)
915            `setArityInfo`         arity
916            `setAllStrictnessInfo` Just strict_sig
917
918 -- For each ccall we manufacture a separate CCallOpId, giving it
919 -- a fresh unique, a type that is correct for this particular ccall,
920 -- and a CCall structure that gives the correct details about calling
921 -- convention etc.  
922 --
923 -- The *name* of this Id is a local name whose OccName gives the full
924 -- details of the ccall, type and all.  This means that the interface 
925 -- file reader can reconstruct a suitable Id
926
927 mkFCallId :: Unique -> ForeignCall -> Type -> Id
928 mkFCallId uniq fcall ty
929   = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
930         -- A CCallOpId should have no free type variables; 
931         -- when doing substitutions won't substitute over it
932     mkGlobalId (FCallId fcall) name ty info
933   where
934     occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
935         -- The "occurrence name" of a ccall is the full info about the
936         -- ccall; it is encoded, but may have embedded spaces etc!
937
938     name = mkFCallName uniq occ_str
939
940     info = noCafIdInfo
941            `setArityInfo`               arity
942            `setAllStrictnessInfo`       Just strict_sig
943
944     (_, tau)     = tcSplitForAllTys ty
945     (arg_tys, _) = tcSplitFunTys tau
946     arity        = length arg_tys
947     strict_sig   = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
948
949 -- Tick boxes and breakpoints are both represented as TickBoxOpIds,
950 -- except for the type:
951 --
952 --    a plain HPC tick box has type (State# RealWorld)
953 --    a breakpoint Id has type forall a.a
954 --
955 -- The breakpoint Id will be applied to a list of arbitrary free variables,
956 -- which is why it needs a polymorphic type.
957
958 mkTickBoxOpId :: Unique -> Module -> TickBoxId -> Id
959 mkTickBoxOpId uniq mod ix = mkTickBox' uniq mod ix realWorldStatePrimTy
960
961 mkBreakPointOpId :: Unique -> Module -> TickBoxId -> Id
962 mkBreakPointOpId uniq mod ix = mkTickBox' uniq mod ix ty
963  where ty = mkSigmaTy [openAlphaTyVar] [] openAlphaTy
964
965 mkTickBox' uniq mod ix ty = mkGlobalId (TickBoxOpId tickbox) name ty info    
966   where
967     tickbox = TickBox mod ix
968     occ_str = showSDoc (braces (ppr tickbox))
969     name    = mkTickBoxOpName uniq occ_str
970     info    = noCafIdInfo
971 \end{code}
972
973
974 %************************************************************************
975 %*                                                                      *
976 \subsection{DictFuns and default methods}
977 %*                                                                      *
978 %************************************************************************
979
980 Important notes about dict funs and default methods
981 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
982 Dict funs and default methods are *not* ImplicitIds.  Their definition
983 involves user-written code, so we can't figure out their strictness etc
984 based on fixed info, as we can for constructors and record selectors (say).
985
986 We build them as LocalIds, but with External Names.  This ensures that
987 they are taken to account by free-variable finding and dependency
988 analysis (e.g. CoreFVs.exprFreeVars).
989
990 Why shouldn't they be bound as GlobalIds?  Because, in particular, if
991 they are globals, the specialiser floats dict uses above their defns,
992 which prevents good simplifications happening.  Also the strictness
993 analyser treats a occurrence of a GlobalId as imported and assumes it
994 contains strictness in its IdInfo, which isn't true if the thing is
995 bound in the same module as the occurrence.
996
997 It's OK for dfuns to be LocalIds, because we form the instance-env to
998 pass on to the next module (md_insts) in CoreTidy, afer tidying
999 and globalising the top-level Ids.
1000
1001 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so 
1002 that they aren't discarded by the occurrence analyser.
1003
1004 \begin{code}
1005 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
1006
1007 mkDictFunId :: Name             -- Name to use for the dict fun;
1008             -> [TyVar]
1009             -> ThetaType
1010             -> Class 
1011             -> [Type]
1012             -> Id
1013
1014 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
1015   = mkExportedLocalId dfun_name dfun_ty
1016   where
1017     dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
1018
1019 {-  1 dec 99: disable the Mark Jones optimisation for the sake
1020     of compatibility with Hugs.
1021     See `types/InstEnv' for a discussion related to this.
1022
1023     (class_tyvars, sc_theta, _, _) = classBigSig clas
1024     not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
1025     sc_theta' = substClasses (zipTopTvSubst class_tyvars inst_tys) sc_theta
1026     dfun_theta = case inst_decl_theta of
1027                    []    -> []  -- If inst_decl_theta is empty, then we don't
1028                                 -- want to have any dict arguments, so that we can
1029                                 -- expose the constant methods.
1030
1031                    other -> nub (inst_decl_theta ++ filter not_const sc_theta')
1032                                 -- Otherwise we pass the superclass dictionaries to
1033                                 -- the dictionary function; the Mark Jones optimisation.
1034                                 --
1035                                 -- NOTE the "nub".  I got caught by this one:
1036                                 --   class Monad m => MonadT t m where ...
1037                                 --   instance Monad m => MonadT (EnvT env) m where ...
1038                                 -- Here, the inst_decl_theta has (Monad m); but so
1039                                 -- does the sc_theta'!
1040                                 --
1041                                 -- NOTE the "not_const".  I got caught by this one too:
1042                                 --   class Foo a => Baz a b where ...
1043                                 --   instance Wob b => Baz T b where..
1044                                 -- Now sc_theta' has Foo T
1045 -}
1046 \end{code}
1047
1048
1049 %************************************************************************
1050 %*                                                                      *
1051 \subsection{Un-definable}
1052 %*                                                                      *
1053 %************************************************************************
1054
1055 These Ids can't be defined in Haskell.  They could be defined in
1056 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
1057 ensure that they were definitely, definitely inlined, because there is
1058 no curried identifier for them.  That's what mkCompulsoryUnfolding
1059 does.  If we had a way to get a compulsory unfolding from an interface
1060 file, we could do that, but we don't right now.
1061
1062 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
1063 just gets expanded into a type coercion wherever it occurs.  Hence we
1064 add it as a built-in Id with an unfolding here.
1065
1066 The type variables we use here are "open" type variables: this means
1067 they can unify with both unlifted and lifted types.  Hence we provide
1068 another gun with which to shoot yourself in the foot.
1069
1070 \begin{code}
1071 mkWiredInIdName mod fs uniq id
1072  = mkWiredInName mod (mkOccNameFS varName fs) uniq (AnId id) UserSyntax
1073
1074 unsafeCoerceName = mkWiredInIdName gHC_PRIM FSLIT("unsafeCoerce#") unsafeCoerceIdKey  unsafeCoerceId
1075 nullAddrName     = mkWiredInIdName gHC_PRIM FSLIT("nullAddr#")     nullAddrIdKey      nullAddrId
1076 seqName          = mkWiredInIdName gHC_PRIM FSLIT("seq")           seqIdKey           seqId
1077 realWorldName    = mkWiredInIdName gHC_PRIM FSLIT("realWorld#")    realWorldPrimIdKey realWorldPrimId
1078 lazyIdName       = mkWiredInIdName gHC_BASE FSLIT("lazy")         lazyIdKey           lazyId
1079
1080 errorName                = mkWiredInIdName gHC_ERR FSLIT("error")            errorIdKey eRROR_ID
1081 recSelErrorName          = mkWiredInIdName gHC_ERR FSLIT("recSelError")     recSelErrorIdKey rEC_SEL_ERROR_ID
1082 runtimeErrorName         = mkWiredInIdName gHC_ERR FSLIT("runtimeError")    runtimeErrorIdKey rUNTIME_ERROR_ID
1083 irrefutPatErrorName      = mkWiredInIdName gHC_ERR FSLIT("irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
1084 recConErrorName          = mkWiredInIdName gHC_ERR FSLIT("recConError")     recConErrorIdKey rEC_CON_ERROR_ID
1085 patErrorName             = mkWiredInIdName gHC_ERR FSLIT("patError")         patErrorIdKey pAT_ERROR_ID
1086 noMethodBindingErrorName = mkWiredInIdName gHC_ERR FSLIT("noMethodBindingError")
1087                                            noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
1088 nonExhaustiveGuardsErrorName 
1089   = mkWiredInIdName gHC_ERR FSLIT("nonExhaustiveGuardsError") 
1090                     nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
1091 \end{code}
1092
1093 \begin{code}
1094 -- unsafeCoerce# :: forall a b. a -> b
1095 unsafeCoerceId
1096   = pcMiscPrelId unsafeCoerceName ty info
1097   where
1098     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1099            
1100
1101     ty  = mkForAllTys [openAlphaTyVar,openBetaTyVar]
1102                       (mkFunTy openAlphaTy openBetaTy)
1103     [x] = mkTemplateLocals [openAlphaTy]
1104     rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
1105           Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
1106
1107 -- nullAddr# :: Addr#
1108 -- The reason is is here is because we don't provide 
1109 -- a way to write this literal in Haskell.
1110 nullAddrId 
1111   = pcMiscPrelId nullAddrName addrPrimTy info
1112   where
1113     info = noCafIdInfo `setUnfoldingInfo` 
1114            mkCompulsoryUnfolding (Lit nullAddrLit)
1115
1116 seqId
1117   = pcMiscPrelId seqName ty info
1118   where
1119     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1120            
1121
1122     ty  = mkForAllTys [alphaTyVar,openBetaTyVar]
1123                       (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
1124     [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
1125     rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
1126
1127 -- lazy :: forall a?. a? -> a?   (i.e. works for unboxed types too)
1128 -- Used to lazify pseq:         pseq a b = a `seq` lazy b
1129 -- 
1130 -- Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1131 -- not from GHC.Base.hi.   This is important, because the strictness
1132 -- analyser will spot it as strict!
1133 --
1134 -- Also no unfolding in lazyId: it gets "inlined" by a HACK in the worker/wrapperpass
1135 --      (see WorkWrap.wwExpr)   
1136 -- We could use inline phases to do this, but that would be vulnerable to changes in 
1137 -- phase numbering....we must inline precisely after strictness analysis.
1138 lazyId
1139   = pcMiscPrelId lazyIdName ty info
1140   where
1141     info = noCafIdInfo
1142     ty  = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
1143
1144 lazyIdUnfolding :: CoreExpr     -- Used to expand 'lazyId' after strictness anal
1145 lazyIdUnfolding = mkLams [openAlphaTyVar,x] (Var x)
1146                 where
1147                   [x] = mkTemplateLocals [openAlphaTy]
1148 \end{code}
1149
1150 @realWorld#@ used to be a magic literal, \tr{void#}.  If things get
1151 nasty as-is, change it back to a literal (@Literal@).
1152
1153 voidArgId is a Local Id used simply as an argument in functions
1154 where we just want an arg to avoid having a thunk of unlifted type.
1155 E.g.
1156         x = \ void :: State# RealWorld -> (# p, q #)
1157
1158 This comes up in strictness analysis
1159
1160 \begin{code}
1161 realWorldPrimId -- :: State# RealWorld
1162   = pcMiscPrelId realWorldName realWorldStatePrimTy
1163                  (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1164         -- The evaldUnfolding makes it look that realWorld# is evaluated
1165         -- which in turn makes Simplify.interestingArg return True,
1166         -- which in turn makes INLINE things applied to realWorld# likely
1167         -- to be inlined
1168
1169 voidArgId       -- :: State# RealWorld
1170   = mkSysLocal FSLIT("void") voidArgIdKey realWorldStatePrimTy
1171 \end{code}
1172
1173
1174 %************************************************************************
1175 %*                                                                      *
1176 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1177 %*                                                                      *
1178 %************************************************************************
1179
1180 GHC randomly injects these into the code.
1181
1182 @patError@ is just a version of @error@ for pattern-matching
1183 failures.  It knows various ``codes'' which expand to longer
1184 strings---this saves space!
1185
1186 @absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
1187 well shouldn't be yanked on, but if one is, then you will get a
1188 friendly message from @absentErr@ (rather than a totally random
1189 crash).
1190
1191 @parError@ is a special version of @error@ which the compiler does
1192 not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
1193 templates, but we don't ever expect to generate code for it.
1194
1195 \begin{code}
1196 mkRuntimeErrorApp 
1197         :: Id           -- Should be of type (forall a. Addr# -> a)
1198                         --      where Addr# points to a UTF8 encoded string
1199         -> Type         -- The type to instantiate 'a'
1200         -> String       -- The string to print
1201         -> CoreExpr
1202
1203 mkRuntimeErrorApp err_id res_ty err_msg 
1204   = mkApps (Var err_id) [Type res_ty, err_string]
1205   where
1206     err_string = Lit (mkStringLit err_msg)
1207
1208 rEC_SEL_ERROR_ID                = mkRuntimeErrorId recSelErrorName
1209 rUNTIME_ERROR_ID                = mkRuntimeErrorId runtimeErrorName
1210 iRREFUT_PAT_ERROR_ID            = mkRuntimeErrorId irrefutPatErrorName
1211 rEC_CON_ERROR_ID                = mkRuntimeErrorId recConErrorName
1212 pAT_ERROR_ID                    = mkRuntimeErrorId patErrorName
1213 nO_METHOD_BINDING_ERROR_ID      = mkRuntimeErrorId noMethodBindingErrorName
1214 nON_EXHAUSTIVE_GUARDS_ERROR_ID  = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1215
1216 -- The runtime error Ids take a UTF8-encoded string as argument
1217 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1218 runtimeErrorTy        = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1219 \end{code}
1220
1221 \begin{code}
1222 eRROR_ID = pc_bottoming_Id errorName errorTy
1223
1224 errorTy  :: Type
1225 errorTy  = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1226     -- Notice the openAlphaTyVar.  It says that "error" can be applied
1227     -- to unboxed as well as boxed types.  This is OK because it never
1228     -- returns, so the return type is irrelevant.
1229 \end{code}
1230
1231
1232 %************************************************************************
1233 %*                                                                      *
1234 \subsection{Utilities}
1235 %*                                                                      *
1236 %************************************************************************
1237
1238 \begin{code}
1239 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1240 pcMiscPrelId name ty info
1241   = mkVanillaGlobal name ty info
1242     -- We lie and say the thing is imported; otherwise, we get into
1243     -- a mess with dependency analysis; e.g., core2stg may heave in
1244     -- random calls to GHCbase.unpackPS__.  If GHCbase is the module
1245     -- being compiled, then it's just a matter of luck if the definition
1246     -- will be in "the right place" to be in scope.
1247
1248 pc_bottoming_Id name ty
1249  = pcMiscPrelId name ty bottoming_info
1250  where
1251     bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1252         -- Do *not* mark them as NoCafRefs, because they can indeed have
1253         -- CAF refs.  For example, pAT_ERROR_ID calls GHC.Err.untangle,
1254         -- which has some CAFs
1255         -- In due course we may arrange that these error-y things are
1256         -- regarded by the GC as permanently live, in which case we
1257         -- can give them NoCaf info.  As it is, any function that calls
1258         -- any pc_bottoming_Id will itself have CafRefs, which bloats
1259         -- SRTs.
1260
1261     strict_sig     = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1262         -- These "bottom" out, no matter what their arguments
1263 \end{code}
1264