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