Commit 98688c6e authored by simonpj's avatar simonpj

[project @ 2003-10-09 11:58:39 by simonpj]

-------------------------
		GHC heart/lung transplant
		-------------------------

This major commit changes the way that GHC deals with importing
types and functions defined in other modules, during renaming and
typechecking.  On the way I've changed or cleaned up numerous other
things, including many that I probably fail to mention here.

Major benefit: GHC should suck in many fewer interface files when
compiling (esp with -O).  (You can see this with -ddump-rn-stats.)

It's also some 1500 lines of code shorter than before.

**	So expect bugs!  I can do a 3-stage bootstrap, and run
**	the test suite, but you may be doing stuff I havn't tested.
** 	Don't update if you are relying on a working HEAD.


In particular, (a) External Core and (b) GHCi are very little tested.

	But please, please DO test this version!


	------------------------
		Big things
	------------------------

Interface files, version control, and importing declarations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* There is a totally new data type for stuff that lives in interface files:
	Original names			IfaceType.IfaceExtName
	Types				IfaceType.IfaceType
	Declarations (type,class,id)	IfaceSyn.IfaceDecl
	Unfoldings			IfaceSyn.IfaceExpr
  (Previously we used HsSyn for type/class decls, and UfExpr for unfoldings.)
  The new data types are in iface/IfaceType and iface/IfaceSyn.  They are
  all instances of Binary, so they can be written into interface files.
  Previous engronkulation concering the binary instance of RdrName has
  gone away -- RdrName is not an instance of Binary any more.  Nor does
  Binary.lhs need to know about the ``current module'' which it used to,
  which made it specialised to GHC.

  A good feature of this is that the type checker for source code doesn't
  need to worry about the possibility that we might be typechecking interface
  file stuff.  Nor does it need to do renaming; we can typecheck direct from
  IfaceSyn, saving a whole pass (module TcIface)

* Stuff from interface files is sucked in *lazily*, rather than being eagerly
  sucked in by the renamer. Instead, we use unsafeInterleaveIO to capture
  a thunk for the unfolding of an imported function (say).  If that unfolding
  is every pulled on, TcIface will scramble over the unfolding, which may
  in turn pull in the interface files of things mentioned in the unfolding.

  The External Package State is held in a mutable variable so that it
  can be side-effected by this lazy-sucking-in process (which may happen
  way later, e.g. when the simplifier runs).   In effect, the EPS is a kind
  of lazy memo table, filled in as we suck things in.  Or you could think
  of it as a global symbol table, populated on demand.

* This lazy sucking is very cool, but it can lead to truly awful bugs. The
  intent is that updates to the symbol table happen atomically, but very bad
  things happen if you read the variable for the table, and then force a
  thunk which updates the table.  Updates can get lost that way. I regret
  this subtlety.

  One example of the way it showed up is that the top level of TidyPgm
  (which updates the global name cache) to be much more disciplined about
  those updates, since TidyPgm may itself force thunks which allocate new
  names.

* Version numbering in interface files has changed completely, fixing
  one major bug with ghc --make.  Previously, the version of A.f changed
  only if A.f's type and unfolding was textually different.  That missed
  changes to things that A.f's unfolding mentions; which was fixed by
  eagerly sucking in all of those things, and listing them in the module's
  usage list.  But that didn't work with --make, because they might have
  been already sucked in.

  Now, A.f's version changes if anything reachable from A.f (via interface
  files) changes.  A module with unchanged source code needs recompiling
  only if the versions of any of its free variables changes. [This isn't
  quite right for dictionary functions and rules, which aren't mentioned
  explicitly in the source.  There are extensive comments in module MkIface,
  where all version-handling stuff is done.]

* We don't need equality on HsDecls any more (because they aren't used in
  interface files).  Instead we have a specialised equality for IfaceSyn
  (eqIfDecl etc), which uses IfaceEq instead of Bool as its result type.
  See notes in IfaceSyn.

* The horrid bit of the renamer that tried to predict what instance decls
  would be needed has gone entirely.  Instead, the type checker simply
  sucks in whatever instance decls it needs, when it needs them.  Easy!

  Similarly, no need for 'implicitModuleFVs' and 'implicitTemplateHaskellFVs'
  etc.  Hooray!


