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