[project @ 2000-01-04 17:40:46 by simonpj]
[ghc-hetmet.git] / ghc / compiler / coreSyn / CoreUnfold.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1998
3 %
4 \section[CoreUnfold]{Core-syntax unfoldings}
5
6 Unfoldings (which can travel across module boundaries) are in Core
7 syntax (namely @CoreExpr@s).
8
9 The type @Unfolding@ sits ``above'' simply-Core-expressions
10 unfoldings, capturing ``higher-level'' things we know about a binding,
11 usually things that the simplifier found out (e.g., ``it's a
12 literal'').  In the corner of a @CoreUnfolding@ unfolding, you will
13 find, unsurprisingly, a Core expression.
14
15 \begin{code}
16 module CoreUnfold (
17         Unfolding, UnfoldingGuidance, -- types
18
19         noUnfolding, mkTopUnfolding, mkUnfolding, mkCompulsoryUnfolding, seqUnfolding,
20         mkOtherCon, otherCons,
21         unfoldingTemplate, maybeUnfoldingTemplate,
22         isEvaldUnfolding, isCheapUnfolding,
23         hasUnfolding, hasSomeUnfolding,
24
25         couldBeSmallEnoughToInline, 
26         certainlySmallEnoughToInline, 
27         okToUnfoldInHiFile,
28
29         calcUnfoldingGuidance, 
30
31         callSiteInline, blackListed
32     ) where
33
34 #include "HsVersions.h"
35
36 import CmdLineOpts      ( opt_UF_CreationThreshold,
37                           opt_UF_UseThreshold,
38                           opt_UF_ScrutConDiscount,
39                           opt_UF_FunAppDiscount,
40                           opt_UF_PrimArgDiscount,
41                           opt_UF_KeenessFactor,
42                           opt_UF_CheapOp, opt_UF_DearOp, opt_UF_NoRepLit,
43                           opt_UnfoldCasms, opt_PprStyle_Debug,
44                           opt_D_dump_inlinings
45                         )
46 import CoreSyn
47 import PprCore          ( pprCoreExpr )
48 import OccurAnal        ( occurAnalyseGlobalExpr )
49 import BinderInfo       ( )
50 import CoreUtils        ( coreExprType, exprIsTrivial, exprIsValue, exprIsCheap )
51 import Id               ( Id, idType, idUnique, isId, getIdWorkerInfo,
52                           getIdSpecialisation, getInlinePragma, getIdUnfolding,
53                           isConstantId_maybe
54                         )
55 import VarSet
56 import Name             ( isLocallyDefined )
57 import Const            ( Con(..), isLitLitLit, isWHNFCon )
58 import PrimOp           ( PrimOp(..), primOpIsDupable )
59 import IdInfo           ( ArityInfo(..), InlinePragInfo(..), OccInfo(..), insideLam, workerExists )
60 import TyCon            ( tyConFamilySize )
61 import Type             ( splitAlgTyConApp_maybe, splitFunTy_maybe, isUnLiftedType )
62 import Const            ( isNoRepLit )
63 import Unique           ( Unique, buildIdKey, augmentIdKey )
64 import Maybes           ( maybeToBool )
65 import Bag
66 import Util             ( isIn, lengthExceeds )
67 import Outputable
68
69 #if __GLASGOW_HASKELL__ >= 404
70 import GlaExts          ( fromInt )
71 #endif
72 \end{code}
73
74 %************************************************************************
75 %*                                                                      *
76 \subsection{@Unfolding@ and @UnfoldingGuidance@ types}
77 %*                                                                      *
78 %************************************************************************
79
80 \begin{code}
81 data Unfolding
82   = NoUnfolding
83
84   | OtherCon [Con]              -- It ain't one of these
85                                 -- (OtherCon xs) also indicates that something has been evaluated
86                                 -- and hence there's no point in re-evaluating it.
87                                 -- OtherCon [] is used even for non-data-type values
88                                 -- to indicated evaluated-ness.  Notably:
89                                 --      data C = C !(Int -> Int)
90                                 --      case x of { C f -> ... }
91                                 -- Here, f gets an OtherCon [] unfolding.
92
93   | CompulsoryUnfolding CoreExpr        -- There is no "original" definition,
94                                         -- so you'd better unfold.
95
96   | CoreUnfolding                       -- An unfolding with redundant cached information
97                 CoreExpr                -- Template; binder-info is correct
98                 Bool                    -- This is a top-level binding
99                 Bool                    -- exprIsCheap template (cached); it won't duplicate (much) work 
100                                         --      if you inline this in more than one place
101                 Bool                    -- exprIsValue template (cached); it is ok to discard a `seq` on
102                                         --      this variable
103                 UnfoldingGuidance       -- Tells about the *size* of the template.
104
105 seqUnfolding :: Unfolding -> ()
106 seqUnfolding (CoreUnfolding e top b1 b2 g)
107   = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
108 seqUnfolding other = ()
109 \end{code}
110
111 \begin{code}
112 noUnfolding = NoUnfolding
113 mkOtherCon  = OtherCon
114
115 mkTopUnfolding expr = mkUnfolding True expr
116
117 mkUnfolding top_lvl expr
118   = CoreUnfolding (occurAnalyseGlobalExpr expr)
119                   top_lvl
120                   (exprIsCheap expr)
121                   (exprIsValue expr)
122                   (calcUnfoldingGuidance opt_UF_CreationThreshold expr)
123
124 mkCompulsoryUnfolding expr      -- Used for things that absolutely must be unfolded
125   = CompulsoryUnfolding (occurAnalyseGlobalExpr expr)
126
127 unfoldingTemplate :: Unfolding -> CoreExpr
128 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
129 unfoldingTemplate (CompulsoryUnfolding expr)   = expr
130 unfoldingTemplate other = panic "getUnfoldingTemplate"
131
132 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
133 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
134 maybeUnfoldingTemplate (CompulsoryUnfolding expr)   = Just expr
135 maybeUnfoldingTemplate other                        = Nothing
136
137 otherCons (OtherCon cons) = cons
138 otherCons other           = []
139
140 isEvaldUnfolding :: Unfolding -> Bool
141 isEvaldUnfolding (OtherCon _)                     = True
142 isEvaldUnfolding (CoreUnfolding _ _ _ is_evald _) = is_evald
143 isEvaldUnfolding other                            = False
144
145 isCheapUnfolding :: Unfolding -> Bool
146 isCheapUnfolding (CoreUnfolding _ _ is_cheap _ _) = is_cheap
147 isCheapUnfolding other                            = False
148
149 hasUnfolding :: Unfolding -> Bool
150 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
151 hasUnfolding (CompulsoryUnfolding _)   = True
152 hasUnfolding other                     = False
153
154 hasSomeUnfolding :: Unfolding -> Bool
155 hasSomeUnfolding NoUnfolding = False
156 hasSomeUnfolding other       = True
157
158 data UnfoldingGuidance
159   = UnfoldNever
160   | UnfoldIfGoodArgs    Int     -- and "n" value args
161
162                         [Int]   -- Discount if the argument is evaluated.
163                                 -- (i.e., a simplification will definitely
164                                 -- be possible).  One elt of the list per *value* arg.
165
166                         Int     -- The "size" of the unfolding; to be elaborated
167                                 -- later. ToDo
168
169                         Int     -- Scrutinee discount: the discount to substract if the thing is in
170                                 -- a context (case (thing args) of ...),
171                                 -- (where there are the right number of arguments.)
172
173 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
174 seqGuidance other                       = ()
175 \end{code}
176
177 \begin{code}
178 instance Outputable UnfoldingGuidance where
179     ppr UnfoldNever     = ptext SLIT("NEVER")
180     ppr (UnfoldIfGoodArgs v cs size discount)
181       = hsep [ ptext SLIT("IF_ARGS"), int v,
182                brackets (hsep (map int cs)),
183                int size,
184                int discount ]
185 \end{code}
186
187
188 %************************************************************************
189 %*                                                                      *
190 \subsection[calcUnfoldingGuidance]{Calculate ``unfolding guidance'' for an expression}
191 %*                                                                      *
192 %************************************************************************
193
194 \begin{code}
195 calcUnfoldingGuidance
196         :: Int                  -- bomb out if size gets bigger than this
197         -> CoreExpr             -- expression to look at
198         -> UnfoldingGuidance
199 calcUnfoldingGuidance bOMB_OUT_SIZE expr
200   = case collect_val_bndrs expr of { (inline, val_binders, body) ->
201     let
202         n_val_binders = length val_binders
203     in
204     case (sizeExpr bOMB_OUT_SIZE val_binders body) of
205
206       TooBig 
207         | not inline -> UnfoldNever
208                 -- A big function with an INLINE pragma must
209                 -- have an UnfoldIfGoodArgs guidance
210         | inline     -> UnfoldIfGoodArgs n_val_binders
211                                          (map (const 0) val_binders)
212                                          (n_val_binders + 2) 0
213                                 -- See comments with final_size below
214
215       SizeIs size cased_args scrut_discount
216         -> UnfoldIfGoodArgs
217                         n_val_binders
218                         (map discount_for val_binders)
219                         final_size
220                         (I# scrut_discount)
221         where        
222             boxed_size    = I# size
223
224             final_size | inline     = 0 -- Trying very agresssive inlining of INLINE things.
225                                         -- Reason: we don't want to call the un-inlined version,
226                                         --         because its body is awful
227                                         -- boxed_size `min` (n_val_binders + 2) -- Trying "+2" again...
228                        | otherwise  = boxed_size
229                 -- The idea is that if there is an INLINE pragma (inline is True)
230                 -- and there's a big body, we give a size of n_val_binders+1.  This
231                 -- This is enough to pass the no-size-increase test in callSiteInline,
232                 --   but no more.
233                 -- I tried n_val_binders+2, to just defeat the test, on the grounds that
234                 --   we don't want to inline an INLINE thing into a totally boring context,
235                 --   but I found that some wrappers (notably one for a join point) weren't
236                 --   getting inlined, and that was terrible.  In that particular case, the
237                 --   call site applied the wrapper to realWorld#, so if we made that an 
238                 --   "interesting" value the inlining would have happened... but it was
239                 --   simpler to inline wrappers a little more eagerly instead.
240                 --
241                 -- Sometimes, though, an INLINE thing is smaller than n_val_binders+2.
242                 -- A particular case in point is a constructor, which has size 1.
243                 -- We want to inline this regardless, hence the `min`
244
245             discount_for b 
246                 | num_cases == 0 = 0
247                 | is_fun_ty      = num_cases * opt_UF_FunAppDiscount
248                 | is_data_ty     = num_cases * opt_UF_ScrutConDiscount
249                 | otherwise      = num_cases * opt_UF_PrimArgDiscount
250                 where
251                   num_cases           = foldlBag (\n b' -> if b==b' then n+1 else n) 0 cased_args
252                                         -- Count occurrences of b in cased_args
253                   arg_ty              = idType b
254                   is_fun_ty           = maybeToBool (splitFunTy_maybe arg_ty)
255                   (is_data_ty, tycon) = case (splitAlgTyConApp_maybe (idType b)) of
256                                           Nothing       -> (False, panic "discount")
257                                           Just (tc,_,_) -> (True,  tc)
258         }
259   where
260
261     collect_val_bndrs e = go False [] e
262         -- We need to be a bit careful about how we collect the
263         -- value binders.  In ptic, if we see 
264         --      __inline_me (\x y -> e)
265         -- We want to say "2 value binders".  Why?  So that 
266         -- we take account of information given for the arguments
267
268     go inline rev_vbs (Note InlineMe e)     = go True   rev_vbs     e
269     go inline rev_vbs (Lam b e) | isId b    = go inline (b:rev_vbs) e
270                                 | otherwise = go inline rev_vbs     e
271     go inline rev_vbs e                     = (inline, reverse rev_vbs, e)
272 \end{code}
273
274 \begin{code}
275 sizeExpr :: Int             -- Bomb out if it gets bigger than this
276          -> [Id]            -- Arguments; we're interested in which of these
277                             -- get case'd
278          -> CoreExpr
279          -> ExprSize
280
281 sizeExpr (I# bOMB_OUT_SIZE) top_args expr
282   = size_up expr
283   where
284     size_up (Type t)          = sizeZero        -- Types cost nothing
285     size_up (Var v)           = sizeOne
286
287     size_up (Note _ body)     = size_up body    -- Notes cost nothing
288
289     size_up (App fun (Type t))  = size_up fun
290     size_up (App fun arg)       = size_up_app fun [arg]
291
292     size_up (Con con args) = foldr (addSize . nukeScrutDiscount . size_up) 
293                                    (size_up_con con args)
294                                    args
295
296     size_up (Lam b e) | isId b    = size_up e `addSizeN` 1
297                       | otherwise = size_up e
298
299     size_up (Let (NonRec binder rhs) body)
300       = nukeScrutDiscount (size_up rhs)         `addSize`
301         size_up body                            `addSizeN`
302         (if isUnLiftedType (idType binder) then 0 else 1)
303                 -- For the allocation
304                 -- If the binder has an unlifted type there is no allocation
305
306     size_up (Let (Rec pairs) body)
307       = nukeScrutDiscount rhs_size              `addSize`
308         size_up body                            `addSizeN`
309         length pairs            -- For the allocation
310       where
311         rhs_size = foldr (addSize . size_up . snd) sizeZero pairs
312
313     size_up (Case scrut _ alts)
314       = nukeScrutDiscount (size_up scrut)               `addSize`
315         arg_discount scrut                              `addSize`
316         foldr (addSize . size_up_alt) sizeZero alts     
317           `addSizeN` 1  -- charge one for the case itself.
318
319 -- Just charge for the alts that exist, not the ones that might exist
320 --      `addSizeN`
321 --      case (splitAlgTyConApp_maybe (coreExprType scrut)) of
322 --              Nothing       -> 1
323 --              Just (tc,_,_) -> tyConFamilySize tc
324
325     ------------ 
326     size_up_app (App fun arg) args   = size_up_app fun (arg:args)
327     size_up_app fun           args   = foldr (addSize . nukeScrutDiscount . size_up) 
328                                              (size_up_fun fun args)
329                                              args
330
331         -- A function application with at least one value argument
332         -- so if the function is an argument give it an arg-discount
333         -- Also behave specially if the function is a build
334         -- Also if the function is a constant Id (constr or primop)
335         -- compute discounts as if it were actually a Con; in the early
336         -- stages these constructors and primops may not yet be inlined
337     size_up_fun (Var fun) args | idUnique fun == buildIdKey   = buildSize
338                                | idUnique fun == augmentIdKey = augmentSize
339                                | fun `is_elem` top_args       = scrutArg fun `addSize` fun_size
340                                | otherwise                    = fun_size
341                           where
342                             fun_size = case isConstantId_maybe fun of
343                                              Just con -> size_up_con con args
344                                              Nothing  -> sizeOne
345
346     size_up_fun other args = size_up other
347
348     ------------ 
349     size_up_alt (con, bndrs, rhs) = size_up rhs
350             -- Don't charge for args, so that wrappers look cheap
351
352     ------------
353     size_up_con (Literal lit) args | isNoRepLit lit = sizeN opt_UF_NoRepLit
354                                    | otherwise      = sizeOne
355
356     size_up_con (DataCon dc) args = conSizeN (valArgCount args)
357                              
358     size_up_con (PrimOp op) args = foldr addSize (sizeN op_cost) (map arg_discount args)
359                 -- Give an arg-discount if a primop is applies to
360                 -- one of the function's arguments
361       where
362         op_cost | primOpIsDupable op = opt_UF_CheapOp
363                 | otherwise          = opt_UF_DearOp
364
365         -- We want to record if we're case'ing, or applying, an argument
366     arg_discount (Var v) | v `is_elem` top_args = scrutArg v
367     arg_discount other                          = sizeZero
368
369     ------------
370     is_elem :: Id -> [Id] -> Bool
371     is_elem = isIn "size_up_scrut"
372
373     ------------
374         -- These addSize things have to be here because
375         -- I don't want to give them bOMB_OUT_SIZE as an argument
376
377     addSizeN TooBig          _ = TooBig
378     addSizeN (SizeIs n xs d) (I# m)
379       | n_tot -# d <# bOMB_OUT_SIZE = SizeIs n_tot xs d
380       | otherwise                   = TooBig
381       where
382         n_tot = n +# m
383     
384     addSize TooBig _ = TooBig
385     addSize _ TooBig = TooBig
386     addSize (SizeIs n1 xs d1) (SizeIs n2 ys d2)
387       | (n_tot -# d_tot) <# bOMB_OUT_SIZE = SizeIs n_tot xys d_tot
388       | otherwise                         = TooBig
389       where
390         n_tot = n1 +# n2
391         d_tot = d1 +# d2
392         xys   = xs `unionBags` ys
393 \end{code}
394
395 Code for manipulating sizes
396
397 \begin{code}
398
399 data ExprSize = TooBig
400               | SizeIs Int#     -- Size found
401                        (Bag Id) -- Arguments cased herein
402                        Int#     -- Size to subtract if result is scrutinised 
403                                 -- by a case expression
404
405 sizeZero        = SizeIs 0# emptyBag 0#
406 sizeOne         = SizeIs 1# emptyBag 0#
407 sizeTwo         = SizeIs 2# emptyBag 0#
408 sizeN (I# n)    = SizeIs n  emptyBag 0#
409 conSizeN (I# n) = SizeIs 1# emptyBag (n +# 1#)
410         -- Treat constructors as size 1, that unfoldAlways responsds 'False'
411         -- when asked about 'x' when x is bound to (C 3#).
412         -- This avoids gratuitous 'ticks' when x itself appears as an
413         -- atomic constructor argument.
414
415 buildSize = SizeIs (-2#) emptyBag 4#
416         -- We really want to inline applications of build
417         -- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
418         -- Indeed, we should add a result_discount becuause build is 
419         -- very like a constructor.  We don't bother to check that the
420         -- build is saturated (it usually is).  The "-2" discounts for the \c n, 
421         -- The "4" is rather arbitrary.
422
423 augmentSize = SizeIs (-2#) emptyBag 4#
424         -- Ditto (augment t (\cn -> e) ys) should cost only the cost of
425         -- e plus ys. The -2 accounts for the \cn 
426                                                 
427 scrutArg v      = SizeIs 0# (unitBag v) 0#
428
429 nukeScrutDiscount (SizeIs n vs d) = SizeIs n vs 0#
430 nukeScrutDiscount TooBig          = TooBig
431 \end{code}
432
433
434 %************************************************************************
435 %*                                                                      *
436 \subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
437 %*                                                                      *
438 %************************************************************************
439
440 We have very limited information about an unfolding expression: (1)~so
441 many type arguments and so many value arguments expected---for our
442 purposes here, we assume we've got those.  (2)~A ``size'' or ``cost,''
443 a single integer.  (3)~An ``argument info'' vector.  For this, what we
444 have at the moment is a Boolean per argument position that says, ``I
445 will look with great favour on an explicit constructor in this
446 position.'' (4)~The ``discount'' to subtract if the expression
447 is being scrutinised. 
448
449 Assuming we have enough type- and value arguments (if not, we give up
450 immediately), then we see if the ``discounted size'' is below some
451 (semi-arbitrary) threshold.  It works like this: for every argument
452 position where we're looking for a constructor AND WE HAVE ONE in our
453 hands, we get a (again, semi-arbitrary) discount [proportion to the
454 number of constructors in the type being scrutinized].
455
456 If we're in the context of a scrutinee ( \tr{(case <expr > of A .. -> ...;.. )})
457 and the expression in question will evaluate to a constructor, we use
458 the computed discount size *for the result only* rather than
459 computing the argument discounts. Since we know the result of
460 the expression is going to be taken apart, discounting its size
461 is more accurate (see @sizeExpr@ above for how this discount size
462 is computed).
463
464 We use this one to avoid exporting inlinings that we ``couldn't possibly
465 use'' on the other side.  Can be overridden w/ flaggery.
466 Just the same as smallEnoughToInline, except that it has no actual arguments.
467
468 \begin{code}
469 couldBeSmallEnoughToInline :: UnfoldingGuidance -> Bool
470 couldBeSmallEnoughToInline UnfoldNever = False
471 couldBeSmallEnoughToInline other       = True
472
473 certainlySmallEnoughToInline :: UnfoldingGuidance -> Bool
474 certainlySmallEnoughToInline UnfoldNever                   = False
475 certainlySmallEnoughToInline (UnfoldIfGoodArgs _ _ size _) = size <= opt_UF_UseThreshold
476 \end{code}
477
478 @okToUnfoldInHifile@ is used when emitting unfolding info into an interface
479 file to determine whether an unfolding candidate really should be unfolded.
480 The predicate is needed to prevent @_casm_@s (+ lit-lits) from being emitted
481 into interface files. 
482
483 The reason for inlining expressions containing _casm_s into interface files
484 is that these fragments of C are likely to mention functions/#defines that
485 will be out-of-scope when inlined into another module. This is not an
486 unfixable problem for the user (just need to -#include the approp. header
487 file), but turning it off seems to the simplest thing to do.
488
489 \begin{code}
490 okToUnfoldInHiFile :: CoreExpr -> Bool
491 okToUnfoldInHiFile e = opt_UnfoldCasms || go e
492  where
493     -- Race over an expression looking for CCalls..
494     go (Var _)                = True
495     go (Con (Literal lit) _)  = not (isLitLitLit lit)
496     go (Con (PrimOp op) args) = okToUnfoldPrimOp op && all go args
497     go (Con con args)         = True -- con args are always atomic
498     go (App fun arg)          = go fun && go arg
499     go (Lam _ body)           = go body
500     go (Let binds body)       = and (map go (body :rhssOfBind binds))
501     go (Case scrut bndr alts) = and (map go (scrut:rhssOfAlts alts))
502     go (Note _ body)          = go body
503     go (Type _)               = True
504
505     -- ok to unfold a PrimOp as long as it's not a _casm_
506     okToUnfoldPrimOp (CCallOp _ is_casm _ _) = not is_casm
507     okToUnfoldPrimOp _                       = True
508 \end{code}
509
510
511 %************************************************************************
512 %*                                                                      *
513 \subsection{callSiteInline}
514 %*                                                                      *
515 %************************************************************************
516
517 This is the key function.  It decides whether to inline a variable at a call site
518
519 callSiteInline is used at call sites, so it is a bit more generous.
520 It's a very important function that embodies lots of heuristics.
521 A non-WHNF can be inlined if it doesn't occur inside a lambda,
522 and occurs exactly once or 
523     occurs once in each branch of a case and is small
524
525 If the thing is in WHNF, there's no danger of duplicating work, 
526 so we can inline if it occurs once, or is small
527
528 \begin{code}
529 callSiteInline :: Bool                  -- True <=> the Id is black listed
530                -> Bool                  -- 'inline' note at call site
531                -> OccInfo
532                -> Id                    -- The Id
533                -> [Bool]                -- One for each value arg; True if it is interesting
534                -> Bool                  -- True <=> continuation is interesting
535                -> Maybe CoreExpr        -- Unfolding, if any
536
537
538 callSiteInline black_listed inline_call occ id arg_infos interesting_cont
539   = case getIdUnfolding id of {
540         NoUnfolding -> Nothing ;
541         OtherCon _  -> Nothing ;
542         CompulsoryUnfolding unf_template | black_listed -> Nothing 
543                                          | otherwise    -> Just unf_template ;
544                 -- Primops have compulsory unfoldings, but
545                 -- may have rules, in which case they are 
546                 -- black listed till later
547         CoreUnfolding unf_template is_top is_cheap _ guidance ->
548
549     let
550         result | yes_or_no = Just unf_template
551                | otherwise = Nothing
552
553         n_val_args  = length arg_infos
554
555         yes_or_no 
556           | black_listed = False
557           | otherwise    = case occ of
558                                 IAmDead              -> pprTrace "callSiteInline: dead" (ppr id) False
559                                 IAmALoopBreaker      -> False
560                                 OneOcc in_lam one_br -> (not in_lam || is_cheap) && consider_safe in_lam True  one_br
561                                 NoOccInfo            -> is_cheap                 && consider_safe True   False False
562
563         consider_safe in_lam once once_in_one_branch
564                 -- consider_safe decides whether it's a good idea to inline something,
565                 -- given that there's no work-duplication issue (the caller checks that).
566                 -- once_in_one_branch = True means there's a unique textual occurrence
567           | inline_call  = True
568
569           | once_in_one_branch  -- Be very keen to inline something if this is its unique occurrence; that
570                                 -- gives a good chance of eliminating the original binding for the thing.
571                                 -- The only time we hold back is when substituting inside a lambda;
572                                 -- then if the context is totally uninteresting (not applied, not scrutinised)
573                                 -- there is no point in substituting because it might just increase allocation.
574           = not in_lam || not (null arg_infos) || interesting_cont
575
576           | otherwise
577           = case guidance of
578               UnfoldNever  -> False ;
579               UnfoldIfGoodArgs n_vals_wanted arg_discounts size res_discount
580
581                   | enough_args && size <= (n_vals_wanted + 1)
582                         -- No size increase
583                         -- Size of call is n_vals_wanted (+1 for the function)
584                   -> True
585
586                   | otherwise
587                   -> some_benefit && small_enough
588
589                   where
590                     some_benefit = or arg_infos || really_interesting_cont || 
591                                  (not is_top && (once || (n_vals_wanted > 0 && enough_args)))
592                         -- If it occurs more than once, there must be something interesting 
593                         -- about some argument, or the result context, to make it worth inlining
594                         --
595                         -- If a function has a nested defn we also record some-benefit,
596                         -- on the grounds that we are often able to eliminate the binding,
597                         -- and hence the allocation, for the function altogether; this is good
598                         -- for join points.  But this only makes sense for *functions*;
599                         -- inlining a constructor doesn't help allocation unless the result is
600                         -- scrutinised.  UNLESS the constructor occurs just once, albeit possibly
601                         -- in multiple case branches.  Then inlining it doesn't increase allocation,
602                         -- but it does increase the chance that the constructor won't be allocated at all
603                         -- in the branches that don't use it.
604             
605                     enough_args           = n_val_args >= n_vals_wanted
606                     really_interesting_cont | n_val_args <  n_vals_wanted = False       -- Too few args
607                                             | n_val_args == n_vals_wanted = interesting_cont
608                                             | otherwise                   = True        -- Extra args
609                 -- really_interesting_cont tells if the result of the
610                 -- call is in an interesting context.
611                 
612                     small_enough = (size - discount) <= opt_UF_UseThreshold
613                     discount     = computeDiscount n_vals_wanted arg_discounts res_discount 
614                                                  arg_infos really_interesting_cont
615                 
616     in    
617 #ifdef DEBUG
618     if opt_D_dump_inlinings then
619         pprTrace "Considering inlining"
620                  (ppr id <+> vcat [text "black listed" <+> ppr black_listed,
621                                    text "occ info:" <+> ppr occ,
622                                    text "arg infos" <+> ppr arg_infos,
623                                    text "interesting continuation" <+> ppr interesting_cont,
624                                    text "is cheap" <+> ppr is_cheap,
625                                    text "guidance" <+> ppr guidance,
626                                    text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO",
627                                    if yes_or_no then
628                                         text "Unfolding =" <+> pprCoreExpr unf_template
629                                    else empty])
630                   result
631     else
632 #endif
633     result
634     }
635
636 computeDiscount :: Int -> [Int] -> Int -> [Bool] -> Bool -> Int
637 computeDiscount n_vals_wanted arg_discounts res_discount arg_infos result_used
638         -- We multiple the raw discounts (args_discount and result_discount)
639         -- ty opt_UnfoldingKeenessFactor because the former have to do with
640         -- *size* whereas the discounts imply that there's some extra 
641         -- *efficiency* to be gained (e.g. beta reductions, case reductions) 
642         -- by inlining.
643
644         -- we also discount 1 for each argument passed, because these will
645         -- reduce with the lambdas in the function (we count 1 for a lambda
646         -- in size_up).
647   = 1 +                 -- Discount of 1 because the result replaces the call
648                         -- so we count 1 for the function itself
649     length (take n_vals_wanted arg_infos) +
650                         -- Discount of 1 for each arg supplied, because the 
651                         -- result replaces the call
652     round (opt_UF_KeenessFactor * 
653            fromInt (arg_discount + result_discount))
654   where
655     arg_discount = sum (zipWith mk_arg_discount arg_discounts arg_infos)
656
657     mk_arg_discount discount is_evald | is_evald  = discount
658                                       | otherwise = 0
659
660         -- Don't give a result discount unless there are enough args
661     result_discount | result_used = res_discount        -- Over-applied, or case scrut
662                     | otherwise   = 0
663 \end{code}
664
665
666 %************************************************************************
667 %*                                                                      *
668 \subsection{Black-listing}
669 %*                                                                      *
670 %************************************************************************
671
672 Inlining is controlled by the "Inline phase" number, which is set
673 by the per-simplification-pass '-finline-phase' flag.
674
675 For optimisation we use phase 1,2 and nothing (i.e. no -finline-phase flag)
676 in that order.  The meanings of these are determined by the @blackListed@ function
677 here.
678
679 The final simplification doesn't have a phase number
680
681 Pragmas
682 ~~~~~~~
683         Pragma          Black list if
684
685 (least black listing, most inlining)
686         INLINE n foo    phase is Just p *and* p<n *and* foo appears on LHS of rule
687         INLINE foo      phase is Just p *and*           foo appears on LHS of rule
688         NOINLINE n foo  phase is Just p *and* (p<n *or* foo appears on LHS of rule)
689         NOINLINE foo    always
690 (most black listing, least inlining)
691
692 \begin{code}
693 blackListed :: IdSet            -- Used in transformation rules
694             -> Maybe Int        -- Inline phase
695             -> Id -> Bool       -- True <=> blacklisted
696         
697 -- The blackListed function sees whether a variable should *not* be 
698 -- inlined because of the inline phase we are in.  This is the sole
699 -- place that the inline phase number is looked at.
700
701 blackListed rule_vars Nothing           -- Last phase
702   = \v -> case getInlinePragma v of
703                 IMustNotBeINLINEd False Nothing -> True         -- An unconditional NOINLINE pragma
704                 other                           -> False
705
706 blackListed rule_vars (Just 0)
707 -- Phase 0: used for 'no imported inlinings please'
708 -- This prevents wrappers getting inlined which in turn is bad for full laziness
709 -- NEW: try using 'not a wrapper' rather than 'not imported' in this phase.
710 -- This allows a little more inlining, which seems to be important, sometimes.
711 -- For example PrelArr.newIntArr gets better.
712   = \v -> -- workerExists (getIdWorkerInfo v) || normal_case rule_vars 0 v
713           -- True       -- Try going back to no inlinings at all
714                         -- BUT: I found that there is some advantage in doing 
715                         -- local inlinings first.  For example in fish/Main.hs
716                         -- it's advantageous to inline scale_vec2 before inlining
717                         -- wrappers from PrelNum that make it look big.
718           not (isLocallyDefined v) || normal_case rule_vars 0 v         -- This seems best at the moment
719
720 blackListed rule_vars (Just phase)
721   = \v -> normal_case rule_vars phase v
722
723 normal_case rule_vars phase v 
724   = case getInlinePragma v of
725         NoInlinePragInfo -> has_rules
726
727         IMustNotBeINLINEd from_INLINE Nothing
728           | from_INLINE -> has_rules    -- Black list until final phase
729           | otherwise   -> True         -- Always blacklisted
730
731         IMustNotBeINLINEd from_inline (Just threshold)
732           | from_inline -> phase < threshold && has_rules
733           | otherwise   -> phase < threshold || has_rules
734   where
735     has_rules =  v `elemVarSet` rule_vars
736               || not (isEmptyCoreRules (getIdSpecialisation v))
737 \end{code}
738
739
740 SLPJ 95/04: Why @runST@ must be inlined very late:
741 \begin{verbatim}
742 f x =
743   runST ( \ s -> let
744                     (a, s')  = newArray# 100 [] s
745                     (_, s'') = fill_in_array_or_something a x s'
746                   in
747                   freezeArray# a s'' )
748 \end{verbatim}
749 If we inline @runST@, we'll get:
750 \begin{verbatim}
751 f x = let
752         (a, s')  = newArray# 100 [] realWorld#{-NB-}
753         (_, s'') = fill_in_array_or_something a x s'
754       in
755       freezeArray# a s''
756 \end{verbatim}
757 And now the @newArray#@ binding can be floated to become a CAF, which
758 is totally and utterly wrong:
759 \begin{verbatim}
760 f = let
761     (a, s')  = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
762     in
763     \ x ->
764         let (_, s'') = fill_in_array_or_something a x s' in
765         freezeArray# a s''
766 \end{verbatim}
767 All calls to @f@ will share a {\em single} array!  
768
769 Yet we do want to inline runST sometime, so we can avoid
770 needless code.  Solution: black list it until the last moment.
771