2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
8 -- | CoreSyn holds all the main data types for use by for the Glasgow Haskell Compiler midsection
11 Expr(..), Alt, Bind(..), AltCon(..), Arg, Note(..),
12 CoreExpr, CoreAlt, CoreBind, CoreArg, CoreBndr,
13 TaggedExpr, TaggedAlt, TaggedBind, TaggedArg, TaggedBndr(..),
15 -- ** 'Expr' construction
17 mkApps, mkTyApps, mkVarApps,
19 mkIntLit, mkIntLitInt,
20 mkWordLit, mkWordLitWord,
21 mkCharLit, mkStringLit,
22 mkFloatLit, mkFloatLitFloat,
23 mkDoubleLit, mkDoubleLitDouble,
26 varToCoreExpr, varsToCoreExprs,
28 isTyVar, isId, cmpAltCon, cmpAlt, ltAlt,
30 -- ** Simple 'Expr' access functions and predicates
31 bindersOf, bindersOfBinds, rhssOfBind, rhssOfAlts,
32 collectBinders, collectTyBinders, collectValBinders, collectTyAndValBinders,
33 collectArgs, coreExprCc, flattenBinds,
35 isValArg, isTypeArg, valArgCount, valBndrCount, isRuntimeArg, isRuntimeVar,
37 -- * Unfolding data types
38 Unfolding(..), UnfoldingGuidance(..), -- Both abstract everywhere but in CoreUnfold.lhs
40 -- ** Constructing 'Unfolding's
41 noUnfolding, evaldUnfolding, mkOtherCon,
43 -- ** Predicates and deconstruction on 'Unfolding'
44 unfoldingTemplate, maybeUnfoldingTemplate, otherCons,
45 isValueUnfolding, isEvaldUnfolding, isCheapUnfolding, isCompulsoryUnfolding,
46 hasUnfolding, hasSomeUnfolding, neverUnfold,
49 seqExpr, seqExprs, seqUnfolding,
51 -- * Annotated expression data types
52 AnnExpr, AnnExpr'(..), AnnBind(..), AnnAlt,
54 -- ** Operations on annotations
55 deAnnotate, deAnnotate', deAnnAlt, collectAnnBndrs,
57 -- * Core rule data types
58 CoreRule(..), -- CoreSubst, CoreTidy, CoreFVs, PprCore only
61 -- ** Operations on 'CoreRule's
62 seqRules, ruleArity, ruleName, ruleIdName, ruleActivation_maybe,
64 isBuiltinRule, isLocalRule
67 #include "HsVersions.h"
84 infixl 4 `mkApps`, `mkTyApps`, `mkVarApps`
85 -- Left associative, so that we can say (f `mkTyApps` xs `mkVarApps` ys)
88 %************************************************************************
90 \subsection{The main data types}
92 %************************************************************************
94 These data types are the heart of the compiler
97 infixl 8 `App` -- App brackets to the left
99 -- | This is the data type that represents GHCs core intermediate language. Currently
100 -- GHC uses System FC <http://research.microsoft.com/~simonpj/papers/ext-f/> for this purpose,
101 -- which is closely related to the simpler and better known System F <http://en.wikipedia.org/wiki/System_F>.
103 -- We get from Haskell source to this Core language in a number of stages:
105 -- 1. The source code is parsed into an abstract syntax tree, which is represented
106 -- by the data type 'HsExpr.HsExpr' with the names being 'RdrName.RdrNames'
108 -- 2. This syntax tree is /renamed/, which attaches a 'Unique.Unique' to every 'RdrName.RdrName'
109 -- (yielding a 'Name.Name') to disambiguate identifiers which are lexically identical.
110 -- For example, this program:
113 -- f x = let f x = x + 1
117 -- Would be renamed by having 'Unique's attached so it looked something like this:
120 -- f_1 x_2 = let f_3 x_4 = x_4 + 1
124 -- 3. The resulting syntax tree undergoes type checking (which also deals with instantiating
125 -- type class arguments) to yield a 'HsExpr.HsExpr' type that has 'Id.Id' as it's names.
127 -- 4. Finally the syntax tree is /desugared/ from the expressive 'HsExpr.HsExpr' type into
128 -- this 'Expr' type, which has far fewer constructors and hence is easier to perform
129 -- optimization, analysis and code generation on.
131 -- The type parameter @b@ is for the type of binders in the expression tree.
133 = Var Id -- ^ Variables
134 | Lit Literal -- ^ Primitive literals
135 | App (Expr b) (Arg b) -- ^ Applications: note that the argument may be a 'Type'.
137 -- See "CoreSyn#let_app_invariant" for another invariant
138 | Lam b (Expr b) -- ^ Lambda abstraction
139 | Let (Bind b) (Expr b) -- ^ Recursive and non recursive @let@s. Operationally
140 -- this corresponds to allocating a thunk for the things
141 -- bound and then executing the sub-expression.
143 -- #top_level_invariant#
144 -- #letrec_invariant#
146 -- The right hand sides of all top-level and recursive @let@s
147 -- /must/ be of lifted type (see "Type#type_classification" for
148 -- the meaning of /lifted/ vs. /unlifted/).
150 -- #let_app_invariant#
151 -- The right hand side of of a non-recursive 'Let' _and_ the argument of an 'App',
152 -- /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. For example, this is OK:
156 -- > y::Int# = x +# 1#
158 -- But this is not, as it may affect termination if the expression is floated out:
160 -- > y::Int# = fac 4#
162 -- In this situation you should use @case@ rather than a @let@. The function
163 -- 'CoreUtils.needsCaseBinding' can help you determine which to generate, or
164 -- alternatively use 'MkCore.mkCoreLet' rather than this constructor directly,
165 -- which will generate a @case@ if necessary
168 -- We allow a /non-recursive/ let to bind a type variable, thus:
170 -- > Let (NonRec tv (Type ty)) body
172 -- This can be very convenient for postponing type substitutions until
173 -- the next run of the simplifier.
175 -- At the moment, the rest of the compiler only deals with type-let
176 -- in a Let expression, rather than at top level. We may want to revist
178 | Case (Expr b) b Type [Alt b] -- ^ Case split. Operationally this corresponds to evaluating
179 -- the scrutinee (expression examined) to weak head normal form
180 -- and then examining at most one level of resulting constructor (i.e. you
181 -- cannot do nested pattern matching directly with this).
183 -- The binder gets bound to the value of the scrutinee,
184 -- and the 'Type' must be that of all the case alternatives
187 -- This is one of the more complicated elements of the Core language, and comes
188 -- with a number of restrictions:
190 -- The 'DEFAULT' case alternative must be first in the list, if it occurs at all.
192 -- The remaining cases are in order of increasing
193 -- tag (for 'DataAlts') or
194 -- lit (for 'LitAlts').
195 -- This makes finding the relevant constructor easy, and makes comparison easier too.
197 -- The list of alternatives must be exhaustive. An /exhaustive/ case
198 -- does not necessarily mention all constructors:
201 -- data Foo = Red | Green | Blue
204 -- other -> f (case x of
209 -- The inner case does not need a @Red@ alternative, because @x@ can't be @Red@ at
210 -- that program point.
211 | Cast (Expr b) Coercion -- ^ Cast an expression to a particular type. This is used to implement @newtype@s
212 -- (a @newtype@ constructor or destructor just becomes a 'Cast' in Core) and GADTs.
213 | Note Note (Expr b) -- ^ Notes. These allow general information to be
214 -- added to expressions in the syntax tree
215 | Type Type -- ^ A type: this should only show up at the top
218 -- | Type synonym for expressions that occur in function argument positions.
219 -- Only 'Arg' should contain a 'Type' at top level, general 'Expr' should not
222 -- | A case split alternative. Consists of the constructor leading to the alternative,
223 -- the variables bound from the constructor, and the expression to be executed given that binding.
224 -- The default alternative is @(DEFAULT, [], rhs)@
225 type Alt b = (AltCon, [b], Expr b)
227 -- | A case alternative constructor (i.e. pattern match)
228 data AltCon = DataAlt DataCon -- ^ A plain data constructor: @case e of { Foo x -> ... }@.
229 -- Invariant: the 'DataCon' is always from a @data@ type, and never from a @newtype@
230 | LitAlt Literal -- ^ A literal: @case e of { 1 -> ... }@
231 | DEFAULT -- ^ Trivial alternative: @case e of { _ -> ... }@
234 -- | Binding, used for top level bindings in a module and local bindings in a @let@.
235 data Bind b = NonRec b (Expr b)
236 | Rec [(b, (Expr b))]
239 -------------------------- CoreSyn INVARIANTS ---------------------------
241 Note [CoreSyn top-level invariant]
242 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
243 See #toplevel_invariant#
245 Note [CoreSyn letrec invariant]
246 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
247 See #letrec_invariant#
249 Note [CoreSyn let/app invariant]
250 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
251 See #let_app_invariant#
253 This is intially enforced by DsUtils.mkCoreLet and mkCoreApp
255 Note [CoreSyn case invariants]
256 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
257 See #case_invariants#
259 Note [CoreSyn let goal]
260 ~~~~~~~~~~~~~~~~~~~~~~~
261 * The simplifier tries to ensure that if the RHS of a let is a constructor
262 application, its arguments are trivial, so that the constructor can be
272 -- | Allows attaching extra information to points in expressions rather than e.g. identifiers.
274 = SCC CostCentre -- ^ A cost centre annotation for profiling
276 | InlineMe -- ^ Instructs the core simplifer to treat the enclosed expression
277 -- as very small, and inline it at its call sites
279 | CoreNote String -- ^ A generic core annotation, propagated but not used by GHC
281 -- NOTE: we also treat expressions wrapped in InlineMe as
282 -- 'cheap' and 'dupable' (in the sense of exprIsCheap, exprIsDupable)
283 -- What this means is that we obediently inline even things that don't
284 -- look like valuse. This is sometimes important:
287 -- Here, f looks like a redex, and we aren't going to inline (.) because it's
288 -- inside an INLINE, so it'll stay looking like a redex. Nevertheless, we
289 -- should inline f even inside lambdas. In effect, we should trust the programmer.
293 %************************************************************************
295 \subsection{Transformation rules}
297 %************************************************************************
299 The CoreRule type and its friends are dealt with mainly in CoreRules,
300 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
303 -- | A 'CoreRule' is:
305 -- * \"Local\" if the function it is a rule for is defined in the
306 -- same module as the rule itself.
308 -- * \"Orphan\" if nothing on the LHS is defined in the same module
309 -- as the rule itself
312 ru_name :: RuleName, -- ^ Name of the rule, for communication with the user
313 ru_act :: Activation, -- ^ When the rule is active
315 -- Rough-matching stuff
316 -- see comments with InstEnv.Instance( is_cls, is_rough )
317 ru_fn :: Name, -- ^ Name of the 'Id.Id' at the head of this rule
318 ru_rough :: [Maybe Name], -- ^ Name at the head of each argument to the left hand side
320 -- Proper-matching stuff
321 -- see comments with InstEnv.Instance( is_tvs, is_tys )
322 ru_bndrs :: [CoreBndr], -- ^ Variables quantified over
323 ru_args :: [CoreExpr], -- ^ Left hand side arguments
325 -- And the right-hand side
326 ru_rhs :: CoreExpr, -- ^ Right hand side of the rule
329 ru_local :: Bool -- ^ @True@ iff the fn at the head of the rule is
330 -- defined in the same module as the rule
331 -- and is not an implicit 'Id' (like a record selector,
332 -- class operation, or data constructor)
334 -- NB: ru_local is *not* used to decide orphan-hood
335 -- c.g. MkIface.coreRuleToIfaceRule
338 -- | Built-in rules are used for constant folding
339 -- and suchlike. They have no free variables.
341 ru_name :: RuleName, -- ^ As above
342 ru_fn :: Name, -- ^ As above
343 ru_nargs :: Int, -- ^ Number of arguments that 'ru_try' expects,
344 -- including type arguments
345 ru_try :: [CoreExpr] -> Maybe CoreExpr
346 -- ^ This function does the rewrite. It given too many
347 -- arguments, it simply discards them; the returned 'CoreExpr'
348 -- is just the rewrite of 'ru_fn' applied to the first 'ru_nargs' args
350 -- See Note [Extra args in rule matching] in Rules.lhs
352 isBuiltinRule :: CoreRule -> Bool
353 isBuiltinRule (BuiltinRule {}) = True
354 isBuiltinRule _ = False
356 -- | The number of arguments the 'ru_fn' must be applied
357 -- to before the rule can match on it
358 ruleArity :: CoreRule -> Int
359 ruleArity (BuiltinRule {ru_nargs = n}) = n
360 ruleArity (Rule {ru_args = args}) = length args
362 ruleName :: CoreRule -> RuleName
365 ruleActivation_maybe :: CoreRule -> Maybe Activation
366 ruleActivation_maybe (BuiltinRule { }) = Nothing
367 ruleActivation_maybe (Rule { ru_act = act }) = Just act
369 -- | The 'Name' of the 'Id.Id' at the head of the rule left hand side
370 ruleIdName :: CoreRule -> Name
373 isLocalRule :: CoreRule -> Bool
374 isLocalRule = ru_local
376 -- | Set the 'Name' of the 'Id.Id' at the head of the rule left hand side
377 setRuleIdName :: Name -> CoreRule -> CoreRule
378 setRuleIdName nm ru = ru { ru_fn = nm }
382 %************************************************************************
386 %************************************************************************
388 The @Unfolding@ type is declared here to avoid numerous loops
391 -- | Records the /unfolding/ of an identifier, which is approximately the form the
392 -- identifier would have if we substituted its definition in for the identifier.
393 -- This type should be treated as abstract everywhere except in "CoreUnfold"
395 = NoUnfolding -- ^ We have no information about the unfolding
397 | OtherCon [AltCon] -- ^ It ain't one of these constructors.
398 -- @OtherCon xs@ also indicates that something has been evaluated
399 -- and hence there's no point in re-evaluating it.
400 -- @OtherCon []@ is used even for non-data-type values
401 -- to indicated evaluated-ness. Notably:
403 -- > data C = C !(Int -> Int)
404 -- > case x of { C f -> ... }
406 -- Here, @f@ gets an @OtherCon []@ unfolding.
408 | CompulsoryUnfolding CoreExpr -- ^ There is /no original definition/,
409 -- so you'd better unfold.
417 -- ^ An unfolding with redundant cached information. Parameters:
419 -- 1) Template used to perform unfolding; binder-info is correct
421 -- 2) Is this a top level binding?
423 -- 3) 'exprIsHNF' template (cached); it is ok to discard a 'seq' on
426 -- 4) Does this waste only a little work if we expand it inside an inlining?
427 -- Basically this is a cached version of 'exprIsCheap'
429 -- 5) Tells us about the /size/ of the unfolding template
431 -- | When unfolding should take place
432 data UnfoldingGuidance
434 | UnfoldIfGoodArgs Int -- and "n" value args
436 [Int] -- Discount if the argument is evaluated.
437 -- (i.e., a simplification will definitely
438 -- be possible). One elt of the list per *value* arg.
440 Int -- The "size" of the unfolding; to be elaborated
443 Int -- Scrutinee discount: the discount to substract if the thing is in
444 -- a context (case (thing args) of ...),
445 -- (where there are the right number of arguments.)
447 noUnfolding :: Unfolding
448 -- ^ There is no known 'Unfolding'
449 evaldUnfolding :: Unfolding
450 -- ^ This unfolding marks the associated thing as being evaluated
452 noUnfolding = NoUnfolding
453 evaldUnfolding = OtherCon []
455 mkOtherCon :: [AltCon] -> Unfolding
456 mkOtherCon = OtherCon
458 seqUnfolding :: Unfolding -> ()
459 seqUnfolding (CoreUnfolding e top b1 b2 g)
460 = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
463 seqGuidance :: UnfoldingGuidance -> ()
464 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
469 -- | Retrieves the template of an unfolding: panics if none is known
470 unfoldingTemplate :: Unfolding -> CoreExpr
471 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
472 unfoldingTemplate (CompulsoryUnfolding expr) = expr
473 unfoldingTemplate _ = panic "getUnfoldingTemplate"
475 -- | Retrieves the template of an unfolding if possible
476 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
477 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
478 maybeUnfoldingTemplate (CompulsoryUnfolding expr) = Just expr
479 maybeUnfoldingTemplate _ = Nothing
481 -- | The constructors that the unfolding could never be:
482 -- returns @[]@ if no information is available
483 otherCons :: Unfolding -> [AltCon]
484 otherCons (OtherCon cons) = cons
487 -- | Determines if it is certainly the case that the unfolding will
488 -- yield a value (something in HNF): returns @False@ if unsure
489 isValueUnfolding :: Unfolding -> Bool
490 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
491 isValueUnfolding _ = False
493 -- | Determines if it possibly the case that the unfolding will
494 -- yield a value. Unlike 'isValueUnfolding' it returns @True@
496 isEvaldUnfolding :: Unfolding -> Bool
497 isEvaldUnfolding (OtherCon _) = True
498 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
499 isEvaldUnfolding _ = False
501 -- | Is the thing we will unfold into certainly cheap?
502 isCheapUnfolding :: Unfolding -> Bool
503 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
504 isCheapUnfolding _ = False
506 -- | Must this unfolding happen for the code to be executable?
507 isCompulsoryUnfolding :: Unfolding -> Bool
508 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
509 isCompulsoryUnfolding _ = False
511 -- | Do we have an available or compulsory unfolding?
512 hasUnfolding :: Unfolding -> Bool
513 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
514 hasUnfolding (CompulsoryUnfolding _) = True
515 hasUnfolding _ = False
517 -- | Only returns False if there is no unfolding information available at all
518 hasSomeUnfolding :: Unfolding -> Bool
519 hasSomeUnfolding NoUnfolding = False
520 hasSomeUnfolding _ = True
522 -- | Similar to @not . hasUnfolding@, but also returns @True@
523 -- if it has an unfolding that says it should never occur
524 neverUnfold :: Unfolding -> Bool
525 neverUnfold NoUnfolding = True
526 neverUnfold (OtherCon _) = True
527 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
528 neverUnfold _ = False
532 %************************************************************************
534 \subsection{The main data type}
536 %************************************************************************
539 -- The Ord is needed for the FiniteMap used in the lookForConstructor
540 -- in SimplEnv. If you declared that lookForConstructor *ignores*
541 -- constructor-applications with LitArg args, then you could get
544 instance Outputable AltCon where
545 ppr (DataAlt dc) = ppr dc
546 ppr (LitAlt lit) = ppr lit
547 ppr DEFAULT = ptext (sLit "__DEFAULT")
549 instance Show AltCon where
550 showsPrec p con = showsPrecSDoc p (ppr con)
552 cmpAlt :: Alt b -> Alt b -> Ordering
553 cmpAlt (con1, _, _) (con2, _, _) = con1 `cmpAltCon` con2
555 ltAlt :: Alt b -> Alt b -> Bool
556 ltAlt a1 a2 = (a1 `cmpAlt` a2) == LT
558 cmpAltCon :: AltCon -> AltCon -> Ordering
559 -- ^ Compares 'AltCon's within a single list of alternatives
560 cmpAltCon DEFAULT DEFAULT = EQ
561 cmpAltCon DEFAULT _ = LT
563 cmpAltCon (DataAlt d1) (DataAlt d2) = dataConTag d1 `compare` dataConTag d2
564 cmpAltCon (DataAlt _) DEFAULT = GT
565 cmpAltCon (LitAlt l1) (LitAlt l2) = l1 `compare` l2
566 cmpAltCon (LitAlt _) DEFAULT = GT
568 cmpAltCon con1 con2 = WARN( True, text "Comparing incomparable AltCons" <+>
569 ppr con1 <+> ppr con2 )
573 %************************************************************************
575 \subsection{Useful synonyms}
577 %************************************************************************
580 -- | The common case for the type of binders and variables when
581 -- we are manipulating the Core language within GHC
583 -- | Expressions where binders are 'CoreBndr's
584 type CoreExpr = Expr CoreBndr
585 -- | Argument expressions where binders are 'CoreBndr's
586 type CoreArg = Arg CoreBndr
587 -- | Binding groups where binders are 'CoreBndr's
588 type CoreBind = Bind CoreBndr
589 -- | Case alternatives where binders are 'CoreBndr's
590 type CoreAlt = Alt CoreBndr
593 %************************************************************************
597 %************************************************************************
600 -- | Binders are /tagged/ with a t
601 data TaggedBndr t = TB CoreBndr t -- TB for "tagged binder"
603 type TaggedBind t = Bind (TaggedBndr t)
604 type TaggedExpr t = Expr (TaggedBndr t)
605 type TaggedArg t = Arg (TaggedBndr t)
606 type TaggedAlt t = Alt (TaggedBndr t)
608 instance Outputable b => Outputable (TaggedBndr b) where
609 ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>'
611 instance Outputable b => OutputableBndr (TaggedBndr b) where
612 pprBndr _ b = ppr b -- Simple
616 %************************************************************************
618 \subsection{Core-constructing functions with checking}
620 %************************************************************************
623 -- | Apply a list of argument expressions to a function expression in a nested fashion. Prefer to
624 -- use 'CoreUtils.mkCoreApps' if possible
625 mkApps :: Expr b -> [Arg b] -> Expr b
626 -- | Apply a list of type argument expressions to a function expression in a nested fashion
627 mkTyApps :: Expr b -> [Type] -> Expr b
628 -- | Apply a list of type or value variables to a function expression in a nested fashion
629 mkVarApps :: Expr b -> [Var] -> Expr b
630 -- | Apply a list of argument expressions to a data constructor in a nested fashion. Prefer to
631 -- use 'MkCore.mkCoreConApps' if possible
632 mkConApp :: DataCon -> [Arg b] -> Expr b
634 mkApps f args = foldl App f args
635 mkTyApps f args = foldl (\ e a -> App e (Type a)) f args
636 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
637 mkConApp con args = mkApps (Var (dataConWorkId con)) args
640 -- | Create a machine integer literal expression of type @Int#@ from an @Integer@.
641 -- If you want an expression of type @Int@ use 'MkCore.mkIntExpr'
642 mkIntLit :: Integer -> Expr b
643 -- | Create a machine integer literal expression of type @Int#@ from an @Int@.
644 -- If you want an expression of type @Int@ use 'MkCore.mkIntExpr'
645 mkIntLitInt :: Int -> Expr b
647 mkIntLit n = Lit (mkMachInt n)
648 mkIntLitInt n = Lit (mkMachInt (toInteger n))
650 -- | Create a machine word literal expression of type @Word#@ from an @Integer@.
651 -- If you want an expression of type @Word@ use 'MkCore.mkWordExpr'
652 mkWordLit :: Integer -> Expr b
653 -- | Create a machine word literal expression of type @Word#@ from a @Word@.
654 -- If you want an expression of type @Word@ use 'MkCore.mkWordExpr'
655 mkWordLitWord :: Word -> Expr b
657 mkWordLit w = Lit (mkMachWord w)
658 mkWordLitWord w = Lit (mkMachWord (toInteger w))
660 -- | Create a machine character literal expression of type @Char#@.
661 -- If you want an expression of type @Char@ use 'MkCore.mkCharExpr'
662 mkCharLit :: Char -> Expr b
663 -- | Create a machine string literal expression of type @Addr#@.
664 -- If you want an expression of type @String@ use 'MkCore.mkStringExpr'
665 mkStringLit :: String -> Expr b
667 mkCharLit c = Lit (mkMachChar c)
668 mkStringLit s = Lit (mkMachString s)
670 -- | Create a machine single precision literal expression of type @Float#@ from a @Rational@.
671 -- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr'
672 mkFloatLit :: Rational -> Expr b
673 -- | Create a machine single precision literal expression of type @Float#@ from a @Float@.
674 -- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr'
675 mkFloatLitFloat :: Float -> Expr b
677 mkFloatLit f = Lit (mkMachFloat f)
678 mkFloatLitFloat f = Lit (mkMachFloat (toRational f))
680 -- | Create a machine double precision literal expression of type @Double#@ from a @Rational@.
681 -- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr'
682 mkDoubleLit :: Rational -> Expr b
683 -- | Create a machine double precision literal expression of type @Double#@ from a @Double@.
684 -- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr'
685 mkDoubleLitDouble :: Double -> Expr b
687 mkDoubleLit d = Lit (mkMachDouble d)
688 mkDoubleLitDouble d = Lit (mkMachDouble (toRational d))
690 -- | Bind all supplied binding groups over an expression in a nested let expression. Prefer to
691 -- use 'CoreUtils.mkCoreLets' if possible
692 mkLets :: [Bind b] -> Expr b -> Expr b
693 -- | Bind all supplied binders over an expression in a nested lambda expression. Prefer to
694 -- use 'CoreUtils.mkCoreLams' if possible
695 mkLams :: [b] -> Expr b -> Expr b
697 mkLams binders body = foldr Lam body binders
698 mkLets binds body = foldr Let body binds
701 -- | Create a binding group where a type variable is bound to a type. Per "CoreSyn#type_let",
702 -- this can only be used to bind something in a non-recursive @let@ expression
703 mkTyBind :: TyVar -> Type -> CoreBind
704 mkTyBind tv ty = NonRec tv (Type ty)
706 -- | Convert a binder into either a 'Var' or 'Type' 'Expr' appropriately
707 varToCoreExpr :: CoreBndr -> Expr b
708 varToCoreExpr v | isId v = Var v
709 | otherwise = Type (mkTyVarTy v)
711 varsToCoreExprs :: [CoreBndr] -> [Expr b]
712 varsToCoreExprs vs = map varToCoreExpr vs
716 %************************************************************************
718 \subsection{Simple access functions}
720 %************************************************************************
723 -- | Extract every variable by this group
724 bindersOf :: Bind b -> [b]
725 bindersOf (NonRec binder _) = [binder]
726 bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
728 -- | 'bindersOf' applied to a list of binding groups
729 bindersOfBinds :: [Bind b] -> [b]
730 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
732 rhssOfBind :: Bind b -> [Expr b]
733 rhssOfBind (NonRec _ rhs) = [rhs]
734 rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
736 rhssOfAlts :: [Alt b] -> [Expr b]
737 rhssOfAlts alts = [e | (_,_,e) <- alts]
739 -- | Collapse all the bindings in the supplied groups into a single
740 -- list of lhs\/rhs pairs suitable for binding in a 'Rec' binding group
741 flattenBinds :: [Bind b] -> [(b, Expr b)]
742 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
743 flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
748 -- | We often want to strip off leading lambdas before getting down to
749 -- business. This function is your friend.
750 collectBinders :: Expr b -> ([b], Expr b)
751 -- | Collect as many type bindings as possible from the front of a nested lambda
752 collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr)
753 -- | Collect as many value bindings as possible from the front of a nested lambda
754 collectValBinders :: CoreExpr -> ([Id], CoreExpr)
755 -- | Collect type binders from the front of the lambda first,
756 -- then follow up by collecting as many value bindings as possible
757 -- from the resulting stripped expression
758 collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
763 go bs (Lam b e) = go (b:bs) e
764 go bs e = (reverse bs, e)
766 collectTyAndValBinders expr
769 (tvs, body1) = collectTyBinders expr
770 (ids, body) = collectValBinders body1
772 collectTyBinders expr
775 go tvs (Lam b e) | isTyVar b = go (b:tvs) e
776 go tvs e = (reverse tvs, e)
778 collectValBinders expr
781 go ids (Lam b e) | isId b = go (b:ids) e
782 go ids body = (reverse ids, body)
786 -- | Takes a nested application expression and returns the the function
787 -- being applied and the arguments to which it is applied
788 collectArgs :: Expr b -> (Expr b, [Arg b])
792 go (App f a) as = go f (a:as)
797 -- | Gets the cost centre enclosing an expression, if any.
798 -- It looks inside lambdas because @(scc \"foo\" \\x.e) = \\x. scc \"foo\" e@
799 coreExprCc :: Expr b -> CostCentre
800 coreExprCc (Note (SCC cc) _) = cc
801 coreExprCc (Note _ e) = coreExprCc e
802 coreExprCc (Lam _ e) = coreExprCc e
803 coreExprCc _ = noCostCentre
806 %************************************************************************
808 \subsection{Predicates}
810 %************************************************************************
812 At one time we optionally carried type arguments through to runtime.
813 @isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
814 i.e. if type applications are actual lambdas because types are kept around
815 at runtime. Similarly isRuntimeArg.
818 -- | Will this variable exist at runtime?
819 isRuntimeVar :: Var -> Bool
822 -- | Will this argument expression exist at runtime?
823 isRuntimeArg :: CoreExpr -> Bool
824 isRuntimeArg = isValArg
826 -- | Returns @False@ iff the expression is a 'Type' expression at its top level
827 isValArg :: Expr b -> Bool
828 isValArg (Type _) = False
831 -- | Returns @True@ iff the expression is a 'Type' expression at its top level
832 isTypeArg :: Expr b -> Bool
833 isTypeArg (Type _) = True
836 -- | The number of binders that bind values rather than types
837 valBndrCount :: [CoreBndr] -> Int
838 valBndrCount = count isId
840 -- | The number of argument expressions that are values rather than types at their top level
841 valArgCount :: [Arg b] -> Int
842 valArgCount = count isValArg
846 %************************************************************************
848 \subsection{Seq stuff}
850 %************************************************************************
853 seqExpr :: CoreExpr -> ()
854 seqExpr (Var v) = v `seq` ()
855 seqExpr (Lit lit) = lit `seq` ()
856 seqExpr (App f a) = seqExpr f `seq` seqExpr a
857 seqExpr (Lam b e) = seqBndr b `seq` seqExpr e
858 seqExpr (Let b e) = seqBind b `seq` seqExpr e
859 seqExpr (Case e b t as) = seqExpr e `seq` seqBndr b `seq` seqType t `seq` seqAlts as
860 seqExpr (Cast e co) = seqExpr e `seq` seqType co
861 seqExpr (Note n e) = seqNote n `seq` seqExpr e
862 seqExpr (Type t) = seqType t
864 seqExprs :: [CoreExpr] -> ()
866 seqExprs (e:es) = seqExpr e `seq` seqExprs es
868 seqNote :: Note -> ()
869 seqNote (CoreNote s) = s `seq` ()
872 seqBndr :: CoreBndr -> ()
873 seqBndr b = b `seq` ()
875 seqBndrs :: [CoreBndr] -> ()
877 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
879 seqBind :: Bind CoreBndr -> ()
880 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
881 seqBind (Rec prs) = seqPairs prs
883 seqPairs :: [(CoreBndr, CoreExpr)] -> ()
885 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
887 seqAlts :: [CoreAlt] -> ()
889 seqAlts ((c,bs,e):alts) = c `seq` seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
891 seqRules :: [CoreRule] -> ()
893 seqRules (Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs } : rules)
894 = seqBndrs bndrs `seq` seqExprs (rhs:args) `seq` seqRules rules
895 seqRules (BuiltinRule {} : rules) = seqRules rules
898 %************************************************************************
900 \subsection{Annotated core}
902 %************************************************************************
905 -- | Annotated core: allows annotation at every node in the tree
906 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
908 -- | A clone of the 'Expr' type but allowing annotation at every tree node
909 data AnnExpr' bndr annot
912 | AnnLam bndr (AnnExpr bndr annot)
913 | AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
914 | AnnCase (AnnExpr bndr annot) bndr Type [AnnAlt bndr annot]
915 | AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
916 | AnnCast (AnnExpr bndr annot) Coercion
917 | AnnNote Note (AnnExpr bndr annot)
920 -- | A clone of the 'Alt' type but allowing annotation at every tree node
921 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
923 -- | A clone of the 'Bind' type but allowing annotation at every tree node
924 data AnnBind bndr annot
925 = AnnNonRec bndr (AnnExpr bndr annot)
926 | AnnRec [(bndr, AnnExpr bndr annot)]
930 deAnnotate :: AnnExpr bndr annot -> Expr bndr
931 deAnnotate (_, e) = deAnnotate' e
933 deAnnotate' :: AnnExpr' bndr annot -> Expr bndr
934 deAnnotate' (AnnType t) = Type t
935 deAnnotate' (AnnVar v) = Var v
936 deAnnotate' (AnnLit lit) = Lit lit
937 deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
938 deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
939 deAnnotate' (AnnCast e co) = Cast (deAnnotate e) co
940 deAnnotate' (AnnNote note body) = Note note (deAnnotate body)
942 deAnnotate' (AnnLet bind body)
943 = Let (deAnnBind bind) (deAnnotate body)
945 deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
946 deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
948 deAnnotate' (AnnCase scrut v t alts)
949 = Case (deAnnotate scrut) v t (map deAnnAlt alts)
951 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
952 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
956 -- | As 'collectBinders' but for 'AnnExpr' rather than 'Expr'
957 collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot)
961 collect bs (_, AnnLam b body) = collect (b:bs) body
962 collect bs body = (reverse bs, body)