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