Minor refactoring
[ghc-hetmet.git] / compiler / coreSyn / MkCore.lhs
1 \begin{code}
2 -- | Handy functions for creating much Core syntax
3 module MkCore (
4         -- * Constructing normal syntax
5         mkCoreLet, mkCoreLets,
6         mkCoreApp, mkCoreApps, mkCoreConApps,
7         mkCoreLams, mkWildCase, mkWildBinder, mkIfThenElse,
8         
9         -- * Constructing boxed literals
10         mkWordExpr, mkWordExprWord,
11         mkIntExpr, mkIntExprInt,
12         mkIntegerExpr,
13         mkFloatExpr, mkDoubleExpr,
14         mkCharExpr, mkStringExpr, mkStringExprFS,
15         
16         -- * Constructing general big tuples
17         -- $big_tuples
18         mkChunkified,
19         
20         -- * Constructing small tuples
21         mkCoreVarTup, mkCoreVarTupTy, mkCoreTup, 
22         
23         -- * Constructing big tuples
24         mkBigCoreVarTup, mkBigCoreVarTupTy,
25         mkBigCoreTup, mkBigCoreTupTy,
26         
27         -- * Deconstructing small tuples
28         mkSmallTupleSelector, mkSmallTupleCase,
29         
30         -- * Deconstructing big tuples
31         mkTupleSelector, mkTupleCase,
32         
33         -- * Constructing list expressions
34         mkNilExpr, mkConsExpr, mkListExpr, 
35         mkFoldrExpr, mkBuildExpr
36     ) where
37
38 #include "HsVersions.h"
39
40 import Id
41 import Var      ( setTyVarUnique )
42
43 import CoreSyn
44 import CoreUtils        ( exprType, needsCaseBinding, bindNonRec )
45 import Literal
46 import HscTypes
47
48 import TysWiredIn
49 import PrelNames
50
51 import Type
52 import TysPrim          ( alphaTyVar )
53 import DataCon          ( DataCon, dataConWorkId )
54
55 import FastString
56 import UniqSupply
57 import Unique           ( mkBuiltinUnique )
58 import BasicTypes
59 import Util             ( notNull, zipEqual )
60 import Panic
61 import Constants
62
63 import Data.Char        ( ord )
64 import Data.Word
65
66 infixl 4 `mkCoreApp`, `mkCoreApps`
67 \end{code}
68
69 %************************************************************************
70 %*                                                                      *
71 \subsection{Basic CoreSyn construction}
72 %*                                                                      *
73 %************************************************************************
74
75 \begin{code}
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)]
82 mkCoreLet bind body
83   = Let bind body
84
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
89
90 -- | Construct an expression which represents the application of one expression
91 -- to the other
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
97                       where
98                         (arg_ty, res_ty) = splitFunTy (exprType fun)
99
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)
104 mkCoreApps fun args
105   = go fun (exprType fun) args
106   where
107     go fun _      []               = fun
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
110                                    where
111                                      (arg_ty, res_ty) = splitFunTy fun_ty
112
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
118
119 -----------
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
124
125 mk_val_app fun arg arg_ty res_ty
126   = Case arg arg_id res_ty [(DEFAULT,[],App fun (Var arg_id))]
127   where
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
131         --
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'.
137
138
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
145
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
151
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) ]
158 \end{code}
159
160 The functions from this point don't really do anything cleverer than
161 their counterparts in CoreSyn, but they are here for consistency
162
163 \begin{code}
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
168 mkCoreLams = mkLams
169 \end{code}
170
171 %************************************************************************
172 %*                                                                      *
173 \subsection{Making literals}
174 %*                                                                      *
175 %************************************************************************
176
177 \begin{code}
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]
181
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]
185
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]
189
190 -- | Create a 'CoreExpr' which will evaluate to the given @Word@
191 mkWordExprWord :: Word       -> CoreExpr
192 mkWordExprWord w = mkConApp wordDataCon [mkWordLitWord w]
193
194 -- | Create a 'CoreExpr' which will evaluate to the given @Integer@
195 mkIntegerExpr  :: MonadThings m => Integer    -> m CoreExpr  -- Result :: Integer
196 mkIntegerExpr i
197   | inIntRange i        -- Small enough, so start from an Int
198     = do integer_id <- lookupId smallIntegerName
199          return (mkSmallIntegerLit integer_id i)
200
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.
204
205   | otherwise = do       -- Big, so start from a string
206       plus_id <- lookupId plusIntegerName
207       times_id <- lookupId timesIntegerName
208       integer_id <- lookupId smallIntegerName
209       let
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
213
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 
217                                      then lit 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)
221                       where
222                         (q,r) = i `quotRem` b
223
224       return (horner tARGET_MAX_INT i)
225   where
226     mkSmallIntegerLit :: Id -> Integer -> CoreExpr
227     mkSmallIntegerLit small_integer i = mkApps (Var small_integer) [mkIntLit i]
228
229
230 -- | Create a 'CoreExpr' which will evaluate to the given @Float@
231 mkFloatExpr :: Float -> CoreExpr
232 mkFloatExpr f = mkConApp floatDataCon [mkFloatLitFloat f]
233
234 -- | Create a 'CoreExpr' which will evaluate to the given @Double@
235 mkDoubleExpr :: Double -> CoreExpr
236 mkDoubleExpr d = mkConApp doubleDataCon [mkDoubleLitDouble d]
237
238
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]
242
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
247
248 mkStringExpr str = mkStringExprFS (mkFastString str)
249
250 mkStringExprFS str
251   | nullFS str
252   = return (mkNilExpr charTy)
253
254   | lengthFS str == 1
255   = do let the_char = mkCharExpr (headFS str)
256        return (mkConsExpr charTy the_char (mkNilExpr charTy))
257
258   | all safeChar chars
259   = do unpack_id <- lookupId unpackCStringName
260        return (App (Var unpack_id) (Lit (MachStr str)))
261
262   | otherwise
263   = do unpack_id <- lookupId unpackCStringUtf8Name
264        return (App (Var unpack_id) (Lit (MachStr str)))
265
266   where
267     chars = unpackFS str
268     safeChar c = ord c >= 1 && ord c <= 0x7F
269 \end{code}
270
271 %************************************************************************
272 %*                                                                      *
273 \subsection{Tuple constructors}
274 %*                                                                      *
275 %************************************************************************
276
277 \begin{code}
278
279 -- $big_tuples
280 -- #big_tuples#
281 --
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).
285 --
286 -- We call tuples above this size \"big tuples\", and emulate them by
287 -- creating and pattern matching on >nested< tuples that are expressible
288 -- by GHC.
289 --
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.
293 --
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.
297
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)
303   where
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))
307
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
312 chunkify xs
313   | n_xs <= mAX_TUPLE_SIZE = [xs] 
314   | otherwise              = split xs
315   where
316     n_xs     = length xs
317     split [] = []
318     split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
319     
320 \end{code}
321
322 Creating tuples and their types for Core expressions 
323
324 @mkBigCoreVarTup@ builds a tuple; the inverse to @mkTupleSelector@.  
325
326 * If it has only one element, it is the identity function.
327
328 * If there are more elements than a big tuple can have, it nests 
329   the tuples.  
330
331 \begin{code}
332
333 -- | Build a small tuple holding the specified variables
334 mkCoreVarTup :: [Id] -> CoreExpr
335 mkCoreVarTup ids = mkCoreTup (map Var ids)
336
337 -- | Bulid the type of a small tuple that holds the specified variables
338 mkCoreVarTupTy :: [Id] -> Type
339 mkCoreVarTupTy ids = mkBoxedTupleTy (map idType ids)
340
341 -- | Build a small tuple holding the specified expressions
342 mkCoreTup :: [CoreExpr] -> CoreExpr
343 mkCoreTup []  = Var unitDataConId
344 mkCoreTup [c] = c
345 mkCoreTup cs  = mkConApp (tupleCon Boxed (length cs))
346                          (map (Type . exprType) cs ++ cs)
347
348 -- | Build a big tuple holding the specified variables
349 mkBigCoreVarTup :: [Id] -> CoreExpr
350 mkBigCoreVarTup ids = mkBigCoreTup (map Var ids)
351
352 -- | Build the type of a big tuple that holds the specified variables
353 mkBigCoreVarTupTy :: [Id] -> Type
354 mkBigCoreVarTupTy ids = mkBigCoreTupTy (map idType ids)
355
356 -- | Build a big tuple holding the specified expressions
357 mkBigCoreTup :: [CoreExpr] -> CoreExpr
358 mkBigCoreTup = mkChunkified mkCoreTup
359
360 -- | Build the type of a big tuple that holds the specified type of thing
361 mkBigCoreTupTy :: [Type] -> Type
362 mkBigCoreTupTy = mkChunkified mkBoxedTupleTy
363 \end{code}
364
365 %************************************************************************
366 %*                                                                      *
367 \subsection{Tuple destructors}
368 %*                                                                      *
369 %************************************************************************
370
371 \begin{code}
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
376 -- are in scope.
377 --
378 -- If there is just one 'Id' in the tuple, then the selector is
379 -- just the identity.
380 --
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
387
388 -- mkTupleSelector [a,b,c,d] b v e
389 --          = case e of v { 
390 --                (p,q) -> case p of p {
391 --                           (a,b) -> b }}
392 -- We use 'tpl' vars for the p,q, since shadowing does not matter.
393 --
394 -- In fact, it's more convenient to generate it innermost first, getting
395 --
396 --        case (case e of v 
397 --                (p,q) -> p) of p
398 --          (a,b) -> b
399 mkTupleSelector vars the_var scrut_var scrut
400   = mk_tup_sel (chunkify vars) the_var
401   where
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
405         where
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,
409                                          the_var `elem` gp ]
410 \end{code}
411
412 \begin{code}
413 -- | Like 'mkTupleSelector' but for tuples that are guaranteed
414 -- never to be \"big\".
415 --
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
422           -> CoreExpr
423 mkSmallTupleSelector [var] should_be_the_same_var _ scrut
424   = ASSERT(var == should_be_the_same_var)
425     scrut
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)]
430 \end{code}
431
432 \begin{code}
433 -- | A generalization of 'mkTupleSelector', allowing the body
434 -- of the case to be an arbitrary expression.
435 --
436 -- To avoid shadowing, we use uniques to invent new variables.
437 --
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
444             -> CoreExpr
445 -- ToDo: eliminate cases where none of the variables are needed.
446 --
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) ->
451 --             body }}}
452 mkTupleCase uniqs vars body scrut_var scrut
453   = mk_tuple_case uniqs (chunkify vars) body
454   where
455     -- This is the case where don't need any nesting
456     mk_tuple_case _ [vars] body
457       = mkSmallTupleCase vars body scrut_var scrut
458       
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'
463     
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')
470 \end{code}
471
472 \begin{code}
473 -- | As 'mkTupleCase', but for a tuple that is small enough to be guaranteed
474 -- not to need nesting.
475 mkSmallTupleCase
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
480         -> CoreExpr
481
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)]
487 \end{code}
488
489 %************************************************************************
490 %*                                                                      *
491 \subsection{Common list manipulation expressions}
492 %*                                                                      *
493 %************************************************************************
494
495 Call the constructor Ids when building explicit lists, so that they
496 interact well with rules.
497
498 \begin{code}
499 -- | Makes a list @[]@ for lists of the specified type
500 mkNilExpr :: Type -> CoreExpr
501 mkNilExpr ty = mkConApp nilDataCon [Type ty]
502
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]
506
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
510
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
518             -> m CoreExpr
519 mkFoldrExpr elt_ty result_ty c n list = do
520     foldr_id <- lookupId foldrName
521     return (Var foldr_id `App` Type elt_ty 
522            `App` Type result_ty
523            `App` c
524            `App` n
525            `App` list)
526
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
533             -> m CoreExpr
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]
539     
540     build_inside <- mk_build_inside (c, c_ty) (n, n_ty)
541     
542     build_id <- lookupId buildName
543     return $ Var build_id `App` Type elt_ty `App` mkLams [n_tyvar, c, n] build_inside
544   where
545     newTyVars tyvar_tmpls = do
546       uniqs <- getUniquesM
547       return (zipWith setTyVarUnique tyvar_tmpls uniqs)
548 \end{code}