Comments, and a couple of asserts, only
[ghc-hetmet.git] / compiler / coreSyn / CoreUnfold.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1994-1998
4 %
5
6 Core-syntax unfoldings
7
8 Unfoldings (which can travel across module boundaries) are in Core
9 syntax (namely @CoreExpr@s).
10
11 The type @Unfolding@ sits ``above'' simply-Core-expressions
12 unfoldings, capturing ``higher-level'' things we know about a binding,
13 usually things that the simplifier found out (e.g., ``it's a
14 literal'').  In the corner of a @CoreUnfolding@ unfolding, you will
15 find, unsurprisingly, a Core expression.
16
17 \begin{code}
18 module CoreUnfold (
19         Unfolding, UnfoldingGuidance,   -- Abstract types
20
21         noUnfolding, mkTopUnfolding, mkImplicitUnfolding, mkUnfolding, 
22         mkCompulsoryUnfolding, seqUnfolding,
23         evaldUnfolding, mkOtherCon, otherCons,
24         unfoldingTemplate, maybeUnfoldingTemplate,
25         isEvaldUnfolding, isValueUnfolding, isCheapUnfolding, isCompulsoryUnfolding,
26         hasUnfolding, hasSomeUnfolding, neverUnfold,
27
28         couldBeSmallEnoughToInline, 
29         certainlyWillInline, smallEnoughToInline,
30
31         callSiteInline, CallCtxt(..)
32
33     ) where
34
35 import StaticFlags
36 import DynFlags
37 import CoreSyn
38 import PprCore          ()      -- Instances
39 import OccurAnal
40 import CoreSubst        ( Subst, emptySubst, substTy, extendIdSubst, extendTvSubst
41                         , lookupIdSubst, substBndr, substBndrs, substRecBndrs )
42 import CoreUtils
43 import Id
44 import DataCon
45 import Literal
46 import PrimOp
47 import IdInfo
48 import Type hiding( substTy, extendTvSubst )
49 import PrelNames
50 import Bag
51 import FastTypes
52 import FastString
53 import Outputable
54
55 \end{code}
56
57
58 %************************************************************************
59 %*                                                                      *
60 \subsection{Making unfoldings}
61 %*                                                                      *
62 %************************************************************************
63
64 \begin{code}
65 mkTopUnfolding :: CoreExpr -> Unfolding
66 mkTopUnfolding expr = mkUnfolding True {- Top level -} expr
67
68 mkImplicitUnfolding :: CoreExpr -> Unfolding
69 -- For implicit Ids, do a tiny bit of optimising first
70 mkImplicitUnfolding expr 
71   = CoreUnfolding (simpleOptExpr emptySubst expr)
72                   True
73                   (exprIsHNF expr)
74                   (exprIsCheap expr)
75                   (calcUnfoldingGuidance opt_UF_CreationThreshold expr)
76
77 mkUnfolding :: Bool -> CoreExpr -> Unfolding
78 mkUnfolding top_lvl expr
79   = CoreUnfolding (occurAnalyseExpr expr)
80                   top_lvl
81
82                   (exprIsHNF expr)
83                         -- Already evaluated
84
85                   (exprIsCheap expr)
86                         -- OK to inline inside a lambda
87
88                   (calcUnfoldingGuidance opt_UF_CreationThreshold expr)
89         -- Sometimes during simplification, there's a large let-bound thing     
90         -- which has been substituted, and so is now dead; so 'expr' contains
91         -- two copies of the thing while the occurrence-analysed expression doesn't
92         -- Nevertheless, we don't occ-analyse before computing the size because the
93         -- size computation bales out after a while, whereas occurrence analysis does not.
94         --
95         -- This can occasionally mean that the guidance is very pessimistic;
96         -- it gets fixed up next round
97
98 instance Outputable Unfolding where
99   ppr NoUnfolding = ptext (sLit "No unfolding")
100   ppr (OtherCon cs) = ptext (sLit "OtherCon") <+> ppr cs
101   ppr (CompulsoryUnfolding e) = ptext (sLit "Compulsory") <+> ppr e
102   ppr (CoreUnfolding e top hnf cheap g) 
103         = ptext (sLit "Unf") <+> sep [ppr top <+> ppr hnf <+> ppr cheap <+> ppr g, 
104                                      ppr e]
105
106 mkCompulsoryUnfolding :: CoreExpr -> Unfolding
107 mkCompulsoryUnfolding expr      -- Used for things that absolutely must be unfolded
108   = CompulsoryUnfolding (occurAnalyseExpr expr)
109 \end{code}
110
111
112 %************************************************************************
113 %*                                                                      *
114 \subsection{The UnfoldingGuidance type}
115 %*                                                                      *
116 %************************************************************************
117
118 \begin{code}
119 instance Outputable UnfoldingGuidance where
120     ppr UnfoldNever     = ptext (sLit "NEVER")
121     ppr (UnfoldIfGoodArgs v cs size discount)
122       = hsep [ ptext (sLit "IF_ARGS"), int v,
123                brackets (hsep (map int cs)),
124                int size,
125                int discount ]
126 \end{code}
127
128
129 \begin{code}
130 calcUnfoldingGuidance
131         :: Int                  -- bomb out if size gets bigger than this
132         -> CoreExpr             -- expression to look at
133         -> UnfoldingGuidance
134 calcUnfoldingGuidance bOMB_OUT_SIZE expr
135   = case collect_val_bndrs expr of { (inline, val_binders, body) ->
136     let
137         n_val_binders = length val_binders
138
139         max_inline_size = n_val_binders+2
140         -- The idea is that if there is an INLINE pragma (inline is True)
141         -- and there's a big body, we give a size of n_val_binders+2.  This
142         -- This is just enough to fail the no-size-increase test in callSiteInline,
143         --   so that INLINE things don't get inlined into entirely boring contexts,
144         --   but no more.
145
146     in
147     case (sizeExpr (iUnbox bOMB_OUT_SIZE) val_binders body) of
148
149       TooBig 
150         | not inline -> UnfoldNever
151                 -- A big function with an INLINE pragma must
152                 -- have an UnfoldIfGoodArgs guidance
153         | otherwise  -> UnfoldIfGoodArgs n_val_binders
154                                          (map (const 0) val_binders)
155                                          max_inline_size 0
156
157       SizeIs size cased_args scrut_discount
158         -> UnfoldIfGoodArgs
159                         n_val_binders
160                         (map discount_for val_binders)
161                         final_size
162                         (iBox scrut_discount)
163         where        
164             boxed_size    = iBox size
165
166             final_size | inline     = boxed_size `min` max_inline_size
167                        | otherwise  = boxed_size
168
169                 -- Sometimes an INLINE thing is smaller than n_val_binders+2.
170                 -- A particular case in point is a constructor, which has size 1.
171                 -- We want to inline this regardless, hence the `min`
172
173             discount_for b = foldlBag (\acc (b',n) -> if b==b' then acc+n else acc) 
174                                       0 cased_args
175         }
176   where
177     collect_val_bndrs e = go False [] e
178         -- We need to be a bit careful about how we collect the
179         -- value binders.  In ptic, if we see 
180         --      __inline_me (\x y -> e)
181         -- We want to say "2 value binders".  Why?  So that 
182         -- we take account of information given for the arguments
183
184     go _      rev_vbs (Note InlineMe e)     = go True   rev_vbs     e
185     go inline rev_vbs (Lam b e) | isId b    = go inline (b:rev_vbs) e
186                                 | otherwise = go inline rev_vbs     e
187     go inline rev_vbs e                     = (inline, reverse rev_vbs, e)
188 \end{code}
189
190 \begin{code}
191 sizeExpr :: FastInt         -- Bomb out if it gets bigger than this
192          -> [Id]            -- Arguments; we're interested in which of these
193                             -- get case'd
194          -> CoreExpr
195          -> ExprSize
196
197 sizeExpr bOMB_OUT_SIZE top_args expr
198   = size_up expr
199   where
200     size_up (Type _)           = sizeZero        -- Types cost nothing
201     size_up (Var _)            = sizeOne
202
203     size_up (Note InlineMe _)  = sizeOne         -- Inline notes make it look very small
204         -- This can be important.  If you have an instance decl like this:
205         --      instance Foo a => Foo [a] where
206         --         {-# INLINE op1, op2 #-}
207         --         op1 = ...
208         --         op2 = ...
209         -- then we'll get a dfun which is a pair of two INLINE lambdas
210
211     size_up (Note _      body) = size_up body  -- Other notes cost nothing
212     
213     size_up (Cast e _)         = size_up e
214
215     size_up (App fun (Type _)) = size_up fun
216     size_up (App fun arg)      = size_up_app fun [arg]
217
218     size_up (Lit lit)          = sizeN (litSize lit)
219
220     size_up (Lam b e) | isId b    = lamScrutDiscount (size_up e `addSizeN` 1)
221                       | otherwise = size_up e
222
223     size_up (Let (NonRec binder rhs) body)
224       = nukeScrutDiscount (size_up rhs)         `addSize`
225         size_up body                            `addSizeN`
226         (if isUnLiftedType (idType binder) then 0 else 1)
227                 -- For the allocation
228                 -- If the binder has an unlifted type there is no allocation
229
230     size_up (Let (Rec pairs) body)
231       = nukeScrutDiscount rhs_size              `addSize`
232         size_up body                            `addSizeN`
233         length pairs            -- For the allocation
234       where
235         rhs_size = foldr (addSize . size_up . snd) sizeZero pairs
236
237     size_up (Case (Var v) _ _ alts) 
238         | v `elem` top_args             -- We are scrutinising an argument variable
239         = 
240 {-      I'm nuking this special case; BUT see the comment with case alternatives.
241
242         (a) It's too eager.  We don't want to inline a wrapper into a
243             context with no benefit.  
244             E.g.  \ x. f (x+x)          no point in inlining (+) here!
245
246         (b) It's ineffective. Once g's wrapper is inlined, its case-expressions 
247             aren't scrutinising arguments any more
248
249             case alts of
250
251                 [alt] -> size_up_alt alt `addSize` SizeIs (_ILIT(0)) (unitBag (v, 1)) (_ILIT(0))
252                 -- We want to make wrapper-style evaluation look cheap, so that
253                 -- when we inline a wrapper it doesn't make call site (much) bigger
254                 -- Otherwise we get nasty phase ordering stuff: 
255                 --      f x = g x x
256                 --      h y = ...(f e)...
257                 -- If we inline g's wrapper, f looks big, and doesn't get inlined
258                 -- into h; if we inline f first, while it looks small, then g's 
259                 -- wrapper will get inlined later anyway.  To avoid this nasty
260                 -- ordering difference, we make (case a of (x,y) -> ...), 
261                 --  *where a is one of the arguments* look free.
262
263                 other -> 
264 -}
265                          alts_size (foldr addSize sizeOne alt_sizes)    -- The 1 is for the scrutinee
266                                    (foldr1 maxSize alt_sizes)
267
268                 -- Good to inline if an arg is scrutinised, because
269                 -- that may eliminate allocation in the caller
270                 -- And it eliminates the case itself
271
272         where
273           alt_sizes = map size_up_alt alts
274
275                 -- alts_size tries to compute a good discount for
276                 -- the case when we are scrutinising an argument variable
277           alts_size (SizeIs tot _tot_disc _tot_scrut)           -- Size of all alternatives
278                     (SizeIs max  max_disc  max_scrut)           -- Size of biggest alternative
279                 = SizeIs tot (unitBag (v, iBox (_ILIT(1) +# tot -# max)) `unionBags` max_disc) max_scrut
280                         -- If the variable is known, we produce a discount that
281                         -- will take us back to 'max', the size of rh largest alternative
282                         -- The 1+ is a little discount for reduced allocation in the caller
283           alts_size tot_size _ = tot_size
284
285     size_up (Case e _ _ alts) = nukeScrutDiscount (size_up e) `addSize` 
286                                  foldr (addSize . size_up_alt) sizeZero alts
287                 -- We don't charge for the case itself
288                 -- It's a strict thing, and the price of the call
289                 -- is paid by scrut.  Also consider
290                 --      case f x of DEFAULT -> e
291                 -- This is just ';'!  Don't charge for it.
292
293     ------------ 
294     size_up_app (App fun arg) args   
295         | isTypeArg arg              = size_up_app fun args
296         | otherwise                  = size_up_app fun (arg:args)
297     size_up_app fun           args   = foldr (addSize . nukeScrutDiscount . size_up) 
298                                              (size_up_fun fun args)
299                                              args
300
301         -- A function application with at least one value argument
302         -- so if the function is an argument give it an arg-discount
303         --
304         -- Also behave specially if the function is a build
305         --
306         -- Also if the function is a constant Id (constr or primop)
307         -- compute discounts specially
308     size_up_fun (Var fun) args
309       | fun `hasKey` buildIdKey   = buildSize
310       | fun `hasKey` augmentIdKey = augmentSize
311       | otherwise 
312       = case globalIdDetails fun of
313           DataConWorkId dc -> conSizeN dc (valArgCount args)
314
315           FCallId _    -> sizeN opt_UF_DearOp
316           PrimOpId op  -> primOpSize op (valArgCount args)
317                           -- foldr addSize (primOpSize op) (map arg_discount args)
318                           -- At one time I tried giving an arg-discount if a primop 
319                           -- is applied to one of the function's arguments, but it's
320                           -- not good.  At the moment, any unlifted-type arg gets a
321                           -- 'True' for 'yes I'm evald', so we collect the discount even
322                           -- if we know nothing about it.  And just having it in a primop
323                           -- doesn't help at all if we don't know something more.
324
325           _            -> fun_discount fun `addSizeN`
326                           (1 + length (filter (not . exprIsTrivial) args))
327                                 -- The 1+ is for the function itself
328                                 -- Add 1 for each non-trivial arg;
329                                 -- the allocation cost, as in let(rec)
330                                 -- Slight hack here: for constructors the args are almost always
331                                 --      trivial; and for primops they are almost always prim typed
332                                 --      We should really only count for non-prim-typed args in the
333                                 --      general case, but that seems too much like hard work
334
335     size_up_fun other _ = size_up other
336
337     ------------ 
338     size_up_alt (_con, _bndrs, rhs) = size_up rhs
339         -- Don't charge for args, so that wrappers look cheap
340         -- (See comments about wrappers with Case)
341
342     ------------
343         -- We want to record if we're case'ing, or applying, an argument
344     fun_discount v | v `elem` top_args = SizeIs (_ILIT(0)) (unitBag (v, opt_UF_FunAppDiscount)) (_ILIT(0))
345     fun_discount _                     = sizeZero
346
347     ------------
348         -- These addSize things have to be here because
349         -- I don't want to give them bOMB_OUT_SIZE as an argument
350
351     addSizeN TooBig          _  = TooBig
352     addSizeN (SizeIs n xs d) m  = mkSizeIs bOMB_OUT_SIZE (n +# iUnbox m) xs d
353     
354     addSize TooBig            _                 = TooBig
355     addSize _                 TooBig            = TooBig
356     addSize (SizeIs n1 xs d1) (SizeIs n2 ys d2) 
357         = mkSizeIs bOMB_OUT_SIZE (n1 +# n2) (xs `unionBags` ys) (d1 +# d2)
358 \end{code}
359
360 Code for manipulating sizes
361
362 \begin{code}
363 data ExprSize = TooBig
364               | SizeIs FastInt          -- Size found
365                        (Bag (Id,Int))   -- Arguments cased herein, and discount for each such
366                        FastInt          -- Size to subtract if result is scrutinised 
367                                         -- by a case expression
368
369 -- subtract the discount before deciding whether to bale out. eg. we
370 -- want to inline a large constructor application into a selector:
371 --      tup = (a_1, ..., a_99)
372 --      x = case tup of ...
373 --
374 mkSizeIs :: FastInt -> FastInt -> Bag (Id, Int) -> FastInt -> ExprSize
375 mkSizeIs max n xs d | (n -# d) ># max = TooBig
376                     | otherwise       = SizeIs n xs d
377  
378 maxSize :: ExprSize -> ExprSize -> ExprSize
379 maxSize TooBig         _                                  = TooBig
380 maxSize _              TooBig                             = TooBig
381 maxSize s1@(SizeIs n1 _ _) s2@(SizeIs n2 _ _) | n1 ># n2  = s1
382                                               | otherwise = s2
383
384 sizeZero, sizeOne :: ExprSize
385 sizeN :: Int -> ExprSize
386 conSizeN :: DataCon ->Int -> ExprSize
387
388 sizeZero        = SizeIs (_ILIT(0))  emptyBag (_ILIT(0))
389 sizeOne         = SizeIs (_ILIT(1))  emptyBag (_ILIT(0))
390 sizeN n         = SizeIs (iUnbox n) emptyBag (_ILIT(0))
391 conSizeN dc n   
392   | isUnboxedTupleCon dc = SizeIs (_ILIT(0)) emptyBag (iUnbox n +# _ILIT(1))
393   | otherwise            = SizeIs (_ILIT(1)) emptyBag (iUnbox n +# _ILIT(1))
394         -- Treat constructors as size 1; we are keen to expose them
395         -- (and we charge separately for their args).  We can't treat
396         -- them as size zero, else we find that (iBox x) has size 1,
397         -- which is the same as a lone variable; and hence 'v' will 
398         -- always be replaced by (iBox x), where v is bound to iBox x.
399         --
400         -- However, unboxed tuples count as size zero
401         -- I found occasions where we had 
402         --      f x y z = case op# x y z of { s -> (# s, () #) }
403         -- and f wasn't getting inlined
404
405 primOpSize :: PrimOp -> Int -> ExprSize
406 primOpSize op n_args
407  | not (primOpIsDupable op) = sizeN opt_UF_DearOp
408  | not (primOpOutOfLine op) = sizeN (2 - n_args)
409         -- Be very keen to inline simple primops.
410         -- We give a discount of 1 for each arg so that (op# x y z) costs 2.
411         -- We can't make it cost 1, else we'll inline let v = (op# x y z) 
412         -- at every use of v, which is excessive.
413         --
414         -- A good example is:
415         --      let x = +# p q in C {x}
416         -- Even though x get's an occurrence of 'many', its RHS looks cheap,
417         -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
418  | otherwise                = sizeOne
419
420 buildSize :: ExprSize
421 buildSize = SizeIs (_ILIT(-2)) emptyBag (_ILIT(4))
422         -- We really want to inline applications of build
423         -- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
424         -- Indeed, we should add a result_discount becuause build is 
425         -- very like a constructor.  We don't bother to check that the
426         -- build is saturated (it usually is).  The "-2" discounts for the \c n, 
427         -- The "4" is rather arbitrary.
428
429 augmentSize :: ExprSize
430 augmentSize = SizeIs (_ILIT(-2)) emptyBag (_ILIT(4))
431         -- Ditto (augment t (\cn -> e) ys) should cost only the cost of
432         -- e plus ys. The -2 accounts for the \cn 
433
434 nukeScrutDiscount :: ExprSize -> ExprSize
435 nukeScrutDiscount (SizeIs n vs _) = SizeIs n vs (_ILIT(0))
436 nukeScrutDiscount TooBig          = TooBig
437
438 -- When we return a lambda, give a discount if it's used (applied)
439 lamScrutDiscount :: ExprSize -> ExprSize
440 lamScrutDiscount (SizeIs n vs _) = case opt_UF_FunAppDiscount of { d -> SizeIs n vs (iUnbox d) }
441 lamScrutDiscount TooBig          = TooBig
442 \end{code}
443
444
445 %************************************************************************
446 %*                                                                      *
447 \subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
448 %*                                                                      *
449 %************************************************************************
450
451 We have very limited information about an unfolding expression: (1)~so
452 many type arguments and so many value arguments expected---for our
453 purposes here, we assume we've got those.  (2)~A ``size'' or ``cost,''
454 a single integer.  (3)~An ``argument info'' vector.  For this, what we
455 have at the moment is a Boolean per argument position that says, ``I
456 will look with great favour on an explicit constructor in this
457 position.'' (4)~The ``discount'' to subtract if the expression
458 is being scrutinised. 
459
460 Assuming we have enough type- and value arguments (if not, we give up
461 immediately), then we see if the ``discounted size'' is below some
462 (semi-arbitrary) threshold.  It works like this: for every argument
463 position where we're looking for a constructor AND WE HAVE ONE in our
464 hands, we get a (again, semi-arbitrary) discount [proportion to the
465 number of constructors in the type being scrutinized].
466
467 If we're in the context of a scrutinee ( \tr{(case <expr > of A .. -> ...;.. )})
468 and the expression in question will evaluate to a constructor, we use
469 the computed discount size *for the result only* rather than
470 computing the argument discounts. Since we know the result of
471 the expression is going to be taken apart, discounting its size
472 is more accurate (see @sizeExpr@ above for how this discount size
473 is computed).
474
475 We use this one to avoid exporting inlinings that we ``couldn't possibly
476 use'' on the other side.  Can be overridden w/ flaggery.
477 Just the same as smallEnoughToInline, except that it has no actual arguments.
478
479 \begin{code}
480 couldBeSmallEnoughToInline :: Int -> CoreExpr -> Bool
481 couldBeSmallEnoughToInline threshold rhs = case calcUnfoldingGuidance threshold rhs of
482                                                 UnfoldNever -> False
483                                                 _           -> True
484
485 certainlyWillInline :: Unfolding -> Bool
486   -- Sees if the unfolding is pretty certain to inline  
487 certainlyWillInline (CoreUnfolding _ _ _ is_cheap (UnfoldIfGoodArgs n_vals _ size _))
488   = is_cheap && size - (n_vals +1) <= opt_UF_UseThreshold
489 certainlyWillInline _
490   = False
491
492 smallEnoughToInline :: Unfolding -> Bool
493 smallEnoughToInline (CoreUnfolding _ _ _ _ (UnfoldIfGoodArgs _ _ size _))
494   = size <= opt_UF_UseThreshold
495 smallEnoughToInline _
496   = False
497 \end{code}
498
499 %************************************************************************
500 %*                                                                      *
501 \subsection{callSiteInline}
502 %*                                                                      *
503 %************************************************************************
504
505 This is the key function.  It decides whether to inline a variable at a call site
506
507 callSiteInline is used at call sites, so it is a bit more generous.
508 It's a very important function that embodies lots of heuristics.
509 A non-WHNF can be inlined if it doesn't occur inside a lambda,
510 and occurs exactly once or 
511     occurs once in each branch of a case and is small
512
513 If the thing is in WHNF, there's no danger of duplicating work, 
514 so we can inline if it occurs once, or is small
515
516 NOTE: we don't want to inline top-level functions that always diverge.
517 It just makes the code bigger.  Tt turns out that the convenient way to prevent
518 them inlining is to give them a NOINLINE pragma, which we do in 
519 StrictAnal.addStrictnessInfoToTopId
520
521 \begin{code}
522 callSiteInline :: DynFlags
523                -> Bool                  -- True <=> the Id can be inlined
524                -> Id                    -- The Id
525                -> Bool                  -- True if there are are no arguments at all (incl type args)
526                -> [Bool]                -- One for each value arg; True if it is interesting
527                -> CallCtxt              -- True <=> continuation is interesting
528                -> Maybe CoreExpr        -- Unfolding, if any
529
530
531 data CallCtxt = BoringCtxt
532
533               | ArgCtxt Bool    -- We're somewhere in the RHS of function with rules
534                                 --      => be keener to inline
535                         Int     -- We *are* the argument of a function with this arg discount
536                                 --      => be keener to inline
537                 -- INVARIANT: ArgCtxt False 0 ==> BoringCtxt
538
539               | CaseCtxt        -- We're the scrutinee of a case
540                                 -- that decomposes its scrutinee
541
542 instance Outputable CallCtxt where
543   ppr BoringCtxt    = ptext (sLit "BoringCtxt")
544   ppr (ArgCtxt _ _) = ptext (sLit "ArgCtxt")
545   ppr CaseCtxt      = ptext (sLit "CaseCtxt")
546
547 callSiteInline dflags active_inline id lone_variable arg_infos cont_info
548   = case idUnfolding id of {
549         NoUnfolding -> Nothing ;
550         OtherCon _  -> Nothing ;
551
552         CompulsoryUnfolding unf_template -> Just unf_template ;
553                 -- CompulsoryUnfolding => there is no top-level binding
554                 -- for these things, so we must inline it.
555                 -- Only a couple of primop-like things have 
556                 -- compulsory unfoldings (see MkId.lhs).
557                 -- We don't allow them to be inactive
558
559         CoreUnfolding unf_template is_top is_value is_cheap guidance ->
560
561     let
562         result | yes_or_no = Just unf_template
563                | otherwise = Nothing
564
565         n_val_args  = length arg_infos
566
567         yes_or_no = active_inline && is_cheap && consider_safe
568                 -- We consider even the once-in-one-branch
569                 -- occurrences, because they won't all have been
570                 -- caught by preInlineUnconditionally.  In particular,
571                 -- if the occurrence is once inside a lambda, and the
572                 -- rhs is cheap but not a manifest lambda, then
573                 -- pre-inline will not have inlined it for fear of
574                 -- invalidating the occurrence info in the rhs.
575
576         consider_safe
577                 -- consider_safe decides whether it's a good idea to
578                 -- inline something, given that there's no
579                 -- work-duplication issue (the caller checks that).
580           = case guidance of
581               UnfoldNever  -> False
582               UnfoldIfGoodArgs n_vals_wanted arg_discounts size res_discount
583                   | enough_args && size <= (n_vals_wanted + 1)
584                         -- Inline unconditionally if there no size increase
585                         -- Size of call is n_vals_wanted (+1 for the function)
586                   -> True
587
588                   | otherwise
589                   -> some_benefit && small_enough
590
591                   where
592                     enough_args = n_val_args >= n_vals_wanted
593
594                     some_benefit = or arg_infos || really_interesting_cont
595                                 -- There must be something interesting
596                                 -- about some argument, or the result
597                                 -- context, to make it worth inlining
598
599                     really_interesting_cont 
600                         | n_val_args <  n_vals_wanted = False   -- Too few args
601                         | n_val_args == n_vals_wanted = interesting_saturated_call
602                         | otherwise                   = True    -- Extra args
603                         -- really_interesting_cont tells if the result of the
604                         -- call is in an interesting context.
605
606                     interesting_saturated_call 
607                         = case cont_info of
608                             BoringCtxt -> not is_top && n_vals_wanted > 0       -- Note [Nested functions] 
609                             CaseCtxt   -> not lone_variable || not is_value     -- Note [Lone variables]
610                             ArgCtxt {} -> n_vals_wanted > 0 
611                                 -- See Note [Inlining in ArgCtxt]
612
613                     small_enough = (size - discount) <= opt_UF_UseThreshold
614                     discount = computeDiscount n_vals_wanted arg_discounts 
615                                                res_discount' arg_infos
616                     res_discount' = case cont_info of
617                                         BoringCtxt  -> 0
618                                         CaseCtxt    -> res_discount
619                                         ArgCtxt _ _ -> 4 `min` res_discount
620                         -- res_discount can be very large when a function returns
621                         -- construtors; but we only want to invoke that large discount
622                         -- when there's a case continuation.
623                         -- Otherwise we, rather arbitrarily, threshold it.  Yuk.
624                         -- But we want to aovid inlining large functions that return 
625                         -- constructors into contexts that are simply "interesting"
626                 
627     in    
628     if dopt Opt_D_dump_inlinings dflags then
629         pprTrace "Considering inlining"
630                  (ppr id <+> vcat [text "active:" <+> ppr active_inline,
631                                    text "arg infos" <+> ppr arg_infos,
632                                    text "interesting continuation" <+> ppr cont_info,
633                                    text "is value:" <+> ppr is_value,
634                                    text "is cheap:" <+> ppr is_cheap,
635                                    text "guidance" <+> ppr guidance,
636                                    text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO"])
637                   result
638     else
639     result
640     }
641 \end{code}
642
643 Note [Nested functions]
644 ~~~~~~~~~~~~~~~~~~~~~~~
645 If a function has a nested defn we also record some-benefit, on the
646 grounds that we are often able to eliminate the binding, and hence the
647 allocation, for the function altogether; this is good for join points.
648 But this only makes sense for *functions*; inlining a constructor
649 doesn't help allocation unless the result is scrutinised.  UNLESS the
650 constructor occurs just once, albeit possibly in multiple case
651 branches.  Then inlining it doesn't increase allocation, but it does
652 increase the chance that the constructor won't be allocated at all in
653 the branches that don't use it.
654
655 Note [Inlining in ArgCtxt]
656 ~~~~~~~~~~~~~~~~~~~~~~~~~~
657 The condition (n_vals_wanted > 0) here is very important, because otherwise
658 we end up inlining top-level stuff into useless places; eg
659    x = I# 3#
660    f = \y.  g x
661 This can make a very big difference: it adds 16% to nofib 'integer' allocs,
662 and 20% to 'power'.
663
664 At one stage I replaced this condition by 'True' (leading to the above 
665 slow-down).  The motivation was test eyeball/inline1.hs; but that seems
666 to work ok now.
667
668 Note [Lone variables]
669 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
670 The "lone-variable" case is important.  I spent ages messing about
671 with unsatisfactory varaints, but this is nice.  The idea is that if a
672 variable appears all alone
673         as an arg of lazy fn, or rhs    Stop
674         as scrutinee of a case          Select
675         as arg of a strict fn           ArgOf
676 AND
677         it is bound to a value
678 then we should not inline it (unless there is some other reason,
679 e.g. is is the sole occurrence).  That is what is happening at 
680 the use of 'lone_variable' in 'interesting_saturated_call'.
681
682 Why?  At least in the case-scrutinee situation, turning
683         let x = (a,b) in case x of y -> ...
684 into
685         let x = (a,b) in case (a,b) of y -> ...
686 and thence to 
687         let x = (a,b) in let y = (a,b) in ...
688 is bad if the binding for x will remain.
689
690 Another example: I discovered that strings
691 were getting inlined straight back into applications of 'error'
692 because the latter is strict.
693         s = "foo"
694         f = \x -> ...(error s)...
695
696 Fundamentally such contexts should not encourage inlining because the
697 context can ``see'' the unfolding of the variable (e.g. case or a
698 RULE) so there's no gain.  If the thing is bound to a value.
699
700 However, watch out:
701
702  * Consider this:
703         foo = _inline_ (\n. [n])
704         bar = _inline_ (foo 20)
705         baz = \n. case bar of { (m:_) -> m + n }
706    Here we really want to inline 'bar' so that we can inline 'foo'
707    and the whole thing unravels as it should obviously do.  This is 
708    important: in the NDP project, 'bar' generates a closure data
709    structure rather than a list. 
710
711  * Even a type application or coercion isn't a lone variable.
712    Consider
713         case $fMonadST @ RealWorld of { :DMonad a b c -> c }
714    We had better inline that sucker!  The case won't see through it.
715
716    For now, I'm treating treating a variable applied to types 
717    in a *lazy* context "lone". The motivating example was
718         f = /\a. \x. BIG
719         g = /\a. \y.  h (f a)
720    There's no advantage in inlining f here, and perhaps
721    a significant disadvantage.  Hence some_val_args in the Stop case
722
723 \begin{code}
724 computeDiscount :: Int -> [Int] -> Int -> [Bool] -> Int
725 computeDiscount n_vals_wanted arg_discounts result_discount arg_infos
726         -- We multiple the raw discounts (args_discount and result_discount)
727         -- ty opt_UnfoldingKeenessFactor because the former have to do with
728         --  *size* whereas the discounts imply that there's some extra 
729         --  *efficiency* to be gained (e.g. beta reductions, case reductions) 
730         -- by inlining.
731
732         -- we also discount 1 for each argument passed, because these will
733         -- reduce with the lambdas in the function (we count 1 for a lambda
734         -- in size_up).
735   = 1 +                 -- Discount of 1 because the result replaces the call
736                         -- so we count 1 for the function itself
737     length (take n_vals_wanted arg_infos) +
738                         -- Discount of 1 for each arg supplied, because the 
739                         -- result replaces the call
740     round (opt_UF_KeenessFactor * 
741            fromIntegral (arg_discount + result_discount))
742   where
743     arg_discount = sum (zipWith mk_arg_discount arg_discounts arg_infos)
744
745     mk_arg_discount discount is_evald | is_evald  = discount
746                                       | otherwise = 0
747 \end{code}
748
749 %************************************************************************
750 %*                                                                      *
751         The Very Simple Optimiser
752 %*                                                                      *
753 %************************************************************************
754
755
756 \begin{code}
757 simpleOptExpr :: Subst -> CoreExpr -> CoreExpr
758 -- Return an occur-analysed and slightly optimised expression
759 -- The optimisation is very straightforward: just
760 -- inline non-recursive bindings that are used only once, 
761 -- or wheere the RHS is trivial
762
763 simpleOptExpr subst expr
764   = go subst (occurAnalyseExpr expr)
765   where
766     go subst (Var v)          = lookupIdSubst subst v
767     go subst (App e1 e2)      = App (go subst e1) (go subst e2)
768     go subst (Type ty)        = Type (substTy subst ty)
769     go _     (Lit lit)        = Lit lit
770     go subst (Note note e)    = Note note (go subst e)
771     go subst (Cast e co)      = Cast (go subst e) (substTy subst co)
772     go subst (Let bind body)  = go_bind subst bind body
773     go subst (Lam bndr body)  = Lam bndr' (go subst' body)
774                               where
775                                 (subst', bndr') = substBndr subst bndr
776
777     go subst (Case e b ty as) = Case (go subst e) b' 
778                                      (substTy subst ty)
779                                      (map (go_alt subst') as)
780                               where
781                                  (subst', b') = substBndr subst b
782
783
784     ----------------------
785     go_alt subst (con, bndrs, rhs) = (con, bndrs', go subst' rhs)
786                                  where
787                                    (subst', bndrs') = substBndrs subst bndrs
788
789     ----------------------
790     go_bind subst (Rec prs) body = Let (Rec (bndrs' `zip` rhss'))
791                                        (go subst' body)
792                             where
793                               (bndrs, rhss)    = unzip prs
794                               (subst', bndrs') = substRecBndrs subst bndrs
795                               rhss'            = map (go subst') rhss
796
797     go_bind subst (NonRec b r) body = go_nonrec subst b (go subst r) body
798
799     ----------------------
800     go_nonrec subst b (Type ty') body
801       | isTyVar b = go (extendTvSubst subst b ty') body
802         -- let a::* = TYPE ty in <body>
803     go_nonrec subst b r' body
804       | isId b  -- let x = e in <body>
805       , exprIsTrivial r' || safe_to_inline (idOccInfo b)
806       = go (extendIdSubst subst b r') body
807     go_nonrec subst b r' body
808       = Let (NonRec b' r') (go subst' body)
809       where
810         (subst', b') = substBndr subst b
811
812     ----------------------
813         -- Unconditionally safe to inline
814     safe_to_inline :: OccInfo -> Bool
815     safe_to_inline IAmDead                  = True
816     safe_to_inline (OneOcc in_lam one_br _) = not in_lam && one_br
817     safe_to_inline (IAmALoopBreaker {})     = False
818     safe_to_inline NoOccInfo                = False
819 \end{code}