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