Case-of-empty-alts is trivial (Trac #11155)
[ghc.git] / compiler / coreSyn / CorePrep.hs
1 {-
2 (c) The University of Glasgow, 1994-2006
3
4
5 Core pass to saturate constructors and PrimOps
6 -}
7
8 {-# LANGUAGE BangPatterns, CPP #-}
9
10 module CorePrep (
11 corePrepPgm, corePrepExpr, cvtLitInteger,
12 lookupMkIntegerName, lookupIntegerSDataConName
13 ) where
14
15 #include "HsVersions.h"
16
17 import OccurAnal
18
19 import HscTypes
20 import PrelNames
21 import MkId ( realWorldPrimId )
22 import CoreUtils
23 import CoreArity
24 import CoreFVs
25 import CoreMonad ( CoreToDo(..) )
26 import CoreLint ( endPassIO )
27 import CoreSyn
28 import CoreSubst
29 import MkCore hiding( FloatBind(..) ) -- We use our own FloatBind here
30 import Type
31 import Literal
32 import Coercion
33 import TcEnv
34 import TyCon
35 import Demand
36 import Var
37 import VarSet
38 import VarEnv
39 import Id
40 import IdInfo
41 import TysWiredIn
42 import DataCon
43 import PrimOp
44 import BasicTypes
45 import Module
46 import UniqSupply
47 import Maybes
48 import OrdList
49 import ErrUtils
50 import DynFlags
51 import Util
52 import Pair
53 import Outputable
54 import Platform
55 import FastString
56 import Config
57 import Name ( NamedThing(..), nameSrcSpan )
58 import SrcLoc ( SrcSpan(..), realSrcLocSpan, mkRealSrcLoc )
59 import Data.Bits
60 import MonadUtils ( mapAccumLM )
61 import Data.List ( mapAccumL )
62 import Control.Monad
63
64 #if __GLASGOW_HASKELL__ < 710
65 import Control.Applicative
66 #endif
67
68 {-
69 -- ---------------------------------------------------------------------------
70 -- Overview
71 -- ---------------------------------------------------------------------------
72
73 The goal of this pass is to prepare for code generation.
74
75 1. Saturate constructor and primop applications.
76
77 2. Convert to A-normal form; that is, function arguments
78 are always variables.
79
80 * Use case for strict arguments:
81 f E ==> case E of x -> f x
82 (where f is strict)
83
84 * Use let for non-trivial lazy arguments
85 f E ==> let x = E in f x
86 (were f is lazy and x is non-trivial)
87
88 3. Similarly, convert any unboxed lets into cases.
89 [I'm experimenting with leaving 'ok-for-speculation'
90 rhss in let-form right up to this point.]
91
92 4. Ensure that *value* lambdas only occur as the RHS of a binding
93 (The code generator can't deal with anything else.)
94 Type lambdas are ok, however, because the code gen discards them.
95
96 5. [Not any more; nuked Jun 2002] Do the seq/par munging.
97
98 6. Clone all local Ids.
99 This means that all such Ids are unique, rather than the
100 weaker guarantee of no clashes which the simplifier provides.
101 And that is what the code generator needs.
102
103 We don't clone TyVars or CoVars. The code gen doesn't need that,
104 and doing so would be tiresome because then we'd need
105 to substitute in types and coercions.
106
107 7. Give each dynamic CCall occurrence a fresh unique; this is
108 rather like the cloning step above.
109
110 8. Inject bindings for the "implicit" Ids:
111 * Constructor wrappers
112 * Constructor workers
113 We want curried definitions for all of these in case they
114 aren't inlined by some caller.
115
116 9. Replace (lazy e) by e. See Note [lazyId magic] in MkId.hs
117
118 10. Convert (LitInteger i t) into the core representation
119 for the Integer i. Normally this uses mkInteger, but if
120 we are using the integer-gmp implementation then there is a
121 special case where we use the S# constructor for Integers that
122 are in the range of Int.
123
124 11. Uphold tick consistency while doing this: We move ticks out of
125 (non-type) applications where we can, and make sure that we
126 annotate according to scoping rules when floating.
127
128 This is all done modulo type applications and abstractions, so that
129 when type erasure is done for conversion to STG, we don't end up with
130 any trivial or useless bindings.
131
132
133 Invariants
134 ~~~~~~~~~~
135 Here is the syntax of the Core produced by CorePrep:
136
137 Trivial expressions
138 triv ::= lit | var
139 | triv ty | /\a. triv
140 | truv co | /\c. triv | triv |> co
141
142 Applications
143 app ::= lit | var | app triv | app ty | app co | app |> co
144
145 Expressions
146 body ::= app
147 | let(rec) x = rhs in body -- Boxed only
148 | case body of pat -> body
149 | /\a. body | /\c. body
150 | body |> co
151
152 Right hand sides (only place where value lambdas can occur)
153 rhs ::= /\a.rhs | \x.rhs | body
154
155 We define a synonym for each of these non-terminals. Functions
156 with the corresponding name produce a result in that syntax.
157 -}
158
159 type CpeTriv = CoreExpr -- Non-terminal 'triv'
160 type CpeApp = CoreExpr -- Non-terminal 'app'
161 type CpeBody = CoreExpr -- Non-terminal 'body'
162 type CpeRhs = CoreExpr -- Non-terminal 'rhs'
163
164 {-
165 ************************************************************************
166 * *
167 Top level stuff
168 * *
169 ************************************************************************
170 -}
171
172 corePrepPgm :: HscEnv -> ModLocation -> CoreProgram -> [TyCon] -> IO CoreProgram
173 corePrepPgm hsc_env mod_loc binds data_tycons = do
174 let dflags = hsc_dflags hsc_env
175 showPass dflags "CorePrep"
176 us <- mkSplitUniqSupply 's'
177 initialCorePrepEnv <- mkInitialCorePrepEnv dflags hsc_env
178
179 let implicit_binds = mkDataConWorkers dflags mod_loc data_tycons
180 -- NB: we must feed mkImplicitBinds through corePrep too
181 -- so that they are suitably cloned and eta-expanded
182
183 binds_out = initUs_ us $ do
184 floats1 <- corePrepTopBinds initialCorePrepEnv binds
185 floats2 <- corePrepTopBinds initialCorePrepEnv implicit_binds
186 return (deFloatTop (floats1 `appendFloats` floats2))
187
188 endPassIO hsc_env alwaysQualify CorePrep binds_out []
189 return binds_out
190
191 corePrepExpr :: DynFlags -> HscEnv -> CoreExpr -> IO CoreExpr
192 corePrepExpr dflags hsc_env expr = do
193 showPass dflags "CorePrep"
194 us <- mkSplitUniqSupply 's'
195 initialCorePrepEnv <- mkInitialCorePrepEnv dflags hsc_env
196 let new_expr = initUs_ us (cpeBodyNF initialCorePrepEnv expr)
197 dumpIfSet_dyn dflags Opt_D_dump_prep "CorePrep" (ppr new_expr)
198 return new_expr
199
200 corePrepTopBinds :: CorePrepEnv -> [CoreBind] -> UniqSM Floats
201 -- Note [Floating out of top level bindings]
202 corePrepTopBinds initialCorePrepEnv binds
203 = go initialCorePrepEnv binds
204 where
205 go _ [] = return emptyFloats
206 go env (bind : binds) = do (env', bind') <- cpeBind TopLevel env bind
207 binds' <- go env' binds
208 return (bind' `appendFloats` binds')
209
210 mkDataConWorkers :: DynFlags -> ModLocation -> [TyCon] -> [CoreBind]
211 -- See Note [Data constructor workers]
212 -- c.f. Note [Injecting implicit bindings] in TidyPgm
213 mkDataConWorkers dflags mod_loc data_tycons
214 = [ NonRec id (tick_it (getName data_con) (Var id))
215 -- The ice is thin here, but it works
216 | tycon <- data_tycons, -- CorePrep will eta-expand it
217 data_con <- tyConDataCons tycon,
218 let id = dataConWorkId data_con
219 ]
220 where
221 -- If we want to generate debug info, we put a source note on the
222 -- worker. This is useful, especially for heap profiling.
223 tick_it name
224 | debugLevel dflags == 0 = id
225 | RealSrcSpan span <- nameSrcSpan name = tick span
226 | Just file <- ml_hs_file mod_loc = tick (span1 file)
227 | otherwise = tick (span1 "???")
228 where tick span = Tick (SourceNote span $ showSDoc dflags (ppr name))
229 span1 file = realSrcLocSpan $ mkRealSrcLoc (mkFastString file) 1 1
230
231 {-
232 Note [Floating out of top level bindings]
233 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
234 NB: we do need to float out of top-level bindings
235 Consider x = length [True,False]
236 We want to get
237 s1 = False : []
238 s2 = True : s1
239 x = length s2
240
241 We return a *list* of bindings, because we may start with
242 x* = f (g y)
243 where x is demanded, in which case we want to finish with
244 a = g y
245 x* = f a
246 And then x will actually end up case-bound
247
248 Note [CafInfo and floating]
249 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
250 What happens when we try to float bindings to the top level? At this
251 point all the CafInfo is supposed to be correct, and we must make certain
252 that is true of the new top-level bindings. There are two cases
253 to consider
254
255 a) The top-level binding is marked asCafRefs. In that case we are
256 basically fine. The floated bindings had better all be lazy lets,
257 so they can float to top level, but they'll all have HasCafRefs
258 (the default) which is safe.
259
260 b) The top-level binding is marked NoCafRefs. This really happens
261 Example. CoreTidy produces
262 $fApplicativeSTM [NoCafRefs] = D:Alternative retry# ...blah...
263 Now CorePrep has to eta-expand to
264 $fApplicativeSTM = let sat = \xy. retry x y
265 in D:Alternative sat ...blah...
266 So what we *want* is
267 sat [NoCafRefs] = \xy. retry x y
268 $fApplicativeSTM [NoCafRefs] = D:Alternative sat ...blah...
269
270 So, gruesomely, we must set the NoCafRefs flag on the sat bindings,
271 *and* substutite the modified 'sat' into the old RHS.
272
273 It should be the case that 'sat' is itself [NoCafRefs] (a value, no
274 cafs) else the original top-level binding would not itself have been
275 marked [NoCafRefs]. The DEBUG check in CoreToStg for
276 consistentCafInfo will find this.
277
278 This is all very gruesome and horrible. It would be better to figure
279 out CafInfo later, after CorePrep. We'll do that in due course.
280 Meanwhile this horrible hack works.
281
282
283 Note [Data constructor workers]
284 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
285 Create any necessary "implicit" bindings for data con workers. We
286 create the rather strange (non-recursive!) binding
287
288 $wC = \x y -> $wC x y
289
290 i.e. a curried constructor that allocates. This means that we can
291 treat the worker for a constructor like any other function in the rest
292 of the compiler. The point here is that CoreToStg will generate a
293 StgConApp for the RHS, rather than a call to the worker (which would
294 give a loop). As Lennart says: the ice is thin here, but it works.
295
296 Hmm. Should we create bindings for dictionary constructors? They are
297 always fully applied, and the bindings are just there to support
298 partial applications. But it's easier to let them through.
299
300
301 Note [Dead code in CorePrep]
302 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
303 Imagine that we got an input program like this (see Trac #4962):
304
305 f :: Show b => Int -> (Int, b -> Maybe Int -> Int)
306 f x = (g True (Just x) + g () (Just x), g)
307 where
308 g :: Show a => a -> Maybe Int -> Int
309 g _ Nothing = x
310 g y (Just z) = if z > 100 then g y (Just (z + length (show y))) else g y unknown
311
312 After specialisation and SpecConstr, we would get something like this:
313
314 f :: Show b => Int -> (Int, b -> Maybe Int -> Int)
315 f x = (g$Bool_True_Just x + g$Unit_Unit_Just x, g)
316 where
317 {-# RULES g $dBool = g$Bool
318 g $dUnit = g$Unit #-}
319 g = ...
320 {-# RULES forall x. g$Bool True (Just x) = g$Bool_True_Just x #-}
321 g$Bool = ...
322 {-# RULES forall x. g$Unit () (Just x) = g$Unit_Unit_Just x #-}
323 g$Unit = ...
324 g$Bool_True_Just = ...
325 g$Unit_Unit_Just = ...
326
327 Note that the g$Bool and g$Unit functions are actually dead code: they
328 are only kept alive by the occurrence analyser because they are
329 referred to by the rules of g, which is being kept alive by the fact
330 that it is used (unspecialised) in the returned pair.
331
332 However, at the CorePrep stage there is no way that the rules for g
333 will ever fire, and it really seems like a shame to produce an output
334 program that goes to the trouble of allocating a closure for the
335 unreachable g$Bool and g$Unit functions.
336
337 The way we fix this is to:
338 * In cloneBndr, drop all unfoldings/rules
339
340 * In deFloatTop, run a simple dead code analyser on each top-level
341 RHS to drop the dead local bindings. For that call to OccAnal, we
342 disable the binder swap, else the occurrence analyser sometimes
343 introduces new let bindings for cased binders, which lead to the bug
344 in #5433.
345
346 The reason we don't just OccAnal the whole output of CorePrep is that
347 the tidier ensures that all top-level binders are GlobalIds, so they
348 don't show up in the free variables any longer. So if you run the
349 occurrence analyser on the output of CoreTidy (or later) you e.g. turn
350 this program:
351
352 Rec {
353 f = ... f ...
354 }
355
356 Into this one:
357
358 f = ... f ...
359
360 (Since f is not considered to be free in its own RHS.)
361
362
363 ************************************************************************
364 * *
365 The main code
366 * *
367 ************************************************************************
368 -}
369
370 cpeBind :: TopLevelFlag -> CorePrepEnv -> CoreBind
371 -> UniqSM (CorePrepEnv, Floats)
372 cpeBind top_lvl env (NonRec bndr rhs)
373 = do { (_, bndr1) <- cpCloneBndr env bndr
374 ; let dmd = idDemandInfo bndr
375 is_unlifted = isUnLiftedType (idType bndr)
376 ; (floats, bndr2, rhs2) <- cpePair top_lvl NonRecursive
377 dmd
378 is_unlifted
379 env bndr1 rhs
380 ; let new_float = mkFloat dmd is_unlifted bndr2 rhs2
381
382 -- We want bndr'' in the envt, because it records
383 -- the evaluated-ness of the binder
384 ; return (extendCorePrepEnv env bndr bndr2,
385 addFloat floats new_float) }
386
387 cpeBind top_lvl env (Rec pairs)
388 = do { let (bndrs,rhss) = unzip pairs
389 ; (env', bndrs1) <- cpCloneBndrs env (map fst pairs)
390 ; stuff <- zipWithM (cpePair top_lvl Recursive topDmd False env') bndrs1 rhss
391
392 ; let (floats_s, bndrs2, rhss2) = unzip3 stuff
393 all_pairs = foldrOL add_float (bndrs2 `zip` rhss2)
394 (concatFloats floats_s)
395 ; return (extendCorePrepEnvList env (bndrs `zip` bndrs2),
396 unitFloat (FloatLet (Rec all_pairs))) }
397 where
398 -- Flatten all the floats, and the currrent
399 -- group into a single giant Rec
400 add_float (FloatLet (NonRec b r)) prs2 = (b,r) : prs2
401 add_float (FloatLet (Rec prs1)) prs2 = prs1 ++ prs2
402 add_float b _ = pprPanic "cpeBind" (ppr b)
403
404 ---------------
405 cpePair :: TopLevelFlag -> RecFlag -> Demand -> Bool
406 -> CorePrepEnv -> Id -> CoreExpr
407 -> UniqSM (Floats, Id, CpeRhs)
408 -- Used for all bindings
409 cpePair top_lvl is_rec dmd is_unlifted env bndr rhs
410 = do { (floats1, rhs1) <- cpeRhsE env rhs
411
412 -- See if we are allowed to float this stuff out of the RHS
413 ; (floats2, rhs2) <- float_from_rhs floats1 rhs1
414
415 -- Make the arity match up
416 ; (floats3, rhs3)
417 <- if manifestArity rhs1 <= arity
418 then return (floats2, cpeEtaExpand arity rhs2)
419 else WARN(True, text "CorePrep: silly extra arguments:" <+> ppr bndr)
420 -- Note [Silly extra arguments]
421 (do { v <- newVar (idType bndr)
422 ; let float = mkFloat topDmd False v rhs2
423 ; return ( addFloat floats2 float
424 , cpeEtaExpand arity (Var v)) })
425
426 -- Wrap floating ticks
427 ; let (floats4, rhs4) = wrapTicks floats3 rhs3
428
429 -- Record if the binder is evaluated
430 -- and otherwise trim off the unfolding altogether
431 -- It's not used by the code generator; getting rid of it reduces
432 -- heap usage and, since we may be changing uniques, we'd have
433 -- to substitute to keep it right
434 ; let bndr' | exprIsHNF rhs3 = bndr `setIdUnfolding` evaldUnfolding
435 | otherwise = bndr `setIdUnfolding` noUnfolding
436
437 ; return (floats4, bndr', rhs4) }
438 where
439 is_strict_or_unlifted = (isStrictDmd dmd) || is_unlifted
440
441 platform = targetPlatform (cpe_dynFlags env)
442
443 arity = idArity bndr -- We must match this arity
444
445 ---------------------
446 float_from_rhs floats rhs
447 | isEmptyFloats floats = return (emptyFloats, rhs)
448 | isTopLevel top_lvl = float_top floats rhs
449 | otherwise = float_nested floats rhs
450
451 ---------------------
452 float_nested floats rhs
453 | wantFloatNested is_rec is_strict_or_unlifted floats rhs
454 = return (floats, rhs)
455 | otherwise = dont_float floats rhs
456
457 ---------------------
458 float_top floats rhs -- Urhgh! See Note [CafInfo and floating]
459 | mayHaveCafRefs (idCafInfo bndr)
460 , allLazyTop floats
461 = return (floats, rhs)
462
463 -- So the top-level binding is marked NoCafRefs
464 | Just (floats', rhs') <- canFloatFromNoCaf platform floats rhs
465 = return (floats', rhs')
466
467 | otherwise
468 = dont_float floats rhs
469
470 ---------------------
471 dont_float floats rhs
472 -- Non-empty floats, but do not want to float from rhs
473 -- So wrap the rhs in the floats
474 -- But: rhs1 might have lambdas, and we can't
475 -- put them inside a wrapBinds
476 = do { body <- rhsToBodyNF rhs
477 ; return (emptyFloats, wrapBinds floats body) }
478
479 {- Note [Silly extra arguments]
480 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
481 Suppose we had this
482 f{arity=1} = \x\y. e
483 We *must* match the arity on the Id, so we have to generate
484 f' = \x\y. e
485 f = \x. f' x
486
487 It's a bizarre case: why is the arity on the Id wrong? Reason
488 (in the days of __inline_me__):
489 f{arity=0} = __inline_me__ (let v = expensive in \xy. e)
490 When InlineMe notes go away this won't happen any more. But
491 it seems good for CorePrep to be robust.
492 -}
493
494 -- ---------------------------------------------------------------------------
495 -- CpeRhs: produces a result satisfying CpeRhs
496 -- ---------------------------------------------------------------------------
497
498 cpeRhsE :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
499 -- If
500 -- e ===> (bs, e')
501 -- then
502 -- e = let bs in e' (semantically, that is!)
503 --
504 -- For example
505 -- f (g x) ===> ([v = g x], f v)
506
507 cpeRhsE _env expr@(Type {}) = return (emptyFloats, expr)
508 cpeRhsE _env expr@(Coercion {}) = return (emptyFloats, expr)
509 cpeRhsE env (Lit (LitInteger i _))
510 = cpeRhsE env (cvtLitInteger (cpe_dynFlags env) (getMkIntegerId env)
511 (cpe_integerSDataCon env) i)
512 cpeRhsE _env expr@(Lit {}) = return (emptyFloats, expr)
513 cpeRhsE env expr@(Var {}) = cpeApp env expr
514
515 cpeRhsE env (Var f `App` _{-type-} `App` arg)
516 | f `hasKey` lazyIdKey -- Replace (lazy a) by a
517 = cpeRhsE env arg -- See Note [lazyId magic] in MkId
518
519 -- See Note [runRW magic] in MkId
520 | f `hasKey` runRWKey -- Replace (runRW# f) by (f realWorld#),
521 = case arg of -- beta reducing if possible
522 Lam s body -> cpeRhsE env (substExpr (text "runRW#") subst body)
523 where subst = extendIdSubst emptySubst s (Var realWorldPrimId)
524 -- XXX I think we can use emptySubst here
525 -- because realWorldPrimId is a global variable
526 -- and so cannot be bound by a lambda in body
527 _ -> cpeRhsE env (arg `App` Var realWorldPrimId)
528
529 cpeRhsE env expr@(App {}) = cpeApp env expr
530
531 cpeRhsE env (Let bind expr)
532 = do { (env', new_binds) <- cpeBind NotTopLevel env bind
533 ; (floats, body) <- cpeRhsE env' expr
534 ; return (new_binds `appendFloats` floats, body) }
535
536 cpeRhsE env (Tick tickish expr)
537 | tickishPlace tickish == PlaceNonLam && tickish `tickishScopesLike` SoftScope
538 = do { (floats, body) <- cpeRhsE env expr
539 -- See [Floating Ticks in CorePrep]
540 ; return (unitFloat (FloatTick tickish) `appendFloats` floats, body) }
541 | otherwise
542 = do { body <- cpeBodyNF env expr
543 ; return (emptyFloats, mkTick tickish' body) }
544 where
545 tickish' | Breakpoint n fvs <- tickish
546 = Breakpoint n (map (lookupCorePrepEnv env) fvs)
547 | otherwise
548 = tickish
549
550 cpeRhsE env (Cast expr co)
551 = do { (floats, expr') <- cpeRhsE env expr
552 ; return (floats, Cast expr' co) }
553
554 cpeRhsE env expr@(Lam {})
555 = do { let (bndrs,body) = collectBinders expr
556 ; (env', bndrs') <- cpCloneBndrs env bndrs
557 ; body' <- cpeBodyNF env' body
558 ; return (emptyFloats, mkLams bndrs' body') }
559
560 cpeRhsE env (Case scrut bndr ty alts)
561 = do { (floats, scrut') <- cpeBody env scrut
562 ; let bndr1 = bndr `setIdUnfolding` evaldUnfolding
563 -- Record that the case binder is evaluated in the alternatives
564 ; (env', bndr2) <- cpCloneBndr env bndr1
565 ; alts' <- mapM (sat_alt env') alts
566 ; return (floats, Case scrut' bndr2 ty alts') }
567 where
568 sat_alt env (con, bs, rhs)
569 = do { (env2, bs') <- cpCloneBndrs env bs
570 ; rhs' <- cpeBodyNF env2 rhs
571 ; return (con, bs', rhs') }
572
573 cvtLitInteger :: DynFlags -> Id -> Maybe DataCon -> Integer -> CoreExpr
574 -- Here we convert a literal Integer to the low-level
575 -- represenation. Exactly how we do this depends on the
576 -- library that implements Integer. If it's GMP we
577 -- use the S# data constructor for small literals.
578 -- See Note [Integer literals] in Literal
579 cvtLitInteger dflags _ (Just sdatacon) i
580 | inIntRange dflags i -- Special case for small integers
581 = mkConApp sdatacon [Lit (mkMachInt dflags i)]
582
583 cvtLitInteger dflags mk_integer _ i
584 = mkApps (Var mk_integer) [isNonNegative, ints]
585 where isNonNegative = if i < 0 then mkConApp falseDataCon []
586 else mkConApp trueDataCon []
587 ints = mkListExpr intTy (f (abs i))
588 f 0 = []
589 f x = let low = x .&. mask
590 high = x `shiftR` bits
591 in mkConApp intDataCon [Lit (mkMachInt dflags low)] : f high
592 bits = 31
593 mask = 2 ^ bits - 1
594
595 -- ---------------------------------------------------------------------------
596 -- CpeBody: produces a result satisfying CpeBody
597 -- ---------------------------------------------------------------------------
598
599 cpeBodyNF :: CorePrepEnv -> CoreExpr -> UniqSM CpeBody
600 cpeBodyNF env expr
601 = do { (floats, body) <- cpeBody env expr
602 ; return (wrapBinds floats body) }
603
604 --------
605 cpeBody :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeBody)
606 cpeBody env expr
607 = do { (floats1, rhs) <- cpeRhsE env expr
608 ; (floats2, body) <- rhsToBody rhs
609 ; return (floats1 `appendFloats` floats2, body) }
610
611 --------
612 rhsToBodyNF :: CpeRhs -> UniqSM CpeBody
613 rhsToBodyNF rhs = do { (floats,body) <- rhsToBody rhs
614 ; return (wrapBinds floats body) }
615
616 --------
617 rhsToBody :: CpeRhs -> UniqSM (Floats, CpeBody)
618 -- Remove top level lambdas by let-binding
619
620 rhsToBody (Tick t expr)
621 | tickishScoped t == NoScope -- only float out of non-scoped annotations
622 = do { (floats, expr') <- rhsToBody expr
623 ; return (floats, mkTick t expr') }
624
625 rhsToBody (Cast e co)
626 -- You can get things like
627 -- case e of { p -> coerce t (\s -> ...) }
628 = do { (floats, e') <- rhsToBody e
629 ; return (floats, Cast e' co) }
630
631 rhsToBody expr@(Lam {})
632 | Just no_lam_result <- tryEtaReducePrep bndrs body
633 = return (emptyFloats, no_lam_result)
634 | all isTyVar bndrs -- Type lambdas are ok
635 = return (emptyFloats, expr)
636 | otherwise -- Some value lambdas
637 = do { fn <- newVar (exprType expr)
638 ; let rhs = cpeEtaExpand (exprArity expr) expr
639 float = FloatLet (NonRec fn rhs)
640 ; return (unitFloat float, Var fn) }
641 where
642 (bndrs,body) = collectBinders expr
643
644 rhsToBody expr = return (emptyFloats, expr)
645
646
647
648 -- ---------------------------------------------------------------------------
649 -- CpeApp: produces a result satisfying CpeApp
650 -- ---------------------------------------------------------------------------
651
652 cpeApp :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
653 -- May return a CpeRhs because of saturating primops
654 cpeApp env expr
655 = do { (app, (head,depth), _, floats, ss) <- collect_args expr 0
656 ; MASSERT(null ss) -- make sure we used all the strictness info
657
658 -- Now deal with the function
659 ; case head of
660 Var fn_id -> do { sat_app <- maybeSaturate fn_id app depth
661 ; return (floats, sat_app) }
662 _other -> return (floats, app) }
663
664 where
665 -- Deconstruct and rebuild the application, floating any non-atomic
666 -- arguments to the outside. We collect the type of the expression,
667 -- the head of the application, and the number of actual value arguments,
668 -- all of which are used to possibly saturate this application if it
669 -- has a constructor or primop at the head.
670
671 collect_args
672 :: CoreExpr
673 -> Int -- Current app depth
674 -> UniqSM (CpeApp, -- The rebuilt expression
675 (CoreExpr,Int), -- The head of the application,
676 -- and no. of args it was applied to
677 Type, -- Type of the whole expr
678 Floats, -- Any floats we pulled out
679 [Demand]) -- Remaining argument demands
680
681 collect_args (App fun arg@(Type arg_ty)) depth
682 = do { (fun',hd,fun_ty,floats,ss) <- collect_args fun depth
683 ; return (App fun' arg, hd, applyTy fun_ty arg_ty, floats, ss) }
684
685 collect_args (App fun arg@(Coercion arg_co)) depth
686 = do { (fun',hd,fun_ty,floats,ss) <- collect_args fun depth
687 ; return (App fun' arg, hd, applyCo fun_ty arg_co, floats, ss) }
688
689 collect_args (App fun arg) depth
690 = do { (fun',hd,fun_ty,floats,ss) <- collect_args fun (depth+1)
691 ; let
692 (ss1, ss_rest) = case ss of
693 (ss1:ss_rest) -> (ss1, ss_rest)
694 [] -> (topDmd, [])
695 (arg_ty, res_ty) = expectJust "cpeBody:collect_args" $
696 splitFunTy_maybe fun_ty
697
698 ; (fs, arg') <- cpeArg env ss1 arg arg_ty
699 ; return (App fun' arg', hd, res_ty, fs `appendFloats` floats, ss_rest) }
700
701 collect_args (Var v) depth
702 = do { v1 <- fiddleCCall v
703 ; let v2 = lookupCorePrepEnv env v1
704 ; return (Var v2, (Var v2, depth), idType v2, emptyFloats, stricts) }
705 where
706 stricts = case idStrictness v of
707 StrictSig (DmdType _ demands _)
708 | listLengthCmp demands depth /= GT -> demands
709 -- length demands <= depth
710 | otherwise -> []
711 -- If depth < length demands, then we have too few args to
712 -- satisfy strictness info so we have to ignore all the
713 -- strictness info, e.g. + (error "urk")
714 -- Here, we can't evaluate the arg strictly, because this
715 -- partial application might be seq'd
716
717 collect_args (Cast fun co) depth
718 = do { let Pair _ty1 ty2 = coercionKind co
719 ; (fun', hd, _, floats, ss) <- collect_args fun depth
720 ; return (Cast fun' co, hd, ty2, floats, ss) }
721
722 collect_args (Tick tickish fun) depth
723 | tickishPlace tickish == PlaceNonLam
724 && tickish `tickishScopesLike` SoftScope
725 = do { (fun',hd,fun_ty,floats,ss) <- collect_args fun depth
726 -- See [Floating Ticks in CorePrep]
727 ; return (fun',hd,fun_ty,addFloat floats (FloatTick tickish),ss) }
728
729 -- N-variable fun, better let-bind it
730 collect_args fun depth
731 = do { (fun_floats, fun') <- cpeArg env evalDmd fun ty
732 -- The evalDmd says that it's sure to be evaluated,
733 -- so we'll end up case-binding it
734 ; return (fun', (fun', depth), ty, fun_floats, []) }
735 where
736 ty = exprType fun
737
738 -- ---------------------------------------------------------------------------
739 -- CpeArg: produces a result satisfying CpeArg
740 -- ---------------------------------------------------------------------------
741
742 -- This is where we arrange that a non-trivial argument is let-bound
743 cpeArg :: CorePrepEnv -> Demand
744 -> CoreArg -> Type -> UniqSM (Floats, CpeTriv)
745 cpeArg env dmd arg arg_ty
746 = do { (floats1, arg1) <- cpeRhsE env arg -- arg1 can be a lambda
747 ; (floats2, arg2) <- if want_float floats1 arg1
748 then return (floats1, arg1)
749 else do { body1 <- rhsToBodyNF arg1
750 ; return (emptyFloats, wrapBinds floats1 body1) }
751 -- Else case: arg1 might have lambdas, and we can't
752 -- put them inside a wrapBinds
753
754 ; if cpe_ExprIsTrivial arg2 -- Do not eta expand a trivial argument
755 then return (floats2, arg2)
756 else do
757 { v <- newVar arg_ty
758 ; let arg3 = cpeEtaExpand (exprArity arg2) arg2
759 arg_float = mkFloat dmd is_unlifted v arg3
760 ; return (addFloat floats2 arg_float, varToCoreExpr v) } }
761 where
762 is_unlifted = isUnLiftedType arg_ty
763 is_strict = isStrictDmd dmd
764 want_float = wantFloatNested NonRecursive (is_strict || is_unlifted)
765
766 {-
767 Note [Floating unlifted arguments]
768 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
769 Consider C (let v* = expensive in v)
770
771 where the "*" indicates "will be demanded". Usually v will have been
772 inlined by now, but let's suppose it hasn't (see Trac #2756). Then we
773 do *not* want to get
774
775 let v* = expensive in C v
776
777 because that has different strictness. Hence the use of 'allLazy'.
778 (NB: the let v* turns into a FloatCase, in mkLocalNonRec.)
779
780
781 ------------------------------------------------------------------------------
782 -- Building the saturated syntax
783 -- ---------------------------------------------------------------------------
784
785 maybeSaturate deals with saturating primops and constructors
786 The type is the type of the entire application
787 -}
788
789 maybeSaturate :: Id -> CpeApp -> Int -> UniqSM CpeRhs
790 maybeSaturate fn expr n_args
791 | Just DataToTagOp <- isPrimOpId_maybe fn -- DataToTag must have an evaluated arg
792 -- A gruesome special case
793 = saturateDataToTag sat_expr
794
795 | hasNoBinding fn -- There's no binding
796 = return sat_expr
797
798 | otherwise
799 = return expr
800 where
801 fn_arity = idArity fn
802 excess_arity = fn_arity - n_args
803 sat_expr = cpeEtaExpand excess_arity expr
804
805 -------------
806 saturateDataToTag :: CpeApp -> UniqSM CpeApp
807 -- See Note [dataToTag magic]
808 saturateDataToTag sat_expr
809 = do { let (eta_bndrs, eta_body) = collectBinders sat_expr
810 ; eta_body' <- eval_data2tag_arg eta_body
811 ; return (mkLams eta_bndrs eta_body') }
812 where
813 eval_data2tag_arg :: CpeApp -> UniqSM CpeBody
814 eval_data2tag_arg app@(fun `App` arg)
815 | exprIsHNF arg -- Includes nullary constructors
816 = return app -- The arg is evaluated
817 | otherwise -- Arg not evaluated, so evaluate it
818 = do { arg_id <- newVar (exprType arg)
819 ; let arg_id1 = setIdUnfolding arg_id evaldUnfolding
820 ; return (Case arg arg_id1 (exprType app)
821 [(DEFAULT, [], fun `App` Var arg_id1)]) }
822
823 eval_data2tag_arg (Tick t app) -- Scc notes can appear
824 = do { app' <- eval_data2tag_arg app
825 ; return (Tick t app') }
826
827 eval_data2tag_arg other -- Should not happen
828 = pprPanic "eval_data2tag" (ppr other)
829
830 {-
831 Note [dataToTag magic]
832 ~~~~~~~~~~~~~~~~~~~~~~
833 Horrid: we must ensure that the arg of data2TagOp is evaluated
834 (data2tag x) --> (case x of y -> data2tag y)
835 (yuk yuk) take into account the lambdas we've now introduced
836
837 How might it not be evaluated? Well, we might have floated it out
838 of the scope of a `seq`, or dropped the `seq` altogether.
839
840
841 ************************************************************************
842 * *
843 Simple CoreSyn operations
844 * *
845 ************************************************************************
846 -}
847
848 cpe_ExprIsTrivial :: CoreExpr -> Bool
849 -- Version that doesn't consider an scc annotation to be trivial.
850 cpe_ExprIsTrivial (Var _) = True
851 cpe_ExprIsTrivial (Type _) = True
852 cpe_ExprIsTrivial (Coercion _) = True
853 cpe_ExprIsTrivial (Lit _) = True
854 cpe_ExprIsTrivial (App e arg) = not (isRuntimeArg arg) && cpe_ExprIsTrivial e
855 cpe_ExprIsTrivial (Lam b e) = not (isRuntimeVar b) && cpe_ExprIsTrivial e
856 cpe_ExprIsTrivial (Tick t e) = not (tickishIsCode t) && cpe_ExprIsTrivial e
857 cpe_ExprIsTrivial (Cast e _) = cpe_ExprIsTrivial e
858 cpe_ExprIsTrivial (Case e _ _ []) = cpe_ExprIsTrivial e
859 -- See Note [Empty case is trivial] in CoreUtils
860 cpe_ExprIsTrivial _ = False
861
862 {-
863 -- -----------------------------------------------------------------------------
864 -- Eta reduction
865 -- -----------------------------------------------------------------------------
866
867 Note [Eta expansion]
868 ~~~~~~~~~~~~~~~~~~~~~
869 Eta expand to match the arity claimed by the binder Remember,
870 CorePrep must not change arity
871
872 Eta expansion might not have happened already, because it is done by
873 the simplifier only when there at least one lambda already.
874
875 NB1:we could refrain when the RHS is trivial (which can happen
876 for exported things). This would reduce the amount of code
877 generated (a little) and make things a little words for
878 code compiled without -O. The case in point is data constructor
879 wrappers.
880
881 NB2: we have to be careful that the result of etaExpand doesn't
882 invalidate any of the assumptions that CorePrep is attempting
883 to establish. One possible cause is eta expanding inside of
884 an SCC note - we're now careful in etaExpand to make sure the
885 SCC is pushed inside any new lambdas that are generated.
886
887 Note [Eta expansion and the CorePrep invariants]
888 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
889 It turns out to be much much easier to do eta expansion
890 *after* the main CorePrep stuff. But that places constraints
891 on the eta expander: given a CpeRhs, it must return a CpeRhs.
892
893 For example here is what we do not want:
894 f = /\a -> g (h 3) -- h has arity 2
895 After ANFing we get
896 f = /\a -> let s = h 3 in g s
897 and now we do NOT want eta expansion to give
898 f = /\a -> \ y -> (let s = h 3 in g s) y
899
900 Instead CoreArity.etaExpand gives
901 f = /\a -> \y -> let s = h 3 in g s y
902 -}
903
904 cpeEtaExpand :: Arity -> CpeRhs -> CpeRhs
905 cpeEtaExpand arity expr
906 | arity == 0 = expr
907 | otherwise = etaExpand arity expr
908
909 {-
910 -- -----------------------------------------------------------------------------
911 -- Eta reduction
912 -- -----------------------------------------------------------------------------
913
914 Why try eta reduction? Hasn't the simplifier already done eta?
915 But the simplifier only eta reduces if that leaves something
916 trivial (like f, or f Int). But for deLam it would be enough to
917 get to a partial application:
918 case x of { p -> \xs. map f xs }
919 ==> case x of { p -> map f }
920 -}
921
922 tryEtaReducePrep :: [CoreBndr] -> CoreExpr -> Maybe CoreExpr
923 tryEtaReducePrep bndrs expr@(App _ _)
924 | ok_to_eta_reduce f
925 , n_remaining >= 0
926 , and (zipWith ok bndrs last_args)
927 , not (any (`elemVarSet` fvs_remaining) bndrs)
928 , exprIsHNF remaining_expr -- Don't turn value into a non-value
929 -- else the behaviour with 'seq' changes
930 = Just remaining_expr
931 where
932 (f, args) = collectArgs expr
933 remaining_expr = mkApps f remaining_args
934 fvs_remaining = exprFreeVars remaining_expr
935 (remaining_args, last_args) = splitAt n_remaining args
936 n_remaining = length args - length bndrs
937
938 ok bndr (Var arg) = bndr == arg
939 ok _ _ = False
940
941 -- We can't eta reduce something which must be saturated.
942 ok_to_eta_reduce (Var f) = not (hasNoBinding f)
943 ok_to_eta_reduce _ = False -- Safe. ToDo: generalise
944
945 tryEtaReducePrep bndrs (Let bind@(NonRec _ r) body)
946 | not (any (`elemVarSet` fvs) bndrs)
947 = case tryEtaReducePrep bndrs body of
948 Just e -> Just (Let bind e)
949 Nothing -> Nothing
950 where
951 fvs = exprFreeVars r
952
953 tryEtaReducePrep bndrs (Tick tickish e)
954 = fmap (mkTick tickish) $ tryEtaReducePrep bndrs e
955
956 tryEtaReducePrep _ _ = Nothing
957
958 {-
959 ************************************************************************
960 * *
961 Floats
962 * *
963 ************************************************************************
964
965 Note [Pin demand info on floats]
966 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
967 We pin demand info on floated lets so that we can see the one-shot thunks.
968 -}
969
970 data FloatingBind
971 = FloatLet CoreBind -- Rhs of bindings are CpeRhss
972 -- They are always of lifted type;
973 -- unlifted ones are done with FloatCase
974
975 | FloatCase
976 Id CpeBody
977 Bool -- The bool indicates "ok-for-speculation"
978
979 -- | See Note [Floating Ticks in CorePrep]
980 | FloatTick (Tickish Id)
981
982 data Floats = Floats OkToSpec (OrdList FloatingBind)
983
984 instance Outputable FloatingBind where
985 ppr (FloatLet b) = ppr b
986 ppr (FloatCase b r ok) = brackets (ppr ok) <+> ppr b <+> equals <+> ppr r
987 ppr (FloatTick t) = ppr t
988
989 instance Outputable Floats where
990 ppr (Floats flag fs) = ptext (sLit "Floats") <> brackets (ppr flag) <+>
991 braces (vcat (map ppr (fromOL fs)))
992
993 instance Outputable OkToSpec where
994 ppr OkToSpec = ptext (sLit "OkToSpec")
995 ppr IfUnboxedOk = ptext (sLit "IfUnboxedOk")
996 ppr NotOkToSpec = ptext (sLit "NotOkToSpec")
997
998 -- Can we float these binds out of the rhs of a let? We cache this decision
999 -- to avoid having to recompute it in a non-linear way when there are
1000 -- deeply nested lets.
1001 data OkToSpec
1002 = OkToSpec -- Lazy bindings of lifted type
1003 | IfUnboxedOk -- A mixture of lazy lifted bindings and n
1004 -- ok-to-speculate unlifted bindings
1005 | NotOkToSpec -- Some not-ok-to-speculate unlifted bindings
1006
1007 mkFloat :: Demand -> Bool -> Id -> CpeRhs -> FloatingBind
1008 mkFloat dmd is_unlifted bndr rhs
1009 | use_case = FloatCase bndr rhs (exprOkForSpeculation rhs)
1010 | is_hnf = FloatLet (NonRec bndr rhs)
1011 | otherwise = FloatLet (NonRec (setIdDemandInfo bndr dmd) rhs)
1012 -- See Note [Pin demand info on floats]
1013 where
1014 is_hnf = exprIsHNF rhs
1015 is_strict = isStrictDmd dmd
1016 use_case = is_unlifted || is_strict && not is_hnf
1017 -- Don't make a case for a value binding,
1018 -- even if it's strict. Otherwise we get
1019 -- case (\x -> e) of ...!
1020
1021 emptyFloats :: Floats
1022 emptyFloats = Floats OkToSpec nilOL
1023
1024 isEmptyFloats :: Floats -> Bool
1025 isEmptyFloats (Floats _ bs) = isNilOL bs
1026
1027 wrapBinds :: Floats -> CpeBody -> CpeBody
1028 wrapBinds (Floats _ binds) body
1029 = foldrOL mk_bind body binds
1030 where
1031 mk_bind (FloatCase bndr rhs _) body = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
1032 mk_bind (FloatLet bind) body = Let bind body
1033 mk_bind (FloatTick tickish) body = mkTick tickish body
1034
1035 addFloat :: Floats -> FloatingBind -> Floats
1036 addFloat (Floats ok_to_spec floats) new_float
1037 = Floats (combine ok_to_spec (check new_float)) (floats `snocOL` new_float)
1038 where
1039 check (FloatLet _) = OkToSpec
1040 check (FloatCase _ _ ok_for_spec)
1041 | ok_for_spec = IfUnboxedOk
1042 | otherwise = NotOkToSpec
1043 check FloatTick{} = OkToSpec
1044 -- The ok-for-speculation flag says that it's safe to
1045 -- float this Case out of a let, and thereby do it more eagerly
1046 -- We need the top-level flag because it's never ok to float
1047 -- an unboxed binding to the top level
1048
1049 unitFloat :: FloatingBind -> Floats
1050 unitFloat = addFloat emptyFloats
1051
1052 appendFloats :: Floats -> Floats -> Floats
1053 appendFloats (Floats spec1 floats1) (Floats spec2 floats2)
1054 = Floats (combine spec1 spec2) (floats1 `appOL` floats2)
1055
1056 concatFloats :: [Floats] -> OrdList FloatingBind
1057 concatFloats = foldr (\ (Floats _ bs1) bs2 -> appOL bs1 bs2) nilOL
1058
1059 combine :: OkToSpec -> OkToSpec -> OkToSpec
1060 combine NotOkToSpec _ = NotOkToSpec
1061 combine _ NotOkToSpec = NotOkToSpec
1062 combine IfUnboxedOk _ = IfUnboxedOk
1063 combine _ IfUnboxedOk = IfUnboxedOk
1064 combine _ _ = OkToSpec
1065
1066 deFloatTop :: Floats -> [CoreBind]
1067 -- For top level only; we don't expect any FloatCases
1068 deFloatTop (Floats _ floats)
1069 = foldrOL get [] floats
1070 where
1071 get (FloatLet b) bs = occurAnalyseRHSs b : bs
1072 get b _ = pprPanic "corePrepPgm" (ppr b)
1073
1074 -- See Note [Dead code in CorePrep]
1075 occurAnalyseRHSs (NonRec x e) = NonRec x (occurAnalyseExpr_NoBinderSwap e)
1076 occurAnalyseRHSs (Rec xes) = Rec [(x, occurAnalyseExpr_NoBinderSwap e) | (x, e) <- xes]
1077
1078 ---------------------------------------------------------------------------
1079
1080 canFloatFromNoCaf :: Platform -> Floats -> CpeRhs -> Maybe (Floats, CpeRhs)
1081 -- Note [CafInfo and floating]
1082 canFloatFromNoCaf platform (Floats ok_to_spec fs) rhs
1083 | OkToSpec <- ok_to_spec -- Worth trying
1084 , Just (subst, fs') <- go (emptySubst, nilOL) (fromOL fs)
1085 = Just (Floats OkToSpec fs', subst_expr subst rhs)
1086 | otherwise
1087 = Nothing
1088 where
1089 subst_expr = substExpr (text "CorePrep")
1090
1091 go :: (Subst, OrdList FloatingBind) -> [FloatingBind]
1092 -> Maybe (Subst, OrdList FloatingBind)
1093
1094 go (subst, fbs_out) [] = Just (subst, fbs_out)
1095
1096 go (subst, fbs_out) (FloatLet (NonRec b r) : fbs_in)
1097 | rhs_ok r
1098 = go (subst', fbs_out `snocOL` new_fb) fbs_in
1099 where
1100 (subst', b') = set_nocaf_bndr subst b
1101 new_fb = FloatLet (NonRec b' (subst_expr subst r))
1102
1103 go (subst, fbs_out) (FloatLet (Rec prs) : fbs_in)
1104 | all rhs_ok rs
1105 = go (subst', fbs_out `snocOL` new_fb) fbs_in
1106 where
1107 (bs,rs) = unzip prs
1108 (subst', bs') = mapAccumL set_nocaf_bndr subst bs
1109 rs' = map (subst_expr subst') rs
1110 new_fb = FloatLet (Rec (bs' `zip` rs'))
1111
1112 go (subst, fbs_out) (ft@FloatTick{} : fbs_in)
1113 = go (subst, fbs_out `snocOL` ft) fbs_in
1114
1115 go _ _ = Nothing -- Encountered a caffy binding
1116
1117 ------------
1118 set_nocaf_bndr subst bndr
1119 = (extendIdSubst subst bndr (Var bndr'), bndr')
1120 where
1121 bndr' = bndr `setIdCafInfo` NoCafRefs
1122
1123 ------------
1124 rhs_ok :: CoreExpr -> Bool
1125 -- We can only float to top level from a NoCaf thing if
1126 -- the new binding is static. However it can't mention
1127 -- any non-static things or it would *already* be Caffy
1128 rhs_ok = rhsIsStatic platform (\_ -> False)
1129 (\i -> pprPanic "rhsIsStatic" (integer i))
1130 -- Integer literals should not show up
1131
1132 wantFloatNested :: RecFlag -> Bool -> Floats -> CpeRhs -> Bool
1133 wantFloatNested is_rec strict_or_unlifted floats rhs
1134 = isEmptyFloats floats
1135 || strict_or_unlifted
1136 || (allLazyNested is_rec floats && exprIsHNF rhs)
1137 -- Why the test for allLazyNested?
1138 -- v = f (x `divInt#` y)
1139 -- we don't want to float the case, even if f has arity 2,
1140 -- because floating the case would make it evaluated too early
1141
1142 allLazyTop :: Floats -> Bool
1143 allLazyTop (Floats OkToSpec _) = True
1144 allLazyTop _ = False
1145
1146 allLazyNested :: RecFlag -> Floats -> Bool
1147 allLazyNested _ (Floats OkToSpec _) = True
1148 allLazyNested _ (Floats NotOkToSpec _) = False
1149 allLazyNested is_rec (Floats IfUnboxedOk _) = isNonRec is_rec
1150
1151 {-
1152 ************************************************************************
1153 * *
1154 Cloning
1155 * *
1156 ************************************************************************
1157 -}
1158
1159 -- ---------------------------------------------------------------------------
1160 -- The environment
1161 -- ---------------------------------------------------------------------------
1162
1163 data CorePrepEnv = CPE {
1164 cpe_dynFlags :: DynFlags,
1165 cpe_env :: (IdEnv Id), -- Clone local Ids
1166 cpe_mkIntegerId :: Id,
1167 cpe_integerSDataCon :: Maybe DataCon
1168 }
1169
1170 lookupMkIntegerName :: DynFlags -> HscEnv -> IO Id
1171 lookupMkIntegerName dflags hsc_env
1172 = guardIntegerUse dflags $ liftM tyThingId $
1173 lookupGlobal hsc_env mkIntegerName
1174
1175 lookupIntegerSDataConName :: DynFlags -> HscEnv -> IO (Maybe DataCon)
1176 lookupIntegerSDataConName dflags hsc_env = case cIntegerLibraryType of
1177 IntegerGMP -> guardIntegerUse dflags $ liftM (Just . tyThingDataCon) $
1178 lookupGlobal hsc_env integerSDataConName
1179 IntegerSimple -> return Nothing
1180
1181 -- | Helper for 'lookupMkIntegerName' and 'lookupIntegerSDataConName'
1182 guardIntegerUse :: DynFlags -> IO a -> IO a
1183 guardIntegerUse dflags act
1184 | thisPackage dflags == primUnitId
1185 = return $ panic "Can't use Integer in ghc-prim"
1186 | thisPackage dflags == integerUnitId
1187 = return $ panic "Can't use Integer in integer-*"
1188 | otherwise = act
1189
1190 mkInitialCorePrepEnv :: DynFlags -> HscEnv -> IO CorePrepEnv
1191 mkInitialCorePrepEnv dflags hsc_env
1192 = do mkIntegerId <- lookupMkIntegerName dflags hsc_env
1193 integerSDataCon <- lookupIntegerSDataConName dflags hsc_env
1194 return $ CPE {
1195 cpe_dynFlags = dflags,
1196 cpe_env = emptyVarEnv,
1197 cpe_mkIntegerId = mkIntegerId,
1198 cpe_integerSDataCon = integerSDataCon
1199 }
1200
1201 extendCorePrepEnv :: CorePrepEnv -> Id -> Id -> CorePrepEnv
1202 extendCorePrepEnv cpe id id'
1203 = cpe { cpe_env = extendVarEnv (cpe_env cpe) id id' }
1204
1205 extendCorePrepEnvList :: CorePrepEnv -> [(Id,Id)] -> CorePrepEnv
1206 extendCorePrepEnvList cpe prs
1207 = cpe { cpe_env = extendVarEnvList (cpe_env cpe) prs }
1208
1209 lookupCorePrepEnv :: CorePrepEnv -> Id -> Id
1210 lookupCorePrepEnv cpe id
1211 = case lookupVarEnv (cpe_env cpe) id of
1212 Nothing -> id
1213 Just id' -> id'
1214
1215 getMkIntegerId :: CorePrepEnv -> Id
1216 getMkIntegerId = cpe_mkIntegerId
1217
1218 ------------------------------------------------------------------------------
1219 -- Cloning binders
1220 -- ---------------------------------------------------------------------------
1221
1222 cpCloneBndrs :: CorePrepEnv -> [Var] -> UniqSM (CorePrepEnv, [Var])
1223 cpCloneBndrs env bs = mapAccumLM cpCloneBndr env bs
1224
1225 cpCloneBndr :: CorePrepEnv -> Var -> UniqSM (CorePrepEnv, Var)
1226 cpCloneBndr env bndr
1227 | isLocalId bndr, not (isCoVar bndr)
1228 = do bndr' <- setVarUnique bndr <$> getUniqueM
1229
1230 -- We are going to OccAnal soon, so drop (now-useless) rules/unfoldings
1231 -- so that we can drop more stuff as dead code.
1232 -- See also Note [Dead code in CorePrep]
1233 let bndr'' = bndr' `setIdUnfolding` noUnfolding
1234 `setIdSpecialisation` emptyRuleInfo
1235 return (extendCorePrepEnv env bndr bndr'', bndr'')
1236
1237 | otherwise -- Top level things, which we don't want
1238 -- to clone, have become GlobalIds by now
1239 -- And we don't clone tyvars, or coercion variables
1240 = return (env, bndr)
1241
1242
1243 ------------------------------------------------------------------------------
1244 -- Cloning ccall Ids; each must have a unique name,
1245 -- to give the code generator a handle to hang it on
1246 -- ---------------------------------------------------------------------------
1247
1248 fiddleCCall :: Id -> UniqSM Id
1249 fiddleCCall id
1250 | isFCallId id = (id `setVarUnique`) <$> getUniqueM
1251 | otherwise = return id
1252
1253 ------------------------------------------------------------------------------
1254 -- Generating new binders
1255 -- ---------------------------------------------------------------------------
1256
1257 newVar :: Type -> UniqSM Id
1258 newVar ty
1259 = seqType ty `seq` do
1260 uniq <- getUniqueM
1261 return (mkSysLocal (fsLit "sat") uniq ty)
1262
1263
1264 ------------------------------------------------------------------------------
1265 -- Floating ticks
1266 -- ---------------------------------------------------------------------------
1267 --
1268 -- Note [Floating Ticks in CorePrep]
1269 --
1270 -- It might seem counter-intuitive to float ticks by default, given
1271 -- that we don't actually want to move them if we can help it. On the
1272 -- other hand, nothing gets very far in CorePrep anyway, and we want
1273 -- to preserve the order of let bindings and tick annotations in
1274 -- relation to each other. For example, if we just wrapped let floats
1275 -- when they pass through ticks, we might end up performing the
1276 -- following transformation:
1277 --
1278 -- src<...> let foo = bar in baz
1279 -- ==> let foo = src<...> bar in src<...> baz
1280 --
1281 -- Because the let-binding would float through the tick, and then
1282 -- immediately materialize, achieving nothing but decreasing tick
1283 -- accuracy. The only special case is the following scenario:
1284 --
1285 -- let foo = src<...> (let a = b in bar) in baz
1286 -- ==> let foo = src<...> bar; a = src<...> b in baz
1287 --
1288 -- Here we would not want the source tick to end up covering "baz" and
1289 -- therefore refrain from pushing ticks outside. Instead, we copy them
1290 -- into the floating binds (here "a") in cpePair. Note that where "b"
1291 -- or "bar" are (value) lambdas we have to push the annotations
1292 -- further inside in order to uphold our rules.
1293 --
1294 -- All of this is implemented below in @wrapTicks@.
1295
1296 -- | Like wrapFloats, but only wraps tick floats
1297 wrapTicks :: Floats -> CoreExpr -> (Floats, CoreExpr)
1298 wrapTicks (Floats flag floats0) expr = (Floats flag floats1, expr')
1299 where (floats1, expr') = foldrOL go (nilOL, expr) floats0
1300 go (FloatTick t) (fs, e) = ASSERT(tickishPlace t == PlaceNonLam)
1301 (mapOL (wrap t) fs, mkTick t e)
1302 go other (fs, e) = (other `consOL` fs, e)
1303 wrap t (FloatLet bind) = FloatLet (wrapBind t bind)
1304 wrap t (FloatCase b r ok) = FloatCase b (mkTick t r) ok
1305 wrap _ other = pprPanic "wrapTicks: unexpected float!"
1306 (ppr other)
1307 wrapBind t (NonRec binder rhs) = NonRec binder (mkTick t rhs)
1308 wrapBind t (Rec pairs) = Rec (mapSnd (mkTick t) pairs)