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,
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,
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, dataConId )
58 import BasicTypes ( Activation )
63 %************************************************************************
65 \subsection{The main data types}
67 %************************************************************************
69 These data types are the heart of the compiler
72 infixl 8 `App` -- App brackets to the left
74 data Expr b -- "b" for the type of binders,
77 | App (Expr b) (Arg b)
79 | Let (Bind b) (Expr b)
80 | Case (Expr b) b [Alt b] -- Binder gets bound to value of scrutinee
81 -- DEFAULT case must be *first*, if it occurs at all
83 | Type Type -- This should only show up at the top
86 type Arg b = Expr b -- Can be a Type
88 type Alt b = (AltCon, [b], Expr b) -- (DEFAULT, [], rhs) is the default alternative
90 data AltCon = DataAlt DataCon
95 data Bind b = NonRec b (Expr b)
102 Type -- The to-type: type of whole coerce expression
103 Type -- The from-type: type of enclosed expression
105 | InlineCall -- Instructs simplifier to inline
108 | InlineMe -- Instructs simplifer to treat the enclosed expression
109 -- as very small, and inline it at its call sites
111 -- NOTE: we also treat expressions wrapped in InlineMe as
112 -- 'cheap' and 'dupable' (in the sense of exprIsCheap, exprIsDupable)
113 -- What this means is that we obediently inline even things that don't
114 -- look like valuse. This is sometimes important:
117 -- Here, f looks like a redex, and we aren't going to inline (.) because it's
118 -- inside an INLINE, so it'll stay looking like a redex. Nevertheless, we
119 -- should inline f even inside lambdas. In effect, we should trust the programmer.
124 * The RHS of a letrec, and the RHSs of all top-level lets,
125 must be of LIFTED type.
127 * The RHS of a let, may be of UNLIFTED type, but only if the expression
128 is ok-for-speculation. This means that the let can be floated around
129 without difficulty. e.g.
131 y::Int# = fac 4# not ok [use case instead]
133 * The argument of an App can be of any type.
135 * The simplifier tries to ensure that if the RHS of a let is a constructor
136 application, its arguments are trivial, so that the constructor can be
140 %************************************************************************
142 \subsection{Transformation rules}
144 %************************************************************************
146 The CoreRule type and its friends are dealt with mainly in CoreRules,
147 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
152 VarSet -- Locally-defined free vars of RHSs
154 emptyCoreRules :: CoreRules
155 emptyCoreRules = Rules [] emptyVarSet
157 isEmptyCoreRules :: CoreRules -> Bool
158 isEmptyCoreRules (Rules rs _) = null rs
160 rulesRhsFreeVars :: CoreRules -> VarSet
161 rulesRhsFreeVars (Rules _ fvs) = fvs
163 rulesRules :: CoreRules -> [CoreRule]
164 rulesRules (Rules rules _) = rules
168 type RuleName = FAST_STRING
169 type IdCoreRule = (Id,CoreRule) -- Rules don't have their leading Id inside them
173 Activation -- When the rule is active
174 [CoreBndr] -- Forall'd variables
175 [CoreExpr] -- LHS args
178 | BuiltinRule -- Built-in rules are used for constant folding
179 RuleName -- and suchlike. It has no free variables.
180 ([CoreExpr] -> Maybe CoreExpr)
182 isBuiltinRule (BuiltinRule _ _) = True
183 isBuiltinRule _ = False
185 ruleName :: CoreRule -> RuleName
186 ruleName (Rule n _ _ _ _) = n
187 ruleName (BuiltinRule n _) = n
191 %************************************************************************
193 \subsection{@Unfolding@ type}
195 %************************************************************************
197 The @Unfolding@ type is declared here to avoid numerous loops, but it
198 should be abstract everywhere except in CoreUnfold.lhs
204 | OtherCon [AltCon] -- It ain't one of these
205 -- (OtherCon xs) also indicates that something has been evaluated
206 -- and hence there's no point in re-evaluating it.
207 -- OtherCon [] is used even for non-data-type values
208 -- to indicated evaluated-ness. Notably:
209 -- data C = C !(Int -> Int)
210 -- case x of { C f -> ... }
211 -- Here, f gets an OtherCon [] unfolding.
213 | CompulsoryUnfolding CoreExpr -- There is no "original" definition,
214 -- so you'd better unfold.
216 | CoreUnfolding -- An unfolding with redundant cached information
217 CoreExpr -- Template; binder-info is correct
218 Bool -- True <=> top level binding
219 Bool -- exprIsValue template (cached); it is ok to discard a `seq` on
221 Bool -- True <=> doesn't waste (much) work to expand inside an inlining
222 -- Basically it's exprIsCheap
223 UnfoldingGuidance -- Tells about the *size* of the template.
226 data UnfoldingGuidance
228 | UnfoldIfGoodArgs Int -- and "n" value args
230 [Int] -- Discount if the argument is evaluated.
231 -- (i.e., a simplification will definitely
232 -- be possible). One elt of the list per *value* arg.
234 Int -- The "size" of the unfolding; to be elaborated
237 Int -- Scrutinee discount: the discount to substract if the thing is in
238 -- a context (case (thing args) of ...),
239 -- (where there are the right number of arguments.)
241 noUnfolding = NoUnfolding
242 mkOtherCon = OtherCon
244 seqUnfolding :: Unfolding -> ()
245 seqUnfolding (CoreUnfolding e top b1 b2 g)
246 = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
247 seqUnfolding other = ()
249 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
250 seqGuidance other = ()
254 unfoldingTemplate :: Unfolding -> CoreExpr
255 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
256 unfoldingTemplate (CompulsoryUnfolding expr) = expr
257 unfoldingTemplate other = panic "getUnfoldingTemplate"
259 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
260 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
261 maybeUnfoldingTemplate (CompulsoryUnfolding expr) = Just expr
262 maybeUnfoldingTemplate other = Nothing
264 otherCons :: Unfolding -> [AltCon]
265 otherCons (OtherCon cons) = cons
268 isValueUnfolding :: Unfolding -> Bool
269 -- Returns False for OtherCon
270 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
271 isValueUnfolding other = False
273 isEvaldUnfolding :: Unfolding -> Bool
274 -- Returns True for OtherCon
275 isEvaldUnfolding (OtherCon _) = True
276 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
277 isEvaldUnfolding other = False
279 isCheapUnfolding :: Unfolding -> Bool
280 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
281 isCheapUnfolding other = False
283 isCompulsoryUnfolding :: Unfolding -> Bool
284 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
285 isCompulsoryUnfolding other = False
287 hasUnfolding :: Unfolding -> Bool
288 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
289 hasUnfolding (CompulsoryUnfolding _) = True
290 hasUnfolding other = False
292 hasSomeUnfolding :: Unfolding -> Bool
293 hasSomeUnfolding NoUnfolding = False
294 hasSomeUnfolding other = True
296 neverUnfold :: Unfolding -> Bool
297 neverUnfold NoUnfolding = True
298 neverUnfold (OtherCon _) = True
299 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
300 neverUnfold other = False
304 %************************************************************************
306 \subsection{The main data type}
308 %************************************************************************
311 -- The Ord is needed for the FiniteMap used in the lookForConstructor
312 -- in SimplEnv. If you declared that lookForConstructor *ignores*
313 -- constructor-applications with LitArg args, then you could get
316 instance Outputable AltCon where
317 ppr (DataAlt dc) = ppr dc
318 ppr (LitAlt lit) = ppr lit
319 ppr DEFAULT = ptext SLIT("__DEFAULT")
321 instance Show AltCon where
322 showsPrec p con = showsPrecSDoc p (ppr con)
326 %************************************************************************
328 \subsection{Useful synonyms}
330 %************************************************************************
336 type CoreExpr = Expr CoreBndr
337 type CoreArg = Arg CoreBndr
338 type CoreBind = Bind CoreBndr
339 type CoreAlt = Alt CoreBndr
342 Binders are ``tagged'' with a \tr{t}:
345 type Tagged t = (CoreBndr, t)
347 type TaggedBind t = Bind (Tagged t)
348 type TaggedExpr t = Expr (Tagged t)
349 type TaggedArg t = Arg (Tagged t)
350 type TaggedAlt t = Alt (Tagged t)
354 %************************************************************************
356 \subsection{Core-constructing functions with checking}
358 %************************************************************************
361 mkApps :: Expr b -> [Arg b] -> Expr b
362 mkTyApps :: Expr b -> [Type] -> Expr b
363 mkValApps :: Expr b -> [Expr b] -> Expr b
364 mkVarApps :: Expr b -> [Var] -> Expr b
366 mkApps f args = foldl App f args
367 mkTyApps f args = foldl (\ e a -> App e (Type a)) f args
368 mkValApps f args = foldl (\ e a -> App e a) f args
369 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
371 mkLit :: Literal -> Expr b
372 mkIntLit :: Integer -> Expr b
373 mkIntLitInt :: Int -> Expr b
374 mkConApp :: DataCon -> [Arg b] -> Expr b
375 mkLets :: [Bind b] -> Expr b -> Expr b
376 mkLams :: [b] -> Expr b -> Expr b
379 mkConApp con args = mkApps (Var (dataConId con)) args
381 mkLams binders body = foldr Lam body binders
382 mkLets binds body = foldr Let body binds
384 mkIntLit n = Lit (mkMachInt n)
385 mkIntLitInt n = Lit (mkMachInt (toInteger n))
387 varToCoreExpr :: CoreBndr -> Expr b
388 varToCoreExpr v | isId v = Var v
389 | otherwise = Type (mkTyVarTy v)
393 %************************************************************************
395 \subsection{Simple access functions}
397 %************************************************************************
400 bindersOf :: Bind b -> [b]
401 bindersOf (NonRec binder _) = [binder]
402 bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
404 bindersOfBinds :: [Bind b] -> [b]
405 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
407 rhssOfBind :: Bind b -> [Expr b]
408 rhssOfBind (NonRec _ rhs) = [rhs]
409 rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
411 rhssOfAlts :: [Alt b] -> [Expr b]
412 rhssOfAlts alts = [e | (_,_,e) <- alts]
414 flattenBinds :: [Bind b] -> [(b, Expr b)] -- Get all the lhs/rhs pairs
415 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
416 flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
420 We often want to strip off leading lambdas before getting down to
421 business. @collectBinders@ is your friend.
423 We expect (by convention) type-, and value- lambdas in that
427 collectBinders :: Expr b -> ([b], Expr b)
428 collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr)
429 collectValBinders :: CoreExpr -> ([Id], CoreExpr)
430 collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
435 go bs (Lam b e) = go (b:bs) e
436 go bs e = (reverse bs, e)
438 collectTyAndValBinders expr
441 (tvs, body1) = collectTyBinders expr
442 (ids, body) = collectValBinders body1
444 collectTyBinders expr
447 go tvs (Lam b e) | isTyVar b = go (b:tvs) e
448 go tvs e = (reverse tvs, e)
450 collectValBinders expr
453 go ids (Lam b e) | isId b = go (b:ids) e
454 go ids body = (reverse ids, body)
458 @collectArgs@ takes an application expression, returning the function
459 and the arguments to which it is applied.
462 collectArgs :: Expr b -> (Expr b, [Arg b])
466 go (App f a) as = go f (a:as)
470 coreExprCc gets the cost centre enclosing an expression, if any.
471 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
474 coreExprCc :: Expr b -> CostCentre
475 coreExprCc (Note (SCC cc) e) = cc
476 coreExprCc (Note other_note e) = coreExprCc e
477 coreExprCc (Lam _ e) = coreExprCc e
478 coreExprCc other = noCostCentre
483 %************************************************************************
485 \subsection{Predicates}
487 %************************************************************************
489 @isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
490 i.e. if type applications are actual lambdas because types are kept around
493 Similarly isRuntimeArg.
496 isRuntimeVar :: Var -> Bool
497 isRuntimeVar | opt_RuntimeTypes = \v -> True
498 | otherwise = \v -> isId v
500 isRuntimeArg :: CoreExpr -> Bool
501 isRuntimeArg | opt_RuntimeTypes = \e -> True
502 | otherwise = \e -> isValArg e
506 isValArg (Type _) = False
507 isValArg other = True
509 isTypeArg (Type _) = True
510 isTypeArg other = False
512 valBndrCount :: [CoreBndr] -> Int
514 valBndrCount (b : bs) | isId b = 1 + valBndrCount bs
515 | otherwise = valBndrCount bs
517 valArgCount :: [Arg b] -> Int
519 valArgCount (Type _ : args) = valArgCount args
520 valArgCount (other : args) = 1 + valArgCount args
524 %************************************************************************
526 \subsection{Seq stuff}
528 %************************************************************************
531 seqExpr :: CoreExpr -> ()
532 seqExpr (Var v) = v `seq` ()
533 seqExpr (Lit lit) = lit `seq` ()
534 seqExpr (App f a) = seqExpr f `seq` seqExpr a
535 seqExpr (Lam b e) = seqBndr b `seq` seqExpr e
536 seqExpr (Let b e) = seqBind b `seq` seqExpr e
537 seqExpr (Case e b as) = seqExpr e `seq` seqBndr b `seq` seqAlts as
538 seqExpr (Note n e) = seqNote n `seq` seqExpr e
539 seqExpr (Type t) = seqType t
542 seqExprs (e:es) = seqExpr e `seq` seqExprs es
544 seqNote (Coerce t1 t2) = seqType t1 `seq` seqType t2
547 seqBndr b = b `seq` ()
550 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
552 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
553 seqBind (Rec prs) = seqPairs prs
556 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
559 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
561 seqRules :: CoreRules -> ()
562 seqRules (Rules rules fvs) = seq_rules rules `seq` seqVarSet fvs
565 seq_rules (Rule fs _ bs es e : rules) = seqBndrs bs `seq` seqExprs (e:es) `seq` seq_rules rules
566 seq_rules (BuiltinRule _ _ : rules) = seq_rules rules
571 %************************************************************************
573 \subsection{Annotated core; annotation at every node in the tree}
575 %************************************************************************
578 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
580 data AnnExpr' bndr annot
583 | AnnLam bndr (AnnExpr bndr annot)
584 | AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
585 | AnnCase (AnnExpr bndr annot) bndr [AnnAlt bndr annot]
586 | AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
587 | AnnNote Note (AnnExpr bndr annot)
590 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
592 data AnnBind bndr annot
593 = AnnNonRec bndr (AnnExpr bndr annot)
594 | AnnRec [(bndr, AnnExpr bndr annot)]
598 deAnnotate :: AnnExpr bndr annot -> Expr bndr
599 deAnnotate (_, e) = deAnnotate' e
601 deAnnotate' (AnnType t) = Type t
602 deAnnotate' (AnnVar v) = Var v
603 deAnnotate' (AnnLit lit) = Lit lit
604 deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
605 deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
606 deAnnotate' (AnnNote note body) = Note note (deAnnotate body)
608 deAnnotate' (AnnLet bind body)
609 = Let (deAnnBind bind) (deAnnotate body)
611 deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
612 deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
614 deAnnotate' (AnnCase scrut v alts)
615 = Case (deAnnotate scrut) v (map deAnnAlt alts)
617 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
618 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)