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,
15 mkStringLit, mkStringLitFS, mkConApp,
18 bindersOf, bindersOfBinds, rhssOfBind, rhssOfAlts, isTyVar, isId,
19 collectBinders, collectTyBinders, collectValBinders, collectTyAndValBinders,
20 collectArgs, collectBindersIgnoringNotes,
24 isValArg, isTypeArg, valArgCount, valBndrCount,
27 Unfolding(..), UnfoldingGuidance(..), -- Both abstract everywhere but in CoreUnfold.lhs
28 noUnfolding, mkOtherCon,
29 unfoldingTemplate, maybeUnfoldingTemplate, otherCons,
30 isValueUnfolding, isEvaldUnfolding, isCheapUnfolding, isCompulsoryUnfolding,
31 hasUnfolding, hasSomeUnfolding,
34 seqRules, seqExpr, seqExprs, seqUnfolding,
36 -- Annotated expressions
37 AnnExpr, AnnExpr'(..), AnnBind(..), AnnAlt, deAnnotate, deAnnotate',
40 CoreRules(..), -- Representation needed by friends
41 CoreRule(..), -- CoreSubst, CoreTidy, CoreFVs, PprCore only
43 emptyCoreRules, isEmptyCoreRules, rulesRhsFreeVars, rulesRules
46 #include "HsVersions.h"
48 import CostCentre ( CostCentre, noCostCentre )
49 import Var ( Var, Id, TyVar, isTyVar, isId, idType )
51 import Type ( Type, UsageAnn, mkTyVarTy, isUnLiftedType, seqType )
52 import Literal ( Literal(MachStr), mkMachInt )
53 import PrimOp ( PrimOp )
54 import DataCon ( DataCon, dataConId )
55 import ThinAir ( unpackCStringId, unpackCString2Id )
60 %************************************************************************
62 \subsection{The main data types}
64 %************************************************************************
66 These data types are the heart of the compiler
69 infixl 8 `App` -- App brackets to the left
71 data Expr b -- "b" for the type of binders,
74 | App (Expr b) (Arg b)
76 | Let (Bind b) (Expr b)
77 | Case (Expr b) b [Alt b] -- Binder gets bound to value of scrutinee
78 -- DEFAULT case must be last, if it occurs at all
80 | Type Type -- This should only show up at the top
83 type Arg b = Expr b -- Can be a Type
85 type Alt b = (AltCon, [b], Expr b) -- (DEFAULT, [], rhs) is the default alternative
87 data AltCon = DataAlt DataCon
92 data Bind b = NonRec b (Expr b)
99 Type -- The to-type: type of whole coerce expression
100 Type -- The from-type: type of enclosed expression
102 | InlineCall -- Instructs simplifier to inline
105 | InlineMe -- Instructs simplifer to treat the enclosed expression
106 -- as very small, and inline it at its call sites
108 | TermUsg -- A term-level usage annotation
109 UsageAnn -- (should not be a variable except during UsageSP inference)
113 %************************************************************************
115 \subsection{Transformation rules}
117 %************************************************************************
119 The CoreRule type and its friends are dealt with mainly in CoreRules,
120 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
125 VarSet -- Locally-defined free vars of RHSs
127 type RuleName = FAST_STRING
131 [CoreBndr] -- Forall'd variables
132 [CoreExpr] -- LHS args
135 | BuiltinRule -- Built-in rules are used for constant folding
136 -- and suchlike. It has no free variables.
137 ([CoreExpr] -> Maybe (RuleName, CoreExpr))
139 emptyCoreRules :: CoreRules
140 emptyCoreRules = Rules [] emptyVarSet
142 isEmptyCoreRules :: CoreRules -> Bool
143 isEmptyCoreRules (Rules rs _) = null rs
145 rulesRhsFreeVars :: CoreRules -> VarSet
146 rulesRhsFreeVars (Rules _ fvs) = fvs
148 rulesRules :: CoreRules -> [CoreRule]
149 rulesRules (Rules rules _) = rules
153 %************************************************************************
155 \subsection{@Unfolding@ type}
157 %************************************************************************
159 The @Unfolding@ type is declared here to avoid numerous loops, but it
160 should be abstract everywhere except in CoreUnfold.lhs
166 | OtherCon [AltCon] -- It ain't one of these
167 -- (OtherCon xs) also indicates that something has been evaluated
168 -- and hence there's no point in re-evaluating it.
169 -- OtherCon [] is used even for non-data-type values
170 -- to indicated evaluated-ness. Notably:
171 -- data C = C !(Int -> Int)
172 -- case x of { C f -> ... }
173 -- Here, f gets an OtherCon [] unfolding.
175 | CompulsoryUnfolding CoreExpr -- There is no "original" definition,
176 -- so you'd better unfold.
178 | CoreUnfolding -- An unfolding with redundant cached information
179 CoreExpr -- Template; binder-info is correct
180 Bool -- This is a top-level binding
181 Bool -- exprIsCheap template (cached); it won't duplicate (much) work
182 -- if you inline this in more than one place
183 Bool -- exprIsValue template (cached); it is ok to discard a `seq` on
185 Bool -- exprIsBottom template (cached)
186 UnfoldingGuidance -- Tells about the *size* of the template.
189 data UnfoldingGuidance
191 | UnfoldIfGoodArgs Int -- and "n" value args
193 [Int] -- Discount if the argument is evaluated.
194 -- (i.e., a simplification will definitely
195 -- be possible). One elt of the list per *value* arg.
197 Int -- The "size" of the unfolding; to be elaborated
200 Int -- Scrutinee discount: the discount to substract if the thing is in
201 -- a context (case (thing args) of ...),
202 -- (where there are the right number of arguments.)
204 noUnfolding = NoUnfolding
205 mkOtherCon = OtherCon
207 seqUnfolding :: Unfolding -> ()
208 seqUnfolding (CoreUnfolding e top b1 b2 b3 g)
209 = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` b3 `seq` seqGuidance g
210 seqUnfolding other = ()
212 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
213 seqGuidance other = ()
217 unfoldingTemplate :: Unfolding -> CoreExpr
218 unfoldingTemplate (CoreUnfolding expr _ _ _ _ _) = expr
219 unfoldingTemplate (CompulsoryUnfolding expr) = expr
220 unfoldingTemplate other = panic "getUnfoldingTemplate"
222 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
223 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _ _) = Just expr
224 maybeUnfoldingTemplate (CompulsoryUnfolding expr) = Just expr
225 maybeUnfoldingTemplate other = Nothing
227 otherCons :: Unfolding -> [AltCon]
228 otherCons (OtherCon cons) = cons
231 isValueUnfolding :: Unfolding -> Bool
232 -- Returns False for OtherCon
233 isValueUnfolding (CoreUnfolding _ _ _ is_evald _ _) = is_evald
234 isValueUnfolding other = False
236 isEvaldUnfolding :: Unfolding -> Bool
237 -- Returns True for OtherCon
238 isEvaldUnfolding (OtherCon _) = True
239 isEvaldUnfolding (CoreUnfolding _ _ _ is_evald _ _) = is_evald
240 isEvaldUnfolding other = False
242 isCheapUnfolding :: Unfolding -> Bool
243 isCheapUnfolding (CoreUnfolding _ _ is_cheap _ _ _) = is_cheap
244 isCheapUnfolding other = False
246 isCompulsoryUnfolding :: Unfolding -> Bool
247 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
248 isCompulsoryUnfolding other = False
250 hasUnfolding :: Unfolding -> Bool
251 hasUnfolding (CoreUnfolding _ _ _ _ _ _) = True
252 hasUnfolding (CompulsoryUnfolding _) = True
253 hasUnfolding other = False
255 hasSomeUnfolding :: Unfolding -> Bool
256 hasSomeUnfolding NoUnfolding = False
257 hasSomeUnfolding other = True
261 %************************************************************************
263 \subsection{The main data type}
265 %************************************************************************
268 -- The Ord is needed for the FiniteMap used in the lookForConstructor
269 -- in SimplEnv. If you declared that lookForConstructor *ignores*
270 -- constructor-applications with LitArg args, then you could get
273 instance Outputable AltCon where
274 ppr (DataAlt dc) = ppr dc
275 ppr (LitAlt lit) = ppr lit
276 ppr DEFAULT = ptext SLIT("__DEFAULT")
278 instance Show AltCon where
279 showsPrec p con = showsPrecSDoc p (ppr con)
283 %************************************************************************
285 \subsection{Useful synonyms}
287 %************************************************************************
293 type CoreExpr = Expr CoreBndr
294 type CoreArg = Arg CoreBndr
295 type CoreBind = Bind CoreBndr
296 type CoreAlt = Alt CoreBndr
300 Binders are ``tagged'' with a \tr{t}:
303 type Tagged t = (CoreBndr, t)
305 type TaggedBind t = Bind (Tagged t)
306 type TaggedExpr t = Expr (Tagged t)
307 type TaggedArg t = Arg (Tagged t)
308 type TaggedAlt t = Alt (Tagged t)
312 %************************************************************************
314 \subsection{Core-constructing functions with checking}
316 %************************************************************************
319 mkApps :: Expr b -> [Arg b] -> Expr b
320 mkTyApps :: Expr b -> [Type] -> Expr b
321 mkValApps :: Expr b -> [Expr b] -> Expr b
322 mkVarApps :: Expr b -> [Var] -> Expr b
324 mkApps f args = foldl App f args
325 mkTyApps f args = foldl (\ e a -> App e (Type a)) f args
326 mkValApps f args = foldl (\ e a -> App e a) f args
327 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
329 mkLit :: Literal -> Expr b
330 mkIntLit :: Integer -> Expr b
331 mkIntLitInt :: Int -> Expr b
332 mkStringLit :: String -> Expr b -- Makes a [Char] literal
333 mkStringLitFS :: FAST_STRING -> Expr b -- Makes a [Char] literal
334 mkConApp :: DataCon -> [Arg b] -> Expr b
335 mkLets :: [Bind b] -> Expr b -> Expr b
336 mkLams :: [b] -> Expr b -> Expr b
339 mkConApp con args = mkApps (Var (dataConId con)) args
341 mkLams binders body = foldr Lam body binders
342 mkLets binds body = foldr Let body binds
344 mkIntLit n = Lit (mkMachInt n)
345 mkIntLitInt n = Lit (mkMachInt (toInteger n))
347 mkStringLit str = mkStringLitFS (_PK_ str)
350 | any is_NUL (_UNPK_ str)
351 = -- Must cater for NULs in literal string
352 mkApps (Var unpackCString2Id)
354 mkIntLitInt (_LENGTH_ str)]
357 = -- No NULs in the string
358 App (Var unpackCStringId) (Lit (MachStr str))
363 varToCoreExpr :: CoreBndr -> Expr b
364 varToCoreExpr v | isId v = Var v
365 | otherwise = Type (mkTyVarTy v)
369 %************************************************************************
371 \subsection{Simple access functions}
373 %************************************************************************
376 bindersOf :: Bind b -> [b]
377 bindersOf (NonRec binder _) = [binder]
378 bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
380 bindersOfBinds :: [Bind b] -> [b]
381 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
383 rhssOfBind :: Bind b -> [Expr b]
384 rhssOfBind (NonRec _ rhs) = [rhs]
385 rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
387 rhssOfAlts :: [Alt b] -> [Expr b]
388 rhssOfAlts alts = [e | (_,_,e) <- alts]
390 flattenBinds :: [Bind b] -> [(b, Expr b)] -- Get all the lhs/rhs pairs
391 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
392 flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
396 We often want to strip off leading lambdas before getting down to
397 business. @collectBinders@ is your friend.
399 We expect (by convention) type-, and value- lambdas in that
403 collectBinders :: Expr b -> ([b], Expr b)
404 collectBindersIgnoringNotes :: Expr b -> ([b], Expr b)
405 collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr)
406 collectValBinders :: CoreExpr -> ([Id], CoreExpr)
407 collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
412 go bs (Lam b e) = go (b:bs) e
413 go bs e = (reverse bs, e)
415 -- This one ignores notes. It's used in CoreUnfold and StrAnal
416 -- when we aren't going to put the expression back together from
417 -- the pieces, so we don't mind losing the Notes
418 collectBindersIgnoringNotes expr
421 go bs (Lam b e) = go (b:bs) e
422 go bs (Note _ e) = go bs e
423 go bs e = (reverse bs, e)
425 collectTyAndValBinders expr
428 (tvs, body1) = collectTyBinders expr
429 (ids, body) = collectValBinders body1
431 collectTyBinders expr
434 go tvs (Lam b e) | isTyVar b = go (b:tvs) e
435 go tvs e = (reverse tvs, e)
437 collectValBinders expr
440 go ids (Lam b e) | isId b = go (b:ids) e
441 go ids body = (reverse ids, body)
445 @collectArgs@ takes an application expression, returning the function
446 and the arguments to which it is applied.
449 collectArgs :: Expr b -> (Expr b, [Arg b])
453 go (App f a) as = go f (a:as)
457 coreExprCc gets the cost centre enclosing an expression, if any.
458 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
461 coreExprCc :: Expr b -> CostCentre
462 coreExprCc (Note (SCC cc) e) = cc
463 coreExprCc (Note other_note e) = coreExprCc e
464 coreExprCc (Lam _ e) = coreExprCc e
465 coreExprCc other = noCostCentre
469 %************************************************************************
471 \subsection{Predicates}
473 %************************************************************************
476 isValArg (Type _) = False
477 isValArg other = True
479 isTypeArg (Type _) = True
480 isTypeArg other = False
482 valBndrCount :: [CoreBndr] -> Int
484 valBndrCount (b : bs) | isId b = 1 + valBndrCount bs
485 | otherwise = valBndrCount bs
487 valArgCount :: [Arg b] -> Int
489 valArgCount (Type _ : args) = valArgCount args
490 valArgCount (other : args) = 1 + valArgCount args
494 %************************************************************************
496 \subsection{Seq stuff}
498 %************************************************************************
501 seqExpr :: CoreExpr -> ()
502 seqExpr (Var v) = v `seq` ()
503 seqExpr (Lit lit) = lit `seq` ()
504 seqExpr (App f a) = seqExpr f `seq` seqExpr a
505 seqExpr (Lam b e) = seqBndr b `seq` seqExpr e
506 seqExpr (Let b e) = seqBind b `seq` seqExpr e
507 seqExpr (Case e b as) = seqExpr e `seq` seqBndr b `seq` seqAlts as
508 seqExpr (Note n e) = seqNote n `seq` seqExpr e
509 seqExpr (Type t) = seqType t
512 seqExprs (e:es) = seqExpr e `seq` seqExprs es
514 seqNote (Coerce t1 t2) = seqType t1 `seq` seqType t2
517 seqBndr b = b `seq` ()
520 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
522 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
523 seqBind (Rec prs) = seqPairs prs
526 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
529 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
531 seqRules :: CoreRules -> ()
532 seqRules (Rules rules fvs) = seq_rules rules `seq` seqVarSet fvs
535 seq_rules (Rule fs bs es e : rules) = seqBndrs bs `seq` seqExprs (e:es) `seq` seq_rules rules
536 seq_rules (BuiltinRule _ : rules) = seq_rules rules
541 %************************************************************************
543 \subsection{Annotated core; annotation at every node in the tree}
545 %************************************************************************
548 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
550 data AnnExpr' bndr annot
553 | AnnLam bndr (AnnExpr bndr annot)
554 | AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
555 | AnnCase (AnnExpr bndr annot) bndr [AnnAlt bndr annot]
556 | AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
557 | AnnNote Note (AnnExpr bndr annot)
560 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
562 data AnnBind bndr annot
563 = AnnNonRec bndr (AnnExpr bndr annot)
564 | AnnRec [(bndr, AnnExpr bndr annot)]
568 deAnnotate :: AnnExpr bndr annot -> Expr bndr
569 deAnnotate (_, e) = deAnnotate' e
571 deAnnotate' (AnnType t) = Type t
572 deAnnotate' (AnnVar v) = Var v
573 deAnnotate' (AnnLit lit) = Lit lit
574 deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
575 deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
576 deAnnotate' (AnnNote note body) = Note note (deAnnotate body)
578 deAnnotate' (AnnLet bind body)
579 = Let (deAnnBind bind) (deAnnotate body)
581 deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
582 deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
584 deAnnotate' (AnnCase scrut v alts)
585 = Case (deAnnotate scrut) v (map deAnnAlt alts)
587 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)