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