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,
21 collectArgs, collectBindersIgnoringNotes,
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 )
62 %************************************************************************
64 \subsection{The main data types}
66 %************************************************************************
68 These data types are the heart of the compiler
71 infixl 8 `App` -- App brackets to the left
73 data Expr b -- "b" for the type of binders,
76 | App (Expr b) (Arg b)
78 | Let (Bind b) (Expr b)
79 | Case (Expr b) b [Alt b] -- Binder gets bound to value of scrutinee
80 -- DEFAULT case must be *first*, if it occurs at all
82 | Type Type -- This should only show up at the top
85 type Arg b = Expr b -- Can be a Type
87 type Alt b = (AltCon, [b], Expr b) -- (DEFAULT, [], rhs) is the default alternative
89 data AltCon = DataAlt DataCon
94 data Bind b = NonRec b (Expr b)
101 Type -- The to-type: type of whole coerce expression
102 Type -- The from-type: type of enclosed expression
104 | InlineCall -- Instructs simplifier to inline
107 | InlineMe -- Instructs simplifer to treat the enclosed expression
108 -- as very small, and inline it at its call sites
110 -- NOTE: we also treat expressions wrapped in InlineMe as
111 -- 'cheap' and 'dupable' (in the sense of exprIsCheap, exprIsDupable)
112 -- What this means is that we obediently inline even things that don't
113 -- look like valuse. This is sometimes important:
116 -- Here, f looks like a redex, and we aren't going to inline (.) because it's
117 -- inside an INLINE, so it'll stay looking like a redex. Nevertheless, we
118 -- should inline f even inside lambdas. In effect, we should trust the programmer.
123 * The RHS of a letrec, and the RHSs of all top-level lets,
124 must be of LIFTED type.
126 * The RHS of a let, may be of UNLIFTED type, but only if the expression
127 is ok-for-speculation. This means that the let can be floated around
128 without difficulty. e.g.
130 y::Int# = fac 4# not ok [use case instead]
132 * The argument of an App can be of any type.
134 * The simplifier tries to ensure that if the RHS of a let is a constructor
135 application, its arguments are trivial, so that the constructor can be
139 %************************************************************************
141 \subsection{Transformation rules}
143 %************************************************************************
145 The CoreRule type and its friends are dealt with mainly in CoreRules,
146 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
151 VarSet -- Locally-defined free vars of RHSs
153 emptyCoreRules :: CoreRules
154 emptyCoreRules = Rules [] emptyVarSet
156 isEmptyCoreRules :: CoreRules -> Bool
157 isEmptyCoreRules (Rules rs _) = null rs
159 rulesRhsFreeVars :: CoreRules -> VarSet
160 rulesRhsFreeVars (Rules _ fvs) = fvs
162 rulesRules :: CoreRules -> [CoreRule]
163 rulesRules (Rules rules _) = rules
167 type RuleName = FAST_STRING
168 type IdCoreRule = (Id,CoreRule) -- Rules don't have their leading Id inside them
172 [CoreBndr] -- Forall'd variables
173 [CoreExpr] -- LHS args
176 | BuiltinRule -- Built-in rules are used for constant folding
177 RuleName -- and suchlike. It has no free variables.
178 ([CoreExpr] -> Maybe CoreExpr)
180 isBuiltinRule (BuiltinRule _ _) = True
181 isBuiltinRule _ = False
183 ruleName :: CoreRule -> RuleName
184 ruleName (Rule n _ _ _) = n
185 ruleName (BuiltinRule n _) = n
189 %************************************************************************
191 \subsection{@Unfolding@ type}
193 %************************************************************************
195 The @Unfolding@ type is declared here to avoid numerous loops, but it
196 should be abstract everywhere except in CoreUnfold.lhs
202 | OtherCon [AltCon] -- It ain't one of these
203 -- (OtherCon xs) also indicates that something has been evaluated
204 -- and hence there's no point in re-evaluating it.
205 -- OtherCon [] is used even for non-data-type values
206 -- to indicated evaluated-ness. Notably:
207 -- data C = C !(Int -> Int)
208 -- case x of { C f -> ... }
209 -- Here, f gets an OtherCon [] unfolding.
211 | CompulsoryUnfolding CoreExpr -- There is no "original" definition,
212 -- so you'd better unfold.
214 | CoreUnfolding -- An unfolding with redundant cached information
215 CoreExpr -- Template; binder-info is correct
216 Bool -- True <=> top level binding
217 Bool -- exprIsValue template (cached); it is ok to discard a `seq` on
219 Bool -- True <=> doesn't waste (much) work to expand inside an inlining
220 -- Basically it's exprIsCheap
221 UnfoldingGuidance -- Tells about the *size* of the template.
224 data UnfoldingGuidance
226 | UnfoldIfGoodArgs Int -- and "n" value args
228 [Int] -- Discount if the argument is evaluated.
229 -- (i.e., a simplification will definitely
230 -- be possible). One elt of the list per *value* arg.
232 Int -- The "size" of the unfolding; to be elaborated
235 Int -- Scrutinee discount: the discount to substract if the thing is in
236 -- a context (case (thing args) of ...),
237 -- (where there are the right number of arguments.)
239 noUnfolding = NoUnfolding
240 mkOtherCon = OtherCon
242 seqUnfolding :: Unfolding -> ()
243 seqUnfolding (CoreUnfolding e top b1 b2 g)
244 = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
245 seqUnfolding other = ()
247 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
248 seqGuidance other = ()
252 unfoldingTemplate :: Unfolding -> CoreExpr
253 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
254 unfoldingTemplate (CompulsoryUnfolding expr) = expr
255 unfoldingTemplate other = panic "getUnfoldingTemplate"
257 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
258 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
259 maybeUnfoldingTemplate (CompulsoryUnfolding expr) = Just expr
260 maybeUnfoldingTemplate other = Nothing
262 otherCons :: Unfolding -> [AltCon]
263 otherCons (OtherCon cons) = cons
266 isValueUnfolding :: Unfolding -> Bool
267 -- Returns False for OtherCon
268 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
269 isValueUnfolding other = False
271 isEvaldUnfolding :: Unfolding -> Bool
272 -- Returns True for OtherCon
273 isEvaldUnfolding (OtherCon _) = True
274 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
275 isEvaldUnfolding other = False
277 isCheapUnfolding :: Unfolding -> Bool
278 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
279 isCheapUnfolding other = False
281 isCompulsoryUnfolding :: Unfolding -> Bool
282 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
283 isCompulsoryUnfolding other = False
285 hasUnfolding :: Unfolding -> Bool
286 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
287 hasUnfolding (CompulsoryUnfolding _) = True
288 hasUnfolding other = False
290 hasSomeUnfolding :: Unfolding -> Bool
291 hasSomeUnfolding NoUnfolding = False
292 hasSomeUnfolding other = True
294 neverUnfold :: Unfolding -> Bool
295 neverUnfold NoUnfolding = True
296 neverUnfold (OtherCon _) = True
297 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
298 neverUnfold other = False
302 %************************************************************************
304 \subsection{The main data type}
306 %************************************************************************
309 -- The Ord is needed for the FiniteMap used in the lookForConstructor
310 -- in SimplEnv. If you declared that lookForConstructor *ignores*
311 -- constructor-applications with LitArg args, then you could get
314 instance Outputable AltCon where
315 ppr (DataAlt dc) = ppr dc
316 ppr (LitAlt lit) = ppr lit
317 ppr DEFAULT = ptext SLIT("__DEFAULT")
319 instance Show AltCon where
320 showsPrec p con = showsPrecSDoc p (ppr con)
324 %************************************************************************
326 \subsection{Useful synonyms}
328 %************************************************************************
334 type CoreExpr = Expr CoreBndr
335 type CoreArg = Arg CoreBndr
336 type CoreBind = Bind CoreBndr
337 type CoreAlt = Alt CoreBndr
340 Binders are ``tagged'' with a \tr{t}:
343 type Tagged t = (CoreBndr, t)
345 type TaggedBind t = Bind (Tagged t)
346 type TaggedExpr t = Expr (Tagged t)
347 type TaggedArg t = Arg (Tagged t)
348 type TaggedAlt t = Alt (Tagged t)
352 %************************************************************************
354 \subsection{Core-constructing functions with checking}
356 %************************************************************************
359 mkApps :: Expr b -> [Arg b] -> Expr b
360 mkTyApps :: Expr b -> [Type] -> Expr b
361 mkValApps :: Expr b -> [Expr b] -> Expr b
362 mkVarApps :: Expr b -> [Var] -> Expr b
364 mkApps f args = foldl App f args
365 mkTyApps f args = foldl (\ e a -> App e (Type a)) f args
366 mkValApps f args = foldl (\ e a -> App e a) f args
367 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
369 mkLit :: Literal -> Expr b
370 mkIntLit :: Integer -> Expr b
371 mkIntLitInt :: Int -> Expr b
372 mkConApp :: DataCon -> [Arg b] -> Expr b
373 mkLets :: [Bind b] -> Expr b -> Expr b
374 mkLams :: [b] -> Expr b -> Expr b
377 mkConApp con args = mkApps (Var (dataConId con)) args
379 mkLams binders body = foldr Lam body binders
380 mkLets binds body = foldr Let body binds
382 mkIntLit n = Lit (mkMachInt n)
383 mkIntLitInt n = Lit (mkMachInt (toInteger n))
385 varToCoreExpr :: CoreBndr -> Expr b
386 varToCoreExpr v | isId v = Var v
387 | otherwise = Type (mkTyVarTy v)
391 %************************************************************************
393 \subsection{Simple access functions}
395 %************************************************************************
398 bindersOf :: Bind b -> [b]
399 bindersOf (NonRec binder _) = [binder]
400 bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
402 bindersOfBinds :: [Bind b] -> [b]
403 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
405 rhssOfBind :: Bind b -> [Expr b]
406 rhssOfBind (NonRec _ rhs) = [rhs]
407 rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
409 rhssOfAlts :: [Alt b] -> [Expr b]
410 rhssOfAlts alts = [e | (_,_,e) <- alts]
412 flattenBinds :: [Bind b] -> [(b, Expr b)] -- Get all the lhs/rhs pairs
413 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
414 flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
418 We often want to strip off leading lambdas before getting down to
419 business. @collectBinders@ is your friend.
421 We expect (by convention) type-, and value- lambdas in that
425 collectBinders :: Expr b -> ([b], Expr b)
426 collectBindersIgnoringNotes :: Expr b -> ([b], Expr b)
427 collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr)
428 collectValBinders :: CoreExpr -> ([Id], CoreExpr)
429 collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
434 go bs (Lam b e) = go (b:bs) e
435 go bs e = (reverse bs, e)
437 -- This one ignores notes. It's used in CoreUnfold and StrAnal
438 -- when we aren't going to put the expression back together from
439 -- the pieces, so we don't mind losing the Notes
440 collectBindersIgnoringNotes expr
443 go bs (Lam b e) = go (b:bs) e
444 go bs (Note _ e) = go 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
556 seqBndr b = b `seq` ()
559 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
561 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
562 seqBind (Rec prs) = seqPairs prs
565 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
568 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
570 seqRules :: CoreRules -> ()
571 seqRules (Rules rules fvs) = seq_rules rules `seq` seqVarSet fvs
574 seq_rules (Rule fs bs es e : rules) = seqBndrs bs `seq` seqExprs (e:es) `seq` seq_rules rules
575 seq_rules (BuiltinRule _ _ : rules) = seq_rules rules
580 %************************************************************************
582 \subsection{Annotated core; annotation at every node in the tree}
584 %************************************************************************
587 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
589 data AnnExpr' bndr annot
592 | AnnLam bndr (AnnExpr bndr annot)
593 | AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
594 | AnnCase (AnnExpr bndr annot) bndr [AnnAlt bndr annot]
595 | AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
596 | AnnNote Note (AnnExpr bndr annot)
599 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
601 data AnnBind bndr annot
602 = AnnNonRec bndr (AnnExpr bndr annot)
603 | AnnRec [(bndr, AnnExpr bndr annot)]
607 deAnnotate :: AnnExpr bndr annot -> Expr bndr
608 deAnnotate (_, e) = deAnnotate' e
610 deAnnotate' (AnnType t) = Type t
611 deAnnotate' (AnnVar v) = Var v
612 deAnnotate' (AnnLit lit) = Lit lit
613 deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
614 deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
615 deAnnotate' (AnnNote note body) = Note note (deAnnotate body)
617 deAnnotate' (AnnLet bind body)
618 = Let (deAnnBind bind) (deAnnotate body)
620 deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
621 deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
623 deAnnotate' (AnnCase scrut v alts)
624 = Case (deAnnotate scrut) v (map deAnnAlt alts)
626 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
627 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)