2 -- | Handy functions for creating much Core syntax
4 -- * Constructing normal syntax
6 mkCoreApp, mkCoreApps, mkCoreConApps,
7 mkCoreLams, mkWildCase, mkWildBinder, mkIfThenElse,
9 -- * Constructing boxed literals
10 mkWordExpr, mkWordExprWord,
11 mkIntExpr, mkIntExprInt,
13 mkFloatExpr, mkDoubleExpr,
14 mkCharExpr, mkStringExpr, mkStringExprFS,
16 -- * Constructing general big tuples
20 -- * Constructing small tuples
21 mkCoreVarTup, mkCoreVarTupTy, mkCoreTup,
23 -- * Constructing big tuples
24 mkBigCoreVarTup, mkBigCoreVarTupTy,
25 mkBigCoreTup, mkBigCoreTupTy,
27 -- * Deconstructing small tuples
28 mkSmallTupleSelector, mkSmallTupleCase,
30 -- * Deconstructing big tuples
31 mkTupleSelector, mkTupleCase,
33 -- * Constructing list expressions
34 mkNilExpr, mkConsExpr, mkListExpr,
35 mkFoldrExpr, mkBuildExpr
38 #include "HsVersions.h"
41 import Var ( setTyVarUnique )
44 import CoreUtils ( exprType, needsCaseBinding, bindNonRec )
52 import TysPrim ( alphaTyVar )
53 import DataCon ( DataCon, dataConWorkId )
57 import Unique ( mkBuiltinUnique )
59 import Util ( notNull, zipEqual )
63 import Data.Char ( ord )
66 infixl 4 `mkCoreApp`, `mkCoreApps`
69 %************************************************************************
71 \subsection{Basic CoreSyn construction}
73 %************************************************************************
76 -- | Bind a binding group over an expression, using a @let@ or @case@ as
77 -- appropriate (see "CoreSyn#let_app_invariant")
78 mkCoreLet :: CoreBind -> CoreExpr -> CoreExpr
79 mkCoreLet (NonRec bndr rhs) body -- See Note [CoreSyn let/app invariant]
80 | needsCaseBinding (idType bndr) rhs
81 = Case rhs bndr (exprType body) [(DEFAULT,[],body)]
85 -- | Bind a list of binding groups over an expression. The leftmost binding
86 -- group becomes the outermost group in the resulting expression
87 mkCoreLets :: [CoreBind] -> CoreExpr -> CoreExpr
88 mkCoreLets binds body = foldr mkCoreLet body binds
90 -- | Construct an expression which represents the application of one expression
92 mkCoreApp :: CoreExpr -> CoreExpr -> CoreExpr
93 -- Check the invariant that the arg of an App is ok-for-speculation if unlifted
94 -- See CoreSyn Note [CoreSyn let/app invariant]
95 mkCoreApp fun (Type ty) = App fun (Type ty)
96 mkCoreApp fun arg = mk_val_app fun arg arg_ty res_ty
98 (arg_ty, res_ty) = splitFunTy (exprType fun)
100 -- | Construct an expression which represents the application of a number of
101 -- expressions to another. The leftmost expression in the list is applied first
102 mkCoreApps :: CoreExpr -> [CoreExpr] -> CoreExpr
103 -- Slightly more efficient version of (foldl mkCoreApp)
105 = go fun (exprType fun) args
108 go fun fun_ty (Type ty : args) = go (App fun (Type ty)) (applyTy fun_ty ty) args
109 go fun fun_ty (arg : args) = go (mk_val_app fun arg arg_ty res_ty) res_ty args
111 (arg_ty, res_ty) = splitFunTy fun_ty
113 -- | Construct an expression which represents the application of a number of
114 -- expressions to that of a data constructor expression. The leftmost expression
115 -- in the list is applied first
116 mkCoreConApps :: DataCon -> [CoreExpr] -> CoreExpr
117 mkCoreConApps con args = mkCoreApps (Var (dataConWorkId con)) args
120 mk_val_app :: CoreExpr -> CoreExpr -> Type -> Type -> CoreExpr
121 mk_val_app fun arg arg_ty _ -- See Note [CoreSyn let/app invariant]
122 | not (needsCaseBinding arg_ty arg)
123 = App fun arg -- The vastly common case
125 mk_val_app fun arg arg_ty res_ty
126 = Case arg arg_id res_ty [(DEFAULT,[],App fun (Var arg_id))]
128 arg_id = mkWildBinder arg_ty
129 -- Lots of shadowing, but it doesn't matter,
130 -- because 'fun ' should not have a free wild-id
132 -- This is Dangerous. But this is the only place we play this
133 -- game, mk_val_app returns an expression that does not have
134 -- have a free wild-id. So the only thing that can go wrong
135 -- is if you take apart this case expression, and pass a
136 -- fragmet of it as the fun part of a 'mk_val_app'.
139 -- | Make a /wildcard binder/. This is typically used when you need a binder
140 -- that you expect to use only at a *binding* site. Do not use it at
141 -- occurrence sites because it has a single, fixed unique, and it's very
142 -- easy to get into difficulties with shadowing. That's why it is used so little.
143 mkWildBinder :: Type -> Id
144 mkWildBinder ty = mkSysLocal (fsLit "wild") (mkBuiltinUnique 1) ty
146 mkWildCase :: CoreExpr -> Type -> Type -> [CoreAlt] -> CoreExpr
147 -- Make a case expression whose case binder is unused
148 -- The alts should not have any occurrences of WildId
149 mkWildCase scrut scrut_ty res_ty alts
150 = Case scrut (mkWildBinder scrut_ty) res_ty alts
152 mkIfThenElse :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
153 mkIfThenElse guard then_expr else_expr
154 -- Not going to be refining, so okay to take the type of the "then" clause
155 = mkWildCase guard boolTy (exprType then_expr)
156 [ (DataAlt falseDataCon, [], else_expr), -- Increasing order of tag!
157 (DataAlt trueDataCon, [], then_expr) ]
160 The functions from this point don't really do anything cleverer than
161 their counterparts in CoreSyn, but they are here for consistency
164 -- | Create a lambda where the given expression has a number of variables
165 -- bound over it. The leftmost binder is that bound by the outermost
166 -- lambda in the result
167 mkCoreLams :: [CoreBndr] -> CoreExpr -> CoreExpr
171 %************************************************************************
173 \subsection{Making literals}
175 %************************************************************************
178 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
179 mkIntExpr :: Integer -> CoreExpr -- Result = I# i :: Int
180 mkIntExpr i = mkConApp intDataCon [mkIntLit i]
182 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
183 mkIntExprInt :: Int -> CoreExpr -- Result = I# i :: Int
184 mkIntExprInt i = mkConApp intDataCon [mkIntLitInt i]
186 -- | Create a 'CoreExpr' which will evaluate to the a @Word@ with the given value
187 mkWordExpr :: Integer -> CoreExpr
188 mkWordExpr w = mkConApp wordDataCon [mkWordLit w]
190 -- | Create a 'CoreExpr' which will evaluate to the given @Word@
191 mkWordExprWord :: Word -> CoreExpr
192 mkWordExprWord w = mkConApp wordDataCon [mkWordLitWord w]
194 -- | Create a 'CoreExpr' which will evaluate to the given @Integer@
195 mkIntegerExpr :: MonadThings m => Integer -> m CoreExpr -- Result :: Integer
197 | inIntRange i -- Small enough, so start from an Int
198 = do integer_id <- lookupId smallIntegerName
199 return (mkSmallIntegerLit integer_id i)
201 -- Special case for integral literals with a large magnitude:
202 -- They are transformed into an expression involving only smaller
203 -- integral literals. This improves constant folding.
205 | otherwise = do -- Big, so start from a string
206 plus_id <- lookupId plusIntegerName
207 times_id <- lookupId timesIntegerName
208 integer_id <- lookupId smallIntegerName
210 lit i = mkSmallIntegerLit integer_id i
211 plus a b = Var plus_id `App` a `App` b
212 times a b = Var times_id `App` a `App` b
214 -- Transform i into (x1 + (x2 + (x3 + (...) * b) * b) * b) with abs xi <= b
215 horner :: Integer -> Integer -> CoreExpr
216 horner b i | abs q <= 1 = if r == 0 || r == i
218 else lit r `plus` lit (i-r)
219 | r == 0 = horner b q `times` lit b
220 | otherwise = lit r `plus` (horner b q `times` lit b)
222 (q,r) = i `quotRem` b
224 return (horner tARGET_MAX_INT i)
226 mkSmallIntegerLit :: Id -> Integer -> CoreExpr
227 mkSmallIntegerLit small_integer i = mkApps (Var small_integer) [mkIntLit i]
230 -- | Create a 'CoreExpr' which will evaluate to the given @Float@
231 mkFloatExpr :: Float -> CoreExpr
232 mkFloatExpr f = mkConApp floatDataCon [mkFloatLitFloat f]
234 -- | Create a 'CoreExpr' which will evaluate to the given @Double@
235 mkDoubleExpr :: Double -> CoreExpr
236 mkDoubleExpr d = mkConApp doubleDataCon [mkDoubleLitDouble d]
239 -- | Create a 'CoreExpr' which will evaluate to the given @Char@
240 mkCharExpr :: Char -> CoreExpr -- Result = C# c :: Int
241 mkCharExpr c = mkConApp charDataCon [mkCharLit c]
243 -- | Create a 'CoreExpr' which will evaluate to the given @String@
244 mkStringExpr :: MonadThings m => String -> m CoreExpr -- Result :: String
245 -- | Create a 'CoreExpr' which will evaluate to a string morally equivalent to the given @FastString@
246 mkStringExprFS :: MonadThings m => FastString -> m CoreExpr -- Result :: String
248 mkStringExpr str = mkStringExprFS (mkFastString str)
252 = return (mkNilExpr charTy)
255 = do let the_char = mkCharExpr (headFS str)
256 return (mkConsExpr charTy the_char (mkNilExpr charTy))
259 = do unpack_id <- lookupId unpackCStringName
260 return (App (Var unpack_id) (Lit (MachStr str)))
263 = do unpack_id <- lookupId unpackCStringUtf8Name
264 return (App (Var unpack_id) (Lit (MachStr str)))
268 safeChar c = ord c >= 1 && ord c <= 0x7F
271 %************************************************************************
273 \subsection{Tuple constructors}
275 %************************************************************************
282 -- GHCs built in tuples can only go up to 'mAX_TUPLE_SIZE' in arity, but
283 -- we might concievably want to build such a massive tuple as part of the
284 -- output of a desugaring stage (notably that for list comprehensions).
286 -- We call tuples above this size \"big tuples\", and emulate them by
287 -- creating and pattern matching on >nested< tuples that are expressible
290 -- Nesting policy: it's better to have a 2-tuple of 10-tuples (3 objects)
291 -- than a 10-tuple of 2-tuples (11 objects), so we want the leaves of any
292 -- construction to be big.
294 -- If you just use the 'mkBigCoreTup', 'mkBigCoreVarTupTy', 'mkTupleSelector'
295 -- and 'mkTupleCase' functions to do all your work with tuples you should be
296 -- fine, and not have to worry about the arity limitation at all.
298 -- | Lifts a \"small\" constructor into a \"big\" constructor by recursive decompositon
299 mkChunkified :: ([a] -> a) -- ^ \"Small\" constructor function, of maximum input arity 'mAX_TUPLE_SIZE'
300 -> [a] -- ^ Possible \"big\" list of things to construct from
301 -> a -- ^ Constructed thing made possible by recursive decomposition
302 mkChunkified small_tuple as = mk_big_tuple (chunkify as)
304 -- Each sub-list is short enough to fit in a tuple
305 mk_big_tuple [as] = small_tuple as
306 mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
308 chunkify :: [a] -> [[a]]
309 -- ^ Split a list into lists that are small enough to have a corresponding
310 -- tuple arity. The sub-lists of the result all have length <= 'mAX_TUPLE_SIZE'
311 -- But there may be more than 'mAX_TUPLE_SIZE' sub-lists
313 | n_xs <= mAX_TUPLE_SIZE = [xs]
314 | otherwise = split xs
318 split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
322 Creating tuples and their types for Core expressions
324 @mkBigCoreVarTup@ builds a tuple; the inverse to @mkTupleSelector@.
326 * If it has only one element, it is the identity function.
328 * If there are more elements than a big tuple can have, it nests
333 -- | Build a small tuple holding the specified variables
334 mkCoreVarTup :: [Id] -> CoreExpr
335 mkCoreVarTup ids = mkCoreTup (map Var ids)
337 -- | Bulid the type of a small tuple that holds the specified variables
338 mkCoreVarTupTy :: [Id] -> Type
339 mkCoreVarTupTy ids = mkBoxedTupleTy (map idType ids)
341 -- | Build a small tuple holding the specified expressions
342 mkCoreTup :: [CoreExpr] -> CoreExpr
343 mkCoreTup [] = Var unitDataConId
345 mkCoreTup cs = mkConApp (tupleCon Boxed (length cs))
346 (map (Type . exprType) cs ++ cs)
348 -- | Build a big tuple holding the specified variables
349 mkBigCoreVarTup :: [Id] -> CoreExpr
350 mkBigCoreVarTup ids = mkBigCoreTup (map Var ids)
352 -- | Build the type of a big tuple that holds the specified variables
353 mkBigCoreVarTupTy :: [Id] -> Type
354 mkBigCoreVarTupTy ids = mkBigCoreTupTy (map idType ids)
356 -- | Build a big tuple holding the specified expressions
357 mkBigCoreTup :: [CoreExpr] -> CoreExpr
358 mkBigCoreTup = mkChunkified mkCoreTup
360 -- | Build the type of a big tuple that holds the specified type of thing
361 mkBigCoreTupTy :: [Type] -> Type
362 mkBigCoreTupTy = mkChunkified mkBoxedTupleTy
365 %************************************************************************
367 \subsection{Tuple destructors}
369 %************************************************************************
372 -- | Builds a selector which scrutises the given
373 -- expression and extracts the one name from the list given.
374 -- If you want the no-shadowing rule to apply, the caller
375 -- is responsible for making sure that none of these names
378 -- If there is just one 'Id' in the tuple, then the selector is
379 -- just the identity.
381 -- If necessary, we pattern match on a \"big\" tuple.
382 mkTupleSelector :: [Id] -- ^ The 'Id's to pattern match the tuple against
383 -> Id -- ^ The 'Id' to select
384 -> Id -- ^ A variable of the same type as the scrutinee
385 -> CoreExpr -- ^ Scrutinee
386 -> CoreExpr -- ^ Selector expression
388 -- mkTupleSelector [a,b,c,d] b v e
390 -- (p,q) -> case p of p {
392 -- We use 'tpl' vars for the p,q, since shadowing does not matter.
394 -- In fact, it's more convenient to generate it innermost first, getting
399 mkTupleSelector vars the_var scrut_var scrut
400 = mk_tup_sel (chunkify vars) the_var
402 mk_tup_sel [vars] the_var = mkSmallTupleSelector vars the_var scrut_var scrut
403 mk_tup_sel vars_s the_var = mkSmallTupleSelector group the_var tpl_v $
404 mk_tup_sel (chunkify tpl_vs) tpl_v
406 tpl_tys = [mkBoxedTupleTy (map idType gp) | gp <- vars_s]
407 tpl_vs = mkTemplateLocals tpl_tys
408 [(tpl_v, group)] = [(tpl,gp) | (tpl,gp) <- zipEqual "mkTupleSelector" tpl_vs vars_s,
413 -- | Like 'mkTupleSelector' but for tuples that are guaranteed
414 -- never to be \"big\".
416 -- > mkSmallTupleSelector [x] x v e = [| e |]
417 -- > mkSmallTupleSelector [x,y,z] x v e = [| case e of v { (x,y,z) -> x } |]
418 mkSmallTupleSelector :: [Id] -- The tuple args
419 -> Id -- The selected one
420 -> Id -- A variable of the same type as the scrutinee
421 -> CoreExpr -- Scrutinee
423 mkSmallTupleSelector [var] should_be_the_same_var _ scrut
424 = ASSERT(var == should_be_the_same_var)
426 mkSmallTupleSelector vars the_var scrut_var scrut
427 = ASSERT( notNull vars )
428 Case scrut scrut_var (idType the_var)
429 [(DataAlt (tupleCon Boxed (length vars)), vars, Var the_var)]
433 -- | A generalization of 'mkTupleSelector', allowing the body
434 -- of the case to be an arbitrary expression.
436 -- To avoid shadowing, we use uniques to invent new variables.
438 -- If necessary we pattern match on a \"big\" tuple.
439 mkTupleCase :: UniqSupply -- ^ For inventing names of intermediate variables
440 -> [Id] -- ^ The tuple identifiers to pattern match on
441 -> CoreExpr -- ^ Body of the case
442 -> Id -- ^ A variable of the same type as the scrutinee
443 -> CoreExpr -- ^ Scrutinee
445 -- ToDo: eliminate cases where none of the variables are needed.
447 -- mkTupleCase uniqs [a,b,c,d] body v e
448 -- = case e of v { (p,q) ->
449 -- case p of p { (a,b) ->
450 -- case q of q { (c,d) ->
452 mkTupleCase uniqs vars body scrut_var scrut
453 = mk_tuple_case uniqs (chunkify vars) body
455 -- This is the case where don't need any nesting
456 mk_tuple_case _ [vars] body
457 = mkSmallTupleCase vars body scrut_var scrut
459 -- This is the case where we must make nest tuples at least once
460 mk_tuple_case us vars_s body
461 = let (us', vars', body') = foldr one_tuple_case (us, [], body) vars_s
462 in mk_tuple_case us' (chunkify vars') body'
464 one_tuple_case chunk_vars (us, vs, body)
465 = let (us1, us2) = splitUniqSupply us
466 scrut_var = mkSysLocal (fsLit "ds") (uniqFromSupply us1)
467 (mkBoxedTupleTy (map idType chunk_vars))
468 body' = mkSmallTupleCase chunk_vars body scrut_var (Var scrut_var)
469 in (us2, scrut_var:vs, body')
473 -- | As 'mkTupleCase', but for a tuple that is small enough to be guaranteed
474 -- not to need nesting.
476 :: [Id] -- ^ The tuple args
477 -> CoreExpr -- ^ Body of the case
478 -> Id -- ^ A variable of the same type as the scrutinee
479 -> CoreExpr -- ^ Scrutinee
482 mkSmallTupleCase [var] body _scrut_var scrut
483 = bindNonRec var scrut body
484 mkSmallTupleCase vars body scrut_var scrut
485 -- One branch no refinement?
486 = Case scrut scrut_var (exprType body) [(DataAlt (tupleCon Boxed (length vars)), vars, body)]
489 %************************************************************************
491 \subsection{Common list manipulation expressions}
493 %************************************************************************
495 Call the constructor Ids when building explicit lists, so that they
496 interact well with rules.
499 -- | Makes a list @[]@ for lists of the specified type
500 mkNilExpr :: Type -> CoreExpr
501 mkNilExpr ty = mkConApp nilDataCon [Type ty]
503 -- | Makes a list @(:)@ for lists of the specified type
504 mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
505 mkConsExpr ty hd tl = mkConApp consDataCon [Type ty, hd, tl]
507 -- | Make a list containing the given expressions, where the list has the given type
508 mkListExpr :: Type -> [CoreExpr] -> CoreExpr
509 mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
511 -- | Make a fully applied 'foldr' expression
512 mkFoldrExpr :: MonadThings m
513 => Type -- ^ Element type of the list
514 -> Type -- ^ Fold result type
515 -> CoreExpr -- ^ "Cons" function expression for the fold
516 -> CoreExpr -- ^ "Nil" expression for the fold
517 -> CoreExpr -- ^ List expression being folded acress
519 mkFoldrExpr elt_ty result_ty c n list = do
520 foldr_id <- lookupId foldrName
521 return (Var foldr_id `App` Type elt_ty
527 -- | Make a 'build' expression applied to a locally-bound worker function
528 mkBuildExpr :: (MonadThings m, MonadUnique m)
529 => Type -- ^ Type of list elements to be built
530 -> ((Id, Type) -> (Id, Type) -> m CoreExpr) -- ^ Function that, given information about the 'Id's
531 -- of the binders for the build worker function, returns
532 -- the body of that worker
534 mkBuildExpr elt_ty mk_build_inside = do
535 [n_tyvar] <- newTyVars [alphaTyVar]
536 let n_ty = mkTyVarTy n_tyvar
537 c_ty = mkFunTys [elt_ty, n_ty] n_ty
538 [c, n] <- sequence [mkSysLocalM (fsLit "c") c_ty, mkSysLocalM (fsLit "n") n_ty]
540 build_inside <- mk_build_inside (c, c_ty) (n, n_ty)
542 build_id <- lookupId buildName
543 return $ Var build_id `App` Type elt_ty `App` mkLams [n_tyvar, c, n] build_inside
545 newTyVars tyvar_tmpls = do
547 return (zipWith setTyVarUnique tyvar_tmpls uniqs)