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, coreEqType )
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, setIdType )
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
584 result = mkUnpackCase the_id arg arg_ty con_args boxing_con rhs
585 (tycon, tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
586 ([the_id], i') = mkLocals i [arg_ty]
587 (con_args, i'') = mkLocals i' tys
588 rhs = body i'' con_args
590 mkUnpackCase :: Id -> CoreExpr -> Type -> [Id] -> DataCon -> CoreExpr -> CoreExpr
591 -- (mkUnpackCase x e args Con body)
593 -- case (e `cast` ...) of bndr { Con args -> body }
595 -- the type of the bndr passed in is irrelevent
596 mkUnpackCase bndr arg arg_ty unpk_args boxing_con body
597 = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
599 (cast_arg, bndr_ty) = go (idType bndr) arg
601 | res@(tycon, tycon_args, _, _) <- splitProductType "mkUnpackCase" ty
602 , isNewTyCon tycon && not (isRecursiveTyCon tycon)
603 = go (newTyConInstRhs tycon tycon_args)
604 (unwrapNewTypeBody tycon tycon_args arg)
605 | otherwise = (arg, ty)
608 reboxProduct :: [Unique] -- uniques to create new local binders
609 -> Type -- type of product to box
610 -> ([Unique], -- remaining uniques
611 CoreExpr, -- boxed product
612 [Id]) -- Ids being boxed into product
615 (tycon, tycon_args, pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
617 us' = dropList con_arg_tys us
619 arg_ids = zipWith (mkSysLocal FSLIT("rb")) us con_arg_tys
621 bind_rhs = mkProductBox arg_ids ty
624 (us', bind_rhs, arg_ids)
626 mkProductBox :: [Id] -> Type -> CoreExpr
627 mkProductBox arg_ids ty
630 (tycon, tycon_args, pack_con, con_arg_tys) = splitProductType "mkProductBox" ty
633 | isNewTyCon tycon && not (isRecursiveTyCon tycon)
634 = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
635 | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
637 wrap expr = wrapNewTypeBody tycon tycon_args expr
640 -- (mkReboxingAlt us con xs rhs) basically constructs the case
641 -- alternative (con, xs, rhs)
642 -- but it does the reboxing necessary to construct the *source*
643 -- arguments, xs, from the representation arguments ys.
645 -- data T = MkT !(Int,Int) Bool
647 -- mkReboxingAlt MkT [x,b] r
648 -- = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
650 -- mkDataAlt should really be in DataCon, but it can't because
651 -- it manipulates CoreSyn.
654 :: [Unique] -- Uniques for the new Ids
656 -> [Var] -- Source-level args, including existential dicts
660 mkReboxingAlt us con args rhs
661 | not (any isMarkedUnboxed stricts)
662 = (DataAlt con, args, rhs)
666 (binds, args') = go args stricts us
668 (DataAlt con, args', mkLets binds rhs)
671 stricts = dataConExStricts con ++ dataConStrictMarks con
673 go [] stricts us = ([], [])
675 -- Type variable case
676 go (arg:args) stricts us
678 = let (binds, args') = go args stricts us
679 in (binds, arg:args')
681 -- Term variable case
682 go (arg:args) (str:stricts) us
683 | isMarkedUnboxed str
685 let (binds, unpacked_args') = go args stricts us'
686 (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
688 (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
690 = let (binds, args') = go args stricts us
691 in (binds, arg:args')
695 %************************************************************************
697 \subsection{Dictionary selectors}
699 %************************************************************************
701 Selecting a field for a dictionary. If there is just one field, then
702 there's nothing to do.
704 Dictionary selectors may get nested forall-types. Thus:
707 op :: forall b. Ord b => a -> b -> b
709 Then the top-level type for op is
711 op :: forall a. Foo a =>
715 This is unlike ordinary record selectors, which have all the for-alls
716 at the outside. When dealing with classes it's very convenient to
717 recover the original type signature from the class op selector.
720 mkDictSelId :: Name -> Class -> Id
721 mkDictSelId name clas
722 = mkGlobalId (ClassOpId clas) name sel_ty info
724 sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
725 -- We can't just say (exprType rhs), because that would give a type
727 -- for a single-op class (after all, the selector is the identity)
728 -- But it's type must expose the representation of the dictionary
729 -- to gat (say) C a -> (a -> a)
733 `setUnfoldingInfo` mkTopUnfolding rhs
734 `setAllStrictnessInfo` Just strict_sig
736 -- We no longer use 'must-inline' on record selectors. They'll
737 -- inline like crazy if they scrutinise a constructor
739 -- The strictness signature is of the form U(AAAVAAAA) -> T
740 -- where the V depends on which item we are selecting
741 -- It's worth giving one, so that absence info etc is generated
742 -- even if the selector isn't inlined
743 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
744 arg_dmd | isNewTyCon tycon = evalDmd
745 | otherwise = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
748 tycon = classTyCon clas
749 [data_con] = tyConDataCons tycon
750 tyvars = dataConUnivTyVars data_con
751 arg_tys = ASSERT( isVanillaDataCon data_con ) dataConRepArgTys data_con
752 the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
754 pred = mkClassPred clas (mkTyVarTys tyvars)
755 (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
757 rhs = mkLams tyvars (Lam dict_id rhs_body)
758 rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
759 | otherwise = Case (Var dict_id) dict_id (idType the_arg_id)
760 [(DataAlt data_con, arg_ids, Var the_arg_id)]
762 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
763 -- The wrapper for the data constructor for a newtype looks like this:
764 -- newtype T a = MkT (a,Int)
765 -- MkT :: forall a. (a,Int) -> T a
766 -- MkT = /\a. \(x:(a,Int)). x `cast` CoT a
767 -- where CoT is the coercion TyCon assoicated with the newtype
769 -- The call (wrapNewTypeBody T [a] e) returns the
770 -- body of the wrapper, namely
773 -- If a coercion constructor is prodivided in the newtype, then we use
774 -- it, otherwise the wrap/unwrap are both no-ops
776 wrapNewTypeBody tycon args result_expr
777 | Just co_con <- newTyConCo tycon
778 = Cast result_expr (mkTyConApp co_con args)
782 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
783 unwrapNewTypeBody tycon args result_expr
784 | Just co_con <- newTyConCo tycon
785 = Cast result_expr (mkSymCoercion (mkTyConApp co_con args))
793 %************************************************************************
795 \subsection{Primitive operations
797 %************************************************************************
800 mkPrimOpId :: PrimOp -> Id
804 (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
805 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
806 name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
807 (mkPrimOpIdUnique (primOpTag prim_op))
808 Nothing (AnId id) UserSyntax
809 id = mkGlobalId (PrimOpId prim_op) name ty info
812 `setSpecInfo` mkSpecInfo (primOpRules prim_op name)
814 `setAllStrictnessInfo` Just strict_sig
816 -- For each ccall we manufacture a separate CCallOpId, giving it
817 -- a fresh unique, a type that is correct for this particular ccall,
818 -- and a CCall structure that gives the correct details about calling
821 -- The *name* of this Id is a local name whose OccName gives the full
822 -- details of the ccall, type and all. This means that the interface
823 -- file reader can reconstruct a suitable Id
825 mkFCallId :: Unique -> ForeignCall -> Type -> Id
826 mkFCallId uniq fcall ty
827 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
828 -- A CCallOpId should have no free type variables;
829 -- when doing substitutions won't substitute over it
830 mkGlobalId (FCallId fcall) name ty info
832 occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
833 -- The "occurrence name" of a ccall is the full info about the
834 -- ccall; it is encoded, but may have embedded spaces etc!
836 name = mkFCallName uniq occ_str
840 `setAllStrictnessInfo` Just strict_sig
842 (_, tau) = tcSplitForAllTys ty
843 (arg_tys, _) = tcSplitFunTys tau
844 arity = length arg_tys
845 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
849 %************************************************************************
851 \subsection{DictFuns and default methods}
853 %************************************************************************
855 Important notes about dict funs and default methods
856 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
857 Dict funs and default methods are *not* ImplicitIds. Their definition
858 involves user-written code, so we can't figure out their strictness etc
859 based on fixed info, as we can for constructors and record selectors (say).
861 We build them as LocalIds, but with External Names. This ensures that
862 they are taken to account by free-variable finding and dependency
863 analysis (e.g. CoreFVs.exprFreeVars).
865 Why shouldn't they be bound as GlobalIds? Because, in particular, if
866 they are globals, the specialiser floats dict uses above their defns,
867 which prevents good simplifications happening. Also the strictness
868 analyser treats a occurrence of a GlobalId as imported and assumes it
869 contains strictness in its IdInfo, which isn't true if the thing is
870 bound in the same module as the occurrence.
872 It's OK for dfuns to be LocalIds, because we form the instance-env to
873 pass on to the next module (md_insts) in CoreTidy, afer tidying
874 and globalising the top-level Ids.
876 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so
877 that they aren't discarded by the occurrence analyser.
880 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
882 mkDictFunId :: Name -- Name to use for the dict fun;
889 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
890 = mkExportedLocalId dfun_name dfun_ty
892 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
894 {- 1 dec 99: disable the Mark Jones optimisation for the sake
895 of compatibility with Hugs.
896 See `types/InstEnv' for a discussion related to this.
898 (class_tyvars, sc_theta, _, _) = classBigSig clas
899 not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
900 sc_theta' = substClasses (zipTopTvSubst class_tyvars inst_tys) sc_theta
901 dfun_theta = case inst_decl_theta of
902 [] -> [] -- If inst_decl_theta is empty, then we don't
903 -- want to have any dict arguments, so that we can
904 -- expose the constant methods.
906 other -> nub (inst_decl_theta ++ filter not_const sc_theta')
907 -- Otherwise we pass the superclass dictionaries to
908 -- the dictionary function; the Mark Jones optimisation.
910 -- NOTE the "nub". I got caught by this one:
911 -- class Monad m => MonadT t m where ...
912 -- instance Monad m => MonadT (EnvT env) m where ...
913 -- Here, the inst_decl_theta has (Monad m); but so
914 -- does the sc_theta'!
916 -- NOTE the "not_const". I got caught by this one too:
917 -- class Foo a => Baz a b where ...
918 -- instance Wob b => Baz T b where..
919 -- Now sc_theta' has Foo T
924 %************************************************************************
926 \subsection{Un-definable}
928 %************************************************************************
930 These Ids can't be defined in Haskell. They could be defined in
931 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
932 ensure that they were definitely, definitely inlined, because there is
933 no curried identifier for them. That's what mkCompulsoryUnfolding
934 does. If we had a way to get a compulsory unfolding from an interface
935 file, we could do that, but we don't right now.
937 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
938 just gets expanded into a type coercion wherever it occurs. Hence we
939 add it as a built-in Id with an unfolding here.
941 The type variables we use here are "open" type variables: this means
942 they can unify with both unlifted and lifted types. Hence we provide
943 another gun with which to shoot yourself in the foot.
946 mkWiredInIdName mod fs uniq id
947 = mkWiredInName mod (mkOccNameFS varName fs) uniq Nothing (AnId id) UserSyntax
949 unsafeCoerceName = mkWiredInIdName gHC_PRIM FSLIT("unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
950 nullAddrName = mkWiredInIdName gHC_PRIM FSLIT("nullAddr#") nullAddrIdKey nullAddrId
951 seqName = mkWiredInIdName gHC_PRIM FSLIT("seq") seqIdKey seqId
952 realWorldName = mkWiredInIdName gHC_PRIM FSLIT("realWorld#") realWorldPrimIdKey realWorldPrimId
953 lazyIdName = mkWiredInIdName gHC_BASE FSLIT("lazy") lazyIdKey lazyId
955 errorName = mkWiredInIdName gHC_ERR FSLIT("error") errorIdKey eRROR_ID
956 recSelErrorName = mkWiredInIdName gHC_ERR FSLIT("recSelError") recSelErrorIdKey rEC_SEL_ERROR_ID
957 runtimeErrorName = mkWiredInIdName gHC_ERR FSLIT("runtimeError") runtimeErrorIdKey rUNTIME_ERROR_ID
958 irrefutPatErrorName = mkWiredInIdName gHC_ERR FSLIT("irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
959 recConErrorName = mkWiredInIdName gHC_ERR FSLIT("recConError") recConErrorIdKey rEC_CON_ERROR_ID
960 patErrorName = mkWiredInIdName gHC_ERR FSLIT("patError") patErrorIdKey pAT_ERROR_ID
961 noMethodBindingErrorName = mkWiredInIdName gHC_ERR FSLIT("noMethodBindingError")
962 noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
963 nonExhaustiveGuardsErrorName
964 = mkWiredInIdName gHC_ERR FSLIT("nonExhaustiveGuardsError")
965 nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
969 -- unsafeCoerce# :: forall a b. a -> b
971 = pcMiscPrelId unsafeCoerceName ty info
973 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
976 ty = mkForAllTys [openAlphaTyVar,openBetaTyVar]
977 (mkFunTy openAlphaTy openBetaTy)
978 [x] = mkTemplateLocals [openAlphaTy]
979 rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
980 -- Note (Coerce openBetaTy openAlphaTy) (Var x)
981 Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
983 -- nullAddr# :: Addr#
984 -- The reason is is here is because we don't provide
985 -- a way to write this literal in Haskell.
987 = pcMiscPrelId nullAddrName addrPrimTy info
989 info = noCafIdInfo `setUnfoldingInfo`
990 mkCompulsoryUnfolding (Lit nullAddrLit)
993 = pcMiscPrelId seqName ty info
995 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
998 ty = mkForAllTys [alphaTyVar,openBetaTyVar]
999 (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
1000 [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
1001 rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
1003 -- lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
1004 -- Used to lazify pseq: pseq a b = a `seq` lazy b
1006 -- Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1007 -- not from GHC.Base.hi. This is important, because the strictness
1008 -- analyser will spot it as strict!
1010 -- Also no unfolding in lazyId: it gets "inlined" by a HACK in the worker/wrapper pass
1011 -- (see WorkWrap.wwExpr)
1012 -- We could use inline phases to do this, but that would be vulnerable to changes in
1013 -- phase numbering....we must inline precisely after strictness analysis.
1015 = pcMiscPrelId lazyIdName ty info
1018 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
1020 lazyIdUnfolding :: CoreExpr -- Used to expand 'lazyId' after strictness anal
1021 lazyIdUnfolding = mkLams [openAlphaTyVar,x] (Var x)
1023 [x] = mkTemplateLocals [openAlphaTy]
1026 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
1027 nasty as-is, change it back to a literal (@Literal@).
1029 voidArgId is a Local Id used simply as an argument in functions
1030 where we just want an arg to avoid having a thunk of unlifted type.
1032 x = \ void :: State# RealWorld -> (# p, q #)
1034 This comes up in strictness analysis
1037 realWorldPrimId -- :: State# RealWorld
1038 = pcMiscPrelId realWorldName realWorldStatePrimTy
1039 (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1040 -- The evaldUnfolding makes it look that realWorld# is evaluated
1041 -- which in turn makes Simplify.interestingArg return True,
1042 -- which in turn makes INLINE things applied to realWorld# likely
1045 voidArgId -- :: State# RealWorld
1046 = mkSysLocal FSLIT("void") voidArgIdKey realWorldStatePrimTy
1050 %************************************************************************
1052 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1054 %************************************************************************
1056 GHC randomly injects these into the code.
1058 @patError@ is just a version of @error@ for pattern-matching
1059 failures. It knows various ``codes'' which expand to longer
1060 strings---this saves space!
1062 @absentErr@ is a thing we put in for ``absent'' arguments. They jolly
1063 well shouldn't be yanked on, but if one is, then you will get a
1064 friendly message from @absentErr@ (rather than a totally random
1067 @parError@ is a special version of @error@ which the compiler does
1068 not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
1069 templates, but we don't ever expect to generate code for it.
1073 :: Id -- Should be of type (forall a. Addr# -> a)
1074 -- where Addr# points to a UTF8 encoded string
1075 -> Type -- The type to instantiate 'a'
1076 -> String -- The string to print
1079 mkRuntimeErrorApp err_id res_ty err_msg
1080 = mkApps (Var err_id) [Type res_ty, err_string]
1082 err_string = Lit (mkStringLit err_msg)
1084 rEC_SEL_ERROR_ID = mkRuntimeErrorId recSelErrorName
1085 rUNTIME_ERROR_ID = mkRuntimeErrorId runtimeErrorName
1086 iRREFUT_PAT_ERROR_ID = mkRuntimeErrorId irrefutPatErrorName
1087 rEC_CON_ERROR_ID = mkRuntimeErrorId recConErrorName
1088 pAT_ERROR_ID = mkRuntimeErrorId patErrorName
1089 nO_METHOD_BINDING_ERROR_ID = mkRuntimeErrorId noMethodBindingErrorName
1090 nON_EXHAUSTIVE_GUARDS_ERROR_ID = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1092 -- The runtime error Ids take a UTF8-encoded string as argument
1093 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1094 runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1098 eRROR_ID = pc_bottoming_Id errorName errorTy
1101 errorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1102 -- Notice the openAlphaTyVar. It says that "error" can be applied
1103 -- to unboxed as well as boxed types. This is OK because it never
1104 -- returns, so the return type is irrelevant.
1108 %************************************************************************
1110 \subsection{Utilities}
1112 %************************************************************************
1115 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1116 pcMiscPrelId name ty info
1117 = mkVanillaGlobal name ty info
1118 -- We lie and say the thing is imported; otherwise, we get into
1119 -- a mess with dependency analysis; e.g., core2stg may heave in
1120 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
1121 -- being compiled, then it's just a matter of luck if the definition
1122 -- will be in "the right place" to be in scope.
1124 pc_bottoming_Id name ty
1125 = pcMiscPrelId name ty bottoming_info
1127 bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1128 -- Do *not* mark them as NoCafRefs, because they can indeed have
1129 -- CAF refs. For example, pAT_ERROR_ID calls GHC.Err.untangle,
1130 -- which has some CAFs
1131 -- In due course we may arrange that these error-y things are
1132 -- regarded by the GC as permanently live, in which case we
1133 -- can give them NoCaf info. As it is, any function that calls
1134 -- any pc_bottoming_Id will itself have CafRefs, which bloats
1137 strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1138 -- These "bottom" out, no matter what their arguments
1140 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
1141 openAlphaTy = mkTyVarTy openAlphaTyVar
1142 openBetaTy = mkTyVarTy openBetaTyVar