2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1998
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
15 {-# OPTIONS -fno-warn-missing-signatures #-}
16 -- The above warning supression flag is a temporary kludge.
17 -- While working on this module you are encouraged to remove it and fix
18 -- any warnings in the module. See
19 -- <http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings>
23 mkDictFunId, mkDefaultMethodId,
27 mkPrimOpId, mkFCallId, mkTickBoxOpId, mkBreakPointOpId,
29 mkReboxingAlt, wrapNewTypeBody, unwrapNewTypeBody,
30 wrapFamInstBody, unwrapFamInstScrut,
31 mkUnpackCase, mkProductBox,
33 -- And some particular Ids; see below for why they are wired in
34 wiredInIds, ghcPrimIds,
35 unsafeCoerceId, realWorldPrimId, voidArgId, nullAddrId, seqId,
36 lazyId, lazyIdUnfolding, lazyIdKey,
38 mkRuntimeErrorApp, mkImpossibleExpr,
39 rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID, rUNTIME_ERROR_ID,
40 nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
41 pAT_ERROR_ID, eRROR_ID, rEC_SEL_ERROR_ID,
46 #include "HsVersions.h"
56 import CoreUtils ( exprType, mkCoerce )
68 import Var ( Var, TyVar, mkCoVar, mkExportedLocalVar )
75 import BasicTypes hiding ( SuccessFlag(..) )
83 %************************************************************************
85 \subsection{Wired in Ids}
87 %************************************************************************
92 = [ -- These error-y things are wired in because we don't yet have
93 -- a way to express in an interface file that the result type variable
94 -- is 'open'; that is can be unified with an unboxed type
96 -- [The interface file format now carry such information, but there's
97 -- no way yet of expressing at the definition site for these
98 -- error-reporting functions that they have an 'open'
99 -- result type. -- sof 1/99]
101 eRROR_ID, -- This one isn't used anywhere else in the compiler
102 -- But we still need it in wiredInIds so that when GHC
103 -- compiles a program that mentions 'error' we don't
104 -- import its type from the interface file; we just get
105 -- the Id defined here. Which has an 'open-tyvar' type.
108 iRREFUT_PAT_ERROR_ID,
109 nON_EXHAUSTIVE_GUARDS_ERROR_ID,
110 nO_METHOD_BINDING_ERROR_ID,
118 -- These Ids are exported from GHC.Prim
121 = [ -- These can't be defined in Haskell, but they have
122 -- perfectly reasonable unfoldings in Core
130 %************************************************************************
132 \subsection{Data constructors}
134 %************************************************************************
136 The wrapper for a constructor is an ordinary top-level binding that evaluates
137 any strict args, unboxes any args that are going to be flattened, and calls
140 We're going to build a constructor that looks like:
142 data (Data a, C b) => T a b = T1 !a !Int b
145 \d1::Data a, d2::C b ->
146 \p q r -> case p of { p ->
148 Con T1 [a,b] [p,q,r]}}
152 * d2 is thrown away --- a context in a data decl is used to make sure
153 one *could* construct dictionaries at the site the constructor
154 is used, but the dictionary isn't actually used.
156 * We have to check that we can construct Data dictionaries for
157 the types a and Int. Once we've done that we can throw d1 away too.
159 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
160 all that matters is that the arguments are evaluated. "seq" is
161 very careful to preserve evaluation order, which we don't need
164 You might think that we could simply give constructors some strictness
165 info, like PrimOps, and let CoreToStg do the let-to-case transformation.
166 But we don't do that because in the case of primops and functions strictness
167 is a *property* not a *requirement*. In the case of constructors we need to
168 do something active to evaluate the argument.
170 Making an explicit case expression allows the simplifier to eliminate
171 it in the (common) case where the constructor arg is already evaluated.
173 Note [Wrappers for data instance tycons]
174 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
175 In the case of data instances, the wrapper also applies the coercion turning
176 the representation type into the family instance type to cast the result of
177 the wrapper. For example, consider the declarations
179 data family Map k :: * -> *
180 data instance Map (a, b) v = MapPair (Map a (Pair b v))
182 The tycon to which the datacon MapPair belongs gets a unique internal
183 name of the form :R123Map, and we call it the representation tycon.
184 In contrast, Map is the family tycon (accessible via
185 tyConFamInst_maybe). A coercion allows you to move between
186 representation and family type. It is accessible from :R123Map via
187 tyConFamilyCoercion_maybe and has kind
189 Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
191 The wrapper and worker of MapPair get the types
194 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
195 $WMapPair a b v = MapPair a b v `cast` sym (Co123Map a b v)
198 MapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
200 This coercion is conditionally applied by wrapFamInstBody.
202 It's a bit more complicated if the data instance is a GADT as well!
204 data instance T [a] where
205 T1 :: forall b. b -> T [Maybe b]
207 Co7T a :: T [a] ~ :R7T a
212 $WT1 :: forall b. b -> T [Maybe b]
213 $WT1 b v = T1 (Maybe b) b (Maybe b) v
214 `cast` sym (Co7T (Maybe b))
217 T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c
220 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
221 mkDataConIds wrap_name wkr_name data_con
222 | isNewTyCon tycon -- Newtype, only has a worker
223 = DCIds Nothing nt_work_id
225 | any isMarkedStrict all_strict_marks -- Algebraic, needs wrapper
226 || not (null eq_spec) -- NB: LoadIface.ifaceDeclSubBndrs
227 || isFamInstTyCon tycon -- depends on this test
228 = DCIds (Just alg_wrap_id) wrk_id
230 | otherwise -- Algebraic, no wrapper
231 = DCIds Nothing wrk_id
233 (univ_tvs, ex_tvs, eq_spec,
234 eq_theta, dict_theta, orig_arg_tys, res_ty) = dataConFullSig data_con
235 tycon = dataConTyCon data_con -- The representation TyCon (not family)
237 ----------- Worker (algebraic data types only) --------------
238 -- The *worker* for the data constructor is the function that
239 -- takes the representation arguments and builds the constructor.
240 wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
241 (dataConRepType data_con) wkr_info
243 wkr_arity = dataConRepArity data_con
244 wkr_info = noCafIdInfo
245 `setArityInfo` wkr_arity
246 `setAllStrictnessInfo` Just wkr_sig
247 `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated,
250 wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
251 -- Note [Data-con worker strictness]
252 -- Notice that we do *not* say the worker is strict
253 -- even if the data constructor is declared strict
254 -- e.g. data T = MkT !(Int,Int)
255 -- Why? Because the *wrapper* is strict (and its unfolding has case
256 -- expresssions that do the evals) but the *worker* itself is not.
257 -- If we pretend it is strict then when we see
258 -- case x of y -> $wMkT y
259 -- the simplifier thinks that y is "sure to be evaluated" (because
260 -- $wMkT is strict) and drops the case. No, $wMkT is not strict.
262 -- When the simplifer sees a pattern
263 -- case e of MkT x -> ...
264 -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
265 -- but that's fine... dataConRepStrictness comes from the data con
266 -- not from the worker Id.
268 cpr_info | isProductTyCon tycon &&
271 wkr_arity <= mAX_CPR_SIZE = retCPR
273 -- RetCPR is only true for products that are real data types;
274 -- that is, not unboxed tuples or [non-recursive] newtypes
276 ----------- Workers for newtypes --------------
277 nt_work_id = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
278 nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
279 `setArityInfo` 1 -- Arity 1
280 `setUnfoldingInfo` newtype_unf
281 id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
282 newtype_unf = ASSERT2( isVanillaDataCon data_con &&
283 isSingleton orig_arg_tys, ppr data_con )
284 -- Note [Newtype datacons]
285 mkCompulsoryUnfolding $
286 mkLams wrap_tvs $ Lam id_arg1 $
287 wrapNewTypeBody tycon res_ty_args (Var id_arg1)
290 ----------- Wrapper --------------
291 -- We used to include the stupid theta in the wrapper's args
292 -- but now we don't. Instead the type checker just injects these
293 -- extra constraints where necessary.
294 wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
295 res_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
296 eq_tys = mkPredTys eq_theta
297 dict_tys = mkPredTys dict_theta
298 wrap_ty = mkForAllTys wrap_tvs $ mkFunTys eq_tys $ mkFunTys dict_tys $
299 mkFunTys orig_arg_tys $ res_ty
300 -- NB: watch out here if you allow user-written equality
301 -- constraints in data constructor signatures
303 ----------- Wrappers for algebraic data types --------------
304 alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
305 alg_wrap_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
306 `setArityInfo` wrap_arity
307 -- It's important to specify the arity, so that partial
308 -- applications are treated as values
309 `setUnfoldingInfo` wrap_unf
310 `setAllStrictnessInfo` Just wrap_sig
312 all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
313 wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
314 arg_dmds = map mk_dmd all_strict_marks
315 mk_dmd str | isMarkedStrict str = evalDmd
316 | otherwise = lazyDmd
317 -- The Cpr info can be important inside INLINE rhss, where the
318 -- wrapper constructor isn't inlined.
319 -- And the argument strictness can be important too; we
320 -- may not inline a contructor when it is partially applied.
322 -- data W = C !Int !Int !Int
323 -- ...(let w = C x in ...(w p q)...)...
324 -- we want to see that w is strict in its two arguments
326 wrap_unf = mkImplicitUnfolding $ Note InlineMe $
329 mkLams dict_args $ mkLams id_args $
330 foldr mk_case con_app
331 (zip (dict_args ++ id_args) all_strict_marks)
334 con_app _ rep_ids = wrapFamInstBody tycon res_ty_args $
335 Var wrk_id `mkTyApps` res_ty_args
337 -- Equality evidence:
338 `mkTyApps` map snd eq_spec
340 `mkVarApps` reverse rep_ids
342 (dict_args,i2) = mkLocals 1 dict_tys
343 (id_args,i3) = mkLocals i2 orig_arg_tys
345 (eq_args,_) = mkCoVarLocals i3 eq_tys
347 mkCoVarLocals i [] = ([],i)
348 mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
349 y = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
353 :: (Id, StrictnessMark) -- Arg, strictness
354 -> (Int -> [Id] -> CoreExpr) -- Body
355 -> Int -- Next rep arg id
356 -> [Id] -- Rep args so far, reversed
358 mk_case (arg,strict) body i rep_args
360 NotMarkedStrict -> body i (arg:rep_args)
362 | isUnLiftedType (idType arg) -> body i (arg:rep_args)
364 Case (Var arg) arg res_ty [(DEFAULT,[], body i (arg:rep_args))]
367 -> unboxProduct i (Var arg) (idType arg) the_body
369 the_body i con_args = body i (reverse con_args ++ rep_args)
371 mAX_CPR_SIZE :: Arity
373 -- We do not treat very big tuples as CPR-ish:
374 -- a) for a start we get into trouble because there aren't
375 -- "enough" unboxed tuple types (a tiresome restriction,
377 -- b) more importantly, big unboxed tuples get returned mainly
378 -- on the stack, and are often then allocated in the heap
379 -- by the caller. So doing CPR for them may in fact make
382 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
387 Note [Newtype datacons]
388 ~~~~~~~~~~~~~~~~~~~~~~~
389 The "data constructor" for a newtype should always be vanilla. At one
390 point this wasn't true, because the newtype arising from
393 newtype T:D a = D:D (C a)
394 so the data constructor for T:C had a single argument, namely the
395 predicate (C a). But now we treat that as an ordinary argument, not
396 part of the theta-type, so all is well.
399 %************************************************************************
401 \subsection{Dictionary selectors}
403 %************************************************************************
405 Selecting a field for a dictionary. If there is just one field, then
406 there's nothing to do.
408 Dictionary selectors may get nested forall-types. Thus:
411 op :: forall b. Ord b => a -> b -> b
413 Then the top-level type for op is
415 op :: forall a. Foo a =>
419 This is unlike ordinary record selectors, which have all the for-alls
420 at the outside. When dealing with classes it's very convenient to
421 recover the original type signature from the class op selector.
424 mkDictSelId :: Bool -- True <=> don't include the unfolding
425 -- Little point on imports without -O, because the
426 -- dictionary itself won't be visible
427 -> Name -> Class -> Id
428 mkDictSelId no_unf name clas
429 = mkGlobalId (ClassOpId clas) name sel_ty info
431 sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
432 -- We can't just say (exprType rhs), because that would give a type
434 -- for a single-op class (after all, the selector is the identity)
435 -- But it's type must expose the representation of the dictionary
436 -- to get (say) C a -> (a -> a)
440 `setAllStrictnessInfo` Just strict_sig
441 `setUnfoldingInfo` (if no_unf then noUnfolding
442 else mkImplicitUnfolding rhs)
444 -- We no longer use 'must-inline' on record selectors. They'll
445 -- inline like crazy if they scrutinise a constructor
447 -- The strictness signature is of the form U(AAAVAAAA) -> T
448 -- where the V depends on which item we are selecting
449 -- It's worth giving one, so that absence info etc is generated
450 -- even if the selector isn't inlined
451 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
452 arg_dmd | isNewTyCon tycon = evalDmd
453 | otherwise = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
456 tycon = classTyCon clas
457 [data_con] = tyConDataCons tycon
458 tyvars = dataConUnivTyVars data_con
459 arg_tys = {- ASSERT( isVanillaDataCon data_con ) -} dataConRepArgTys data_con
460 eq_theta = dataConEqTheta data_con
461 the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
463 pred = mkClassPred clas (mkTyVarTys tyvars)
464 dict_id = mkTemplateLocal 1 $ mkPredTy pred
465 (eq_ids,n) = mkCoVarLocals 2 $ mkPredTys eq_theta
466 arg_ids = mkTemplateLocalsNum n arg_tys
468 mkCoVarLocals i [] = ([],i)
469 mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
470 y = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
473 rhs = mkLams tyvars (Lam dict_id rhs_body)
474 rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
475 | otherwise = Case (Var dict_id) dict_id (idType the_arg_id)
476 [(DataAlt data_con, eq_ids ++ arg_ids, Var the_arg_id)]
480 %************************************************************************
484 %************************************************************************
487 -- unbox a product type...
488 -- we will recurse into newtypes, casting along the way, and unbox at the
489 -- first product data constructor we find. e.g.
491 -- data PairInt = PairInt Int Int
492 -- newtype S = MkS PairInt
495 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
496 -- ids, we get (modulo int passing)
498 -- case (e `cast` CoT) `cast` CoS of
499 -- PairInt a b -> body [a,b]
501 -- The Ints passed around are just for creating fresh locals
502 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
503 unboxProduct i arg arg_ty body
506 result = mkUnpackCase the_id arg con_args boxing_con rhs
507 (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
508 ([the_id], i') = mkLocals i [arg_ty]
509 (con_args, i'') = mkLocals i' tys
510 rhs = body i'' con_args
512 mkUnpackCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
513 -- (mkUnpackCase x e args Con body)
515 -- case (e `cast` ...) of bndr { Con args -> body }
517 -- the type of the bndr passed in is irrelevent
518 mkUnpackCase bndr arg unpk_args boxing_con body
519 = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
521 (cast_arg, bndr_ty) = go (idType bndr) arg
523 | (tycon, tycon_args, _, _) <- splitProductType "mkUnpackCase" ty
524 , isNewTyCon tycon && not (isRecursiveTyCon tycon)
525 = go (newTyConInstRhs tycon tycon_args)
526 (unwrapNewTypeBody tycon tycon_args arg)
527 | otherwise = (arg, ty)
530 reboxProduct :: [Unique] -- uniques to create new local binders
531 -> Type -- type of product to box
532 -> ([Unique], -- remaining uniques
533 CoreExpr, -- boxed product
534 [Id]) -- Ids being boxed into product
537 (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
539 us' = dropList con_arg_tys us
541 arg_ids = zipWith (mkSysLocal (fsLit "rb")) us con_arg_tys
543 bind_rhs = mkProductBox arg_ids ty
546 (us', bind_rhs, arg_ids)
548 mkProductBox :: [Id] -> Type -> CoreExpr
549 mkProductBox arg_ids ty
552 (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
555 | isNewTyCon tycon && not (isRecursiveTyCon tycon)
556 = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
557 | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
559 wrap expr = wrapNewTypeBody tycon tycon_args expr
562 -- (mkReboxingAlt us con xs rhs) basically constructs the case
563 -- alternative (con, xs, rhs)
564 -- but it does the reboxing necessary to construct the *source*
565 -- arguments, xs, from the representation arguments ys.
567 -- data T = MkT !(Int,Int) Bool
569 -- mkReboxingAlt MkT [x,b] r
570 -- = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
572 -- mkDataAlt should really be in DataCon, but it can't because
573 -- it manipulates CoreSyn.
576 :: [Unique] -- Uniques for the new Ids
578 -> [Var] -- Source-level args, including existential dicts
582 mkReboxingAlt us con args rhs
583 | not (any isMarkedUnboxed stricts)
584 = (DataAlt con, args, rhs)
588 (binds, args') = go args stricts us
590 (DataAlt con, args', mkLets binds rhs)
593 stricts = dataConExStricts con ++ dataConStrictMarks con
595 go [] _stricts _us = ([], [])
597 -- Type variable case
598 go (arg:args) stricts us
600 = let (binds, args') = go args stricts us
601 in (binds, arg:args')
603 -- Term variable case
604 go (arg:args) (str:stricts) us
605 | isMarkedUnboxed str
607 let (binds, unpacked_args') = go args stricts us'
608 (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
610 (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
612 = let (binds, args') = go args stricts us
613 in (binds, arg:args')
614 go (_ : _) [] _ = panic "mkReboxingAlt"
618 %************************************************************************
620 Wrapping and unwrapping newtypes and type families
622 %************************************************************************
625 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
626 -- The wrapper for the data constructor for a newtype looks like this:
627 -- newtype T a = MkT (a,Int)
628 -- MkT :: forall a. (a,Int) -> T a
629 -- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
630 -- where CoT is the coercion TyCon assoicated with the newtype
632 -- The call (wrapNewTypeBody T [a] e) returns the
633 -- body of the wrapper, namely
634 -- e `cast` (CoT [a])
636 -- If a coercion constructor is provided in the newtype, then we use
637 -- it, otherwise the wrap/unwrap are both no-ops
639 -- If the we are dealing with a newtype *instance*, we have a second coercion
640 -- identifying the family instance with the constructor of the newtype
641 -- instance. This coercion is applied in any case (ie, composed with the
642 -- coercion constructor of the newtype or applied by itself).
644 wrapNewTypeBody tycon args result_expr
645 = wrapFamInstBody tycon args inner
648 | Just co_con <- newTyConCo_maybe tycon
649 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
653 -- When unwrapping, we do *not* apply any family coercion, because this will
654 -- be done via a CoPat by the type checker. We have to do it this way as
655 -- computing the right type arguments for the coercion requires more than just
656 -- a spliting operation (cf, TcPat.tcConPat).
658 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
659 unwrapNewTypeBody tycon args result_expr
660 | Just co_con <- newTyConCo_maybe tycon
661 = mkCoerce (mkTyConApp co_con args) result_expr
665 -- If the type constructor is a representation type of a data instance, wrap
666 -- the expression into a cast adjusting the expression type, which is an
667 -- instance of the representation type, to the corresponding instance of the
668 -- family instance type.
669 -- See Note [Wrappers for data instance tycons]
670 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
671 wrapFamInstBody tycon args body
672 | Just co_con <- tyConFamilyCoercion_maybe tycon
673 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) body
677 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
678 unwrapFamInstScrut tycon args scrut
679 | Just co_con <- tyConFamilyCoercion_maybe tycon
680 = mkCoerce (mkTyConApp co_con args) scrut
686 %************************************************************************
688 \subsection{Primitive operations}
690 %************************************************************************
693 mkPrimOpId :: PrimOp -> Id
697 (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
698 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
699 name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
700 (mkPrimOpIdUnique (primOpTag prim_op))
702 id = mkGlobalId (PrimOpId prim_op) name ty info
705 `setSpecInfo` mkSpecInfo (primOpRules prim_op name)
707 `setAllStrictnessInfo` Just strict_sig
709 -- For each ccall we manufacture a separate CCallOpId, giving it
710 -- a fresh unique, a type that is correct for this particular ccall,
711 -- and a CCall structure that gives the correct details about calling
714 -- The *name* of this Id is a local name whose OccName gives the full
715 -- details of the ccall, type and all. This means that the interface
716 -- file reader can reconstruct a suitable Id
718 mkFCallId :: Unique -> ForeignCall -> Type -> Id
719 mkFCallId uniq fcall ty
720 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
721 -- A CCallOpId should have no free type variables;
722 -- when doing substitutions won't substitute over it
723 mkGlobalId (FCallId fcall) name ty info
725 occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
726 -- The "occurrence name" of a ccall is the full info about the
727 -- ccall; it is encoded, but may have embedded spaces etc!
729 name = mkFCallName uniq occ_str
733 `setAllStrictnessInfo` Just strict_sig
735 (_, tau) = tcSplitForAllTys ty
736 (arg_tys, _) = tcSplitFunTys tau
737 arity = length arg_tys
738 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
740 -- Tick boxes and breakpoints are both represented as TickBoxOpIds,
741 -- except for the type:
743 -- a plain HPC tick box has type (State# RealWorld)
744 -- a breakpoint Id has type forall a.a
746 -- The breakpoint Id will be applied to a list of arbitrary free variables,
747 -- which is why it needs a polymorphic type.
749 mkTickBoxOpId :: Unique -> Module -> TickBoxId -> Id
750 mkTickBoxOpId uniq mod ix = mkTickBox' uniq mod ix realWorldStatePrimTy
752 mkBreakPointOpId :: Unique -> Module -> TickBoxId -> Id
753 mkBreakPointOpId uniq mod ix = mkTickBox' uniq mod ix ty
754 where ty = mkSigmaTy [openAlphaTyVar] [] openAlphaTy
756 mkTickBox' uniq mod ix ty = mkGlobalId (TickBoxOpId tickbox) name ty info
758 tickbox = TickBox mod ix
759 occ_str = showSDoc (braces (ppr tickbox))
760 name = mkTickBoxOpName uniq occ_str
765 %************************************************************************
767 \subsection{DictFuns and default methods}
769 %************************************************************************
771 Important notes about dict funs and default methods
772 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
773 Dict funs and default methods are *not* ImplicitIds. Their definition
774 involves user-written code, so we can't figure out their strictness etc
775 based on fixed info, as we can for constructors and record selectors (say).
777 We build them as LocalIds, but with External Names. This ensures that
778 they are taken to account by free-variable finding and dependency
779 analysis (e.g. CoreFVs.exprFreeVars).
781 Why shouldn't they be bound as GlobalIds? Because, in particular, if
782 they are globals, the specialiser floats dict uses above their defns,
783 which prevents good simplifications happening. Also the strictness
784 analyser treats a occurrence of a GlobalId as imported and assumes it
785 contains strictness in its IdInfo, which isn't true if the thing is
786 bound in the same module as the occurrence.
788 It's OK for dfuns to be LocalIds, because we form the instance-env to
789 pass on to the next module (md_insts) in CoreTidy, afer tidying
790 and globalising the top-level Ids.
792 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so
793 that they aren't discarded by the occurrence analyser.
796 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
798 mkDictFunId :: Name -- Name to use for the dict fun;
805 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
806 = mkExportedLocalVar DFunId dfun_name dfun_ty vanillaIdInfo
808 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
812 %************************************************************************
814 \subsection{Un-definable}
816 %************************************************************************
818 These Ids can't be defined in Haskell. They could be defined in
819 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
820 ensure that they were definitely, definitely inlined, because there is
821 no curried identifier for them. That's what mkCompulsoryUnfolding
822 does. If we had a way to get a compulsory unfolding from an interface
823 file, we could do that, but we don't right now.
825 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
826 just gets expanded into a type coercion wherever it occurs. Hence we
827 add it as a built-in Id with an unfolding here.
829 The type variables we use here are "open" type variables: this means
830 they can unify with both unlifted and lifted types. Hence we provide
831 another gun with which to shoot yourself in the foot.
834 mkWiredInIdName mod fs uniq id
835 = mkWiredInName mod (mkOccNameFS varName fs) uniq (AnId id) UserSyntax
837 unsafeCoerceName = mkWiredInIdName gHC_PRIM (fsLit "unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
838 nullAddrName = mkWiredInIdName gHC_PRIM (fsLit "nullAddr#") nullAddrIdKey nullAddrId
839 seqName = mkWiredInIdName gHC_PRIM (fsLit "seq") seqIdKey seqId
840 realWorldName = mkWiredInIdName gHC_PRIM (fsLit "realWorld#") realWorldPrimIdKey realWorldPrimId
841 lazyIdName = mkWiredInIdName gHC_BASE (fsLit "lazy") lazyIdKey lazyId
843 errorName = mkWiredInIdName gHC_ERR (fsLit "error") errorIdKey eRROR_ID
844 recSelErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recSelError") recSelErrorIdKey rEC_SEL_ERROR_ID
845 runtimeErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "runtimeError") runtimeErrorIdKey rUNTIME_ERROR_ID
846 irrefutPatErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
847 recConErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recConError") recConErrorIdKey rEC_CON_ERROR_ID
848 patErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "patError") patErrorIdKey pAT_ERROR_ID
849 noMethodBindingErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "noMethodBindingError")
850 noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
851 nonExhaustiveGuardsErrorName
852 = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "nonExhaustiveGuardsError")
853 nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
857 ------------------------------------------------
858 -- unsafeCoerce# :: forall a b. a -> b
860 = pcMiscPrelId unsafeCoerceName ty info
862 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
865 ty = mkForAllTys [openAlphaTyVar,openBetaTyVar]
866 (mkFunTy openAlphaTy openBetaTy)
867 [x] = mkTemplateLocals [openAlphaTy]
868 rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
869 Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
871 ------------------------------------------------
873 -- nullAddr# :: Addr#
874 -- The reason is is here is because we don't provide
875 -- a way to write this literal in Haskell.
876 nullAddrId = pcMiscPrelId nullAddrName addrPrimTy info
878 info = noCafIdInfo `setUnfoldingInfo`
879 mkCompulsoryUnfolding (Lit nullAddrLit)
881 ------------------------------------------------
883 -- 'seq' is very special. See notes with
884 -- See DsUtils.lhs Note [Desugaring seq (1)] and
885 -- Note [Desugaring seq (2)] and
886 -- Fixity is set in LoadIface.ghcPrimIface
887 seqId = pcMiscPrelId seqName ty info
889 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
892 ty = mkForAllTys [alphaTyVar,openBetaTyVar]
893 (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
894 [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
895 rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
897 ------------------------------------------------
899 -- lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
900 -- Used to lazify pseq: pseq a b = a `seq` lazy b
902 -- Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
903 -- not from GHC.Base.hi. This is important, because the strictness
904 -- analyser will spot it as strict!
906 -- Also no unfolding in lazyId: it gets "inlined" by a HACK in the worker/wrapperpass
907 -- (see WorkWrap.wwExpr)
908 -- We could use inline phases to do this, but that would be vulnerable to changes in
909 -- phase numbering....we must inline precisely after strictness analysis.
910 lazyId = pcMiscPrelId lazyIdName ty info
913 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
915 lazyIdUnfolding :: CoreExpr -- Used to expand 'lazyId' after strictness anal
916 lazyIdUnfolding = mkLams [openAlphaTyVar,x] (Var x)
918 [x] = mkTemplateLocals [openAlphaTy]
921 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
922 nasty as-is, change it back to a literal (@Literal@).
924 voidArgId is a Local Id used simply as an argument in functions
925 where we just want an arg to avoid having a thunk of unlifted type.
927 x = \ void :: State# RealWorld -> (# p, q #)
929 This comes up in strictness analysis
932 realWorldPrimId -- :: State# RealWorld
933 = pcMiscPrelId realWorldName realWorldStatePrimTy
934 (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
935 -- The evaldUnfolding makes it look that realWorld# is evaluated
936 -- which in turn makes Simplify.interestingArg return True,
937 -- which in turn makes INLINE things applied to realWorld# likely
941 voidArgId -- :: State# RealWorld
942 = mkSysLocal (fsLit "void") voidArgIdKey realWorldStatePrimTy
946 %************************************************************************
948 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
950 %************************************************************************
952 GHC randomly injects these into the code.
954 @patError@ is just a version of @error@ for pattern-matching
955 failures. It knows various ``codes'' which expand to longer
956 strings---this saves space!
958 @absentErr@ is a thing we put in for ``absent'' arguments. They jolly
959 well shouldn't be yanked on, but if one is, then you will get a
960 friendly message from @absentErr@ (rather than a totally random
963 @parError@ is a special version of @error@ which the compiler does
964 not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
965 templates, but we don't ever expect to generate code for it.
969 :: Id -- Should be of type (forall a. Addr# -> a)
970 -- where Addr# points to a UTF8 encoded string
971 -> Type -- The type to instantiate 'a'
972 -> String -- The string to print
975 mkRuntimeErrorApp err_id res_ty err_msg
976 = mkApps (Var err_id) [Type res_ty, err_string]
978 err_string = Lit (mkMachString err_msg)
980 mkImpossibleExpr :: Type -> CoreExpr
981 mkImpossibleExpr res_ty
982 = mkRuntimeErrorApp rUNTIME_ERROR_ID res_ty "Impossible case alternative"
984 rEC_SEL_ERROR_ID = mkRuntimeErrorId recSelErrorName
985 rUNTIME_ERROR_ID = mkRuntimeErrorId runtimeErrorName
986 iRREFUT_PAT_ERROR_ID = mkRuntimeErrorId irrefutPatErrorName
987 rEC_CON_ERROR_ID = mkRuntimeErrorId recConErrorName
988 pAT_ERROR_ID = mkRuntimeErrorId patErrorName
989 nO_METHOD_BINDING_ERROR_ID = mkRuntimeErrorId noMethodBindingErrorName
990 nON_EXHAUSTIVE_GUARDS_ERROR_ID = mkRuntimeErrorId nonExhaustiveGuardsErrorName
992 -- The runtime error Ids take a UTF8-encoded string as argument
994 mkRuntimeErrorId :: Name -> Id
995 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
997 runtimeErrorTy :: Type
998 runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1002 eRROR_ID = pc_bottoming_Id errorName errorTy
1005 errorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1006 -- Notice the openAlphaTyVar. It says that "error" can be applied
1007 -- to unboxed as well as boxed types. This is OK because it never
1008 -- returns, so the return type is irrelevant.
1012 %************************************************************************
1014 \subsection{Utilities}
1016 %************************************************************************
1019 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1020 pcMiscPrelId name ty info
1021 = mkVanillaGlobalWithInfo name ty info
1022 -- We lie and say the thing is imported; otherwise, we get into
1023 -- a mess with dependency analysis; e.g., core2stg may heave in
1024 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
1025 -- being compiled, then it's just a matter of luck if the definition
1026 -- will be in "the right place" to be in scope.
1028 pc_bottoming_Id :: Name -> Type -> Id
1029 -- Function of arity 1, which diverges after being given one argument
1030 pc_bottoming_Id name ty
1031 = pcMiscPrelId name ty bottoming_info
1033 bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1035 -- Make arity and strictness agree
1037 -- Do *not* mark them as NoCafRefs, because they can indeed have
1038 -- CAF refs. For example, pAT_ERROR_ID calls GHC.Err.untangle,
1039 -- which has some CAFs
1040 -- In due course we may arrange that these error-y things are
1041 -- regarded by the GC as permanently live, in which case we
1042 -- can give them NoCaf info. As it is, any function that calls
1043 -- any pc_bottoming_Id will itself have CafRefs, which bloats
1046 strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1047 -- These "bottom" out, no matter what their arguments