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