2 % (c) The AQUA Project, Glasgow University, 1998
4 \section[StdIdInfo]{Standard unfoldings}
6 This module contains definitions for the IdInfo for things that
7 have a standard form, namely:
11 * method and superclass selectors
12 * primitive operations
16 mkDictFunId, mkDefaultMethodId,
21 mkPrimOpId, mkFCallId,
23 mkReboxingAlt, wrapNewTypeBody, unwrapNewTypeBody,
24 mkUnpackCase, mkProductBox,
26 -- And some particular Ids; see below for why they are wired in
27 wiredInIds, ghcPrimIds,
28 unsafeCoerceId, realWorldPrimId, voidArgId, nullAddrId, seqId,
29 lazyId, lazyIdUnfolding, lazyIdKey,
32 rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID, rUNTIME_ERROR_ID,
33 nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
34 pAT_ERROR_ID, eRROR_ID,
39 #include "HsVersions.h"
42 import BasicTypes ( Arity, StrictnessMark(..), isMarkedUnboxed, isMarkedStrict )
43 import Rules ( mkSpecInfo )
44 import TysPrim ( openAlphaTyVars, alphaTyVar, alphaTy,
45 realWorldStatePrimTy, addrPrimTy
47 import TysWiredIn ( charTy, mkListTy )
48 import PrelRules ( primOpRules )
49 import Type ( TyThing(..), mkForAllTy, tyVarsOfTypes, newTyConInstRhs )
50 import Coercion ( mkSymCoercion, mkUnsafeCoercion,
51 splitRecNewTypeCo_maybe )
52 import TcType ( Type, ThetaType, mkDictTy, mkPredTys, mkPredTy,
53 mkTyConApp, mkTyVarTys, mkClassPred,
54 mkFunTys, mkFunTy, mkSigmaTy, tcSplitSigmaTy,
55 isUnLiftedType, mkForAllTys, mkTyVarTy, tyVarsOfType,
56 tcSplitFunTys, tcSplitForAllTys, dataConsStupidTheta
58 import CoreUtils ( exprType )
59 import CoreUnfold ( mkTopUnfolding, mkCompulsoryUnfolding )
60 import Literal ( nullAddrLit, mkStringLit )
61 import TyCon ( TyCon, isNewTyCon, tyConDataCons, FieldLabel,
62 tyConStupidTheta, isProductTyCon, isDataTyCon, isRecursiveTyCon,
63 newTyConCo, tyConArity )
64 import Class ( Class, classTyCon, classSelIds )
65 import Var ( Id, TyVar, Var )
66 import VarSet ( isEmptyVarSet, subVarSet, varSetElems )
67 import Name ( mkFCallName, mkWiredInName, Name, BuiltInSyntax(..) )
68 import OccName ( mkOccNameFS, varName )
69 import PrimOp ( PrimOp, primOpSig, primOpOcc, primOpTag )
70 import ForeignCall ( ForeignCall )
71 import DataCon ( DataCon, DataConIds(..), dataConTyCon, dataConUnivTyVars,
72 dataConFieldLabels, dataConRepArity, dataConResTys,
73 dataConRepArgTys, dataConRepType,
74 dataConSig, dataConStrictMarks, dataConExStricts,
75 splitProductType, isVanillaDataCon, dataConFieldType,
76 dataConInstOrigArgTys, deepSplitProductType
78 import Id ( idType, mkGlobalId, mkVanillaGlobal, mkSysLocal,
79 mkTemplateLocals, mkTemplateLocalsNum, mkExportedLocalId,
80 mkTemplateLocal, idName, mkWildId
82 import IdInfo ( IdInfo, noCafIdInfo, setUnfoldingInfo,
83 setArityInfo, setSpecInfo, setCafInfo,
84 setAllStrictnessInfo, vanillaIdInfo,
85 GlobalIdDetails(..), CafInfo(..)
87 import NewDemand ( mkStrictSig, DmdResult(..),
88 mkTopDmdType, topDmd, evalDmd, lazyDmd, retCPR,
89 Demand(..), Demands(..) )
90 import DmdAnal ( dmdAnalTopRhs )
92 import Unique ( mkBuiltinUnique, mkPrimOpIdUnique )
95 import Util ( dropList, isSingleton )
98 import ListSetOps ( assoc )
101 %************************************************************************
103 \subsection{Wired in Ids}
105 %************************************************************************
109 = [ -- These error-y things are wired in because we don't yet have
110 -- a way to express in an interface file that the result type variable
111 -- is 'open'; that is can be unified with an unboxed type
113 -- [The interface file format now carry such information, but there's
114 -- no way yet of expressing at the definition site for these
115 -- error-reporting functions that they have an 'open'
116 -- result type. -- sof 1/99]
118 eRROR_ID, -- This one isn't used anywhere else in the compiler
119 -- But we still need it in wiredInIds so that when GHC
120 -- compiles a program that mentions 'error' we don't
121 -- import its type from the interface file; we just get
122 -- the Id defined here. Which has an 'open-tyvar' type.
125 iRREFUT_PAT_ERROR_ID,
126 nON_EXHAUSTIVE_GUARDS_ERROR_ID,
127 nO_METHOD_BINDING_ERROR_ID,
134 -- These Ids are exported from GHC.Prim
136 = [ -- These can't be defined in Haskell, but they have
137 -- perfectly reasonable unfoldings in Core
145 %************************************************************************
147 \subsection{Data constructors}
149 %************************************************************************
151 The wrapper for a constructor is an ordinary top-level binding that evaluates
152 any strict args, unboxes any args that are going to be flattened, and calls
155 We're going to build a constructor that looks like:
157 data (Data a, C b) => T a b = T1 !a !Int b
160 \d1::Data a, d2::C b ->
161 \p q r -> case p of { p ->
163 Con T1 [a,b] [p,q,r]}}
167 * d2 is thrown away --- a context in a data decl is used to make sure
168 one *could* construct dictionaries at the site the constructor
169 is used, but the dictionary isn't actually used.
171 * We have to check that we can construct Data dictionaries for
172 the types a and Int. Once we've done that we can throw d1 away too.
174 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
175 all that matters is that the arguments are evaluated. "seq" is
176 very careful to preserve evaluation order, which we don't need
179 You might think that we could simply give constructors some strictness
180 info, like PrimOps, and let CoreToStg do the let-to-case transformation.
181 But we don't do that because in the case of primops and functions strictness
182 is a *property* not a *requirement*. In the case of constructors we need to
183 do something active to evaluate the argument.
185 Making an explicit case expression allows the simplifier to eliminate
186 it in the (common) case where the constructor arg is already evaluated.
190 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
191 mkDataConIds wrap_name wkr_name data_con
195 | any isMarkedStrict all_strict_marks -- Algebraic, needs wrapper
196 = AlgDC (Just alg_wrap_id) wrk_id
198 | otherwise -- Algebraic, no wrapper
199 = AlgDC Nothing wrk_id
201 (tvs, theta, orig_arg_tys) = dataConSig data_con
202 tycon = dataConTyCon data_con
204 dict_tys = mkPredTys theta
205 all_arg_tys = dict_tys ++ orig_arg_tys
206 tycon_args = dataConUnivTyVars data_con
207 result_ty_args = (mkTyVarTys tycon_args)
208 result_ty = mkTyConApp tycon result_ty_args
210 wrap_ty = mkForAllTys tvs (mkFunTys all_arg_tys result_ty)
211 -- We used to include the stupid theta in the wrapper's args
212 -- but now we don't. Instead the type checker just injects these
213 -- extra constraints where necessary.
215 ----------- Worker (algebraic data types only) --------------
216 -- The *worker* for the data constructor is the function that
217 -- takes the representation arguments and builds the constructor.
218 wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
219 (dataConRepType data_con) wkr_info
221 wkr_arity = dataConRepArity data_con
222 wkr_info = noCafIdInfo
223 `setArityInfo` wkr_arity
224 `setAllStrictnessInfo` Just wkr_sig
225 `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated,
228 wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
229 -- Notice that we do *not* say the worker is strict
230 -- even if the data constructor is declared strict
231 -- e.g. data T = MkT !(Int,Int)
232 -- Why? Because the *wrapper* is strict (and its unfolding has case
233 -- expresssions that do the evals) but the *worker* itself is not.
234 -- If we pretend it is strict then when we see
235 -- case x of y -> $wMkT y
236 -- the simplifier thinks that y is "sure to be evaluated" (because
237 -- $wMkT is strict) and drops the case. No, $wMkT is not strict.
239 -- When the simplifer sees a pattern
240 -- case e of MkT x -> ...
241 -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
242 -- but that's fine... dataConRepStrictness comes from the data con
243 -- not from the worker Id.
245 cpr_info | isProductTyCon tycon &&
248 wkr_arity <= mAX_CPR_SIZE = retCPR
250 -- RetCPR is only true for products that are real data types;
251 -- that is, not unboxed tuples or [non-recursive] newtypes
253 ----------- Wrappers for newtypes --------------
254 nt_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty nt_wrap_info
255 nt_wrap_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
256 `setArityInfo` 1 -- Arity 1
257 `setUnfoldingInfo` newtype_unf
258 newtype_unf = ASSERT( isVanillaDataCon data_con &&
259 isSingleton orig_arg_tys )
260 -- No existentials on a newtype, but it can have a context
261 -- e.g. newtype Eq a => T a = MkT (...)
262 mkCompulsoryUnfolding $
263 mkLams tvs $ Lam id_arg1 $
264 wrapNewTypeBody tycon result_ty_args
267 id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
269 ----------- Wrappers for algebraic data types --------------
270 alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
271 alg_wrap_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
272 `setArityInfo` alg_arity
273 -- It's important to specify the arity, so that partial
274 -- applications are treated as values
275 `setUnfoldingInfo` alg_unf
276 `setAllStrictnessInfo` Just wrap_sig
278 all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
279 wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
280 arg_dmds = map mk_dmd all_strict_marks
281 mk_dmd str | isMarkedStrict str = evalDmd
282 | otherwise = lazyDmd
283 -- The Cpr info can be important inside INLINE rhss, where the
284 -- wrapper constructor isn't inlined.
285 -- And the argument strictness can be important too; we
286 -- may not inline a contructor when it is partially applied.
288 -- data W = C !Int !Int !Int
289 -- ...(let w = C x in ...(w p q)...)...
290 -- we want to see that w is strict in its two arguments
292 alg_unf = mkTopUnfolding $ Note InlineMe $
294 mkLams dict_args $ mkLams id_args $
295 foldr mk_case con_app
296 (zip (dict_args ++ id_args) all_strict_marks)
299 con_app i rep_ids = mkApps (Var wrk_id)
300 (map varToCoreExpr (tvs ++ reverse rep_ids))
302 (dict_args,i2) = mkLocals 1 dict_tys
303 (id_args,i3) = mkLocals i2 orig_arg_tys
307 :: (Id, StrictnessMark) -- Arg, strictness
308 -> (Int -> [Id] -> CoreExpr) -- Body
309 -> Int -- Next rep arg id
310 -> [Id] -- Rep args so far, reversed
312 mk_case (arg,strict) body i rep_args
314 NotMarkedStrict -> body i (arg:rep_args)
316 | isUnLiftedType (idType arg) -> body i (arg:rep_args)
318 Case (Var arg) arg result_ty [(DEFAULT,[], body i (arg:rep_args))]
321 -> unboxProduct i (Var arg) (idType arg) the_body result_ty
323 the_body i con_args = body i (reverse con_args ++ rep_args)
325 mAX_CPR_SIZE :: Arity
327 -- We do not treat very big tuples as CPR-ish:
328 -- a) for a start we get into trouble because there aren't
329 -- "enough" unboxed tuple types (a tiresome restriction,
331 -- b) more importantly, big unboxed tuples get returned mainly
332 -- on the stack, and are often then allocated in the heap
333 -- by the caller. So doing CPR for them may in fact make
336 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
342 %************************************************************************
344 \subsection{Record selectors}
346 %************************************************************************
348 We're going to build a record selector unfolding that looks like this:
350 data T a b c = T1 { ..., op :: a, ...}
351 | T2 { ..., op :: a, ...}
354 sel = /\ a b c -> \ d -> case d of
359 Similarly for newtypes
361 newtype N a = MkN { unN :: a->a }
364 unN n = coerce (a->a) n
366 We need to take a little care if the field has a polymorphic type:
368 data R = R { f :: forall a. a->a }
372 f :: forall a. R -> a -> a
373 f = /\ a \ r = case r of
376 (not f :: R -> forall a. a->a, which gives the type inference mechanism
377 problems at call sites)
379 Similarly for (recursive) newtypes
381 newtype N = MkN { unN :: forall a. a->a }
383 unN :: forall b. N -> b -> b
384 unN = /\b -> \n:N -> (coerce (forall a. a->a) n)
387 Note [Naughty record selectors]
388 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
389 A "naughty" field is one for which we can't define a record
390 selector, because an existential type variable would escape. For example:
391 data T = forall a. MkT { x,y::a }
392 We obviously can't define
394 Nevertheless we *do* put a RecordSelId into the type environment
395 so that if the user tries to use 'x' as a selector we can bleat
396 helpfully, rather than saying unhelpfully that 'x' is not in scope.
397 Hence the sel_naughty flag, to identify record selectors that don't really exist.
399 In general, a field is naughty if its type mentions a type variable that
400 isn't in the result type of the constructor.
402 Note [GADT record selectors]
403 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
404 For GADTs, we require that all constructors with a common field 'f' have the same
405 result type (modulo alpha conversion). [Checked in TcTyClsDecls.checkValidTyCon]
408 T1 { f :: a } :: T [a]
409 T2 { f :: a, y :: b } :: T [a]
410 and now the selector takes that type as its argument:
411 f :: forall a. T [a] -> a
415 Note the forall'd tyvars of the selector are just the free tyvars
416 of the result type; there may be other tyvars in the constructor's
417 type (e.g. 'b' in T2).
421 -- Steps for handling "naughty" vs "non-naughty" selectors:
422 -- 1. Determine naughtiness by comparing field type vs result type
423 -- 2. Install naughty ones with selector_ty of type _|_ and fill in mzero for info
424 -- 3. If it's not naughty, do the normal plan.
426 mkRecordSelId :: TyCon -> FieldLabel -> Id
427 mkRecordSelId tycon field_label
428 -- Assumes that all fields with the same field label have the same type
429 | is_naughty = naughty_id
432 is_naughty = not (tyVarsOfType field_ty `subVarSet` res_tv_set)
433 sel_id_details = RecordSelId tycon field_label is_naughty
435 -- Escapist case here for naughty construcotrs
436 -- We give it no IdInfo, and a type of forall a.a (never looked at)
437 naughty_id = mkGlobalId sel_id_details field_label forall_a_a noCafIdInfo
438 forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
440 -- Normal case starts here
441 sel_id = mkGlobalId sel_id_details field_label selector_ty info
442 data_cons = tyConDataCons tycon
443 data_cons_w_field = filter has_field data_cons -- Can't be empty!
444 has_field con = field_label `elem` dataConFieldLabels con
446 con1 = head data_cons_w_field
447 res_tys = dataConResTys con1
448 res_tv_set = tyVarsOfTypes res_tys
449 res_tvs = varSetElems res_tv_set
450 data_ty = mkTyConApp tycon res_tys
451 field_ty = dataConFieldType con1 field_label
453 -- *Very* tiresomely, the selectors are (unnecessarily!) overloaded over
454 -- just the dictionaries in the types of the constructors that contain
455 -- the relevant field. [The Report says that pattern matching on a
456 -- constructor gives the same constraints as applying it.] Urgh.
458 -- However, not all data cons have all constraints (because of
459 -- BuildTyCl.mkDataConStupidTheta). So we need to find all the data cons
460 -- involved in the pattern match and take the union of their constraints.
461 stupid_dict_tys = mkPredTys (dataConsStupidTheta data_cons_w_field)
462 n_stupid_dicts = length stupid_dict_tys
464 (field_tyvars,field_theta,field_tau) = tcSplitSigmaTy field_ty
465 field_dict_tys = mkPredTys field_theta
466 n_field_dict_tys = length field_dict_tys
467 -- If the field has a universally quantified type we have to
468 -- be a bit careful. Suppose we have
469 -- data R = R { op :: forall a. Foo a => a -> a }
470 -- Then we can't give op the type
471 -- op :: R -> forall a. Foo a => a -> a
472 -- because the typechecker doesn't understand foralls to the
473 -- right of an arrow. The "right" type to give it is
474 -- op :: forall a. Foo a => R -> a -> a
475 -- But then we must generate the right unfolding too:
476 -- op = /\a -> \dfoo -> \ r ->
479 -- Note that this is exactly the type we'd infer from a user defn
483 selector_ty = mkForAllTys res_tvs $ mkForAllTys field_tyvars $
484 mkFunTys stupid_dict_tys $ mkFunTys field_dict_tys $
485 mkFunTy data_ty field_tau
487 arity = 1 + n_stupid_dicts + n_field_dict_tys
489 (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
490 -- Use the demand analyser to work out strictness.
491 -- With all this unpackery it's not easy!
494 `setCafInfo` caf_info
496 `setUnfoldingInfo` mkTopUnfolding rhs_w_str
497 `setAllStrictnessInfo` Just strict_sig
499 -- Allocate Ids. We do it a funny way round because field_dict_tys is
500 -- almost always empty. Also note that we use max_dict_tys
501 -- rather than n_dict_tys, because the latter gives an infinite loop:
502 -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
503 -- on arity, which depends on n_dict tys. Sigh! Mega sigh!
504 stupid_dict_ids = mkTemplateLocalsNum 1 stupid_dict_tys
505 max_stupid_dicts = length (tyConStupidTheta tycon)
506 field_dict_base = max_stupid_dicts + 1
507 field_dict_ids = mkTemplateLocalsNum field_dict_base field_dict_tys
508 dict_id_base = field_dict_base + n_field_dict_tys
509 data_id = mkTemplateLocal dict_id_base data_ty
510 arg_base = dict_id_base + 1
512 the_alts :: [CoreAlt]
513 the_alts = map mk_alt data_cons_w_field -- Already sorted by data-con
514 no_default = length data_cons == length data_cons_w_field -- No default needed
516 default_alt | no_default = []
517 | otherwise = [(DEFAULT, [], error_expr)]
519 -- The default branch may have CAF refs, because it calls recSelError etc.
520 caf_info | no_default = NoCafRefs
521 | otherwise = MayHaveCafRefs
523 sel_rhs = mkLams res_tvs $ mkLams field_tyvars $
524 mkLams stupid_dict_ids $ mkLams field_dict_ids $
525 Lam data_id $ mk_result sel_body
527 -- NB: A newtype always has a vanilla DataCon; no existentials etc
528 -- res_tys will simply be the dataConUnivTyVars
529 sel_body | isNewTyCon tycon = unwrapNewTypeBody tycon res_tys (Var data_id)
530 | otherwise = Case (Var data_id) data_id field_ty (default_alt ++ the_alts)
532 mk_result poly_result = mkVarApps (mkVarApps poly_result field_tyvars) field_dict_ids
533 -- We pull the field lambdas to the top, so we need to
534 -- apply them in the body. For example:
535 -- data T = MkT { foo :: forall a. a->a }
537 -- foo :: forall a. T -> a -> a
538 -- foo = /\a. \t:T. case t of { MkT f -> f a }
541 = -- In the non-vanilla case, the pattern must bind type variables and
542 -- the context stuff; hence the arg_prefix binding below
543 mkReboxingAlt uniqs data_con (arg_prefix ++ arg_ids) (Var the_arg_id)
545 (arg_prefix, arg_ids)
546 | isVanillaDataCon data_con -- Instantiate from commmon base
547 = ([], mkTemplateLocalsNum arg_base (dataConInstOrigArgTys data_con res_tys))
548 | otherwise -- The case pattern binds type variables, which are used
549 -- in the types of the arguments of the pattern
550 = (dc_tvs ++ mkTemplateLocalsNum arg_base (mkPredTys dc_theta),
551 mkTemplateLocalsNum arg_base' dc_arg_tys)
553 (dc_tvs, dc_theta, dc_arg_tys) = dataConSig data_con
554 arg_base' = arg_base + length dc_theta
556 unpack_base = arg_base' + length dc_arg_tys
557 uniqs = map mkBuiltinUnique [unpack_base..]
559 the_arg_id = assoc "mkRecordSelId:mk_alt" (field_lbls `zip` arg_ids) field_label
560 field_lbls = dataConFieldLabels data_con
562 error_expr = mkRuntimeErrorApp rEC_SEL_ERROR_ID field_tau full_msg
563 full_msg = showSDoc (sep [text "No match in record selector", ppr sel_id])
565 -- unbox a product type...
566 -- we will recurse into newtypes, casting along the way, and unbox at the
567 -- first product data constructor we find. e.g.
569 -- data PairInt = PairInt Int Int
570 -- newtype S = MkS PairInt
573 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
574 -- ids, we get (modulo int passing)
576 -- case (e `cast` (sym CoT)) `cast` (sym CoS) of
577 -- PairInt a b -> body [a,b]
579 -- The Ints passed around are just for creating fresh locals
580 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> Type -> CoreExpr
581 unboxProduct i arg arg_ty body res_ty
582 = mkUnpackCase the_id arg con_args boxing_con rhs
584 (_, _, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
585 ([the_id], i') = mkLocals i [arg_ty]
586 (con_args, i'') = mkLocals i' tys
587 rhs = body i'' con_args
589 mkUnpackCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
590 mkUnpackCase bndr arg unpk_args boxing_con body
591 = Case cast_arg bndr (exprType body) [(DataAlt boxing_con, unpk_args, body)]
593 cast_arg = go (idType bndr) arg
595 | res@(tycon, tycon_args, _, _) <- splitProductType "mkUnpackCase" ty
596 , isNewTyCon tycon && not (isRecursiveTyCon tycon)
597 = go (newTyConInstRhs tycon tycon_args)
598 (unwrapNewTypeBody tycon tycon_args arg)
602 reboxProduct :: [Unique] -- uniques to create new local binders
603 -> Type -- type of product to box
604 -> ([Unique], -- remaining uniques
605 CoreExpr, -- boxed product
606 [Id]) -- Ids being boxed into product
609 (tycon, tycon_args, pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
611 us' = dropList con_arg_tys us
613 arg_ids = zipWith (mkSysLocal FSLIT("rb")) us con_arg_tys
615 bind_rhs = mkProductBox arg_ids ty
618 (us', bind_rhs, arg_ids)
620 mkProductBox :: [Id] -> Type -> CoreExpr
621 mkProductBox arg_ids ty
624 (tycon, tycon_args, pack_con, con_arg_tys) = splitProductType "mkProductBox" ty
628 = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
629 | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
631 wrap expr = wrapNewTypeBody tycon tycon_args expr
634 -- (mkReboxingAlt us con xs rhs) basically constructs the case
635 -- alternative (con, xs, rhs)
636 -- but it does the reboxing necessary to construct the *source*
637 -- arguments, xs, from the representation arguments ys.
639 -- data T = MkT !(Int,Int) Bool
641 -- mkReboxingAlt MkT [x,b] r
642 -- = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
644 -- mkDataAlt should really be in DataCon, but it can't because
645 -- it manipulates CoreSyn.
648 :: [Unique] -- Uniques for the new Ids
650 -> [Var] -- Source-level args, including existential dicts
654 mkReboxingAlt us con args rhs
655 | not (any isMarkedUnboxed stricts)
656 = (DataAlt con, args, rhs)
660 (binds, args') = go args stricts us
662 (DataAlt con, args', mkLets binds rhs)
665 stricts = dataConExStricts con ++ dataConStrictMarks con
667 go [] stricts us = ([], [])
669 -- Type variable case
670 go (arg:args) stricts us
672 = let (binds, args') = go args stricts us
673 in (binds, arg:args')
675 -- Term variable case
676 go (arg:args) (str:stricts) us
677 | isMarkedUnboxed str
679 let (binds, unpacked_args') = go args stricts us'
680 (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
682 (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
684 = let (binds, args') = go args stricts us
685 in (binds, arg:args')
689 %************************************************************************
691 \subsection{Dictionary selectors}
693 %************************************************************************
695 Selecting a field for a dictionary. If there is just one field, then
696 there's nothing to do.
698 Dictionary selectors may get nested forall-types. Thus:
701 op :: forall b. Ord b => a -> b -> b
703 Then the top-level type for op is
705 op :: forall a. Foo a =>
709 This is unlike ordinary record selectors, which have all the for-alls
710 at the outside. When dealing with classes it's very convenient to
711 recover the original type signature from the class op selector.
714 mkDictSelId :: Name -> Class -> Id
715 mkDictSelId name clas
716 = mkGlobalId (ClassOpId clas) name sel_ty info
718 sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
719 -- We can't just say (exprType rhs), because that would give a type
721 -- for a single-op class (after all, the selector is the identity)
722 -- But it's type must expose the representation of the dictionary
723 -- to gat (say) C a -> (a -> a)
727 `setUnfoldingInfo` mkTopUnfolding rhs
728 `setAllStrictnessInfo` Just strict_sig
730 -- We no longer use 'must-inline' on record selectors. They'll
731 -- inline like crazy if they scrutinise a constructor
733 -- The strictness signature is of the form U(AAAVAAAA) -> T
734 -- where the V depends on which item we are selecting
735 -- It's worth giving one, so that absence info etc is generated
736 -- even if the selector isn't inlined
737 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
738 arg_dmd | isNewTyCon tycon = evalDmd
739 | otherwise = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
742 tycon = classTyCon clas
743 [data_con] = tyConDataCons tycon
744 tyvars = dataConUnivTyVars data_con
745 arg_tys = ASSERT( isVanillaDataCon data_con ) dataConRepArgTys data_con
746 the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
748 pred = mkClassPred clas (mkTyVarTys tyvars)
749 (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
751 rhs = mkLams tyvars (Lam dict_id rhs_body)
752 rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
753 | otherwise = Case (Var dict_id) dict_id (idType the_arg_id)
754 [(DataAlt data_con, arg_ids, Var the_arg_id)]
756 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
757 -- The wrapper for the data constructor for a newtype looks like this:
758 -- newtype T a = MkT (a,Int)
759 -- MkT :: forall a. (a,Int) -> T a
760 -- MkT = /\a. \(x:(a,Int)). x `cast` CoT a
761 -- where CoT is the coercion TyCon assoicated with the newtype
763 -- The call (wrapNewTypeBody T [a] e) returns the
764 -- body of the wrapper, namely
767 -- If a coercion constructor is prodivided in the newtype, then we use
768 -- it, otherwise the wrap/unwrap are both no-ops
770 wrapNewTypeBody tycon args result_expr
771 | Just co_con <- newTyConCo tycon
772 = Cast result_expr (mkTyConApp co_con args)
776 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
777 unwrapNewTypeBody tycon args result_expr
778 | Just co_con <- newTyConCo tycon
779 = Cast result_expr (mkSymCoercion (mkTyConApp co_con args))
787 %************************************************************************
789 \subsection{Primitive operations
791 %************************************************************************
794 mkPrimOpId :: PrimOp -> Id
798 (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
799 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
800 name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
801 (mkPrimOpIdUnique (primOpTag prim_op))
802 Nothing (AnId id) UserSyntax
803 id = mkGlobalId (PrimOpId prim_op) name ty info
806 `setSpecInfo` mkSpecInfo (primOpRules prim_op name)
808 `setAllStrictnessInfo` Just strict_sig
810 -- For each ccall we manufacture a separate CCallOpId, giving it
811 -- a fresh unique, a type that is correct for this particular ccall,
812 -- and a CCall structure that gives the correct details about calling
815 -- The *name* of this Id is a local name whose OccName gives the full
816 -- details of the ccall, type and all. This means that the interface
817 -- file reader can reconstruct a suitable Id
819 mkFCallId :: Unique -> ForeignCall -> Type -> Id
820 mkFCallId uniq fcall ty
821 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
822 -- A CCallOpId should have no free type variables;
823 -- when doing substitutions won't substitute over it
824 mkGlobalId (FCallId fcall) name ty info
826 occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
827 -- The "occurrence name" of a ccall is the full info about the
828 -- ccall; it is encoded, but may have embedded spaces etc!
830 name = mkFCallName uniq occ_str
834 `setAllStrictnessInfo` Just strict_sig
836 (_, tau) = tcSplitForAllTys ty
837 (arg_tys, _) = tcSplitFunTys tau
838 arity = length arg_tys
839 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
843 %************************************************************************
845 \subsection{DictFuns and default methods}
847 %************************************************************************
849 Important notes about dict funs and default methods
850 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
851 Dict funs and default methods are *not* ImplicitIds. Their definition
852 involves user-written code, so we can't figure out their strictness etc
853 based on fixed info, as we can for constructors and record selectors (say).
855 We build them as LocalIds, but with External Names. This ensures that
856 they are taken to account by free-variable finding and dependency
857 analysis (e.g. CoreFVs.exprFreeVars).
859 Why shouldn't they be bound as GlobalIds? Because, in particular, if
860 they are globals, the specialiser floats dict uses above their defns,
861 which prevents good simplifications happening. Also the strictness
862 analyser treats a occurrence of a GlobalId as imported and assumes it
863 contains strictness in its IdInfo, which isn't true if the thing is
864 bound in the same module as the occurrence.
866 It's OK for dfuns to be LocalIds, because we form the instance-env to
867 pass on to the next module (md_insts) in CoreTidy, afer tidying
868 and globalising the top-level Ids.
870 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so
871 that they aren't discarded by the occurrence analyser.
874 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
876 mkDictFunId :: Name -- Name to use for the dict fun;
883 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
884 = mkExportedLocalId dfun_name dfun_ty
886 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
888 {- 1 dec 99: disable the Mark Jones optimisation for the sake
889 of compatibility with Hugs.
890 See `types/InstEnv' for a discussion related to this.
892 (class_tyvars, sc_theta, _, _) = classBigSig clas
893 not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
894 sc_theta' = substClasses (zipTopTvSubst class_tyvars inst_tys) sc_theta
895 dfun_theta = case inst_decl_theta of
896 [] -> [] -- If inst_decl_theta is empty, then we don't
897 -- want to have any dict arguments, so that we can
898 -- expose the constant methods.
900 other -> nub (inst_decl_theta ++ filter not_const sc_theta')
901 -- Otherwise we pass the superclass dictionaries to
902 -- the dictionary function; the Mark Jones optimisation.
904 -- NOTE the "nub". I got caught by this one:
905 -- class Monad m => MonadT t m where ...
906 -- instance Monad m => MonadT (EnvT env) m where ...
907 -- Here, the inst_decl_theta has (Monad m); but so
908 -- does the sc_theta'!
910 -- NOTE the "not_const". I got caught by this one too:
911 -- class Foo a => Baz a b where ...
912 -- instance Wob b => Baz T b where..
913 -- Now sc_theta' has Foo T
918 %************************************************************************
920 \subsection{Un-definable}
922 %************************************************************************
924 These Ids can't be defined in Haskell. They could be defined in
925 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
926 ensure that they were definitely, definitely inlined, because there is
927 no curried identifier for them. That's what mkCompulsoryUnfolding
928 does. If we had a way to get a compulsory unfolding from an interface
929 file, we could do that, but we don't right now.
931 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
932 just gets expanded into a type coercion wherever it occurs. Hence we
933 add it as a built-in Id with an unfolding here.
935 The type variables we use here are "open" type variables: this means
936 they can unify with both unlifted and lifted types. Hence we provide
937 another gun with which to shoot yourself in the foot.
940 mkWiredInIdName mod fs uniq id
941 = mkWiredInName mod (mkOccNameFS varName fs) uniq Nothing (AnId id) UserSyntax
943 unsafeCoerceName = mkWiredInIdName gHC_PRIM FSLIT("unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
944 nullAddrName = mkWiredInIdName gHC_PRIM FSLIT("nullAddr#") nullAddrIdKey nullAddrId
945 seqName = mkWiredInIdName gHC_PRIM FSLIT("seq") seqIdKey seqId
946 realWorldName = mkWiredInIdName gHC_PRIM FSLIT("realWorld#") realWorldPrimIdKey realWorldPrimId
947 lazyIdName = mkWiredInIdName gHC_BASE FSLIT("lazy") lazyIdKey lazyId
949 errorName = mkWiredInIdName gHC_ERR FSLIT("error") errorIdKey eRROR_ID
950 recSelErrorName = mkWiredInIdName gHC_ERR FSLIT("recSelError") recSelErrorIdKey rEC_SEL_ERROR_ID
951 runtimeErrorName = mkWiredInIdName gHC_ERR FSLIT("runtimeError") runtimeErrorIdKey rUNTIME_ERROR_ID
952 irrefutPatErrorName = mkWiredInIdName gHC_ERR FSLIT("irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
953 recConErrorName = mkWiredInIdName gHC_ERR FSLIT("recConError") recConErrorIdKey rEC_CON_ERROR_ID
954 patErrorName = mkWiredInIdName gHC_ERR FSLIT("patError") patErrorIdKey pAT_ERROR_ID
955 noMethodBindingErrorName = mkWiredInIdName gHC_ERR FSLIT("noMethodBindingError")
956 noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
957 nonExhaustiveGuardsErrorName
958 = mkWiredInIdName gHC_ERR FSLIT("nonExhaustiveGuardsError")
959 nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
963 -- unsafeCoerce# :: forall a b. a -> b
965 = pcMiscPrelId unsafeCoerceName ty info
967 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
970 ty = mkForAllTys [openAlphaTyVar,openBetaTyVar]
971 (mkFunTy openAlphaTy openBetaTy)
972 [x] = mkTemplateLocals [openAlphaTy]
973 rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
974 -- Note (Coerce openBetaTy openAlphaTy) (Var x)
975 Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
977 -- nullAddr# :: Addr#
978 -- The reason is is here is because we don't provide
979 -- a way to write this literal in Haskell.
981 = pcMiscPrelId nullAddrName addrPrimTy info
983 info = noCafIdInfo `setUnfoldingInfo`
984 mkCompulsoryUnfolding (Lit nullAddrLit)
987 = pcMiscPrelId seqName ty info
989 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
992 ty = mkForAllTys [alphaTyVar,openBetaTyVar]
993 (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
994 [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
995 rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
997 -- lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
998 -- Used to lazify pseq: pseq a b = a `seq` lazy b
1000 -- Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1001 -- not from GHC.Base.hi. This is important, because the strictness
1002 -- analyser will spot it as strict!
1004 -- Also no unfolding in lazyId: it gets "inlined" by a HACK in the worker/wrapper pass
1005 -- (see WorkWrap.wwExpr)
1006 -- We could use inline phases to do this, but that would be vulnerable to changes in
1007 -- phase numbering....we must inline precisely after strictness analysis.
1009 = pcMiscPrelId lazyIdName ty info
1012 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
1014 lazyIdUnfolding :: CoreExpr -- Used to expand 'lazyId' after strictness anal
1015 lazyIdUnfolding = mkLams [openAlphaTyVar,x] (Var x)
1017 [x] = mkTemplateLocals [openAlphaTy]
1020 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
1021 nasty as-is, change it back to a literal (@Literal@).
1023 voidArgId is a Local Id used simply as an argument in functions
1024 where we just want an arg to avoid having a thunk of unlifted type.
1026 x = \ void :: State# RealWorld -> (# p, q #)
1028 This comes up in strictness analysis
1031 realWorldPrimId -- :: State# RealWorld
1032 = pcMiscPrelId realWorldName realWorldStatePrimTy
1033 (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1034 -- The evaldUnfolding makes it look that realWorld# is evaluated
1035 -- which in turn makes Simplify.interestingArg return True,
1036 -- which in turn makes INLINE things applied to realWorld# likely
1039 voidArgId -- :: State# RealWorld
1040 = mkSysLocal FSLIT("void") voidArgIdKey realWorldStatePrimTy
1044 %************************************************************************
1046 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1048 %************************************************************************
1050 GHC randomly injects these into the code.
1052 @patError@ is just a version of @error@ for pattern-matching
1053 failures. It knows various ``codes'' which expand to longer
1054 strings---this saves space!
1056 @absentErr@ is a thing we put in for ``absent'' arguments. They jolly
1057 well shouldn't be yanked on, but if one is, then you will get a
1058 friendly message from @absentErr@ (rather than a totally random
1061 @parError@ is a special version of @error@ which the compiler does
1062 not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
1063 templates, but we don't ever expect to generate code for it.
1067 :: Id -- Should be of type (forall a. Addr# -> a)
1068 -- where Addr# points to a UTF8 encoded string
1069 -> Type -- The type to instantiate 'a'
1070 -> String -- The string to print
1073 mkRuntimeErrorApp err_id res_ty err_msg
1074 = mkApps (Var err_id) [Type res_ty, err_string]
1076 err_string = Lit (mkStringLit err_msg)
1078 rEC_SEL_ERROR_ID = mkRuntimeErrorId recSelErrorName
1079 rUNTIME_ERROR_ID = mkRuntimeErrorId runtimeErrorName
1080 iRREFUT_PAT_ERROR_ID = mkRuntimeErrorId irrefutPatErrorName
1081 rEC_CON_ERROR_ID = mkRuntimeErrorId recConErrorName
1082 pAT_ERROR_ID = mkRuntimeErrorId patErrorName
1083 nO_METHOD_BINDING_ERROR_ID = mkRuntimeErrorId noMethodBindingErrorName
1084 nON_EXHAUSTIVE_GUARDS_ERROR_ID = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1086 -- The runtime error Ids take a UTF8-encoded string as argument
1087 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1088 runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1092 eRROR_ID = pc_bottoming_Id errorName errorTy
1095 errorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1096 -- Notice the openAlphaTyVar. It says that "error" can be applied
1097 -- to unboxed as well as boxed types. This is OK because it never
1098 -- returns, so the return type is irrelevant.
1102 %************************************************************************
1104 \subsection{Utilities}
1106 %************************************************************************
1109 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1110 pcMiscPrelId name ty info
1111 = mkVanillaGlobal name ty info
1112 -- We lie and say the thing is imported; otherwise, we get into
1113 -- a mess with dependency analysis; e.g., core2stg may heave in
1114 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
1115 -- being compiled, then it's just a matter of luck if the definition
1116 -- will be in "the right place" to be in scope.
1118 pc_bottoming_Id name ty
1119 = pcMiscPrelId name ty bottoming_info
1121 bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1122 -- Do *not* mark them as NoCafRefs, because they can indeed have
1123 -- CAF refs. For example, pAT_ERROR_ID calls GHC.Err.untangle,
1124 -- which has some CAFs
1125 -- In due course we may arrange that these error-y things are
1126 -- regarded by the GC as permanently live, in which case we
1127 -- can give them NoCaf info. As it is, any function that calls
1128 -- any pc_bottoming_Id will itself have CafRefs, which bloats
1131 strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1132 -- These "bottom" out, no matter what their arguments
1134 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
1135 openAlphaTy = mkTyVarTy openAlphaTyVar
1136 openBetaTy = mkTyVarTy openBetaTyVar