Types and type checking
~~~~~~~~~~~~~~~~~~~~~~~
* Kind-checking of types is far far tidier (new module TcHsTypes replaces
  the badly-named TcMonoType).  Strangely, this was one of my
  original goals, because the kind check for types is the Right Place to
  do type splicing, but it just didn't fit there before.

* There's a new representation for newtypes in TypeRep.lhs.  Previously
  they were represented using "SourceTypes" which was a funny compromise.
  Now they have their own constructor in the Type datatype.  SourceType
  has turned back into PredType, which is what it used to be.

* Instance decl overlap checking done lazily.  Consider
	instance C Int b
	instance C a Int
  These were rejected before as overlapping, because when seeking
  (C Int Int) one couldn't tell which to use.  But there's no problem when
  seeking (C Bool Int); it can only be the second.

  So instead of checking for overlap when adding a new instance declaration,
  we check for overlap when looking up an Inst.  If we find more than one
  matching instance, we see if any of the candidates dominates the others
  (in the sense of being a substitution instance of all the others);
  and only if not do we report an error.



	------------------------
	     Medium things
	------------------------

* The TcRn monad is generalised a bit further.  It's now based on utils/IOEnv.lhs,
  the IO monad with an environment.  The desugarer uses the monad too,
  so that anything it needs can get faulted in nicely.

* Reduce the number of wired-in things; in particular Word and Integer
  are no longer wired in.  The latter required HsLit.HsInteger to get a
  Type argument.  The 'derivable type classes' data types (:+:, :*: etc)
  are not wired in any more either (see stuff about derivable type classes
  below).

* The PersistentComilerState is now held in a mutable variable
  in the HscEnv.  Previously (a) it was passed to and then returned by
  many top-level functions, which was painful; (b) it was invariably
  accompanied by the HscEnv.  This change tidies up top-level plumbing
  without changing anything important.

* Derivable type classes are treated much more like 'deriving' clauses.
  Previously, the Ids for the to/from functions lived inside the TyCon,
  but now the TyCon simply records their existence (with a simple boolean).
  Anyone who wants to use them must look them up in the environment.

  This in turn makes it easy to generate the to/from functions (done
  in types/Generics) using HsSyn (like TcGenDeriv for ordinary derivings)
  instead of CoreSyn, which in turn means that (a) we don't have to figure
  out all the type arguments etc; and (b) it'll be type-checked for us.
  Generally, the task of generating the code has become easier, which is
  good for Manuel, who wants to make it more sophisticated.

