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