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,
18 isTyVar, isId, cmpAltCon, cmpAlt, ltAlt,
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
44 IdCoreRule(..), isOrphanRule,
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, dataConTag )
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 Type [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
87 -- Invariant: The remaining cases are in order of increasing
90 -- This makes finding the relevant constructor easy,
91 -- and makes comparison easier too
93 | Type Type -- This should only show up at the top
96 -- An "exhausive" case does not necessarily mention all constructors:
97 -- data Foo = Red | Green | Blue
101 -- other -> f (case x of
104 -- The inner case does not need a Red alternative, because x can't be Red at
105 -- that program point.
108 type Arg b = Expr b -- Can be a Type
110 type Alt b = (AltCon, [b], Expr b) -- (DEFAULT, [], rhs) is the default alternative
112 data AltCon = DataAlt DataCon
118 data Bind b = NonRec b (Expr b)
119 | Rec [(b, (Expr b))]
125 Type -- The to-type: type of whole coerce expression
126 Type -- The from-type: type of enclosed expression
128 | InlineCall -- Instructs simplifier to inline
131 | InlineMe -- Instructs simplifer to treat the enclosed expression
132 -- as very small, and inline it at its call sites
134 | CoreNote String -- A generic core annotation, propagated but not used by GHC
136 -- NOTE: we also treat expressions wrapped in InlineMe as
137 -- 'cheap' and 'dupable' (in the sense of exprIsCheap, exprIsDupable)
138 -- What this means is that we obediently inline even things that don't
139 -- look like valuse. This is sometimes important:
142 -- Here, f looks like a redex, and we aren't going to inline (.) because it's
143 -- inside an INLINE, so it'll stay looking like a redex. Nevertheless, we
144 -- should inline f even inside lambdas. In effect, we should trust the programmer.
149 * The RHS of a letrec, and the RHSs of all top-level lets,
150 must be of LIFTED type.
152 * The RHS of a let, may be of UNLIFTED type, but only if the expression
153 is ok-for-speculation. This means that the let can be floated around
154 without difficulty. e.g.
156 y::Int# = fac 4# not ok [use case instead]
158 * The argument of an App can be of any type.
160 * The simplifier tries to ensure that if the RHS of a let is a constructor
161 application, its arguments are trivial, so that the constructor can be
165 %************************************************************************
167 \subsection{Transformation rules}
169 %************************************************************************
171 The CoreRule type and its friends are dealt with mainly in CoreRules,
172 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
177 VarSet -- Locally-defined free vars of RHSs
179 emptyCoreRules :: CoreRules
180 emptyCoreRules = Rules [] emptyVarSet
182 isEmptyCoreRules :: CoreRules -> Bool
183 isEmptyCoreRules (Rules rs _) = null rs
185 rulesRhsFreeVars :: CoreRules -> VarSet
186 rulesRhsFreeVars (Rules _ fvs) = fvs
188 rulesRules :: CoreRules -> [CoreRule]
189 rulesRules (Rules rules _) = rules
193 type RuleName = FastString
194 data IdCoreRule = IdCoreRule Id -- A rule for this Id
195 Bool -- True <=> orphan rule
196 CoreRule -- The rule itself
198 isOrphanRule :: IdCoreRule -> Bool
199 isOrphanRule (IdCoreRule _ is_orphan _) = is_orphan
203 Activation -- When the rule is active
204 [CoreBndr] -- Forall'd variables
205 [CoreExpr] -- LHS args
208 | BuiltinRule -- Built-in rules are used for constant folding
209 RuleName -- and suchlike. It has no free variables.
210 ([CoreExpr] -> Maybe CoreExpr)
212 isBuiltinRule (BuiltinRule _ _) = True
213 isBuiltinRule _ = False
215 ruleName :: CoreRule -> RuleName
216 ruleName (Rule n _ _ _ _) = n
217 ruleName (BuiltinRule n _) = n
221 %************************************************************************
223 \subsection{@Unfolding@ type}
225 %************************************************************************
227 The @Unfolding@ type is declared here to avoid numerous loops, but it
228 should be abstract everywhere except in CoreUnfold.lhs
234 | OtherCon [AltCon] -- It ain't one of these
235 -- (OtherCon xs) also indicates that something has been evaluated
236 -- and hence there's no point in re-evaluating it.
237 -- OtherCon [] is used even for non-data-type values
238 -- to indicated evaluated-ness. Notably:
239 -- data C = C !(Int -> Int)
240 -- case x of { C f -> ... }
241 -- Here, f gets an OtherCon [] unfolding.
243 | CompulsoryUnfolding CoreExpr -- There is no "original" definition,
244 -- so you'd better unfold.
246 | CoreUnfolding -- An unfolding with redundant cached information
247 CoreExpr -- Template; binder-info is correct
248 Bool -- True <=> top level binding
249 Bool -- exprIsValue template (cached); it is ok to discard a `seq` on
251 Bool -- True <=> doesn't waste (much) work to expand inside an inlining
252 -- Basically it's exprIsCheap
253 UnfoldingGuidance -- Tells about the *size* of the template.
256 data UnfoldingGuidance
258 | UnfoldIfGoodArgs Int -- and "n" value args
260 [Int] -- Discount if the argument is evaluated.
261 -- (i.e., a simplification will definitely
262 -- be possible). One elt of the list per *value* arg.
264 Int -- The "size" of the unfolding; to be elaborated
267 Int -- Scrutinee discount: the discount to substract if the thing is in
268 -- a context (case (thing args) of ...),
269 -- (where there are the right number of arguments.)
271 noUnfolding = NoUnfolding
272 mkOtherCon = OtherCon
274 seqUnfolding :: Unfolding -> ()
275 seqUnfolding (CoreUnfolding e top b1 b2 g)
276 = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
277 seqUnfolding other = ()
279 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
280 seqGuidance other = ()
284 unfoldingTemplate :: Unfolding -> CoreExpr
285 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
286 unfoldingTemplate (CompulsoryUnfolding expr) = expr
287 unfoldingTemplate other = panic "getUnfoldingTemplate"
289 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
290 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
291 maybeUnfoldingTemplate (CompulsoryUnfolding expr) = Just expr
292 maybeUnfoldingTemplate other = Nothing
294 otherCons :: Unfolding -> [AltCon]
295 otherCons (OtherCon cons) = cons
298 isValueUnfolding :: Unfolding -> Bool
299 -- Returns False for OtherCon
300 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
301 isValueUnfolding other = False
303 isEvaldUnfolding :: Unfolding -> Bool
304 -- Returns True for OtherCon
305 isEvaldUnfolding (OtherCon _) = True
306 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
307 isEvaldUnfolding other = False
309 isCheapUnfolding :: Unfolding -> Bool
310 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
311 isCheapUnfolding other = False
313 isCompulsoryUnfolding :: Unfolding -> Bool
314 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
315 isCompulsoryUnfolding other = False
317 hasUnfolding :: Unfolding -> Bool
318 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
319 hasUnfolding (CompulsoryUnfolding _) = True
320 hasUnfolding other = False
322 hasSomeUnfolding :: Unfolding -> Bool
323 hasSomeUnfolding NoUnfolding = False
324 hasSomeUnfolding other = True
326 neverUnfold :: Unfolding -> Bool
327 neverUnfold NoUnfolding = True
328 neverUnfold (OtherCon _) = True
329 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
330 neverUnfold other = False
334 %************************************************************************
336 \subsection{The main data type}
338 %************************************************************************
341 -- The Ord is needed for the FiniteMap used in the lookForConstructor
342 -- in SimplEnv. If you declared that lookForConstructor *ignores*
343 -- constructor-applications with LitArg args, then you could get
346 instance Outputable AltCon where
347 ppr (DataAlt dc) = ppr dc
348 ppr (LitAlt lit) = ppr lit
349 ppr DEFAULT = ptext SLIT("__DEFAULT")
351 instance Show AltCon where
352 showsPrec p con = showsPrecSDoc p (ppr con)
354 cmpAlt :: Alt b -> Alt b -> Ordering
355 cmpAlt (con1, _, _) (con2, _, _) = con1 `cmpAltCon` con2
357 ltAlt :: Alt b -> Alt b -> Bool
358 ltAlt a1 a2 = case a1 `cmpAlt` a2 of { LT -> True; other -> False }
360 cmpAltCon :: AltCon -> AltCon -> Ordering
361 -- Compares AltCons within a single list of alternatives
362 cmpAltCon DEFAULT DEFAULT = EQ
363 cmpAltCon DEFAULT con = LT
365 cmpAltCon (DataAlt d1) (DataAlt d2) = dataConTag d1 `compare` dataConTag d2
366 cmpAltCon (DataAlt _) DEFAULT = GT
367 cmpAltCon (LitAlt l1) (LitAlt l2) = l1 `compare` l2
368 cmpAltCon (LitAlt _) DEFAULT = GT
370 cmpAltCon con1 con2 = WARN( True, text "Comparing incomparable AltCons" <+>
371 ppr con1 <+> ppr con2 )
376 %************************************************************************
378 \subsection{Useful synonyms}
380 %************************************************************************
386 type CoreExpr = Expr CoreBndr
387 type CoreArg = Arg CoreBndr
388 type CoreBind = Bind CoreBndr
389 type CoreAlt = Alt CoreBndr
392 Binders are ``tagged'' with a \tr{t}:
395 data TaggedBndr t = TB CoreBndr t -- TB for "tagged binder"
397 type TaggedBind t = Bind (TaggedBndr t)
398 type TaggedExpr t = Expr (TaggedBndr t)
399 type TaggedArg t = Arg (TaggedBndr t)
400 type TaggedAlt t = Alt (TaggedBndr t)
402 instance Outputable b => Outputable (TaggedBndr b) where
403 ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>'
405 instance Outputable b => OutputableBndr (TaggedBndr b) where
406 pprBndr _ b = ppr b -- Simple
410 %************************************************************************
412 \subsection{Core-constructing functions with checking}
414 %************************************************************************
417 mkApps :: Expr b -> [Arg b] -> Expr b
418 mkTyApps :: Expr b -> [Type] -> Expr b
419 mkValApps :: Expr b -> [Expr b] -> Expr b
420 mkVarApps :: Expr b -> [Var] -> Expr b
422 mkApps f args = foldl App f args
423 mkTyApps f args = foldl (\ e a -> App e (Type a)) f args
424 mkValApps f args = foldl (\ e a -> App e a) f args
425 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
427 mkLit :: Literal -> Expr b
428 mkIntLit :: Integer -> Expr b
429 mkIntLitInt :: Int -> Expr b
430 mkConApp :: DataCon -> [Arg b] -> Expr b
431 mkLets :: [Bind b] -> Expr b -> Expr b
432 mkLams :: [b] -> Expr b -> Expr b
435 mkConApp con args = mkApps (Var (dataConWorkId con)) args
437 mkLams binders body = foldr Lam body binders
438 mkLets binds body = foldr Let body binds
440 mkIntLit n = Lit (mkMachInt n)
441 mkIntLitInt n = Lit (mkMachInt (toInteger n))
443 varToCoreExpr :: CoreBndr -> Expr b
444 varToCoreExpr v | isId v = Var v
445 | otherwise = Type (mkTyVarTy v)
449 %************************************************************************
451 \subsection{Simple access functions}
453 %************************************************************************
456 bindersOf :: Bind b -> [b]
457 bindersOf (NonRec binder _) = [binder]
458 bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
460 bindersOfBinds :: [Bind b] -> [b]
461 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
463 rhssOfBind :: Bind b -> [Expr b]
464 rhssOfBind (NonRec _ rhs) = [rhs]
465 rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
467 rhssOfAlts :: [Alt b] -> [Expr b]
468 rhssOfAlts alts = [e | (_,_,e) <- alts]
470 flattenBinds :: [Bind b] -> [(b, Expr b)] -- Get all the lhs/rhs pairs
471 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
472 flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
476 We often want to strip off leading lambdas before getting down to
477 business. @collectBinders@ is your friend.
479 We expect (by convention) type-, and value- lambdas in that
483 collectBinders :: Expr b -> ([b], Expr b)
484 collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr)
485 collectValBinders :: CoreExpr -> ([Id], CoreExpr)
486 collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
491 go bs (Lam b e) = go (b:bs) e
492 go bs e = (reverse bs, e)
494 collectTyAndValBinders expr
497 (tvs, body1) = collectTyBinders expr
498 (ids, body) = collectValBinders body1
500 collectTyBinders expr
503 go tvs (Lam b e) | isTyVar b = go (b:tvs) e
504 go tvs e = (reverse tvs, e)
506 collectValBinders expr
509 go ids (Lam b e) | isId b = go (b:ids) e
510 go ids body = (reverse ids, body)
514 @collectArgs@ takes an application expression, returning the function
515 and the arguments to which it is applied.
518 collectArgs :: Expr b -> (Expr b, [Arg b])
522 go (App f a) as = go f (a:as)
526 coreExprCc gets the cost centre enclosing an expression, if any.
527 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
530 coreExprCc :: Expr b -> CostCentre
531 coreExprCc (Note (SCC cc) e) = cc
532 coreExprCc (Note other_note e) = coreExprCc e
533 coreExprCc (Lam _ e) = coreExprCc e
534 coreExprCc other = noCostCentre
539 %************************************************************************
541 \subsection{Predicates}
543 %************************************************************************
545 @isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
546 i.e. if type applications are actual lambdas because types are kept around
549 Similarly isRuntimeArg.
552 isRuntimeVar :: Var -> Bool
553 isRuntimeVar | opt_RuntimeTypes = \v -> True
554 | otherwise = \v -> isId v
556 isRuntimeArg :: CoreExpr -> Bool
557 isRuntimeArg | opt_RuntimeTypes = \e -> True
558 | otherwise = \e -> isValArg e
562 isValArg (Type _) = False
563 isValArg other = True
565 isTypeArg (Type _) = True
566 isTypeArg other = False
568 valBndrCount :: [CoreBndr] -> Int
570 valBndrCount (b : bs) | isId b = 1 + valBndrCount bs
571 | otherwise = valBndrCount bs
573 valArgCount :: [Arg b] -> Int
575 valArgCount (Type _ : args) = valArgCount args
576 valArgCount (other : args) = 1 + valArgCount args
580 %************************************************************************
582 \subsection{Seq stuff}
584 %************************************************************************
587 seqExpr :: CoreExpr -> ()
588 seqExpr (Var v) = v `seq` ()
589 seqExpr (Lit lit) = lit `seq` ()
590 seqExpr (App f a) = seqExpr f `seq` seqExpr a
591 seqExpr (Lam b e) = seqBndr b `seq` seqExpr e
592 seqExpr (Let b e) = seqBind b `seq` seqExpr e
594 seqExpr (Case e b t as) = seqExpr e `seq` seqBndr b `seq` seqType t `seq` seqAlts as
595 seqExpr (Note n e) = seqNote n `seq` seqExpr e
596 seqExpr (Type t) = seqType t
599 seqExprs (e:es) = seqExpr e `seq` seqExprs es
601 seqNote (Coerce t1 t2) = seqType t1 `seq` seqType t2
602 seqNote (CoreNote s) = s `seq` ()
605 seqBndr b = b `seq` ()
608 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
610 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
611 seqBind (Rec prs) = seqPairs prs
614 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
617 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
619 seqRules :: CoreRules -> ()
620 seqRules (Rules rules fvs) = seq_rules rules `seq` seqVarSet fvs
623 seq_rules (Rule fs _ bs es e : rules) = seqBndrs bs `seq` seqExprs (e:es) `seq` seq_rules rules
624 seq_rules (BuiltinRule _ _ : rules) = seq_rules rules
629 %************************************************************************
631 \subsection{Annotated core; annotation at every node in the tree}
633 %************************************************************************
636 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
638 data AnnExpr' bndr annot
641 | AnnLam bndr (AnnExpr bndr annot)
642 | AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
644 | AnnCase (AnnExpr bndr annot) bndr Type [AnnAlt bndr annot]
645 | AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
646 | AnnNote Note (AnnExpr bndr annot)
649 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
651 data AnnBind bndr annot
652 = AnnNonRec bndr (AnnExpr bndr annot)
653 | AnnRec [(bndr, AnnExpr bndr annot)]
657 deAnnotate :: AnnExpr bndr annot -> Expr bndr
658 deAnnotate (_, e) = deAnnotate' e
660 deAnnotate' (AnnType t) = Type t
661 deAnnotate' (AnnVar v) = Var v
662 deAnnotate' (AnnLit lit) = Lit lit
663 deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
664 deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
665 deAnnotate' (AnnNote note body) = Note note (deAnnotate body)
667 deAnnotate' (AnnLet bind body)
668 = Let (deAnnBind bind) (deAnnotate body)
670 deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
671 deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
674 deAnnotate' (AnnCase scrut v t alts)
675 = Case (deAnnotate scrut) v t (map deAnnAlt alts)
677 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
678 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
682 collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot)
686 collect bs (_, AnnLam b body) = collect (b:bs) body
687 collect bs body = (reverse bs, body)