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,
19 mkDataConId, mkDataConWrapId,
20 mkRecordSelId, rebuildConArgs,
21 mkPrimOpId, mkFCallId,
23 -- And some particular Ids; see below for why they are wired in
25 unsafeCoerceId, realWorldPrimId, nullAddrId,
26 eRROR_ID, eRROR_CSTRING_ID, rEC_SEL_ERROR_ID, pAT_ERROR_ID, rEC_CON_ERROR_ID,
27 rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID, nON_EXHAUSTIVE_GUARDS_ERROR_ID,
28 nO_METHOD_BINDING_ERROR_ID, aBSENT_ERROR_ID, pAR_ERROR_ID
31 #include "HsVersions.h"
34 import BasicTypes ( Arity, StrictnessMark(..), isMarkedUnboxed, isMarkedStrict )
35 import TysPrim ( openAlphaTyVars, alphaTyVar, alphaTy, betaTyVar, betaTy,
36 intPrimTy, realWorldStatePrimTy, addrPrimTy
38 import TysWiredIn ( charTy, mkListTy )
39 import PrelRules ( primOpRules )
40 import Rules ( addRule )
41 import TcType ( Type, ThetaType, mkDictTy, mkPredTys, mkTyConApp,
42 mkTyVarTys, mkClassPred, tcEqPred,
43 mkFunTys, mkFunTy, mkSigmaTy, tcSplitSigmaTy,
44 isUnLiftedType, mkForAllTys, mkTyVarTy, tyVarsOfType,
45 tcSplitFunTys, tcSplitForAllTys, mkPredTy
47 import Module ( Module )
48 import CoreUtils ( mkInlineMe )
49 import CoreUnfold ( mkTopUnfolding, mkCompulsoryUnfolding, mkOtherCon )
50 import Literal ( Literal(..), nullAddrLit )
51 import TyCon ( TyCon, isNewTyCon, tyConTyVars, tyConDataCons,
52 tyConTheta, isProductTyCon, isDataTyCon, isRecursiveTyCon )
53 import Class ( Class, classTyCon, classTyVars, classSelIds )
54 import Var ( Id, TyVar )
55 import VarSet ( isEmptyVarSet )
56 import Name ( mkWiredInName, mkFCallName, Name )
57 import OccName ( mkVarOcc )
58 import PrimOp ( PrimOp(DataToTagOp), primOpSig, mkPrimOpIdName )
59 import ForeignCall ( ForeignCall )
60 import DataCon ( DataCon,
61 dataConFieldLabels, dataConRepArity, dataConTyCon,
62 dataConArgTys, dataConRepType,
63 dataConInstOrigArgTys,
64 dataConName, dataConTheta,
65 dataConSig, dataConStrictMarks, dataConId,
68 import Id ( idType, mkGlobalId, mkVanillaGlobal, mkSysLocal,
69 mkTemplateLocals, mkTemplateLocalsNum,
70 mkTemplateLocal, idNewStrictness, idName
72 import IdInfo ( IdInfo, noCafNoTyGenIdInfo,
74 setArityInfo, setSpecInfo, setCgInfo, setCafInfo,
75 mkNewStrictnessInfo, setNewStrictnessInfo,
76 GlobalIdDetails(..), CafInfo(..), CprInfo(..),
79 import NewDemand ( mkStrictSig, strictSigResInfo, DmdResult(..),
80 mkTopDmdType, topDmd, evalDmd, Demand(..), Keepity(..) )
81 import FieldLabel ( mkFieldLabel, fieldLabelName,
82 firstFieldLabelTag, allFieldLabelTags, fieldLabelType
84 import DmdAnal ( dmdAnalTopRhs )
86 import Unique ( mkBuiltinUnique )
89 import Maybe ( isJust )
90 import Util ( dropList, isSingleton )
92 import ListSetOps ( assoc, assocMaybe )
93 import UnicodeUtil ( stringToUtf8 )
97 %************************************************************************
99 \subsection{Wired in Ids}
101 %************************************************************************
105 = [ -- These error-y things are wired in because we don't yet have
106 -- a way to express in an interface file that the result type variable
107 -- is 'open'; that is can be unified with an unboxed type
109 -- [The interface file format now carry such information, but there's
110 -- no way yet of expressing at the definition site for these
111 -- error-reporting functions that they have an 'open'
112 -- result type. -- sof 1/99]
117 , iRREFUT_PAT_ERROR_ID
118 , nON_EXHAUSTIVE_GUARDS_ERROR_ID
119 , nO_METHOD_BINDING_ERROR_ID
125 -- These can't be defined in Haskell, but they have
126 -- perfectly reasonable unfoldings in Core
135 %************************************************************************
137 \subsection{Data constructors}
139 %************************************************************************
142 mkDataConId :: Name -> DataCon -> Id
143 -- Makes the *worker* for the data constructor; that is, the function
144 -- that takes the reprsentation arguments and builds the constructor.
145 mkDataConId work_name data_con
146 = mkGlobalId (DataConId data_con) work_name (dataConRepType data_con) info
148 info = noCafNoTyGenIdInfo
150 `setNewStrictnessInfo` Just strict_sig
152 arity = dataConRepArity data_con
154 strict_sig = mkStrictSig (mkTopDmdType (replicate arity topDmd) cpr_info)
155 -- Notice that we do *not* say the worker is strict
156 -- even if the data constructor is declared strict
157 -- e.g. data T = MkT !(Int,Int)
158 -- Why? Because the *wrapper* is strict (and its unfolding has case
159 -- expresssions that do the evals) but the *worker* itself is not.
160 -- If we pretend it is strict then when we see
161 -- case x of y -> $wMkT y
162 -- the simplifier thinks that y is "sure to be evaluated" (because
163 -- $wMkT is strict) and drops the case. No, $wMkT is not strict.
165 -- When the simplifer sees a pattern
166 -- case e of MkT x -> ...
167 -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
168 -- but that's fine... dataConRepStrictness comes from the data con
169 -- not from the worker Id.
171 tycon = dataConTyCon data_con
172 cpr_info | isProductTyCon tycon &&
175 arity <= mAX_CPR_SIZE = RetCPR
177 -- RetCPR is only true for products that are real data types;
178 -- that is, not unboxed tuples or [non-recursive] newtypes
180 mAX_CPR_SIZE :: Arity
182 -- We do not treat very big tuples as CPR-ish:
183 -- a) for a start we get into trouble because there aren't
184 -- "enough" unboxed tuple types (a tiresome restriction,
186 -- b) more importantly, big unboxed tuples get returned mainly
187 -- on the stack, and are often then allocated in the heap
188 -- by the caller. So doing CPR for them may in fact make
192 The wrapper for a constructor is an ordinary top-level binding that evaluates
193 any strict args, unboxes any args that are going to be flattened, and calls
196 We're going to build a constructor that looks like:
198 data (Data a, C b) => T a b = T1 !a !Int b
201 \d1::Data a, d2::C b ->
202 \p q r -> case p of { p ->
204 Con T1 [a,b] [p,q,r]}}
208 * d2 is thrown away --- a context in a data decl is used to make sure
209 one *could* construct dictionaries at the site the constructor
210 is used, but the dictionary isn't actually used.
212 * We have to check that we can construct Data dictionaries for
213 the types a and Int. Once we've done that we can throw d1 away too.
215 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
216 all that matters is that the arguments are evaluated. "seq" is
217 very careful to preserve evaluation order, which we don't need
220 You might think that we could simply give constructors some strictness
221 info, like PrimOps, and let CoreToStg do the let-to-case transformation.
222 But we don't do that because in the case of primops and functions strictness
223 is a *property* not a *requirement*. In the case of constructors we need to
224 do something active to evaluate the argument.
226 Making an explicit case expression allows the simplifier to eliminate
227 it in the (common) case where the constructor arg is already evaluated.
230 mkDataConWrapId data_con
231 = mkGlobalId (DataConWrapId data_con) (dataConName data_con) wrap_ty info
233 work_id = dataConId data_con
235 info = noCafNoTyGenIdInfo
236 `setUnfoldingInfo` mkTopUnfolding (mkInlineMe wrap_rhs)
237 -- The NoCaf-ness is set by noCafNoTyGenIdInfo
239 -- It's important to specify the arity, so that partial
240 -- applications are treated as values
241 `setNewStrictnessInfo` Just wrap_sig
243 wrap_ty = mkForAllTys all_tyvars (mkFunTys all_arg_tys result_ty)
245 wrap_sig = mkStrictSig (mkTopDmdType arg_dmds res_info)
246 res_info = strictSigResInfo (idNewStrictness work_id)
247 arg_dmds = [Abs | d <- dict_args] ++ map mk_dmd strict_marks
248 mk_dmd str | isMarkedStrict str = Eval
250 -- The Cpr info can be important inside INLINE rhss, where the
251 -- wrapper constructor isn't inlined
252 -- And the argument strictness can be important too; we
253 -- may not inline a contructor when it is partially applied.
255 -- data W = C !Int !Int !Int
256 -- ...(let w = C x in ...(w p q)...)...
257 -- we want to see that w is strict in its two arguments
259 wrap_rhs | isNewTyCon tycon
260 = ASSERT( null ex_tyvars && null ex_dict_args && isSingleton orig_arg_tys )
261 -- No existentials on a newtype, but it can have a context
262 -- e.g. newtype Eq a => T a = MkT (...)
263 mkLams tyvars $ mkLams dict_args $ Lam id_arg1 $
264 mkNewTypeBody tycon result_ty id_arg1
266 | null dict_args && not (any isMarkedStrict strict_marks)
267 = Var work_id -- The common case. Not only is this efficient,
268 -- but it also ensures that the wrapper is replaced
269 -- by the worker even when there are no args.
273 -- This is really important in rule matching,
274 -- (We could match on the wrappers,
275 -- but that makes it less likely that rules will match
276 -- when we bring bits of unfoldings together.)
278 -- NB: because of this special case, (map (:) ys) turns into
279 -- (map $w: ys), and thence into (map (\x xs. $w: x xs) ys)
280 -- in core-to-stg. The top-level defn for (:) is never used.
281 -- This is somewhat of a bore, but I'm currently leaving it
282 -- as is, so that there still is a top level curried (:) for
283 -- the interpreter to call.
286 = mkLams all_tyvars $ mkLams dict_args $
287 mkLams ex_dict_args $ mkLams id_args $
288 foldr mk_case con_app
289 (zip (ex_dict_args++id_args) strict_marks) i3 []
291 con_app i rep_ids = mkApps (Var work_id)
292 (map varToCoreExpr (all_tyvars ++ reverse rep_ids))
294 (tyvars, theta, ex_tyvars, ex_theta, orig_arg_tys, tycon) = dataConSig data_con
295 all_tyvars = tyvars ++ ex_tyvars
297 dict_tys = mkPredTys theta
298 ex_dict_tys = mkPredTys ex_theta
299 all_arg_tys = dict_tys ++ ex_dict_tys ++ orig_arg_tys
300 result_ty = mkTyConApp tycon (mkTyVarTys tyvars)
302 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
306 (dict_args, i1) = mkLocals 1 dict_tys
307 (ex_dict_args,i2) = mkLocals i1 ex_dict_tys
308 (id_args,i3) = mkLocals i2 orig_arg_tys
310 (id_arg1:_) = id_args -- Used for newtype only
312 strict_marks = dataConStrictMarks data_con
315 :: (Id, StrictnessMark) -- Arg, strictness
316 -> (Int -> [Id] -> CoreExpr) -- Body
317 -> Int -- Next rep arg id
318 -> [Id] -- Rep args so far, reversed
320 mk_case (arg,strict) body i rep_args
322 NotMarkedStrict -> body i (arg:rep_args)
324 | isUnLiftedType (idType arg) -> body i (arg:rep_args)
326 Case (Var arg) arg [(DEFAULT,[], body i (arg:rep_args))]
329 -> case splitProductType "do_unbox" (idType arg) of
330 (tycon, tycon_args, con, tys) ->
331 Case (Var arg) arg [(DataAlt con, con_args,
332 body i' (reverse con_args ++ rep_args))]
334 (con_args, i') = mkLocals i tys
338 %************************************************************************
340 \subsection{Record selectors}
342 %************************************************************************
344 We're going to build a record selector unfolding that looks like this:
346 data T a b c = T1 { ..., op :: a, ...}
347 | T2 { ..., op :: a, ...}
350 sel = /\ a b c -> \ d -> case d of
355 Similarly for newtypes
357 newtype N a = MkN { unN :: a->a }
360 unN n = coerce (a->a) n
362 We need to take a little care if the field has a polymorphic type:
364 data R = R { f :: forall a. a->a }
368 f :: forall a. R -> a -> a
369 f = /\ a \ r = case r of
372 (not f :: R -> forall a. a->a, which gives the type inference mechanism
373 problems at call sites)
375 Similarly for newtypes
377 newtype N = MkN { unN :: forall a. a->a }
379 unN :: forall a. N -> a -> a
380 unN = /\a -> \n:N -> coerce (a->a) n
383 mkRecordSelId tycon field_label unpack_id unpackUtf8_id
384 -- Assumes that all fields with the same field label have the same type
386 -- Annoyingly, we have to pass in the unpackCString# Id, because
387 -- we can't conjure it up out of thin air
390 sel_id = mkGlobalId (RecordSelId field_label) (fieldLabelName field_label) selector_ty info
391 field_ty = fieldLabelType field_label
392 data_cons = tyConDataCons tycon
393 tyvars = tyConTyVars tycon -- These scope over the types in
394 -- the FieldLabels of constructors of this type
395 data_ty = mkTyConApp tycon tyvar_tys
396 tyvar_tys = mkTyVarTys tyvars
398 tycon_theta = tyConTheta tycon -- The context on the data decl
399 -- eg data (Eq a, Ord b) => T a b = ...
400 dict_tys = [mkPredTy pred | pred <- tycon_theta,
402 needed_dict pred = or [ tcEqPred pred p
403 | (DataAlt dc, _, _) <- the_alts, p <- dataConTheta dc]
404 n_dict_tys = length dict_tys
406 (field_tyvars,field_theta,field_tau) = tcSplitSigmaTy field_ty
407 field_dict_tys = map mkPredTy field_theta
408 n_field_dict_tys = length field_dict_tys
409 -- If the field has a universally quantified type we have to
410 -- be a bit careful. Suppose we have
411 -- data R = R { op :: forall a. Foo a => a -> a }
412 -- Then we can't give op the type
413 -- op :: R -> forall a. Foo a => a -> a
414 -- because the typechecker doesn't understand foralls to the
415 -- right of an arrow. The "right" type to give it is
416 -- op :: forall a. Foo a => R -> a -> a
417 -- But then we must generate the right unfolding too:
418 -- op = /\a -> \dfoo -> \ r ->
421 -- Note that this is exactly the type we'd infer from a user defn
424 -- Very tiresomely, the selectors are (unnecessarily!) overloaded over
425 -- just the dictionaries in the types of the constructors that contain
426 -- the relevant field. Urgh.
427 -- NB: this code relies on the fact that DataCons are quantified over
428 -- the identical type variables as their parent TyCon
431 selector_ty = mkForAllTys tyvars $ mkForAllTys field_tyvars $
432 mkFunTys dict_tys $ mkFunTys field_dict_tys $
433 mkFunTy data_ty field_tau
435 arity = 1 + n_dict_tys + n_field_dict_tys
437 (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
438 -- Use the demand analyser to work out strictness.
439 -- With all this unpackery it's not easy!
441 info = noCafNoTyGenIdInfo
442 `setCafInfo` caf_info
444 `setUnfoldingInfo` mkTopUnfolding rhs_w_str
445 `setNewStrictnessInfo` Just strict_sig
447 -- Allocate Ids. We do it a funny way round because field_dict_tys is
448 -- almost always empty. Also note that we use length_tycon_theta
449 -- rather than n_dict_tys, because the latter gives an infinite loop:
450 -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
451 -- on arity, which depends on n_dict tys. Sigh! Mega sigh!
452 field_dict_base = length tycon_theta + 1
453 dict_id_base = field_dict_base + n_field_dict_tys
454 field_base = dict_id_base + 1
455 dict_ids = mkTemplateLocalsNum 1 dict_tys
456 field_dict_ids = mkTemplateLocalsNum field_dict_base field_dict_tys
457 data_id = mkTemplateLocal dict_id_base data_ty
459 alts = map mk_maybe_alt data_cons
460 the_alts = catMaybes alts
462 no_default = all isJust alts -- No default needed
463 default_alt | no_default = []
464 | otherwise = [(DEFAULT, [], error_expr)]
466 -- the default branch may have CAF refs, because it calls recSelError etc.
467 caf_info | no_default = NoCafRefs
468 | otherwise = MayHaveCafRefs
470 sel_rhs = mkLams tyvars $ mkLams field_tyvars $
471 mkLams dict_ids $ mkLams field_dict_ids $
472 Lam data_id $ sel_body
474 sel_body | isNewTyCon tycon = mkNewTypeBody tycon field_tau data_id
475 | otherwise = Case (Var data_id) data_id (default_alt ++ the_alts)
477 mk_maybe_alt data_con
478 = case maybe_the_arg_id of
480 Just the_arg_id -> Just (DataAlt data_con, real_args, mkLets binds body)
482 body = mkVarApps (mkVarApps (Var the_arg_id) field_tyvars) field_dict_ids
483 strict_marks = dataConStrictMarks data_con
484 (binds, real_args) = rebuildConArgs arg_ids strict_marks
485 (map mkBuiltinUnique [unpack_base..])
487 arg_ids = mkTemplateLocalsNum field_base (dataConInstOrigArgTys data_con tyvar_tys)
489 unpack_base = field_base + length arg_ids
491 -- arity+1 avoids all shadowing
492 maybe_the_arg_id = assocMaybe (field_lbls `zip` arg_ids) field_label
493 field_lbls = dataConFieldLabels data_con
495 error_expr = mkApps (Var rEC_SEL_ERROR_ID) [Type field_tau, err_string]
497 | all safeChar full_msg
498 = App (Var unpack_id) (Lit (MachStr (_PK_ full_msg)))
500 = App (Var unpackUtf8_id) (Lit (MachStr (_PK_ (stringToUtf8 (map ord full_msg)))))
502 safeChar c = c >= '\1' && c <= '\xFF'
503 -- TODO: Putting this Unicode stuff here is ugly. Find a better
504 -- generic place to make string literals. This logic is repeated
506 full_msg = showSDoc (sep [text "No match in record selector", ppr sel_id])
509 -- This rather ugly function converts the unpacked data con
510 -- arguments back into their packed form.
513 :: [Id] -- Source-level args
514 -> [StrictnessMark] -- Strictness annotations (per-arg)
515 -> [Unique] -- Uniques for the new Ids
516 -> ([CoreBind], [Id]) -- A binding for each source-level arg, plus
517 -- a list of the representation-level arguments
518 -- e.g. data T = MkT Int !Int
520 -- rebuild [x::Int, y::Int] [Not, Unbox]
521 -- = ([ y = I# t ], [x,t])
523 rebuildConArgs [] stricts us = ([], [])
525 -- Type variable case
526 rebuildConArgs (arg:args) stricts us
528 = let (binds, args') = rebuildConArgs args stricts us
529 in (binds, arg:args')
531 -- Term variable case
532 rebuildConArgs (arg:args) (str:stricts) us
533 | isMarkedUnboxed str
537 (_, tycon_args, pack_con, con_arg_tys)
538 = splitProductType "rebuildConArgs" arg_ty
540 unpacked_args = zipWith (mkSysLocal SLIT("rb")) us con_arg_tys
541 (binds, args') = rebuildConArgs args stricts (dropList con_arg_tys us)
542 con_app = mkConApp pack_con (map Type tycon_args ++ map Var unpacked_args)
544 (NonRec arg con_app : binds, unpacked_args ++ args')
547 = let (binds, args') = rebuildConArgs args stricts us
548 in (binds, arg:args')
552 %************************************************************************
554 \subsection{Dictionary selectors}
556 %************************************************************************
558 Selecting a field for a dictionary. If there is just one field, then
559 there's nothing to do.
561 ToDo: unify with mkRecordSelId.
564 mkDictSelId :: Name -> Class -> Id
565 mkDictSelId name clas
566 = mkGlobalId (RecordSelId field_lbl) name sel_ty info
568 sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
569 -- We can't just say (exprType rhs), because that would give a type
571 -- for a single-op class (after all, the selector is the identity)
572 -- But it's type must expose the representation of the dictionary
573 -- to gat (say) C a -> (a -> a)
575 field_lbl = mkFieldLabel name tycon sel_ty tag
576 tag = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` allFieldLabelTags) name
578 info = noCafNoTyGenIdInfo
580 `setUnfoldingInfo` mkTopUnfolding rhs
581 `setNewStrictnessInfo` Just strict_sig
583 -- We no longer use 'must-inline' on record selectors. They'll
584 -- inline like crazy if they scrutinise a constructor
586 -- The strictness signature is of the form U(AAAVAAAA) -> T
587 -- where the V depends on which item we are selecting
588 -- It's worth giving one, so that absence info etc is generated
589 -- even if the selector isn't inlined
590 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
591 arg_dmd | isNewTyCon tycon = Eval
592 | otherwise = Seq Drop [ if the_arg_id == id then Eval else Abs
595 tyvars = classTyVars clas
597 tycon = classTyCon clas
598 [data_con] = tyConDataCons tycon
599 tyvar_tys = mkTyVarTys tyvars
600 arg_tys = dataConArgTys data_con tyvar_tys
601 the_arg_id = arg_ids !! (tag - firstFieldLabelTag)
603 pred = mkClassPred clas tyvar_tys
604 (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
606 rhs | isNewTyCon tycon = mkLams tyvars $ Lam dict_id $
607 mkNewTypeBody tycon (head arg_tys) dict_id
608 | otherwise = mkLams tyvars $ Lam dict_id $
609 Case (Var dict_id) dict_id
610 [(DataAlt data_con, arg_ids, Var the_arg_id)]
612 mkNewTypeBody tycon result_ty result_id
613 | isRecursiveTyCon tycon -- Recursive case; use a coerce
614 = Note (Coerce result_ty (idType result_id)) (Var result_id)
615 | otherwise -- Normal case
620 %************************************************************************
622 \subsection{Primitive operations
624 %************************************************************************
627 mkPrimOpId :: PrimOp -> Id
631 (tyvars,arg_tys,res_ty, arity, strict_info) = primOpSig prim_op
632 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
633 name = mkPrimOpIdName prim_op
634 id = mkGlobalId (PrimOpId prim_op) name ty info
636 info = noCafNoTyGenIdInfo
639 `setNewStrictnessInfo` Just (mkNewStrictnessInfo id arity strict_info NoCPRInfo)
640 -- Until we modify the primop generation code
642 rules = foldl (addRule id) emptyCoreRules (primOpRules prim_op)
645 -- For each ccall we manufacture a separate CCallOpId, giving it
646 -- a fresh unique, a type that is correct for this particular ccall,
647 -- and a CCall structure that gives the correct details about calling
650 -- The *name* of this Id is a local name whose OccName gives the full
651 -- details of the ccall, type and all. This means that the interface
652 -- file reader can reconstruct a suitable Id
654 mkFCallId :: Unique -> ForeignCall -> Type -> Id
655 mkFCallId uniq fcall ty
656 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
657 -- A CCallOpId should have no free type variables;
658 -- when doing substitutions won't substitute over it
659 mkGlobalId (FCallId fcall) name ty info
661 occ_str = showSDocIface (braces (ppr fcall <+> ppr ty))
662 -- The "occurrence name" of a ccall is the full info about the
663 -- ccall; it is encoded, but may have embedded spaces etc!
665 name = mkFCallName uniq occ_str
667 info = noCafNoTyGenIdInfo
669 `setNewStrictnessInfo` Just strict_sig
671 (_, tau) = tcSplitForAllTys ty
672 (arg_tys, _) = tcSplitFunTys tau
673 arity = length arg_tys
674 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
678 %************************************************************************
680 \subsection{DictFuns and default methods}
682 %************************************************************************
684 Important notes about dict funs and default methods
685 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
686 Dict funs and default methods are *not* ImplicitIds. Their definition
687 involves user-written code, so we can't figure out their strictness etc
688 based on fixed info, as we can for constructors and record selectors (say).
690 We build them as GlobalIds, but when in the module where they are
691 bound, we turn the Id at the *binding site* into an exported LocalId.
692 This ensures that they are taken to account by free-variable finding
693 and dependency analysis (e.g. CoreFVs.exprFreeVars). The simplifier
694 will propagate the LocalId to all occurrence sites.
696 Why shouldn't they be bound as GlobalIds? Because, in particular, if
697 they are globals, the specialiser floats dict uses above their defns,
698 which prevents good simplifications happening. Also the strictness
699 analyser treats a occurrence of a GlobalId as imported and assumes it
700 contains strictness in its IdInfo, which isn't true if the thing is
701 bound in the same module as the occurrence.
703 It's OK for dfuns to be LocalIds, because we form the instance-env to
704 pass on to the next module (md_insts) in CoreTidy, afer tidying
705 and globalising the top-level Ids.
707 BUT make sure they are *exported* LocalIds (setIdLocalExported) so
708 that they aren't discarded by the occurrence analyser.
711 mkDefaultMethodId dm_name ty = mkVanillaGlobal dm_name ty noCafNoTyGenIdInfo
713 mkDictFunId :: Name -- Name to use for the dict fun;
720 mkDictFunId dfun_name clas inst_tyvars inst_tys dfun_theta
721 = mkVanillaGlobal dfun_name dfun_ty noCafNoTyGenIdInfo
723 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
725 {- 1 dec 99: disable the Mark Jones optimisation for the sake
726 of compatibility with Hugs.
727 See `types/InstEnv' for a discussion related to this.
729 (class_tyvars, sc_theta, _, _) = classBigSig clas
730 not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
731 sc_theta' = substClasses (mkTopTyVarSubst class_tyvars inst_tys) sc_theta
732 dfun_theta = case inst_decl_theta of
733 [] -> [] -- If inst_decl_theta is empty, then we don't
734 -- want to have any dict arguments, so that we can
735 -- expose the constant methods.
737 other -> nub (inst_decl_theta ++ filter not_const sc_theta')
738 -- Otherwise we pass the superclass dictionaries to
739 -- the dictionary function; the Mark Jones optimisation.
741 -- NOTE the "nub". I got caught by this one:
742 -- class Monad m => MonadT t m where ...
743 -- instance Monad m => MonadT (EnvT env) m where ...
744 -- Here, the inst_decl_theta has (Monad m); but so
745 -- does the sc_theta'!
747 -- NOTE the "not_const". I got caught by this one too:
748 -- class Foo a => Baz a b where ...
749 -- instance Wob b => Baz T b where..
750 -- Now sc_theta' has Foo T
755 %************************************************************************
757 \subsection{Un-definable}
759 %************************************************************************
761 These Ids can't be defined in Haskell. They could be defined in
762 unfoldings in PrelGHC.hi-boot, but we'd have to ensure that they
763 were definitely, definitely inlined, because there is no curried
764 identifier for them. That's what mkCompulsoryUnfolding does.
765 If we had a way to get a compulsory unfolding from an interface file,
766 we could do that, but we don't right now.
768 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
769 just gets expanded into a type coercion wherever it occurs. Hence we
770 add it as a built-in Id with an unfolding here.
772 The type variables we use here are "open" type variables: this means
773 they can unify with both unlifted and lifted types. Hence we provide
774 another gun with which to shoot yourself in the foot.
777 -- unsafeCoerce# :: forall a b. a -> b
779 = pcMiscPrelId unsafeCoerceIdKey pREL_GHC SLIT("unsafeCoerce#") ty info
781 info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
784 ty = mkForAllTys [openAlphaTyVar,openBetaTyVar]
785 (mkFunTy openAlphaTy openBetaTy)
786 [x] = mkTemplateLocals [openAlphaTy]
787 rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
788 Note (Coerce openBetaTy openAlphaTy) (Var x)
790 -- nullAddr# :: Addr#
791 -- The reason is is here is because we don't provide
792 -- a way to write this literal in Haskell.
794 = pcMiscPrelId nullAddrIdKey pREL_GHC SLIT("nullAddr#") addrPrimTy info
796 info = noCafNoTyGenIdInfo `setUnfoldingInfo`
797 mkCompulsoryUnfolding (Lit nullAddrLit)
800 = pcMiscPrelId seqIdKey pREL_GHC SLIT("seq") ty info
802 info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
805 ty = mkForAllTys [alphaTyVar,betaTyVar]
806 (mkFunTy alphaTy (mkFunTy betaTy betaTy))
807 [x,y] = mkTemplateLocals [alphaTy, betaTy]
808 rhs = mkLams [alphaTyVar,betaTyVar,x,y] (Case (Var x) x [(DEFAULT, [], Var y)])
811 @getTag#@ is another function which can't be defined in Haskell. It needs to
812 evaluate its argument and call the dataToTag# primitive.
816 = pcMiscPrelId getTagIdKey pREL_GHC SLIT("getTag#") ty info
818 info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
819 -- We don't provide a defn for this; you must inline it
821 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy intPrimTy)
822 [x,y] = mkTemplateLocals [alphaTy,alphaTy]
823 rhs = mkLams [alphaTyVar,x] $
824 Case (Var x) y [ (DEFAULT, [], mkApps (Var dataToTagId) [Type alphaTy, Var y]) ]
826 dataToTagId = mkPrimOpId DataToTagOp
829 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
830 nasty as-is, change it back to a literal (@Literal@).
833 realWorldPrimId -- :: State# RealWorld
834 = pcMiscPrelId realWorldPrimIdKey pREL_GHC SLIT("realWorld#")
836 (noCafNoTyGenIdInfo `setUnfoldingInfo` mkOtherCon [])
837 -- The mkOtherCon makes it look that realWorld# is evaluated
838 -- which in turn makes Simplify.interestingArg return True,
839 -- which in turn makes INLINE things applied to realWorld# likely
844 %************************************************************************
846 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
848 %************************************************************************
850 GHC randomly injects these into the code.
852 @patError@ is just a version of @error@ for pattern-matching
853 failures. It knows various ``codes'' which expand to longer
854 strings---this saves space!
856 @absentErr@ is a thing we put in for ``absent'' arguments. They jolly
857 well shouldn't be yanked on, but if one is, then you will get a
858 friendly message from @absentErr@ (rather than a totally random
861 @parError@ is a special version of @error@ which the compiler does
862 not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
863 templates, but we don't ever expect to generate code for it.
867 = pc_bottoming_Id errorIdKey pREL_ERR SLIT("error") errorTy
869 = pc_bottoming_Id errorCStringIdKey pREL_ERR SLIT("errorCString")
870 (mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy))
872 = generic_ERROR_ID patErrorIdKey SLIT("patError")
874 = generic_ERROR_ID recSelErrIdKey SLIT("recSelError")
876 = generic_ERROR_ID recConErrorIdKey SLIT("recConError")
878 = generic_ERROR_ID recUpdErrorIdKey SLIT("recUpdError")
880 = generic_ERROR_ID irrefutPatErrorIdKey SLIT("irrefutPatError")
881 nON_EXHAUSTIVE_GUARDS_ERROR_ID
882 = generic_ERROR_ID nonExhaustiveGuardsErrorIdKey SLIT("nonExhaustiveGuardsError")
883 nO_METHOD_BINDING_ERROR_ID
884 = generic_ERROR_ID noMethodBindingErrorIdKey SLIT("noMethodBindingError")
887 = pc_bottoming_Id absentErrorIdKey pREL_ERR SLIT("absentErr")
888 (mkSigmaTy [openAlphaTyVar] [] openAlphaTy)
891 = pcMiscPrelId parErrorIdKey pREL_ERR SLIT("parError")
892 (mkSigmaTy [openAlphaTyVar] [] openAlphaTy) noCafNoTyGenIdInfo
896 %************************************************************************
898 \subsection{Utilities}
900 %************************************************************************
903 pcMiscPrelId :: Unique{-IdKey-} -> Module -> FAST_STRING -> Type -> IdInfo -> Id
904 pcMiscPrelId key mod str ty info
906 name = mkWiredInName mod (mkVarOcc str) key
907 imp = mkVanillaGlobal name ty info -- the usual case...
910 -- We lie and say the thing is imported; otherwise, we get into
911 -- a mess with dependency analysis; e.g., core2stg may heave in
912 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
913 -- being compiled, then it's just a matter of luck if the definition
914 -- will be in "the right place" to be in scope.
916 pc_bottoming_Id key mod name ty
917 = pcMiscPrelId key mod name ty bottoming_info
919 strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
920 bottoming_info = noCafNoTyGenIdInfo `setNewStrictnessInfo` Just strict_sig
921 -- these "bottom" out, no matter what their arguments
923 generic_ERROR_ID u n = pc_bottoming_Id u pREL_ERR n errorTy
925 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
926 openAlphaTy = mkTyVarTy openAlphaTyVar
927 openBetaTy = mkTyVarTy openBetaTyVar
930 errorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy]
932 -- Notice the openAlphaTyVar. It says that "error" can be applied
933 -- to unboxed as well as boxed types. This is OK because it never
934 -- returns, so the return type is irrelevant.