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