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