* A Name now says what its "parent" is. For example, the parent of a data
  constructor is its type constructor; the parent of a class op is its
  class.  This relationship corresponds exactly to the Avail data type;
  there may be other places we can exploit it.  (I made the change so that
  version comparison in interface files would be a bit easier; but in
  fact it tided up other things here and there (see calls to
  Name.nameParent).  For example, the declaration pool, of declararations
  read from interface files, but not yet used, is now keyed only by the 'main'
  name of the declaration, not the subordinate names.

* New types OccEnv and OccSet, with the usual operations.
  OccNames can be efficiently compared, because they have uniques, thanks
  to the hashing implementation of FastStrings.

* The GlobalRdrEnv is now keyed by OccName rather than RdrName.  Not only
  does this halve the size of the env (because we don't need both qualified
  and unqualified versions in the env), but it's also more efficient because
  we can use a UniqFM instead of a FiniteMap.

  Consequential changes to Provenance, which has moved to RdrName.

* External Core remains a bit of a hack, as it was before, done with a mixture
  of HsDecls (so that recursiveness and argument variance is still inferred),
  and IfaceExprs (for value declarations).  It's not thoroughly tested.


	------------------------
	     Minor things
	------------------------

* DataCon fields dcWorkId, dcWrapId combined into a single field
  dcIds, that is explicit about whether the data con is a newtype or not.
  MkId.mkDataConWorkId and mkDataConWrapId are similarly combined into
  MkId.mkDataConIds

* Choosing the boxing strategy is done for *source* type decls only, and
  hence is now in TcTyDecls, not DataCon.

* WiredIn names are distinguished by their n_sort field, not by their location,
  which was rather strange

* Define Maybes.mapCatMaybes :: (a -> Maybe b) -> [a] -> [b]
  and use it here and there

* Much better pretty-printing of interface files (--show-iface)

Many, many other small things.


	------------------------
	     File changes
	------------------------
* New iface/ subdirectory
* Much of RnEnv has moved to iface/IfaceEnv
* MkIface and BinIface have moved from main/ to iface/
* types/Variance has been absorbed into typecheck/TcTyDecls
* RnHiFiles and RnIfaces have vanished entirely.  Their
  work is done by iface/LoadIface
* hsSyn/HsCore has gone, replaced by iface/IfaceSyn
* typecheck/TcIfaceSig has gone, replaced by iface/TcIface
* typecheck/TcMonoType has been renamed to typecheck/TcHsType
* basicTypes/Var.hi-boot and basicTypes/Generics.hi-boot have gone altogether
parent 79c93a8a
......@@ -232,7 +232,7 @@ CLEAN_FILES += $(CONFIG_HS)
ALL_DIRS = \
utils basicTypes types hsSyn prelude rename typecheck deSugar coreSyn \
specialise simplCore stranal stgSyn simplStg codeGen absCSyn main \
profiling parser cprAnalysis compMan ndpFlatten cbits
profiling parser cprAnalysis compMan ndpFlatten cbits iface
# Make sure we include Config.hs even if it doesn't exist yet...
ALL_SRCS += $(CONFIG_HS)
......@@ -345,7 +345,9 @@ endif
# The standard suffix rule for compiling a Haskell file
# adds these flags to the command line
prelude/PrimOp_HC_OPTS = -no-recomp -H80m
# There used to be a -no-recomp flag on PrimOp, but why?
# It's an expensive module to recompile!
prelude/PrimOp_HC_OPTS = -H80m
# because the NCG can't handle the 64-bit math in here
prelude/PrelRules_HC_OPTS = -fvia-C
......
......@@ -423,13 +423,6 @@ flatAbsC stmt@(CRetVector _ _ _ _) = returnFlt (AbsCNop, stmt)
flatAbsC stmt@(CModuleInitBlock _ _ _) = returnFlt (AbsCNop, stmt)
\end{code}
\begin{code}
flat_maybe :: Maybe AbstractC -> FlatM (Maybe AbstractC, AbstractC)
flat_maybe Nothing = returnFlt (Nothing, AbsCNop)
flat_maybe (Just abs_c) = flatAbsC abs_c `thenFlt` \ (heres, tops) ->
returnFlt (Just heres, tops)
\end{code}
%************************************************************************
%* *
\subsection[flat-simultaneous]{Doing things simultaneously}
......@@ -606,6 +599,7 @@ mkHalfWord_HIADDR res arg
let
hw_shift = mkIntCLit (wORD_SIZE_IN_BITS `quot` 2)
# if WORDS_BIGENDIAN
a_hw_mask1
= CMachOpStmt t_hw_mask1
MO_Nat_Shl [CLit (mkMachWord 1), hw_shift] Nothing
......@@ -613,12 +607,11 @@ mkHalfWord_HIADDR res arg
= CMachOpStmt t_hw_mask2
MO_Nat_Sub [t_hw_mask1, CLit (mkMachWord 1)] Nothing
final
# if WORDS_BIGENDIAN
= CSequential [ a_hw_mask1, a_hw_mask2,
CMachOpStmt res MO_Nat_And [arg, t_hw_mask2] Nothing
]
# else
= CMachOpStmt res MO_Nat_Shr [arg, hw_shift] Nothing
final = CMachOpStmt res MO_Nat_Shr [arg, hw_shift] Nothing
# endif
in
returnFlt final
......
......@@ -846,9 +846,7 @@ pprFCall call uniq args results vol_regs
]
DNCall (DNCallSpec isStatic kind assem nm argTys resTy) ->
let
target = StaticTarget (mkFastString nm)
resultVar = "_ccall_result"
hasAssemArg = isStatic || kind == DNConstructor
invokeOp =
case kind of
......
......@@ -17,10 +17,12 @@ module BasicTypes(
Version, bumpVersion, initialVersion, bogusVersion,
Arity,
DeprecTxt,
Unused, unused,
FixitySig(..), Fixity(..), FixityDirection(..),
Fixity(..), FixityDirection(..),
defaultFixity, maxPrecedence,
arrowFixity, negateFixity, negatePrecedence,
compareFixity,
......@@ -29,11 +31,13 @@ module BasicTypes(
NewOrData(..),
RecFlag(..), isRec, isNonRec,
RecFlag(..), isRec, isNonRec, boolToRecFlag,
TopLevelFlag(..), isTopLevel, isNotTopLevel,
Boxity(..), isBoxed, tupleParens,
Boxity(..), isBoxed,
TupCon(..), tupParens, tupleParens,
OccInfo(..), seqOccInfo, isFragileOcc, isOneOcc,
isDeadOcc, isLoopBreaker,
......@@ -53,8 +57,8 @@ module BasicTypes(
#include "HsVersions.h"
import FastString( FastString )
import Outputable
import SrcLoc
\end{code}
%************************************************************************
......@@ -96,15 +100,23 @@ type Version = Int
bogusVersion :: Version -- Shouldn't look at these
bogusVersion = error "bogusVersion"
bumpVersion :: Bool -> Version -> Version
-- Bump if the predicate (typically equality between old and new) is false
bumpVersion False v = v+1
bumpVersion True v = v
bumpVersion :: Version -> Version
bumpVersion v = v+1
initialVersion :: Version
initialVersion = 1
\end{code}
%************************************************************************
%* *
Deprecations
%* *
%************************************************************************
\begin{code}
type DeprecTxt = FastString -- reason/explanation for deprecation
\end{code}
%************************************************************************
%* *
......@@ -130,9 +142,13 @@ ipNameName (Linear n) = n
mapIPName :: (a->b) -> IPName a -> IPName b
mapIPName f (Dupable n) = Dupable (f n)
mapIPName f (Linear n) = Linear (f n)
instance Outputable name => Outputable (IPName name) where
ppr (Dupable n) = char '?' <> ppr n -- Ordinary implicit parameters
ppr (Linear n) = char '%' <> ppr n -- Splittable implicit parameters
\end{code}
%************************************************************************
%* *
\subsection[Fixity]{Fixity info}
......@@ -140,15 +156,6 @@ mapIPName f (Linear n) = Linear (f n)
%************************************************************************
\begin{code}
------------------------
data FixitySig name = FixitySig name Fixity SrcLoc
instance Eq name => Eq (FixitySig name) where
(FixitySig n1 f1 _) == (FixitySig n2 f2 _) = n1==n2 && f1==f2
instance Outputable name => Outputable (FixitySig name) where
ppr (FixitySig name fixity loc) = sep [ppr fixity, ppr name]
------------------------
data Fixity = Fixity Int FixityDirection
......@@ -219,6 +226,10 @@ data NewOrData
= NewType -- "newtype Blah ..."
| DataType -- "data Blah ..."
deriving( Eq ) -- Needed because Demand derives Eq
instance Outputable NewOrData where
ppr NewType = ptext SLIT("newtype")
ppr DataType = ptext SLIT("data")
\end{code}
......@@ -240,8 +251,13 @@ isNotTopLevel TopLevel = False
isTopLevel TopLevel = True
isTopLevel NotTopLevel = False
instance Outputable TopLevelFlag where
ppr TopLevel = ptext SLIT("<TopLevel>")
ppr NotTopLevel = ptext SLIT("<NotTopLevel>")
\end{code}
%************************************************************************
%* *
\subsection[Top-level/local]{Top-level/not-top level flag}
......@@ -257,10 +273,6 @@ data Boxity
isBoxed :: Boxity -> Bool
isBoxed Boxed = True
isBoxed Unboxed = False
tupleParens :: Boxity -> SDoc -> SDoc
tupleParens Boxed p = parens p
tupleParens Unboxed p = ptext SLIT("(#") <+> p <+> ptext SLIT("#)")
\end{code}
......@@ -273,6 +285,7 @@ tupleParens Unboxed p = ptext SLIT("(#") <+> p <+> ptext SLIT("#)")
\begin{code}
data RecFlag = Recursive
| NonRecursive
deriving( Eq )
isRec :: RecFlag -> Bool
isRec Recursive = True
......@@ -281,6 +294,34 @@ isRec NonRecursive = False
isNonRec :: RecFlag -> Bool
isNonRec Recursive = False
isNonRec NonRecursive = True
boolToRecFlag :: Bool -> RecFlag
boolToRecFlag True = Recursive
boolToRecFlag False = NonRecursive
instance Outputable RecFlag where
ppr Recursive = ptext SLIT("Recursive")
ppr NonRecursive = ptext SLIT("NonRecursive")
\end{code}
%************************************************************************
%* *
Tuples
%* *
%************************************************************************
\begin{code}
data TupCon = TupCon Boxity Arity
instance Eq TupCon where
(TupCon b1 a1) == (TupCon b2 a2) = b1==b2 && a1==a2
tupParens :: TupCon -> SDoc -> SDoc
tupParens (TupCon b _) p = tupleParens b p
tupleParens :: Boxity -> SDoc -> SDoc
tupleParens Boxed p = parens p
tupleParens Unboxed p = ptext SLIT("(#") <+> p <+> ptext SLIT("#)")
\end{code}
%************************************************************************
......@@ -290,7 +331,7 @@ isNonRec NonRecursive = True
%************************************************************************
This is the "Embedding-Projection pair" datatype, it contains
two pieces of code (normally either RenamedHsExpr's or Id's)
two pieces of code (normally either RenamedExpr's or Id's)
If we have a such a pair (EP from to), the idea is that 'from' and 'to'
represents functions of type
......@@ -400,12 +441,10 @@ The strictness annotations on types in data type declarations
e.g. data T = MkT !Int !(Bool,Bool)
\begin{code}
data StrictnessMark
= MarkedUserStrict -- "!" in a source decl
| MarkedUserUnboxed -- "!!" in a source decl
| MarkedStrict -- "!" in an interface decl: strict but not unboxed
| MarkedUnboxed -- "!!" in an interface decl: unboxed
| NotMarkedStrict -- No annotation at all
data StrictnessMark -- Used in interface decls only
= MarkedStrict
| MarkedUnboxed
| NotMarkedStrict
deriving( Eq )
isMarkedUnboxed MarkedUnboxed = True
......@@ -415,10 +454,9 @@ isMarkedStrict NotMarkedStrict = False
isMarkedStrict other = True -- All others are strict
instance Outputable StrictnessMark where
ppr MarkedUserStrict = ptext SLIT("!u")
ppr MarkedStrict = ptext SLIT("!")
ppr MarkedUnboxed = ptext SLIT("! !")
ppr NotMarkedStrict = empty
ppr MarkedUnboxed = ptext SLIT("!!")
ppr NotMarkedStrict = ptext SLIT("_")
\end{code}
......
......@@ -5,16 +5,16 @@
\begin{code}
module DataCon (
DataCon,
DataCon, DataConIds(..),
ConTag, fIRST_TAG,
mkDataCon,
dataConRepType, dataConSig, dataConName, dataConTag, dataConTyCon,
dataConArgTys, dataConOrigArgTys, dataConInstOrigArgTys,
dataConRepArgTys, dataConTheta,
dataConFieldLabels, dataConStrictMarks,
dataConFieldLabels, dataConStrictMarks, dataConExStricts,
dataConSourceArity, dataConRepArity,
dataConNumInstArgs,
dataConWorkId, dataConWrapId, dataConWrapId_maybe,
dataConWorkId, dataConWrapId, dataConWrapId_maybe, dataConImplicitIds,
dataConRepStrictness,
isNullaryDataCon, isTupleCon, isUnboxedTupleCon,
isExistentialDataCon, classDataCon, dataConExistentialTyVars,
......@@ -29,11 +29,11 @@ import {-# SOURCE #-} PprType( pprType )
import Type ( Type, ThetaType,
mkForAllTys, mkFunTys, mkTyConApp,
mkTyVarTys, splitTyConApp_maybe, repType,
mkPredTys, isStrictType
mkTyVarTys, splitTyConApp_maybe,
mkPredTys, isStrictPred
)
import TyCon ( TyCon, tyConDataCons, tyConDataCons, isProductTyCon,
isTupleTyCon, isUnboxedTupleTyCon, isRecursiveTyCon )
isTupleTyCon, isUnboxedTupleTyCon )
import Class ( Class, classTyCon )
import Name ( Name, NamedThing(..), nameUnique )
import Var ( TyVar, Id )
......@@ -41,7 +41,6 @@ import FieldLabel ( FieldLabel )
import BasicTypes ( Arity, StrictnessMark(..) )
import Outputable
import Unique ( Unique, Uniquable(..) )
import Maybes ( orElse )
import ListSetOps ( assoc )
import Util ( zipEqual, zipWithEqual, notNull )
\end{code}
......@@ -217,7 +216,7 @@ data DataCon
-- "Stupid", because the dictionaries aren't used for anything.
--
-- Indeed, [as of March 02] they are no
-- longer in the type of the dcWrapId, because
-- longer in the type of the wrapper Id, because
-- that makes it harder to use the wrap-id to rebuild
-- values after record selection or in generics.
......@@ -228,41 +227,59 @@ data DataCon
-- (before unboxing and flattening of
-- strict fields)
dcRepArgTys :: [Type], -- Final, representation argument types, after unboxing and flattening,
-- and including existential dictionaries
dcRepStrictness :: [StrictnessMark], -- One for each representation argument
dcTyCon :: TyCon, -- Result tycon
-- Now the strictness annotations and field labels of the constructor
dcStrictMarks :: [StrictnessMark],
-- Strictness annotations as deduced by the compiler.
-- Has no MarkedUserStrict; they have been changed to MarkedStrict
-- or MarkedUnboxed by the compiler.
-- *Includes the existential dictionaries*
-- length = length dcExTheta + dataConSourceArity dataCon
-- Strictness annotations as decided by the compiler.
-- Does *not* include the existential dictionaries
-- length = dataConSourceArity dataCon
dcFields :: [FieldLabel],
-- Field labels for this constructor, in the
-- same order as the argument types;
-- length = 0 (if not a record) or dataConSourceArity.
-- Constructor representation
dcRepArgTys :: [Type], -- Final, representation argument types,
-- after unboxing and flattening,
-- and *including* existential dictionaries
dcRepStrictness :: [StrictnessMark], -- One for each representation argument
dcTyCon :: TyCon, -- Result tycon
-- Finally, the curried worker function that corresponds to the constructor
-- It doesn't have an unfolding; the code generator saturates these Ids
-- and allocates a real constructor when it finds one.
--
-- An entirely separate wrapper function is built in TcTyDecls
dcWorkId :: Id, -- The corresponding worker Id
-- Takes dcRepArgTys as its arguments
-- Perhaps this should be a 'Maybe'; not reqd for newtype constructors
dcWrapId :: Maybe Id -- The wrapper Id, if it's necessary
-- It's deemed unnecessary if it performs the
-- identity function
dcIds :: DataConIds
}
data DataConIds
= NewDC Id -- Newtypes have only a wrapper, but no worker
| AlgDC (Maybe Id) Id -- Algebraic data types always have a worker, and
-- may or may not have a wrapper, depending on whether
-- the wrapper does anything.
-- *Neither* the worker *nor* the wrapper take the dcStupidTheta dicts as arguments
-- The wrapper takes dcOrigArgTys as its arguments
-- The worker takes dcRepArgTys as its arguments
-- If the worker is absent, dcRepArgTys is the same as dcOrigArgTys
-- The 'Nothing' case of AlgDC is important
-- Not only is this efficient,
-- but it also ensures that the wrapper is replaced
-- by the worker (becuase it *is* the wroker)
-- even when there are no args. E.g. in
-- f (:) x
-- the (:) *is* the worker.
-- This is really important in rule matching,
-- (We could match on the wrappers,
-- but that makes it less likely that rules will match
-- when we bring bits of unfoldings together.)
type ConTag = Int
fIRST_TAG :: ConTag
......@@ -330,15 +347,15 @@ mkDataCon :: Name
-> [TyVar] -> ThetaType
-> [TyVar] -> ThetaType
-> [Type] -> TyCon
-> Id -> Maybe Id -- Worker and possible wrapper
-> DataConIds
-> DataCon
-- Can get the tag from the TyCon
mkDataCon name
arg_stricts -- Use [] to mean 'all non-strict'
arg_stricts -- Must match orig_arg_tys 1-1
fields
tyvars theta ex_tyvars ex_theta orig_arg_tys tycon
work_id wrap_id
ids
= con
where
con = MkData {dcName = name,
......@@ -347,9 +364,9 @@ mkDataCon name
dcOrigArgTys = orig_arg_tys,
dcRepArgTys = rep_arg_tys,
dcExTyVars = ex_tyvars, dcExTheta = ex_theta,
dcStrictMarks = real_stricts, dcRepStrictness = rep_arg_stricts,
dcStrictMarks = arg_stricts, dcRepStrictness = rep_arg_stricts,
dcFields = fields, dcTag = tag, dcTyCon = tycon, dcRepType = ty,
dcWorkId = work_id, dcWrapId = wrap_id}
dcIds = ids}
-- Strictness marks for source-args
-- *after unboxing choices*,
......@@ -359,11 +376,8 @@ mkDataCon name
-- source-language arguments. We add extra ones for the
-- dictionary arguments right here.
ex_dict_tys = mkPredTys ex_theta
real_stricts = map mk_dict_strict_mark ex_dict_tys ++
zipWith (chooseBoxingStrategy tycon)
orig_arg_tys
(arg_stricts ++ repeat NotMarkedStrict)
real_arg_tys = ex_dict_tys ++ orig_arg_tys
real_arg_tys = ex_dict_tys ++ orig_arg_tys
real_stricts = map mk_dict_strict_mark ex_theta ++ arg_stricts
-- Representation arguments and demands
(rep_arg_stricts, rep_arg_tys) = computeRep real_stricts real_arg_tys
......@@ -375,8 +389,8 @@ mkDataCon name
result_ty = mkTyConApp tycon (mkTyVarTys tyvars)
mk_dict_strict_mark ty | isStrictType ty = MarkedStrict
| otherwise = NotMarkedStrict
mk_dict_strict_mark pred | isStrictPred pred = MarkedStrict
| otherwise = NotMarkedStrict
\end{code}
\begin{code}
......@@ -393,16 +407,27 @@ dataConRepType :: DataCon -> Type
dataConRepType = dcRepType
dataConWorkId :: DataCon -> Id
dataConWorkId = dcWorkId
dataConWorkId dc = case dcIds dc of
AlgDC _ wrk_id -> wrk_id
NewDC _ -> pprPanic "dataConWorkId" (ppr dc)
dataConWrapId_maybe :: DataCon -> Maybe Id
dataConWrapId_maybe = dcWrapId
dataConWrapId_maybe dc = case dcIds dc of
AlgDC mb_wrap _ -> mb_wrap
NewDC wrap -> Just wrap
dataConWrapId :: DataCon -> Id
-- Returns an Id which looks like the Haskell-source constructor
-- If there is no dcWrapId it's because there is no need for a
-- wrapper, so the worker is the Right Thing
dataConWrapId dc = dcWrapId dc `orElse` dcWorkId dc
dataConWrapId dc = case dcIds dc of
AlgDC (Just wrap) _ -> wrap
AlgDC Nothing wrk -> wrk -- worker=wrapper
NewDC wrap -> wrap
dataConImplicitIds :: DataCon -> [Id]
dataConImplicitIds dc = case dcIds dc of
AlgDC (Just wrap) work -> [wrap,work]
AlgDC Nothing work -> [work]
NewDC wrap -> [wrap]
dataConFieldLabels :: DataCon -> [FieldLabel]
dataConFieldLabels = dcFields
......@@ -410,6 +435,11 @@ dataConFieldLabels = dcFields
dataConStrictMarks :: DataCon -> [StrictnessMark]
dataConStrictMarks = dcStrictMarks
dataConExStricts :: DataCon -> [StrictnessMark]
-- Strictness of *existential* arguments only
-- Usually empty, so we don't bother to cache this
dataConExStricts dc = map mk_dict_strict_mark (dcExTheta dc)
-- Number of type-instantiation arguments
-- All the remaining arguments of the DataCon are (notionally)
-- stored in the DataCon, and are matched in a case expression
......@@ -541,40 +571,8 @@ splitProductType str ty
Just stuff -> stuff
Nothing -> pprPanic (str ++ ": not a product") (pprType ty)
-- We attempt to unbox/unpack a strict field when either:
-- (i) The tycon is imported, and the field is marked '! !', or
-- (ii) The tycon is defined in this module, the field is marked '!',
-- and the -funbox-strict-fields flag is on.
--
-- This ensures that if we compile some modules with -funbox-strict-fields and
-- some without, the compiler doesn't get confused about the constructor
-- representations.
chooseBoxingStrategy :: TyCon -> Type -> StrictnessMark -> StrictnessMark
-- Transforms any MarkedUserStricts into MarkUnboxed or MarkedStrict
chooseBoxingStrategy tycon arg_ty strict
= case strict of
MarkedUserStrict -> MarkedStrict
MarkedUserUnboxed
| can_unbox -> MarkedUnboxed
| otherwise -> MarkedStrict
other -> strict
where
can_unbox = unbox arg_ty
-- beware: repType will go into a loop if we try this on a recursive
-- type (for reasons unknown...), hence the check for recursion below.
unbox ty =
case splitTyConApp_maybe ty of
Nothing -> False
Just (arg_tycon, _)
| isRecursiveTyCon arg_tycon -> False
| otherwise ->
case splitTyConApp_maybe (repType ty) of
Nothing -> False
Just (arg_tycon, _) -> isProductTyCon arg_tycon
computeRep :: [StrictnessMark] -- Original arg strictness
-- [after strategy choice; can't be MarkedUserStrict]
-> [Type] -- and types
-> ([StrictnessMark], -- Representation arg strictness
[Type]) -- And type
......@@ -586,5 +584,5 @@ computeRep stricts tys
unbox MarkedStrict ty = [(MarkedStrict, ty)]
unbox MarkedUnboxed ty = zipEqual "computeRep" (dataConRepStrictness arg_dc) arg_tys
where
(_, _, arg_dc, arg_tys) = splitProductType "unbox_strict_arg_ty" (repType ty)
(_, _, arg_dc, arg_tys) = splitProductType "unbox_strict_arg_ty" ty
\end{code}
......@@ -30,7 +30,6 @@ module Id (
isPrimOpId, isPrimOpId_maybe,
isFCallId, isFCallId_maybe,
isDataConWorkId, isDataConWorkId_maybe,
isDataConWrapId, isDataConWrapId_maybe,
isBottomingId,
hasNoBinding,
......@@ -90,8 +89,7 @@ import Var ( Id, DictId,
globalIdDetails, setGlobalIdDetails
)
import qualified Var ( mkLocalId, mkGlobalId, mkSpecPragmaId )
import Type ( Type, typePrimRep, addFreeTyVars,
seqType, splitTyConApp_maybe )
import Type ( Type, typePrimRep, addFreeTyVars, seqType)
import IdInfo
......@@ -238,6 +236,7 @@ Meanwhile, it is not discarded as dead code.
recordSelectorFieldLabel :: Id -> FieldLabel
recordSelectorFieldLabel id = case globalIdDetails id of
RecordSelId lbl -> lbl
other -> panic "recordSelectorFieldLabel"
isRecordSelector id = case globalIdDetails id of
RecordSelId lbl -> True
......@@ -267,14 +266,6 @@ isDataConWorkId_maybe id = case globalIdDetails id of
DataConWorkId con -> Just con
other -> Nothing
isDataConWrapId_maybe id = case globalIdDetails id of
DataConWrapId con -> Just con
other -> Nothing
isDataConWrapId id = case globalIdDetails id of
DataConWrapId con -> True
other -> False
-- hasNoBinding returns True of an Id which may not have a
-- binding, even though it is defined in this module.
-- Data constructor workers used to be things of this kind, but
......@@ -297,7 +288,6 @@ isImplicitId id
FCallId _ -> True
PrimOpId _ -> True
ClassOpId _ -> True
GenericOpId _ -> True
DataConWorkId _ -> True
DataConWrapId _ -> True
-- These are are implied by their type or class decl;
......
......@@ -77,7 +77,6 @@ module IdInfo (
import CoreSyn
import TyCon ( TyCon )
import Class ( Class )
import PrimOp ( PrimOp )
import Var ( Id )
......@@ -231,7 +230,6 @@ an IdInfo.hi-boot, but no Id.hi-boot, and GlobalIdDetails is imported