2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[CoreSyn]{A data type for the Haskell compiler midsection}
8 Expr(..), Alt, Bind(..), AltCon(..), Arg, Note(..),
9 CoreExpr, CoreAlt, CoreBind, CoreArg, CoreBndr,
10 TaggedExpr, TaggedAlt, TaggedBind, TaggedArg, TaggedBndr(..),
13 mkApps, mkTyApps, mkValApps, mkVarApps,
14 mkLit, mkIntLitInt, mkIntLit,
19 bindersOf, bindersOfBinds, rhssOfBind, rhssOfAlts,
20 collectBinders, collectTyBinders, collectValBinders, collectTyAndValBinders,
25 isValArg, isTypeArg, valArgCount, valBndrCount, isRuntimeArg, isRuntimeVar,
28 Unfolding(..), UnfoldingGuidance(..), -- Both abstract everywhere but in CoreUnfold.lhs
29 noUnfolding, mkOtherCon,
30 unfoldingTemplate, maybeUnfoldingTemplate, otherCons,
31 isValueUnfolding, isEvaldUnfolding, isCheapUnfolding, isCompulsoryUnfolding,
32 hasUnfolding, hasSomeUnfolding, neverUnfold,
35 seqRules, seqExpr, seqExprs, seqUnfolding,
37 -- Annotated expressions
38 AnnExpr, AnnExpr'(..), AnnBind(..), AnnAlt,
39 deAnnotate, deAnnotate', deAnnAlt, collectAnnBndrs,
42 CoreRules(..), -- Representation needed by friends
43 CoreRule(..), -- CoreSubst, CoreTidy, CoreFVs, PprCore only
46 emptyCoreRules, isEmptyCoreRules, rulesRhsFreeVars, rulesRules,
47 isBuiltinRule, ruleName
50 #include "HsVersions.h"
52 import CmdLineOpts ( opt_RuntimeTypes )
53 import CostCentre ( CostCentre, noCostCentre )
54 import Var ( Var, Id, TyVar, isTyVar, isId )
55 import Type ( Type, mkTyVarTy, seqType )
56 import Literal ( Literal, mkMachInt )
57 import DataCon ( DataCon, dataConWorkId )
58 import BasicTypes ( Activation )
64 %************************************************************************
66 \subsection{The main data types}
68 %************************************************************************
70 These data types are the heart of the compiler
73 infixl 8 `App` -- App brackets to the left
75 data Expr b -- "b" for the type of binders,
78 | App (Expr b) (Arg b)
80 | Let (Bind b) (Expr b)
81 | Case (Expr b) b [Alt b] -- Binder gets bound to value of scrutinee
82 -- DEFAULT case must be *first*, if it occurs at all
84 | Type Type -- This should only show up at the top
87 type Arg b = Expr b -- Can be a Type
89 type Alt b = (AltCon, [b], Expr b) -- (DEFAULT, [], rhs) is the default alternative
91 data AltCon = DataAlt DataCon
96 data Bind b = NonRec b (Expr b)
103 Type -- The to-type: type of whole coerce expression
104 Type -- The from-type: type of enclosed expression
106 | InlineCall -- Instructs simplifier to inline
109 | InlineMe -- Instructs simplifer to treat the enclosed expression
110 -- as very small, and inline it at its call sites
112 | CoreNote String -- A generic core annotation, propagated but not used by GHC
114 -- NOTE: we also treat expressions wrapped in InlineMe as
115 -- 'cheap' and 'dupable' (in the sense of exprIsCheap, exprIsDupable)
116 -- What this means is that we obediently inline even things that don't
117 -- look like valuse. This is sometimes important:
120 -- Here, f looks like a redex, and we aren't going to inline (.) because it's
121 -- inside an INLINE, so it'll stay looking like a redex. Nevertheless, we
122 -- should inline f even inside lambdas. In effect, we should trust the programmer.
127 * The RHS of a letrec, and the RHSs of all top-level lets,
128 must be of LIFTED type.
130 * The RHS of a let, may be of UNLIFTED type, but only if the expression
131 is ok-for-speculation. This means that the let can be floated around
132 without difficulty. e.g.
134 y::Int# = fac 4# not ok [use case instead]
136 * The argument of an App can be of any type.
138 * The simplifier tries to ensure that if the RHS of a let is a constructor
139 application, its arguments are trivial, so that the constructor can be
143 %************************************************************************
145 \subsection{Transformation rules}
147 %************************************************************************
149 The CoreRule type and its friends are dealt with mainly in CoreRules,
150 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
155 VarSet -- Locally-defined free vars of RHSs
157 emptyCoreRules :: CoreRules
158 emptyCoreRules = Rules [] emptyVarSet
160 isEmptyCoreRules :: CoreRules -> Bool
161 isEmptyCoreRules (Rules rs _) = null rs
163 rulesRhsFreeVars :: CoreRules -> VarSet
164 rulesRhsFreeVars (Rules _ fvs) = fvs
166 rulesRules :: CoreRules -> [CoreRule]
167 rulesRules (Rules rules _) = rules
171 type RuleName = FastString
172 type IdCoreRule = (Id,CoreRule) -- Rules don't have their leading Id inside them
176 Activation -- When the rule is active
177 [CoreBndr] -- Forall'd variables
178 [CoreExpr] -- LHS args
181 | BuiltinRule -- Built-in rules are used for constant folding
182 RuleName -- and suchlike. It has no free variables.
183 ([CoreExpr] -> Maybe CoreExpr)
185 isBuiltinRule (BuiltinRule _ _) = True
186 isBuiltinRule _ = False
188 ruleName :: CoreRule -> RuleName
189 ruleName (Rule n _ _ _ _) = n
190 ruleName (BuiltinRule n _) = n
194 %************************************************************************
196 \subsection{@Unfolding@ type}
198 %************************************************************************
200 The @Unfolding@ type is declared here to avoid numerous loops, but it
201 should be abstract everywhere except in CoreUnfold.lhs
207 | OtherCon [AltCon] -- It ain't one of these
208 -- (OtherCon xs) also indicates that something has been evaluated
209 -- and hence there's no point in re-evaluating it.
210 -- OtherCon [] is used even for non-data-type values
211 -- to indicated evaluated-ness. Notably:
212 -- data C = C !(Int -> Int)
213 -- case x of { C f -> ... }
214 -- Here, f gets an OtherCon [] unfolding.
216 | CompulsoryUnfolding CoreExpr -- There is no "original" definition,
217 -- so you'd better unfold.
219 | CoreUnfolding -- An unfolding with redundant cached information
220 CoreExpr -- Template; binder-info is correct
221 Bool -- True <=> top level binding
222 Bool -- exprIsValue template (cached); it is ok to discard a `seq` on
224 Bool -- True <=> doesn't waste (much) work to expand inside an inlining
225 -- Basically it's exprIsCheap
226 UnfoldingGuidance -- Tells about the *size* of the template.
229 data UnfoldingGuidance
231 | UnfoldIfGoodArgs Int -- and "n" value args
233 [Int] -- Discount if the argument is evaluated.
234 -- (i.e., a simplification will definitely
235 -- be possible). One elt of the list per *value* arg.
237 Int -- The "size" of the unfolding; to be elaborated
240 Int -- Scrutinee discount: the discount to substract if the thing is in
241 -- a context (case (thing args) of ...),
242 -- (where there are the right number of arguments.)
244 noUnfolding = NoUnfolding
245 mkOtherCon = OtherCon
247 seqUnfolding :: Unfolding -> ()
248 seqUnfolding (CoreUnfolding e top b1 b2 g)
249 = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
250 seqUnfolding other = ()
252 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
253 seqGuidance other = ()
257 unfoldingTemplate :: Unfolding -> CoreExpr
258 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
259 unfoldingTemplate (CompulsoryUnfolding expr) = expr
260 unfoldingTemplate other = panic "getUnfoldingTemplate"
262 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
263 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
264 maybeUnfoldingTemplate (CompulsoryUnfolding expr) = Just expr
265 maybeUnfoldingTemplate other = Nothing
267 otherCons :: Unfolding -> [AltCon]
268 otherCons (OtherCon cons) = cons
271 isValueUnfolding :: Unfolding -> Bool
272 -- Returns False for OtherCon
273 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
274 isValueUnfolding other = False
276 isEvaldUnfolding :: Unfolding -> Bool
277 -- Returns True for OtherCon
278 isEvaldUnfolding (OtherCon _) = True
279 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
280 isEvaldUnfolding other = False
282 isCheapUnfolding :: Unfolding -> Bool
283 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
284 isCheapUnfolding other = False
286 isCompulsoryUnfolding :: Unfolding -> Bool
287 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
288 isCompulsoryUnfolding other = False
290 hasUnfolding :: Unfolding -> Bool
291 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
292 hasUnfolding (CompulsoryUnfolding _) = True
293 hasUnfolding other = False
295 hasSomeUnfolding :: Unfolding -> Bool
296 hasSomeUnfolding NoUnfolding = False
297 hasSomeUnfolding other = True
299 neverUnfold :: Unfolding -> Bool
300 neverUnfold NoUnfolding = True
301 neverUnfold (OtherCon _) = True
302 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
303 neverUnfold other = False
307 %************************************************************************
309 \subsection{The main data type}
311 %************************************************************************
314 -- The Ord is needed for the FiniteMap used in the lookForConstructor
315 -- in SimplEnv. If you declared that lookForConstructor *ignores*
316 -- constructor-applications with LitArg args, then you could get
319 instance Outputable AltCon where
320 ppr (DataAlt dc) = ppr dc
321 ppr (LitAlt lit) = ppr lit
322 ppr DEFAULT = ptext SLIT("__DEFAULT")
324 instance Show AltCon where
325 showsPrec p con = showsPrecSDoc p (ppr con)
329 %************************************************************************
331 \subsection{Useful synonyms}
333 %************************************************************************
339 type CoreExpr = Expr CoreBndr
340 type CoreArg = Arg CoreBndr
341 type CoreBind = Bind CoreBndr
342 type CoreAlt = Alt CoreBndr
345 Binders are ``tagged'' with a \tr{t}:
348 data TaggedBndr t = TB CoreBndr t -- TB for "tagged binder"
350 type TaggedBind t = Bind (TaggedBndr t)
351 type TaggedExpr t = Expr (TaggedBndr t)
352 type TaggedArg t = Arg (TaggedBndr t)
353 type TaggedAlt t = Alt (TaggedBndr t)
355 instance Outputable b => Outputable (TaggedBndr b) where
356 ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>'
358 instance Outputable b => OutputableBndr (TaggedBndr b) where
359 pprBndr _ b = ppr b -- Simple
363 %************************************************************************
365 \subsection{Core-constructing functions with checking}
367 %************************************************************************
370 mkApps :: Expr b -> [Arg b] -> Expr b
371 mkTyApps :: Expr b -> [Type] -> Expr b
372 mkValApps :: Expr b -> [Expr b] -> Expr b
373 mkVarApps :: Expr b -> [Var] -> Expr b
375 mkApps f args = foldl App f args
376 mkTyApps f args = foldl (\ e a -> App e (Type a)) f args
377 mkValApps f args = foldl (\ e a -> App e a) f args
378 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
380 mkLit :: Literal -> Expr b
381 mkIntLit :: Integer -> Expr b
382 mkIntLitInt :: Int -> Expr b
383 mkConApp :: DataCon -> [Arg b] -> Expr b
384 mkLets :: [Bind b] -> Expr b -> Expr b
385 mkLams :: [b] -> Expr b -> Expr b
388 mkConApp con args = mkApps (Var (dataConWorkId con)) args
390 mkLams binders body = foldr Lam body binders
391 mkLets binds body = foldr Let body binds
393 mkIntLit n = Lit (mkMachInt n)
394 mkIntLitInt n = Lit (mkMachInt (toInteger n))
396 varToCoreExpr :: CoreBndr -> Expr b
397 varToCoreExpr v | isId v = Var v
398 | otherwise = Type (mkTyVarTy v)
402 %************************************************************************
404 \subsection{Simple access functions}
406 %************************************************************************
409 bindersOf :: Bind b -> [b]
410 bindersOf (NonRec binder _) = [binder]
411 bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
413 bindersOfBinds :: [Bind b] -> [b]
414 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
416 rhssOfBind :: Bind b -> [Expr b]
417 rhssOfBind (NonRec _ rhs) = [rhs]
418 rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
420 rhssOfAlts :: [Alt b] -> [Expr b]
421 rhssOfAlts alts = [e | (_,_,e) <- alts]
423 flattenBinds :: [Bind b] -> [(b, Expr b)] -- Get all the lhs/rhs pairs
424 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
425 flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
429 We often want to strip off leading lambdas before getting down to
430 business. @collectBinders@ is your friend.
432 We expect (by convention) type-, and value- lambdas in that
436 collectBinders :: Expr b -> ([b], Expr b)
437 collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr)
438 collectValBinders :: CoreExpr -> ([Id], CoreExpr)
439 collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
444 go bs (Lam b e) = go (b:bs) e
445 go bs e = (reverse bs, e)
447 collectTyAndValBinders expr
450 (tvs, body1) = collectTyBinders expr
451 (ids, body) = collectValBinders body1
453 collectTyBinders expr
456 go tvs (Lam b e) | isTyVar b = go (b:tvs) e
457 go tvs e = (reverse tvs, e)
459 collectValBinders expr
462 go ids (Lam b e) | isId b = go (b:ids) e
463 go ids body = (reverse ids, body)
467 @collectArgs@ takes an application expression, returning the function
468 and the arguments to which it is applied.
471 collectArgs :: Expr b -> (Expr b, [Arg b])
475 go (App f a) as = go f (a:as)
479 coreExprCc gets the cost centre enclosing an expression, if any.
480 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
483 coreExprCc :: Expr b -> CostCentre
484 coreExprCc (Note (SCC cc) e) = cc
485 coreExprCc (Note other_note e) = coreExprCc e
486 coreExprCc (Lam _ e) = coreExprCc e
487 coreExprCc other = noCostCentre
492 %************************************************************************
494 \subsection{Predicates}
496 %************************************************************************
498 @isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
499 i.e. if type applications are actual lambdas because types are kept around
502 Similarly isRuntimeArg.
505 isRuntimeVar :: Var -> Bool
506 isRuntimeVar | opt_RuntimeTypes = \v -> True
507 | otherwise = \v -> isId v
509 isRuntimeArg :: CoreExpr -> Bool
510 isRuntimeArg | opt_RuntimeTypes = \e -> True
511 | otherwise = \e -> isValArg e
515 isValArg (Type _) = False
516 isValArg other = True
518 isTypeArg (Type _) = True
519 isTypeArg other = False
521 valBndrCount :: [CoreBndr] -> Int
523 valBndrCount (b : bs) | isId b = 1 + valBndrCount bs
524 | otherwise = valBndrCount bs
526 valArgCount :: [Arg b] -> Int
528 valArgCount (Type _ : args) = valArgCount args
529 valArgCount (other : args) = 1 + valArgCount args
533 %************************************************************************
535 \subsection{Seq stuff}
537 %************************************************************************
540 seqExpr :: CoreExpr -> ()
541 seqExpr (Var v) = v `seq` ()
542 seqExpr (Lit lit) = lit `seq` ()
543 seqExpr (App f a) = seqExpr f `seq` seqExpr a
544 seqExpr (Lam b e) = seqBndr b `seq` seqExpr e
545 seqExpr (Let b e) = seqBind b `seq` seqExpr e
546 seqExpr (Case e b as) = seqExpr e `seq` seqBndr b `seq` seqAlts as
547 seqExpr (Note n e) = seqNote n `seq` seqExpr e
548 seqExpr (Type t) = seqType t
551 seqExprs (e:es) = seqExpr e `seq` seqExprs es
553 seqNote (Coerce t1 t2) = seqType t1 `seq` seqType t2
554 seqNote (CoreNote s) = s `seq` ()
557 seqBndr b = b `seq` ()
560 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
562 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
563 seqBind (Rec prs) = seqPairs prs
566 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
569 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
571 seqRules :: CoreRules -> ()
572 seqRules (Rules rules fvs) = seq_rules rules `seq` seqVarSet fvs
575 seq_rules (Rule fs _ bs es e : rules) = seqBndrs bs `seq` seqExprs (e:es) `seq` seq_rules rules
576 seq_rules (BuiltinRule _ _ : rules) = seq_rules rules
581 %************************************************************************
583 \subsection{Annotated core; annotation at every node in the tree}
585 %************************************************************************
588 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
590 data AnnExpr' bndr annot
593 | AnnLam bndr (AnnExpr bndr annot)
594 | AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
595 | AnnCase (AnnExpr bndr annot) bndr [AnnAlt bndr annot]
596 | AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
597 | AnnNote Note (AnnExpr bndr annot)
600 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
602 data AnnBind bndr annot
603 = AnnNonRec bndr (AnnExpr bndr annot)
604 | AnnRec [(bndr, AnnExpr bndr annot)]
608 deAnnotate :: AnnExpr bndr annot -> Expr bndr
609 deAnnotate (_, e) = deAnnotate' e
611 deAnnotate' (AnnType t) = Type t
612 deAnnotate' (AnnVar v) = Var v
613 deAnnotate' (AnnLit lit) = Lit lit
614 deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
615 deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
616 deAnnotate' (AnnNote note body) = Note note (deAnnotate body)
618 deAnnotate' (AnnLet bind body)
619 = Let (deAnnBind bind) (deAnnotate body)
621 deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
622 deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
624 deAnnotate' (AnnCase scrut v alts)
625 = Case (deAnnotate scrut) v (map deAnnAlt alts)
627 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
628 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
632 collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot)
636 collect bs (_, AnnLam b body) = collect (b:bs) body
637 collect bs body = (reverse bs, body)