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 mkSpecPragmaId, mkWorkerId,
18 mkDictFunId, mkDefaultMethodId,
26 -- And some particular Ids; see below for why they are wired in
28 unsafeCoerceId, realWorldPrimId,
29 eRROR_ID, rEC_SEL_ERROR_ID, pAT_ERROR_ID, rEC_CON_ERROR_ID,
30 rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID, nON_EXHAUSTIVE_GUARDS_ERROR_ID,
31 nO_METHOD_BINDING_ERROR_ID, aBSENT_ERROR_ID, pAR_ERROR_ID
34 #include "HsVersions.h"
37 import TysPrim ( openAlphaTyVars, alphaTyVar, alphaTy,
38 intPrimTy, realWorldStatePrimTy
40 import TysWiredIn ( boolTy, charTy, mkListTy )
41 import PrelMods ( pREL_ERR, pREL_GHC )
42 import Type ( Type, ThetaType,
43 mkDictTy, mkTyConApp, mkTyVarTys, mkFunTys, mkFunTy, mkSigmaTy,
44 isUnLiftedType, mkForAllTys, mkTyVarTy, tyVarsOfTypes,
45 splitSigmaTy, splitFunTy_maybe, splitAlgTyConApp,
46 splitFunTys, splitForAllTys, unUsgTy,
49 import Module ( Module )
50 import CoreUnfold ( mkTopUnfolding, mkCompulsoryUnfolding )
51 import Subst ( mkTopTyVarSubst, substTheta )
52 import TyCon ( TyCon, isNewTyCon, tyConDataCons, isDataTyCon )
53 import Class ( Class, classBigSig, classTyCon, classTyVars, classSelIds )
54 import Var ( Id, TyVar )
55 import VarSet ( isEmptyVarSet )
56 import Const ( Con(..) )
57 import Name ( mkDerivedName, mkWiredInIdName, mkLocalName,
58 mkWorkerOcc, mkSuperDictSelOcc,
61 import OccName ( mkSrcVarOcc )
62 import PrimOp ( PrimOp(DataToTagOp), primOpSig, mkPrimOpIdName )
63 import Demand ( wwStrict )
64 import DataCon ( DataCon, StrictnessMark(..), dataConStrictMarks, dataConFieldLabels,
65 dataConArgTys, dataConSig, dataConRawArgTys
67 import Id ( idType, mkId,
68 mkVanillaId, mkTemplateLocals,
69 mkTemplateLocal, setInlinePragma
71 import IdInfo ( vanillaIdInfo, mkIdInfo,
72 exactArity, setUnfoldingInfo, setCafInfo,
73 setArityInfo, setInlinePragInfo,
74 mkStrictnessInfo, setStrictnessInfo,
75 IdFlavour(..), InlinePragInfo(..), CafInfo(..), IdInfo
77 import FieldLabel ( FieldLabel, FieldLabelTag, mkFieldLabel, fieldLabelName,
78 firstFieldLabelTag, allFieldLabelTags
82 import BasicTypes ( Arity )
84 import Maybe ( isJust )
91 %************************************************************************
93 \subsection{Wired in Ids}
95 %************************************************************************
99 = [ -- These error-y things are wired in because we don't yet have
100 -- a way to express in an interface file that the result type variable
101 -- is 'open'; that is can be unified with an unboxed type
103 -- [The interface file format now carry such information, but there's
104 -- no way yet of expressing at the definition site for these error-reporting
105 -- functions that they have an 'open' result type. -- sof 1/99]
109 , iRREFUT_PAT_ERROR_ID
110 , nON_EXHAUSTIVE_GUARDS_ERROR_ID
111 , nO_METHOD_BINDING_ERROR_ID
117 -- These two can't be defined in Haskell
124 %************************************************************************
126 \subsection{Easy ones}
128 %************************************************************************
131 mkSpecPragmaId occ uniq ty loc
132 = mkId (mkLocalName uniq occ loc) ty (mkIdInfo SpecPragmaId)
133 -- Maybe a SysLocal? But then we'd lose the location
135 mkDefaultMethodId dm_name rec_c ty
136 = mkVanillaId dm_name ty
138 mkWorkerId uniq unwrkr ty
139 = mkVanillaId (mkDerivedName mkWorkerOcc (getName unwrkr) uniq) ty
142 %************************************************************************
144 \subsection{Data constructors}
146 %************************************************************************
149 mkDataConId :: DataCon -> Id
151 = mkId (getName data_con)
153 (dataConInfo data_con)
155 (tyvars, theta, ex_tyvars, ex_theta, arg_tys, tycon) = dataConSig data_con
156 id_ty = mkSigmaTy (tyvars ++ ex_tyvars)
158 (mkFunTys arg_tys (mkTyConApp tycon (mkTyVarTys tyvars)))
161 We're going to build a constructor that looks like:
163 data (Data a, C b) => T a b = T1 !a !Int b
166 \d1::Data a, d2::C b ->
167 \p q r -> case p of { p ->
169 Con T1 [a,b] [p,q,r]}}
173 * d2 is thrown away --- a context in a data decl is used to make sure
174 one *could* construct dictionaries at the site the constructor
175 is used, but the dictionary isn't actually used.
177 * We have to check that we can construct Data dictionaries for
178 the types a and Int. Once we've done that we can throw d1 away too.
180 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
181 all that matters is that the arguments are evaluated. "seq" is
182 very careful to preserve evaluation order, which we don't need
185 You might think that we could simply give constructors some strictness
186 info, like PrimOps, and let CoreToStg do the let-to-case transformation.
187 But we don't do that because in the case of primops and functions strictness
188 is a *property* not a *requirement*. In the case of constructors we need to
189 do something active to evaluate the argument.
191 Making an explicit case expression allows the simplifier to eliminate
192 it in the (common) case where the constructor arg is already evaluated.
195 dataConInfo :: DataCon -> IdInfo
198 = mkIdInfo (ConstantId (DataCon data_con))
199 `setArityInfo` exactArity (n_dicts + n_ex_dicts + n_id_args)
200 `setUnfoldingInfo` unfolding
202 unfolding = mkTopUnfolding (Note InlineMe con_rhs)
203 -- The dictionary constructors of a class don't get a binding,
204 -- but they are always saturated, so they should always be inlined.
206 (tyvars, theta, ex_tyvars, ex_theta, orig_arg_tys, tycon)
207 = dataConSig data_con
208 rep_arg_tys = dataConRawArgTys data_con
209 all_tyvars = tyvars ++ ex_tyvars
211 dict_tys = [mkDictTy clas tys | (clas,tys) <- theta]
212 ex_dict_tys = [mkDictTy clas tys | (clas,tys) <- ex_theta]
214 n_dicts = length dict_tys
215 n_ex_dicts = length ex_dict_tys
216 n_id_args = length orig_arg_tys
217 n_rep_args = length rep_arg_tys
219 result_ty = mkTyConApp tycon (mkTyVarTys tyvars)
221 mkLocals i n tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
222 (dict_args, i1) = mkLocals 1 n_dicts dict_tys
223 (ex_dict_args,i2) = mkLocals i1 n_ex_dicts ex_dict_tys
224 (id_args,i3) = mkLocals i2 n_id_args orig_arg_tys
226 (id_arg1:_) = id_args -- Used for newtype only
227 strict_marks = dataConStrictMarks data_con
231 = ASSERT( length orig_arg_tys == 1 )
232 Note (Coerce result_ty (head orig_arg_tys)) (Var id_arg1)
235 (map Type (mkTyVarTys all_tyvars) ++
236 map Var (reverse rep_ids))
238 con_rhs = mkLams all_tyvars $ mkLams dict_args $
239 mkLams ex_dict_args $ mkLams id_args $
240 foldr mk_case con_app
241 (zip (ex_dict_args++id_args) strict_marks) i3 []
244 :: (Id, StrictnessMark) -- arg, strictness
245 -> (Int -> [Id] -> CoreExpr) -- body
246 -> Int -- next rep arg id
247 -> [Id] -- rep args so far
249 mk_case (arg,strict) body i rep_args
251 NotMarkedStrict -> body i (arg:rep_args)
253 | isUnLiftedType (idType arg) -> body i (arg:rep_args)
255 Case (Var arg) arg [(DEFAULT,[], body i (arg:rep_args))]
257 MarkedUnboxed con tys ->
258 Case (Var arg) arg [(DataCon con, con_args,
259 body i' (reverse con_args++rep_args))]
260 where n_tys = length tys
261 (con_args,i') = mkLocals i (length tys) tys
265 %************************************************************************
267 \subsection{Record selectors}
269 %************************************************************************
271 We're going to build a record selector unfolding that looks like this:
273 data T a b c = T1 { ..., op :: a, ...}
274 | T2 { ..., op :: a, ...}
277 sel = /\ a b c -> \ d -> case d of
283 mkRecordSelId field_label selector_ty
284 = ASSERT( null theta && isDataTyCon tycon )
287 sel_id = mkId (fieldLabelName field_label) selector_ty info
289 info = mkIdInfo (RecordSelId field_label)
290 `setArityInfo` exactArity 1
291 `setUnfoldingInfo` unfolding
293 -- ToDo: consider adding further IdInfo
295 unfolding = mkTopUnfolding sel_rhs
297 (tyvars, theta, tau) = splitSigmaTy selector_ty
298 (data_ty,rhs_ty) = expectJust "StdIdInfoRec" (splitFunTy_maybe tau)
299 -- tau is of form (T a b c -> field-type)
300 (tycon, _, data_cons) = splitAlgTyConApp data_ty
301 tyvar_tys = mkTyVarTys tyvars
303 [data_id] = mkTemplateLocals [data_ty]
304 alts = map mk_maybe_alt data_cons
305 the_alts = catMaybes alts
306 default_alt | all isJust alts = [] -- No default needed
307 | otherwise = [(DEFAULT, [], error_expr)]
309 sel_rhs = mkLams tyvars $ Lam data_id $
310 Case (Var data_id) data_id (the_alts ++ default_alt)
312 mk_maybe_alt data_con
313 = case maybe_the_arg_id of
315 Just the_arg_id -> Just (DataCon data_con, arg_ids, Var the_arg_id)
317 arg_ids = mkTemplateLocals (dataConArgTys data_con tyvar_tys)
318 -- The first one will shadow data_id, but who cares
319 field_lbls = dataConFieldLabels data_con
320 maybe_the_arg_id = assocMaybe (field_lbls `zip` arg_ids) field_label
322 error_expr = mkApps (Var rEC_SEL_ERROR_ID) [Type (unUsgTy rhs_ty), mkStringLit full_msg]
323 -- preserves invariant that type args are *not* usage-annotated on top. KSW 1999-04.
324 full_msg = showSDoc (sep [text "No match in record selector", ppr sel_id])
328 %************************************************************************
330 \subsection{Newtype field selectors}
332 %************************************************************************
334 Possibly overkill to do it this way:
337 mkNewTySelId field_label selector_ty = sel_id
339 sel_id = mkId (fieldLabelName field_label) selector_ty info
342 info = mkIdInfo (RecordSelId field_label)
343 `setArityInfo` exactArity 1
344 `setUnfoldingInfo` unfolding
346 -- ToDo: consider adding further IdInfo
348 unfolding = mkTopUnfolding sel_rhs
350 (tyvars, theta, tau) = splitSigmaTy selector_ty
351 (data_ty,rhs_ty) = expectJust "StdIdInfoRec" (splitFunTy_maybe tau)
352 -- tau is of form (T a b c -> field-type)
353 (tycon, _, data_cons) = splitAlgTyConApp data_ty
354 tyvar_tys = mkTyVarTys tyvars
356 [data_id] = mkTemplateLocals [data_ty]
357 sel_rhs = mkLams tyvars $ Lam data_id $
358 Note (Coerce (unUsgTy rhs_ty) (unUsgTy data_ty)) (Var data_id)
362 %************************************************************************
364 \subsection{Dictionary selectors}
366 %************************************************************************
368 Selecting a field for a dictionary. If there is just one field, then
369 there's nothing to do.
372 mkDictSelId name clas ty
375 sel_id = mkId name ty info
376 field_lbl = mkFieldLabel name ty tag
377 tag = assoc "MkId.mkDictSelId" (classSelIds clas `zip` allFieldLabelTags) sel_id
379 info = mkIdInfo (RecordSelId field_lbl)
380 `setUnfoldingInfo` unfolding
382 -- We no longer use 'must-inline' on record selectors. They'll
383 -- inline like crazy if they scrutinise a constructor
385 unfolding = mkTopUnfolding rhs
387 tyvars = classTyVars clas
389 tycon = classTyCon clas
390 [data_con] = tyConDataCons tycon
391 tyvar_tys = mkTyVarTys tyvars
392 arg_tys = dataConArgTys data_con tyvar_tys
393 the_arg_id = arg_ids !! (tag - firstFieldLabelTag)
395 dict_ty = mkDictTy clas tyvar_tys
396 (dict_id:arg_ids) = mkTemplateLocals (dict_ty : arg_tys)
398 rhs | isNewTyCon tycon = mkLams tyvars $ Lam dict_id $
399 Note (Coerce (head arg_tys) dict_ty) (Var dict_id)
400 | otherwise = mkLams tyvars $ Lam dict_id $
401 Case (Var dict_id) dict_id
402 [(DataCon data_con, arg_ids, Var the_arg_id)]
406 %************************************************************************
408 \subsection{Primitive operations
410 %************************************************************************
413 mkPrimitiveId :: PrimOp -> Id
414 mkPrimitiveId prim_op
417 (tyvars,arg_tys,res_ty) = primOpSig prim_op
418 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
419 name = mkPrimOpIdName prim_op id
420 id = mkId name ty info
422 info = mkIdInfo (ConstantId (PrimOp prim_op))
423 `setUnfoldingInfo` unfolding
425 unfolding = mkCompulsoryUnfolding rhs
426 -- The mkCompulsoryUnfolding says that this Id absolutely
427 -- must be inlined. It's only used for primitives,
428 -- because we don't want to make a closure for each of them.
430 args = mkTemplateLocals arg_tys
431 rhs = mkLams tyvars $ mkLams args $
432 mkPrimApp prim_op (map Type (mkTyVarTys tyvars) ++ map Var args)
436 %************************************************************************
438 \subsection{DictFuns}
440 %************************************************************************
443 mkDictFunId :: Name -- Name to use for the dict fun;
450 mkDictFunId dfun_name clas inst_tyvars inst_tys inst_decl_theta
451 = mkVanillaId dfun_name dfun_ty
453 (class_tyvars, sc_theta, _, _) = classBigSig clas
454 sc_theta' = substTheta (mkTopTyVarSubst class_tyvars inst_tys) sc_theta
456 dfun_theta = inst_decl_theta
458 {- 1 dec 99: disable the Mark Jones optimisation for the sake
459 of compatibility with Hugs.
461 dfun_theta = case inst_decl_theta of
462 [] -> [] -- If inst_decl_theta is empty, then we don't
463 -- want to have any dict arguments, so that we can
464 -- expose the constant methods.
466 other -> nub (inst_decl_theta ++ filter not_const sc_theta')
467 -- Otherwise we pass the superclass dictionaries to
468 -- the dictionary function; the Mark Jones optimisation.
470 -- NOTE the "nub". I got caught by this one:
471 -- class Monad m => MonadT t m where ...
472 -- instance Monad m => MonadT (EnvT env) m where ...
473 -- Here, the inst_decl_theta has (Monad m); but so
474 -- does the sc_theta'!
476 -- NOTE the "not_const". I got caught by this one too:
477 -- class Foo a => Baz a b where ...
478 -- instance Wob b => Baz T b where..
479 -- Now sc_theta' has Foo T
481 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
483 not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
487 %************************************************************************
489 \subsection{Un-definable}
491 %************************************************************************
493 These two can't be defined in Haskell.
495 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
496 just gets expanded into a type coercion wherever it occurs. Hence we
497 add it as a built-in Id with an unfolding here.
499 The type variables we use here are "open" type variables: this means
500 they can unify with both unlifted and lifted types. Hence we provide
501 another gun with which to shoot yourself in the foot.
505 = pcMiscPrelId unsafeCoerceIdKey pREL_GHC SLIT("unsafeCoerce#") ty info
508 `setUnfoldingInfo` mkCompulsoryUnfolding rhs
511 ty = mkForAllTys [openAlphaTyVar,openBetaTyVar]
512 (mkFunTy openAlphaTy openBetaTy)
513 [x] = mkTemplateLocals [openAlphaTy]
514 rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
515 Note (Coerce openBetaTy openAlphaTy) (Var x)
519 @getTag#@ is another function which can't be defined in Haskell. It needs to
520 evaluate its argument and call the dataToTag# primitive.
524 = pcMiscPrelId getTagIdKey pREL_GHC SLIT("getTag#") ty info
527 `setUnfoldingInfo` mkCompulsoryUnfolding rhs
528 -- We don't provide a defn for this; you must inline it
530 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy intPrimTy)
531 [x,y] = mkTemplateLocals [alphaTy,alphaTy]
532 rhs = mkLams [alphaTyVar,x] $
533 Case (Var x) y [ (DEFAULT, [],
534 Con (PrimOp DataToTagOp) [Type alphaTy, Var y]) ]
537 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
538 nasty as-is, change it back to a literal (@Literal@).
541 realWorldPrimId -- :: State# RealWorld
542 = pcMiscPrelId realWorldPrimIdKey pREL_GHC SLIT("realWorld#")
548 %************************************************************************
550 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
552 %************************************************************************
554 GHC randomly injects these into the code.
556 @patError@ is just a version of @error@ for pattern-matching
557 failures. It knows various ``codes'' which expand to longer
558 strings---this saves space!
560 @absentErr@ is a thing we put in for ``absent'' arguments. They jolly
561 well shouldn't be yanked on, but if one is, then you will get a
562 friendly message from @absentErr@ (rather than a totally random
565 @parError@ is a special version of @error@ which the compiler does
566 not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
567 templates, but we don't ever expect to generate code for it.
571 = pc_bottoming_Id errorIdKey pREL_ERR SLIT("error") errorTy
573 = generic_ERROR_ID recSelErrIdKey SLIT("patError")
575 = generic_ERROR_ID patErrorIdKey SLIT("patError")
577 = generic_ERROR_ID recConErrorIdKey SLIT("recConError")
579 = generic_ERROR_ID recUpdErrorIdKey SLIT("recUpdError")
581 = generic_ERROR_ID irrefutPatErrorIdKey SLIT("irrefutPatError")
582 nON_EXHAUSTIVE_GUARDS_ERROR_ID
583 = generic_ERROR_ID nonExhaustiveGuardsErrorIdKey SLIT("nonExhaustiveGuardsError")
584 nO_METHOD_BINDING_ERROR_ID
585 = generic_ERROR_ID noMethodBindingErrorIdKey SLIT("noMethodBindingError")
588 = pc_bottoming_Id absentErrorIdKey pREL_ERR SLIT("absentErr")
589 (mkSigmaTy [openAlphaTyVar] [] openAlphaTy)
592 = pcMiscPrelId parErrorIdKey pREL_ERR SLIT("parError")
593 (mkSigmaTy [openAlphaTyVar] [] openAlphaTy) noCafIdInfo
598 %************************************************************************
600 \subsection{Utilities}
602 %************************************************************************
605 pcMiscPrelId :: Unique{-IdKey-} -> Module -> FAST_STRING -> Type -> IdInfo -> Id
606 pcMiscPrelId key mod str ty info
608 name = mkWiredInIdName key mod (mkSrcVarOcc str) imp
609 imp = mkId name ty info -- the usual case...
612 -- We lie and say the thing is imported; otherwise, we get into
613 -- a mess with dependency analysis; e.g., core2stg may heave in
614 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
615 -- being compiled, then it's just a matter of luck if the definition
616 -- will be in "the right place" to be in scope.
618 pc_bottoming_Id key mod name ty
619 = pcMiscPrelId key mod name ty bottoming_info
621 bottoming_info = noCafIdInfo
622 `setStrictnessInfo` mkStrictnessInfo ([wwStrict], True)
624 -- these "bottom" out, no matter what their arguments
626 generic_ERROR_ID u n = pc_bottoming_Id u pREL_ERR n errorTy
629 noCafIdInfo = vanillaIdInfo `setCafInfo` NoCafRefs
631 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
632 openAlphaTy = mkTyVarTy openAlphaTyVar
633 openBetaTy = mkTyVarTy openBetaTyVar
636 errorTy = mkUsgTy UsMany $
637 mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkUsgTy UsOnce (mkListTy charTy)]
638 (mkUsgTy UsMany openAlphaTy))
639 -- Notice the openAlphaTyVar. It says that "error" can be applied
640 -- to unboxed as well as boxed types. This is OK because it never
641 -- returns, so the return type is irrelevant.