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 )
58 import Unique ( mkBuiltinUnique )
60 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 = ASSERT2( isFunTy fun_ty, ppr fun $$ ppr arg )
97 mk_val_app fun arg arg_ty res_ty
100 (arg_ty, res_ty) = splitFunTy fun_ty
102 -- | Construct an expression which represents the application of a number of
103 -- expressions to another. The leftmost expression in the list is applied first
104 mkCoreApps :: CoreExpr -> [CoreExpr] -> CoreExpr
105 -- Slightly more efficient version of (foldl mkCoreApp)
106 mkCoreApps orig_fun orig_args
107 = go orig_fun (exprType orig_fun) orig_args
110 go fun fun_ty (Type ty : args) = go (App fun (Type ty)) (applyTy fun_ty ty) args
111 go fun fun_ty (arg : args) = ASSERT2( isFunTy fun_ty, ppr fun_ty $$ ppr orig_fun $$ ppr orig_args )
112 go (mk_val_app fun arg arg_ty res_ty) res_ty args
114 (arg_ty, res_ty) = splitFunTy fun_ty
116 -- | Construct an expression which represents the application of a number of
117 -- expressions to that of a data constructor expression. The leftmost expression
118 -- in the list is applied first
119 mkCoreConApps :: DataCon -> [CoreExpr] -> CoreExpr
120 mkCoreConApps con args = mkCoreApps (Var (dataConWorkId con)) args
123 mk_val_app :: CoreExpr -> CoreExpr -> Type -> Type -> CoreExpr
124 mk_val_app fun arg arg_ty _ -- See Note [CoreSyn let/app invariant]
125 | not (needsCaseBinding arg_ty arg)
126 = App fun arg -- The vastly common case
128 mk_val_app fun arg arg_ty res_ty
129 = Case arg arg_id res_ty [(DEFAULT,[],App fun (Var arg_id))]
131 arg_id = mkWildBinder arg_ty
132 -- Lots of shadowing, but it doesn't matter,
133 -- because 'fun ' should not have a free wild-id
135 -- This is Dangerous. But this is the only place we play this
136 -- game, mk_val_app returns an expression that does not have
137 -- have a free wild-id. So the only thing that can go wrong
138 -- is if you take apart this case expression, and pass a
139 -- fragmet of it as the fun part of a 'mk_val_app'.
142 -- | Make a /wildcard binder/. This is typically used when you need a binder
143 -- that you expect to use only at a *binding* site. Do not use it at
144 -- occurrence sites because it has a single, fixed unique, and it's very
145 -- easy to get into difficulties with shadowing. That's why it is used so little.
146 mkWildBinder :: Type -> Id
147 mkWildBinder ty = mkSysLocal (fsLit "wild") (mkBuiltinUnique 1) ty
149 mkWildCase :: CoreExpr -> Type -> Type -> [CoreAlt] -> CoreExpr
150 -- Make a case expression whose case binder is unused
151 -- The alts should not have any occurrences of WildId
152 mkWildCase scrut scrut_ty res_ty alts
153 = Case scrut (mkWildBinder scrut_ty) res_ty alts
155 mkIfThenElse :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
156 mkIfThenElse guard then_expr else_expr
157 -- Not going to be refining, so okay to take the type of the "then" clause
158 = mkWildCase guard boolTy (exprType then_expr)
159 [ (DataAlt falseDataCon, [], else_expr), -- Increasing order of tag!
160 (DataAlt trueDataCon, [], then_expr) ]
163 The functions from this point don't really do anything cleverer than
164 their counterparts in CoreSyn, but they are here for consistency
167 -- | Create a lambda where the given expression has a number of variables
168 -- bound over it. The leftmost binder is that bound by the outermost
169 -- lambda in the result
170 mkCoreLams :: [CoreBndr] -> CoreExpr -> CoreExpr
174 %************************************************************************
176 \subsection{Making literals}
178 %************************************************************************
181 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
182 mkIntExpr :: Integer -> CoreExpr -- Result = I# i :: Int
183 mkIntExpr i = mkConApp intDataCon [mkIntLit i]
185 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
186 mkIntExprInt :: Int -> CoreExpr -- Result = I# i :: Int
187 mkIntExprInt i = mkConApp intDataCon [mkIntLitInt i]
189 -- | Create a 'CoreExpr' which will evaluate to the a @Word@ with the given value
190 mkWordExpr :: Integer -> CoreExpr
191 mkWordExpr w = mkConApp wordDataCon [mkWordLit w]
193 -- | Create a 'CoreExpr' which will evaluate to the given @Word@
194 mkWordExprWord :: Word -> CoreExpr
195 mkWordExprWord w = mkConApp wordDataCon [mkWordLitWord w]
197 -- | Create a 'CoreExpr' which will evaluate to the given @Integer@
198 mkIntegerExpr :: MonadThings m => Integer -> m CoreExpr -- Result :: Integer
200 | inIntRange i -- Small enough, so start from an Int
201 = do integer_id <- lookupId smallIntegerName
202 return (mkSmallIntegerLit integer_id i)
204 -- Special case for integral literals with a large magnitude:
205 -- They are transformed into an expression involving only smaller
206 -- integral literals. This improves constant folding.
208 | otherwise = do -- Big, so start from a string
209 plus_id <- lookupId plusIntegerName
210 times_id <- lookupId timesIntegerName
211 integer_id <- lookupId smallIntegerName
213 lit i = mkSmallIntegerLit integer_id i
214 plus a b = Var plus_id `App` a `App` b
215 times a b = Var times_id `App` a `App` b
217 -- Transform i into (x1 + (x2 + (x3 + (...) * b) * b) * b) with abs xi <= b
218 horner :: Integer -> Integer -> CoreExpr
219 horner b i | abs q <= 1 = if r == 0 || r == i
221 else lit r `plus` lit (i-r)
222 | r == 0 = horner b q `times` lit b
223 | otherwise = lit r `plus` (horner b q `times` lit b)
225 (q,r) = i `quotRem` b
227 return (horner tARGET_MAX_INT i)
229 mkSmallIntegerLit :: Id -> Integer -> CoreExpr
230 mkSmallIntegerLit small_integer i = mkApps (Var small_integer) [mkIntLit i]
233 -- | Create a 'CoreExpr' which will evaluate to the given @Float@
234 mkFloatExpr :: Float -> CoreExpr
235 mkFloatExpr f = mkConApp floatDataCon [mkFloatLitFloat f]
237 -- | Create a 'CoreExpr' which will evaluate to the given @Double@
238 mkDoubleExpr :: Double -> CoreExpr
239 mkDoubleExpr d = mkConApp doubleDataCon [mkDoubleLitDouble d]
242 -- | Create a 'CoreExpr' which will evaluate to the given @Char@
243 mkCharExpr :: Char -> CoreExpr -- Result = C# c :: Int
244 mkCharExpr c = mkConApp charDataCon [mkCharLit c]
246 -- | Create a 'CoreExpr' which will evaluate to the given @String@
247 mkStringExpr :: MonadThings m => String -> m CoreExpr -- Result :: String
248 -- | Create a 'CoreExpr' which will evaluate to a string morally equivalent to the given @FastString@
249 mkStringExprFS :: MonadThings m => FastString -> m CoreExpr -- Result :: String
251 mkStringExpr str = mkStringExprFS (mkFastString str)
255 = return (mkNilExpr charTy)
258 = do let the_char = mkCharExpr (headFS str)
259 return (mkConsExpr charTy the_char (mkNilExpr charTy))
262 = do unpack_id <- lookupId unpackCStringName
263 return (App (Var unpack_id) (Lit (MachStr str)))
266 = do unpack_id <- lookupId unpackCStringUtf8Name
267 return (App (Var unpack_id) (Lit (MachStr str)))
271 safeChar c = ord c >= 1 && ord c <= 0x7F
274 %************************************************************************
276 \subsection{Tuple constructors}
278 %************************************************************************
285 -- GHCs built in tuples can only go up to 'mAX_TUPLE_SIZE' in arity, but
286 -- we might concievably want to build such a massive tuple as part of the
287 -- output of a desugaring stage (notably that for list comprehensions).
289 -- We call tuples above this size \"big tuples\", and emulate them by
290 -- creating and pattern matching on >nested< tuples that are expressible
293 -- Nesting policy: it's better to have a 2-tuple of 10-tuples (3 objects)
294 -- than a 10-tuple of 2-tuples (11 objects), so we want the leaves of any
295 -- construction to be big.
297 -- If you just use the 'mkBigCoreTup', 'mkBigCoreVarTupTy', 'mkTupleSelector'
298 -- and 'mkTupleCase' functions to do all your work with tuples you should be
299 -- fine, and not have to worry about the arity limitation at all.
301 -- | Lifts a \"small\" constructor into a \"big\" constructor by recursive decompositon
302 mkChunkified :: ([a] -> a) -- ^ \"Small\" constructor function, of maximum input arity 'mAX_TUPLE_SIZE'
303 -> [a] -- ^ Possible \"big\" list of things to construct from
304 -> a -- ^ Constructed thing made possible by recursive decomposition
305 mkChunkified small_tuple as = mk_big_tuple (chunkify as)
307 -- Each sub-list is short enough to fit in a tuple
308 mk_big_tuple [as] = small_tuple as
309 mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
311 chunkify :: [a] -> [[a]]
312 -- ^ Split a list into lists that are small enough to have a corresponding
313 -- tuple arity. The sub-lists of the result all have length <= 'mAX_TUPLE_SIZE'
314 -- But there may be more than 'mAX_TUPLE_SIZE' sub-lists
316 | n_xs <= mAX_TUPLE_SIZE = [xs]
317 | otherwise = split xs
321 split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
325 Creating tuples and their types for Core expressions
327 @mkBigCoreVarTup@ builds a tuple; the inverse to @mkTupleSelector@.
329 * If it has only one element, it is the identity function.
331 * If there are more elements than a big tuple can have, it nests
336 -- | Build a small tuple holding the specified variables
337 mkCoreVarTup :: [Id] -> CoreExpr
338 mkCoreVarTup ids = mkCoreTup (map Var ids)
340 -- | Bulid the type of a small tuple that holds the specified variables
341 mkCoreVarTupTy :: [Id] -> Type
342 mkCoreVarTupTy ids = mkBoxedTupleTy (map idType ids)
344 -- | Build a small tuple holding the specified expressions
345 mkCoreTup :: [CoreExpr] -> CoreExpr
346 mkCoreTup [] = Var unitDataConId
348 mkCoreTup cs = mkConApp (tupleCon Boxed (length cs))
349 (map (Type . exprType) cs ++ cs)
351 -- | Build a big tuple holding the specified variables
352 mkBigCoreVarTup :: [Id] -> CoreExpr
353 mkBigCoreVarTup ids = mkBigCoreTup (map Var ids)
355 -- | Build the type of a big tuple that holds the specified variables
356 mkBigCoreVarTupTy :: [Id] -> Type
357 mkBigCoreVarTupTy ids = mkBigCoreTupTy (map idType ids)
359 -- | Build a big tuple holding the specified expressions
360 mkBigCoreTup :: [CoreExpr] -> CoreExpr
361 mkBigCoreTup = mkChunkified mkCoreTup
363 -- | Build the type of a big tuple that holds the specified type of thing
364 mkBigCoreTupTy :: [Type] -> Type
365 mkBigCoreTupTy = mkChunkified mkBoxedTupleTy
368 %************************************************************************
370 \subsection{Tuple destructors}
372 %************************************************************************
375 -- | Builds a selector which scrutises the given
376 -- expression and extracts the one name from the list given.
377 -- If you want the no-shadowing rule to apply, the caller
378 -- is responsible for making sure that none of these names
381 -- If there is just one 'Id' in the tuple, then the selector is
382 -- just the identity.
384 -- If necessary, we pattern match on a \"big\" tuple.
385 mkTupleSelector :: [Id] -- ^ The 'Id's to pattern match the tuple against
386 -> Id -- ^ The 'Id' to select
387 -> Id -- ^ A variable of the same type as the scrutinee
388 -> CoreExpr -- ^ Scrutinee
389 -> CoreExpr -- ^ Selector expression
391 -- mkTupleSelector [a,b,c,d] b v e
393 -- (p,q) -> case p of p {
395 -- We use 'tpl' vars for the p,q, since shadowing does not matter.
397 -- In fact, it's more convenient to generate it innermost first, getting
402 mkTupleSelector vars the_var scrut_var scrut
403 = mk_tup_sel (chunkify vars) the_var
405 mk_tup_sel [vars] the_var = mkSmallTupleSelector vars the_var scrut_var scrut
406 mk_tup_sel vars_s the_var = mkSmallTupleSelector group the_var tpl_v $
407 mk_tup_sel (chunkify tpl_vs) tpl_v
409 tpl_tys = [mkBoxedTupleTy (map idType gp) | gp <- vars_s]
410 tpl_vs = mkTemplateLocals tpl_tys
411 [(tpl_v, group)] = [(tpl,gp) | (tpl,gp) <- zipEqual "mkTupleSelector" tpl_vs vars_s,
416 -- | Like 'mkTupleSelector' but for tuples that are guaranteed
417 -- never to be \"big\".
419 -- > mkSmallTupleSelector [x] x v e = [| e |]
420 -- > mkSmallTupleSelector [x,y,z] x v e = [| case e of v { (x,y,z) -> x } |]
421 mkSmallTupleSelector :: [Id] -- The tuple args
422 -> Id -- The selected one
423 -> Id -- A variable of the same type as the scrutinee
424 -> CoreExpr -- Scrutinee
426 mkSmallTupleSelector [var] should_be_the_same_var _ scrut
427 = ASSERT(var == should_be_the_same_var)
429 mkSmallTupleSelector vars the_var scrut_var scrut
430 = ASSERT( notNull vars )
431 Case scrut scrut_var (idType the_var)
432 [(DataAlt (tupleCon Boxed (length vars)), vars, Var the_var)]
436 -- | A generalization of 'mkTupleSelector', allowing the body
437 -- of the case to be an arbitrary expression.
439 -- To avoid shadowing, we use uniques to invent new variables.
441 -- If necessary we pattern match on a \"big\" tuple.
442 mkTupleCase :: UniqSupply -- ^ For inventing names of intermediate variables
443 -> [Id] -- ^ The tuple identifiers to pattern match on
444 -> CoreExpr -- ^ Body of the case
445 -> Id -- ^ A variable of the same type as the scrutinee
446 -> CoreExpr -- ^ Scrutinee
448 -- ToDo: eliminate cases where none of the variables are needed.
450 -- mkTupleCase uniqs [a,b,c,d] body v e
451 -- = case e of v { (p,q) ->
452 -- case p of p { (a,b) ->
453 -- case q of q { (c,d) ->
455 mkTupleCase uniqs vars body scrut_var scrut
456 = mk_tuple_case uniqs (chunkify vars) body
458 -- This is the case where don't need any nesting
459 mk_tuple_case _ [vars] body
460 = mkSmallTupleCase vars body scrut_var scrut
462 -- This is the case where we must make nest tuples at least once
463 mk_tuple_case us vars_s body
464 = let (us', vars', body') = foldr one_tuple_case (us, [], body) vars_s
465 in mk_tuple_case us' (chunkify vars') body'
467 one_tuple_case chunk_vars (us, vs, body)
468 = let (us1, us2) = splitUniqSupply us
469 scrut_var = mkSysLocal (fsLit "ds") (uniqFromSupply us1)
470 (mkBoxedTupleTy (map idType chunk_vars))
471 body' = mkSmallTupleCase chunk_vars body scrut_var (Var scrut_var)
472 in (us2, scrut_var:vs, body')
476 -- | As 'mkTupleCase', but for a tuple that is small enough to be guaranteed
477 -- not to need nesting.
479 :: [Id] -- ^ The tuple args
480 -> CoreExpr -- ^ Body of the case
481 -> Id -- ^ A variable of the same type as the scrutinee
482 -> CoreExpr -- ^ Scrutinee
485 mkSmallTupleCase [var] body _scrut_var scrut
486 = bindNonRec var scrut body
487 mkSmallTupleCase vars body scrut_var scrut
488 -- One branch no refinement?
489 = Case scrut scrut_var (exprType body) [(DataAlt (tupleCon Boxed (length vars)), vars, body)]
492 %************************************************************************
494 \subsection{Common list manipulation expressions}
496 %************************************************************************
498 Call the constructor Ids when building explicit lists, so that they
499 interact well with rules.
502 -- | Makes a list @[]@ for lists of the specified type
503 mkNilExpr :: Type -> CoreExpr
504 mkNilExpr ty = mkConApp nilDataCon [Type ty]
506 -- | Makes a list @(:)@ for lists of the specified type
507 mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
508 mkConsExpr ty hd tl = mkConApp consDataCon [Type ty, hd, tl]
510 -- | Make a list containing the given expressions, where the list has the given type
511 mkListExpr :: Type -> [CoreExpr] -> CoreExpr
512 mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
514 -- | Make a fully applied 'foldr' expression
515 mkFoldrExpr :: MonadThings m
516 => Type -- ^ Element type of the list
517 -> Type -- ^ Fold result type
518 -> CoreExpr -- ^ "Cons" function expression for the fold
519 -> CoreExpr -- ^ "Nil" expression for the fold
520 -> CoreExpr -- ^ List expression being folded acress
522 mkFoldrExpr elt_ty result_ty c n list = do
523 foldr_id <- lookupId foldrName
524 return (Var foldr_id `App` Type elt_ty
530 -- | Make a 'build' expression applied to a locally-bound worker function
531 mkBuildExpr :: (MonadThings m, MonadUnique m)
532 => Type -- ^ Type of list elements to be built
533 -> ((Id, Type) -> (Id, Type) -> m CoreExpr) -- ^ Function that, given information about the 'Id's
534 -- of the binders for the build worker function, returns
535 -- the body of that worker
537 mkBuildExpr elt_ty mk_build_inside = do
538 [n_tyvar] <- newTyVars [alphaTyVar]
539 let n_ty = mkTyVarTy n_tyvar
540 c_ty = mkFunTys [elt_ty, n_ty] n_ty
541 [c, n] <- sequence [mkSysLocalM (fsLit "c") c_ty, mkSysLocalM (fsLit "n") n_ty]
543 build_inside <- mk_build_inside (c, c_ty) (n, n_ty)
545 build_id <- lookupId buildName
546 return $ Var build_id `App` Type elt_ty `App` mkLams [n_tyvar, c, n] build_inside
548 newTyVars tyvar_tmpls = do
550 return (zipWith setTyVarUnique tyvar_tmpls uniqs)