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 -- Invariant: The list of alternatives is ALWAYS EXHAUSTIVE,
83 -- meaning that it covers all cases that can occur
84 -- See the example below
86 -- Invariant: The DEFAULT case must be *first*, if it occurs at all
88 | Type Type -- This should only show up at the top
91 -- An "exhausive" case does not necessarily mention all constructors:
92 -- data Foo = Red | Green | Blue
96 -- other -> f (case x of
99 -- The inner case does not need a Red alternative, because x can't be Red at
100 -- that program point.
103 type Arg b = Expr b -- Can be a Type
105 type Alt b = (AltCon, [b], Expr b) -- (DEFAULT, [], rhs) is the default alternative
107 data AltCon = DataAlt DataCon
112 data Bind b = NonRec b (Expr b)
113 | Rec [(b, (Expr b))]
119 Type -- The to-type: type of whole coerce expression
120 Type -- The from-type: type of enclosed expression
122 | InlineCall -- Instructs simplifier to inline
125 | InlineMe -- Instructs simplifer to treat the enclosed expression
126 -- as very small, and inline it at its call sites
128 | CoreNote String -- A generic core annotation, propagated but not used by GHC
130 -- NOTE: we also treat expressions wrapped in InlineMe as
131 -- 'cheap' and 'dupable' (in the sense of exprIsCheap, exprIsDupable)
132 -- What this means is that we obediently inline even things that don't
133 -- look like valuse. This is sometimes important:
136 -- Here, f looks like a redex, and we aren't going to inline (.) because it's
137 -- inside an INLINE, so it'll stay looking like a redex. Nevertheless, we
138 -- should inline f even inside lambdas. In effect, we should trust the programmer.
143 * The RHS of a letrec, and the RHSs of all top-level lets,
144 must be of LIFTED type.
146 * The RHS of a let, may be of UNLIFTED type, but only if the expression
147 is ok-for-speculation. This means that the let can be floated around
148 without difficulty. e.g.
150 y::Int# = fac 4# not ok [use case instead]
152 * The argument of an App can be of any type.
154 * The simplifier tries to ensure that if the RHS of a let is a constructor
155 application, its arguments are trivial, so that the constructor can be
159 %************************************************************************
161 \subsection{Transformation rules}
163 %************************************************************************
165 The CoreRule type and its friends are dealt with mainly in CoreRules,
166 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
171 VarSet -- Locally-defined free vars of RHSs
173 emptyCoreRules :: CoreRules
174 emptyCoreRules = Rules [] emptyVarSet
176 isEmptyCoreRules :: CoreRules -> Bool
177 isEmptyCoreRules (Rules rs _) = null rs
179 rulesRhsFreeVars :: CoreRules -> VarSet
180 rulesRhsFreeVars (Rules _ fvs) = fvs
182 rulesRules :: CoreRules -> [CoreRule]
183 rulesRules (Rules rules _) = rules
187 type RuleName = FastString
188 type IdCoreRule = (Id,CoreRule) -- Rules don't have their leading Id inside them
192 Activation -- When the rule is active
193 [CoreBndr] -- Forall'd variables
194 [CoreExpr] -- LHS args
197 | BuiltinRule -- Built-in rules are used for constant folding
198 RuleName -- and suchlike. It has no free variables.
199 ([CoreExpr] -> Maybe CoreExpr)
201 isBuiltinRule (BuiltinRule _ _) = True
202 isBuiltinRule _ = False
204 ruleName :: CoreRule -> RuleName
205 ruleName (Rule n _ _ _ _) = n
206 ruleName (BuiltinRule n _) = n
210 %************************************************************************
212 \subsection{@Unfolding@ type}
214 %************************************************************************
216 The @Unfolding@ type is declared here to avoid numerous loops, but it
217 should be abstract everywhere except in CoreUnfold.lhs
223 | OtherCon [AltCon] -- It ain't one of these
224 -- (OtherCon xs) also indicates that something has been evaluated
225 -- and hence there's no point in re-evaluating it.
226 -- OtherCon [] is used even for non-data-type values
227 -- to indicated evaluated-ness. Notably:
228 -- data C = C !(Int -> Int)
229 -- case x of { C f -> ... }
230 -- Here, f gets an OtherCon [] unfolding.
232 | CompulsoryUnfolding CoreExpr -- There is no "original" definition,
233 -- so you'd better unfold.
235 | CoreUnfolding -- An unfolding with redundant cached information
236 CoreExpr -- Template; binder-info is correct
237 Bool -- True <=> top level binding
238 Bool -- exprIsValue template (cached); it is ok to discard a `seq` on
240 Bool -- True <=> doesn't waste (much) work to expand inside an inlining
241 -- Basically it's exprIsCheap
242 UnfoldingGuidance -- Tells about the *size* of the template.
245 data UnfoldingGuidance
247 | UnfoldIfGoodArgs Int -- and "n" value args
249 [Int] -- Discount if the argument is evaluated.
250 -- (i.e., a simplification will definitely
251 -- be possible). One elt of the list per *value* arg.
253 Int -- The "size" of the unfolding; to be elaborated
256 Int -- Scrutinee discount: the discount to substract if the thing is in
257 -- a context (case (thing args) of ...),
258 -- (where there are the right number of arguments.)
260 noUnfolding = NoUnfolding
261 mkOtherCon = OtherCon
263 seqUnfolding :: Unfolding -> ()
264 seqUnfolding (CoreUnfolding e top b1 b2 g)
265 = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
266 seqUnfolding other = ()
268 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
269 seqGuidance other = ()
273 unfoldingTemplate :: Unfolding -> CoreExpr
274 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
275 unfoldingTemplate (CompulsoryUnfolding expr) = expr
276 unfoldingTemplate other = panic "getUnfoldingTemplate"
278 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
279 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
280 maybeUnfoldingTemplate (CompulsoryUnfolding expr) = Just expr
281 maybeUnfoldingTemplate other = Nothing
283 otherCons :: Unfolding -> [AltCon]
284 otherCons (OtherCon cons) = cons
287 isValueUnfolding :: Unfolding -> Bool
288 -- Returns False for OtherCon
289 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
290 isValueUnfolding other = False
292 isEvaldUnfolding :: Unfolding -> Bool
293 -- Returns True for OtherCon
294 isEvaldUnfolding (OtherCon _) = True
295 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
296 isEvaldUnfolding other = False
298 isCheapUnfolding :: Unfolding -> Bool
299 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
300 isCheapUnfolding other = False
302 isCompulsoryUnfolding :: Unfolding -> Bool
303 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
304 isCompulsoryUnfolding other = False
306 hasUnfolding :: Unfolding -> Bool
307 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
308 hasUnfolding (CompulsoryUnfolding _) = True
309 hasUnfolding other = False
311 hasSomeUnfolding :: Unfolding -> Bool
312 hasSomeUnfolding NoUnfolding = False
313 hasSomeUnfolding other = True
315 neverUnfold :: Unfolding -> Bool
316 neverUnfold NoUnfolding = True
317 neverUnfold (OtherCon _) = True
318 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
319 neverUnfold other = False
323 %************************************************************************
325 \subsection{The main data type}
327 %************************************************************************
330 -- The Ord is needed for the FiniteMap used in the lookForConstructor
331 -- in SimplEnv. If you declared that lookForConstructor *ignores*
332 -- constructor-applications with LitArg args, then you could get
335 instance Outputable AltCon where
336 ppr (DataAlt dc) = ppr dc
337 ppr (LitAlt lit) = ppr lit
338 ppr DEFAULT = ptext SLIT("__DEFAULT")
340 instance Show AltCon where
341 showsPrec p con = showsPrecSDoc p (ppr con)
345 %************************************************************************
347 \subsection{Useful synonyms}
349 %************************************************************************
355 type CoreExpr = Expr CoreBndr
356 type CoreArg = Arg CoreBndr
357 type CoreBind = Bind CoreBndr
358 type CoreAlt = Alt CoreBndr
361 Binders are ``tagged'' with a \tr{t}:
364 data TaggedBndr t = TB CoreBndr t -- TB for "tagged binder"
366 type TaggedBind t = Bind (TaggedBndr t)
367 type TaggedExpr t = Expr (TaggedBndr t)
368 type TaggedArg t = Arg (TaggedBndr t)
369 type TaggedAlt t = Alt (TaggedBndr t)
371 instance Outputable b => Outputable (TaggedBndr b) where
372 ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>'
374 instance Outputable b => OutputableBndr (TaggedBndr b) where
375 pprBndr _ b = ppr b -- Simple
379 %************************************************************************
381 \subsection{Core-constructing functions with checking}
383 %************************************************************************
386 mkApps :: Expr b -> [Arg b] -> Expr b
387 mkTyApps :: Expr b -> [Type] -> Expr b
388 mkValApps :: Expr b -> [Expr b] -> Expr b
389 mkVarApps :: Expr b -> [Var] -> Expr b
391 mkApps f args = foldl App f args
392 mkTyApps f args = foldl (\ e a -> App e (Type a)) f args
393 mkValApps f args = foldl (\ e a -> App e a) f args
394 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
396 mkLit :: Literal -> Expr b
397 mkIntLit :: Integer -> Expr b
398 mkIntLitInt :: Int -> Expr b
399 mkConApp :: DataCon -> [Arg b] -> Expr b
400 mkLets :: [Bind b] -> Expr b -> Expr b
401 mkLams :: [b] -> Expr b -> Expr b
404 mkConApp con args = mkApps (Var (dataConWorkId con)) args
406 mkLams binders body = foldr Lam body binders
407 mkLets binds body = foldr Let body binds
409 mkIntLit n = Lit (mkMachInt n)
410 mkIntLitInt n = Lit (mkMachInt (toInteger n))
412 varToCoreExpr :: CoreBndr -> Expr b
413 varToCoreExpr v | isId v = Var v
414 | otherwise = Type (mkTyVarTy v)
418 %************************************************************************
420 \subsection{Simple access functions}
422 %************************************************************************
425 bindersOf :: Bind b -> [b]
426 bindersOf (NonRec binder _) = [binder]
427 bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
429 bindersOfBinds :: [Bind b] -> [b]
430 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
432 rhssOfBind :: Bind b -> [Expr b]
433 rhssOfBind (NonRec _ rhs) = [rhs]
434 rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
436 rhssOfAlts :: [Alt b] -> [Expr b]
437 rhssOfAlts alts = [e | (_,_,e) <- alts]
439 flattenBinds :: [Bind b] -> [(b, Expr b)] -- Get all the lhs/rhs pairs
440 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
441 flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
445 We often want to strip off leading lambdas before getting down to
446 business. @collectBinders@ is your friend.
448 We expect (by convention) type-, and value- lambdas in that
452 collectBinders :: Expr b -> ([b], Expr b)
453 collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr)
454 collectValBinders :: CoreExpr -> ([Id], CoreExpr)
455 collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
460 go bs (Lam b e) = go (b:bs) e
461 go bs e = (reverse bs, e)
463 collectTyAndValBinders expr
466 (tvs, body1) = collectTyBinders expr
467 (ids, body) = collectValBinders body1
469 collectTyBinders expr
472 go tvs (Lam b e) | isTyVar b = go (b:tvs) e
473 go tvs e = (reverse tvs, e)
475 collectValBinders expr
478 go ids (Lam b e) | isId b = go (b:ids) e
479 go ids body = (reverse ids, body)
483 @collectArgs@ takes an application expression, returning the function
484 and the arguments to which it is applied.
487 collectArgs :: Expr b -> (Expr b, [Arg b])
491 go (App f a) as = go f (a:as)
495 coreExprCc gets the cost centre enclosing an expression, if any.
496 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
499 coreExprCc :: Expr b -> CostCentre
500 coreExprCc (Note (SCC cc) e) = cc
501 coreExprCc (Note other_note e) = coreExprCc e
502 coreExprCc (Lam _ e) = coreExprCc e
503 coreExprCc other = noCostCentre
508 %************************************************************************
510 \subsection{Predicates}
512 %************************************************************************
514 @isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
515 i.e. if type applications are actual lambdas because types are kept around
518 Similarly isRuntimeArg.
521 isRuntimeVar :: Var -> Bool
522 isRuntimeVar | opt_RuntimeTypes = \v -> True
523 | otherwise = \v -> isId v
525 isRuntimeArg :: CoreExpr -> Bool
526 isRuntimeArg | opt_RuntimeTypes = \e -> True
527 | otherwise = \e -> isValArg e
531 isValArg (Type _) = False
532 isValArg other = True
534 isTypeArg (Type _) = True
535 isTypeArg other = False
537 valBndrCount :: [CoreBndr] -> Int
539 valBndrCount (b : bs) | isId b = 1 + valBndrCount bs
540 | otherwise = valBndrCount bs
542 valArgCount :: [Arg b] -> Int
544 valArgCount (Type _ : args) = valArgCount args
545 valArgCount (other : args) = 1 + valArgCount args
549 %************************************************************************
551 \subsection{Seq stuff}
553 %************************************************************************
556 seqExpr :: CoreExpr -> ()
557 seqExpr (Var v) = v `seq` ()
558 seqExpr (Lit lit) = lit `seq` ()
559 seqExpr (App f a) = seqExpr f `seq` seqExpr a
560 seqExpr (Lam b e) = seqBndr b `seq` seqExpr e
561 seqExpr (Let b e) = seqBind b `seq` seqExpr e
562 seqExpr (Case e b as) = seqExpr e `seq` seqBndr b `seq` seqAlts as
563 seqExpr (Note n e) = seqNote n `seq` seqExpr e
564 seqExpr (Type t) = seqType t
567 seqExprs (e:es) = seqExpr e `seq` seqExprs es
569 seqNote (Coerce t1 t2) = seqType t1 `seq` seqType t2
570 seqNote (CoreNote s) = s `seq` ()
573 seqBndr b = b `seq` ()
576 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
578 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
579 seqBind (Rec prs) = seqPairs prs
582 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
585 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
587 seqRules :: CoreRules -> ()
588 seqRules (Rules rules fvs) = seq_rules rules `seq` seqVarSet fvs
591 seq_rules (Rule fs _ bs es e : rules) = seqBndrs bs `seq` seqExprs (e:es) `seq` seq_rules rules
592 seq_rules (BuiltinRule _ _ : rules) = seq_rules rules
597 %************************************************************************
599 \subsection{Annotated core; annotation at every node in the tree}
601 %************************************************************************
604 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
606 data AnnExpr' bndr annot
609 | AnnLam bndr (AnnExpr bndr annot)
610 | AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
611 | AnnCase (AnnExpr bndr annot) bndr [AnnAlt bndr annot]
612 | AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
613 | AnnNote Note (AnnExpr bndr annot)
616 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
618 data AnnBind bndr annot
619 = AnnNonRec bndr (AnnExpr bndr annot)
620 | AnnRec [(bndr, AnnExpr bndr annot)]
624 deAnnotate :: AnnExpr bndr annot -> Expr bndr
625 deAnnotate (_, e) = deAnnotate' e
627 deAnnotate' (AnnType t) = Type t
628 deAnnotate' (AnnVar v) = Var v
629 deAnnotate' (AnnLit lit) = Lit lit
630 deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
631 deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
632 deAnnotate' (AnnNote note body) = Note note (deAnnotate body)
634 deAnnotate' (AnnLet bind body)
635 = Let (deAnnBind bind) (deAnnotate body)
637 deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
638 deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
640 deAnnotate' (AnnCase scrut v alts)
641 = Case (deAnnotate scrut) v (map deAnnAlt alts)
643 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
644 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
648 collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot)
652 collect bs (_, AnnLam b body) = collect (b:bs) body
653 collect bs body = (reverse bs, body)