Fixes the way we check if flattening happened during
[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, mkImplicitUnfolding, 
22         mkUnfolding, mkCoreUnfolding,
23         mkTopUnfolding, mkSimpleUnfolding,
24         mkInlineUnfolding, mkInlinableUnfolding, mkWwInlineRule,
25         mkCompulsoryUnfolding, mkDFunUnfolding,
26
27         interestingArg, ArgSummary(..),
28
29         couldBeSmallEnoughToInline, inlineBoringOk,
30         certainlyWillInline, smallEnoughToInline,
31
32         callSiteInline, CallCtxt(..), 
33
34         exprIsConApp_maybe
35
36     ) where
37
38 #include "HsVersions.h"
39
40 import StaticFlags
41 import DynFlags
42 import CoreSyn
43 import PprCore          ()      -- Instances
44 import TcType           ( tcSplitDFunTy )
45 import OccurAnal        ( occurAnalyseExpr )
46 import CoreSubst hiding( substTy )
47 import CoreFVs         ( exprFreeVars )
48 import CoreArity       ( manifestArity, exprBotStrictness_maybe )
49 import CoreUtils
50 import Id
51 import DataCon
52 import TyCon
53 import Literal
54 import PrimOp
55 import IdInfo
56 import BasicTypes       ( Arity )
57 import Type
58 import Coercion
59 import PrelNames
60 import VarEnv           ( mkInScopeSet )
61 import Bag
62 import Util
63 import FastTypes
64 import FastString
65 import Outputable
66 import Data.Maybe
67 \end{code}
68
69
70 %************************************************************************
71 %*                                                                      *
72 \subsection{Making unfoldings}
73 %*                                                                      *
74 %************************************************************************
75
76 \begin{code}
77 mkTopUnfolding :: Bool -> CoreExpr -> Unfolding
78 mkTopUnfolding = mkUnfolding InlineRhs True {- Top level -}
79
80 mkImplicitUnfolding :: CoreExpr -> Unfolding
81 -- For implicit Ids, do a tiny bit of optimising first
82 mkImplicitUnfolding expr = mkTopUnfolding False (simpleOptExpr expr) 
83
84 -- Note [Top-level flag on inline rules]
85 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
86 -- Slight hack: note that mk_inline_rules conservatively sets the
87 -- top-level flag to True.  It gets set more accurately by the simplifier
88 -- Simplify.simplUnfolding.
89
90 mkSimpleUnfolding :: CoreExpr -> Unfolding
91 mkSimpleUnfolding = mkUnfolding InlineRhs False False
92
93 mkDFunUnfolding :: Type -> [DFunArg CoreExpr] -> Unfolding
94 mkDFunUnfolding dfun_ty ops 
95   = DFunUnfolding dfun_nargs data_con ops
96   where
97     (tvs, n_theta, cls, _) = tcSplitDFunTy dfun_ty
98     dfun_nargs = length tvs + n_theta
99     data_con   = classDataCon cls
100
101 mkWwInlineRule :: Id -> CoreExpr -> Arity -> Unfolding
102 mkWwInlineRule id expr arity
103   = mkCoreUnfolding (InlineWrapper id) True
104                    (simpleOptExpr expr) arity
105                    (UnfWhen unSaturatedOk boringCxtNotOk)
106
107 mkCompulsoryUnfolding :: CoreExpr -> Unfolding
108 mkCompulsoryUnfolding expr         -- Used for things that absolutely must be unfolded
109   = mkCoreUnfolding InlineCompulsory True
110                     expr 0    -- Arity of unfolding doesn't matter
111                     (UnfWhen unSaturatedOk boringCxtOk)
112
113 mkInlineUnfolding :: Maybe Arity -> CoreExpr -> Unfolding
114 mkInlineUnfolding mb_arity expr 
115   = mkCoreUnfolding InlineStable
116                     True         -- Note [Top-level flag on inline rules]
117                     expr' arity 
118                     (UnfWhen unsat_ok boring_ok)
119   where
120     expr' = simpleOptExpr expr
121     (unsat_ok, arity) = case mb_arity of
122                           Nothing -> (unSaturatedOk, manifestArity expr')
123                           Just ar -> (needSaturated, ar)
124               
125     boring_ok = inlineBoringOk expr'
126
127 mkInlinableUnfolding :: CoreExpr -> Unfolding
128 mkInlinableUnfolding expr
129   = mkUnfolding InlineStable True is_bot expr'
130   where
131     expr' = simpleOptExpr expr
132     is_bot = isJust (exprBotStrictness_maybe expr')
133 \end{code}
134
135 Internal functions
136
137 \begin{code}
138 mkCoreUnfolding :: UnfoldingSource -> Bool -> CoreExpr
139                 -> Arity -> UnfoldingGuidance -> Unfolding
140 -- Occurrence-analyses the expression before capturing it
141 mkCoreUnfolding src top_lvl expr arity guidance 
142   = CoreUnfolding { uf_tmpl       = occurAnalyseExpr expr,
143                     uf_src        = src,
144                     uf_arity      = arity,
145                     uf_is_top     = top_lvl,
146                     uf_is_value   = exprIsHNF        expr,
147                     uf_is_conlike = exprIsConLike    expr,
148                     uf_is_cheap   = exprIsCheap      expr,
149                     uf_expandable = exprIsExpandable expr,
150                     uf_guidance   = guidance }
151
152 mkUnfolding :: UnfoldingSource -> Bool -> Bool -> CoreExpr -> Unfolding
153 -- Calculates unfolding guidance
154 -- Occurrence-analyses the expression before capturing it
155 mkUnfolding src top_lvl is_bottoming expr
156   | top_lvl && is_bottoming
157   , not (exprIsTrivial expr)
158   = NoUnfolding    -- See Note [Do not inline top-level bottoming functions]
159   | otherwise
160   = CoreUnfolding { uf_tmpl       = occurAnalyseExpr expr,
161                     uf_src        = src,
162                     uf_arity      = arity,
163                     uf_is_top     = top_lvl,
164                     uf_is_value   = exprIsHNF        expr,
165                     uf_is_conlike = exprIsConLike    expr,
166                     uf_expandable = exprIsExpandable expr,
167                     uf_is_cheap   = is_cheap,
168                     uf_guidance   = guidance }
169   where
170     is_cheap = exprIsCheap expr
171     (arity, guidance) = calcUnfoldingGuidance is_cheap
172                                               opt_UF_CreationThreshold expr
173         -- Sometimes during simplification, there's a large let-bound thing     
174         -- which has been substituted, and so is now dead; so 'expr' contains
175         -- two copies of the thing while the occurrence-analysed expression doesn't
176         -- Nevertheless, we *don't* occ-analyse before computing the size because the
177         -- size computation bales out after a while, whereas occurrence analysis does not.
178         --
179         -- This can occasionally mean that the guidance is very pessimistic;
180         -- it gets fixed up next round.  And it should be rare, because large
181         -- let-bound things that are dead are usually caught by preInlineUnconditionally
182 \end{code}
183
184 %************************************************************************
185 %*                                                                      *
186 \subsection{The UnfoldingGuidance type}
187 %*                                                                      *
188 %************************************************************************
189
190 \begin{code}
191 inlineBoringOk :: CoreExpr -> Bool
192 -- See Note [INLINE for small functions]
193 -- True => the result of inlining the expression is 
194 --         no bigger than the expression itself
195 --     eg      (\x y -> f y x)
196 -- This is a quick and dirty version. It doesn't attempt
197 -- to deal with  (\x y z -> x (y z))
198 -- The really important one is (x `cast` c)
199 inlineBoringOk e
200   = go 0 e
201   where
202     go :: Int -> CoreExpr -> Bool
203     go credit (Lam x e) | isId x           = go (credit+1) e
204                         | otherwise        = go credit e
205     go credit (App f (Type {}))            = go credit f
206     go credit (App f a) | credit > 0  
207                         , exprIsTrivial a  = go (credit-1) f
208     go credit (Note _ e)                   = go credit e     
209     go credit (Cast e _)                   = go credit e
210     go _      (Var {})                     = boringCxtOk
211     go _      _                            = boringCxtNotOk
212
213 calcUnfoldingGuidance
214         :: Bool         -- True <=> the rhs is cheap, or we want to treat it
215                         --          as cheap (INLINE things)     
216         -> Int          -- Bomb out if size gets bigger than this
217         -> CoreExpr     -- Expression to look at
218         -> (Arity, UnfoldingGuidance)
219 calcUnfoldingGuidance expr_is_cheap bOMB_OUT_SIZE expr
220   = case collectBinders expr of { (bndrs, body) ->
221     let
222         val_bndrs   = filter isId bndrs
223         n_val_bndrs = length val_bndrs
224
225         guidance 
226           = case (sizeExpr (iUnbox bOMB_OUT_SIZE) val_bndrs body) of
227               TooBig -> UnfNever
228               SizeIs size cased_bndrs scrut_discount
229                 | uncondInline n_val_bndrs (iBox size)
230                 , expr_is_cheap
231                 -> UnfWhen unSaturatedOk boringCxtOk   -- Note [INLINE for small functions]
232                 | otherwise
233                 -> UnfIfGoodArgs { ug_args  = map (discount cased_bndrs) val_bndrs
234                                  , ug_size  = iBox size
235                                  , ug_res   = iBox scrut_discount }
236
237         discount cbs bndr
238            = foldlBag (\acc (b',n) -> if bndr==b' then acc+n else acc) 
239                       0 cbs
240     in
241     (n_val_bndrs, guidance) }
242 \end{code}
243
244 Note [Computing the size of an expression]
245 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
246 The basic idea of sizeExpr is obvious enough: count nodes.  But getting the
247 heuristics right has taken a long time.  Here's the basic strategy:
248
249     * Variables, literals: 0
250       (Exception for string literals, see litSize.)
251
252     * Function applications (f e1 .. en): 1 + #value args
253
254     * Constructor applications: 1, regardless of #args
255
256     * Let(rec): 1 + size of components
257
258     * Note, cast: 0
259
260 Examples
261
262   Size  Term
263   --------------
264     0     42#
265     0     x
266     0     True
267     2     f x
268     1     Just x
269     4     f (g x)
270
271 Notice that 'x' counts 0, while (f x) counts 2.  That's deliberate: there's
272 a function call to account for.  Notice also that constructor applications 
273 are very cheap, because exposing them to a caller is so valuable.
274
275
276 Note [Do not inline top-level bottoming functions]
277 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
278 The FloatOut pass has gone to some trouble to float out calls to 'error' 
279 and similar friends.  See Note [Bottoming floats] in SetLevels.
280 Do not re-inline them!  But we *do* still inline if they are very small
281 (the uncondInline stuff).
282
283
284 Note [INLINE for small functions]
285 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
286 Consider        {-# INLINE f #-}
287                 f x = Just x
288                 g y = f y
289 Then f's RHS is no larger than its LHS, so we should inline it into
290 even the most boring context.  In general, f the function is
291 sufficiently small that its body is as small as the call itself, the
292 inline unconditionally, regardless of how boring the context is.
293
294 Things to note:
295
296  * We inline *unconditionally* if inlined thing is smaller (using sizeExpr)
297    than the thing it's replacing.  Notice that
298       (f x) --> (g 3)             -- YES, unconditionally
299       (f x) --> x : []            -- YES, *even though* there are two
300                                   --      arguments to the cons
301       x     --> g 3               -- NO
302       x     --> Just v            -- NO
303
304   It's very important not to unconditionally replace a variable by
305   a non-atomic term.
306
307 * We do this even if the thing isn't saturated, else we end up with the
308   silly situation that
309      f x y = x
310      ...map (f 3)...
311   doesn't inline.  Even in a boring context, inlining without being
312   saturated will give a lambda instead of a PAP, and will be more
313   efficient at runtime.
314
315 * However, when the function's arity > 0, we do insist that it 
316   has at least one value argument at the call site.  Otherwise we find this:
317        f = /\a \x:a. x
318        d = /\b. MkD (f b)
319   If we inline f here we get
320        d = /\b. MkD (\x:b. x)
321   and then prepareRhs floats out the argument, abstracting the type
322   variables, so we end up with the original again!
323
324
325 \begin{code}
326 uncondInline :: Arity -> Int -> Bool
327 -- Inline unconditionally if there no size increase
328 -- Size of call is arity (+1 for the function)
329 -- See Note [INLINE for small functions]
330 uncondInline arity size 
331   | arity == 0 = size == 0
332   | otherwise  = size <= arity + 1
333 \end{code}
334
335
336 \begin{code}
337 sizeExpr :: FastInt         -- Bomb out if it gets bigger than this
338          -> [Id]            -- Arguments; we're interested in which of these
339                             -- get case'd
340          -> CoreExpr
341          -> ExprSize
342
343 -- Note [Computing the size of an expression]
344
345 sizeExpr bOMB_OUT_SIZE top_args expr
346   = size_up expr
347   where
348     size_up (Cast e _) = size_up e
349     size_up (Note _ e) = size_up e
350     size_up (Type _)   = sizeZero           -- Types cost nothing
351     size_up (Lit lit)  = sizeN (litSize lit)
352     size_up (Var f)    = size_up_call f []  -- Make sure we get constructor
353                                             -- discounts even on nullary constructors
354
355     size_up (App fun (Type _)) = size_up fun
356     size_up (App fun arg)      = size_up arg  `addSizeNSD`
357                                  size_up_app fun [arg]
358
359     size_up (Lam b e) | isId b    = lamScrutDiscount (size_up e `addSizeN` 1)
360                       | otherwise = size_up e
361
362     size_up (Let (NonRec binder rhs) body)
363       = size_up rhs             `addSizeNSD`
364         size_up body            `addSizeN`
365         (if isUnLiftedType (idType binder) then 0 else 1)
366                 -- For the allocation
367                 -- If the binder has an unlifted type there is no allocation
368
369     size_up (Let (Rec pairs) body)
370       = foldr (addSizeNSD . size_up . snd) 
371               (size_up body `addSizeN` length pairs)    -- (length pairs) for the allocation
372               pairs
373
374     size_up (Case (Var v) _ _ alts) 
375         | v `elem` top_args             -- We are scrutinising an argument variable
376         = alts_size (foldr1 addAltSize alt_sizes)
377                     (foldr1 maxSize alt_sizes)
378                 -- Good to inline if an arg is scrutinised, because
379                 -- that may eliminate allocation in the caller
380                 -- And it eliminates the case itself
381         where
382           alt_sizes = map size_up_alt alts
383
384                 -- alts_size tries to compute a good discount for
385                 -- the case when we are scrutinising an argument variable
386           alts_size (SizeIs tot tot_disc tot_scrut)  -- Size of all alternatives
387                     (SizeIs max _        _)          -- Size of biggest alternative
388                 = SizeIs tot (unitBag (v, iBox (_ILIT(2) +# tot -# max)) `unionBags` tot_disc) tot_scrut
389                         -- If the variable is known, we produce a discount that
390                         -- will take us back to 'max', the size of the largest alternative
391                         -- The 1+ is a little discount for reduced allocation in the caller
392                         --
393                         -- Notice though, that we return tot_disc, the total discount from 
394                         -- all branches.  I think that's right.
395
396           alts_size tot_size _ = tot_size
397
398     size_up (Case e _ _ alts) = size_up e  `addSizeNSD` 
399                                 foldr (addAltSize . size_up_alt) sizeZero alts
400                 -- We don't charge for the case itself
401                 -- It's a strict thing, and the price of the call
402                 -- is paid by scrut.  Also consider
403                 --      case f x of DEFAULT -> e
404                 -- This is just ';'!  Don't charge for it.
405                 --
406                 -- Moreover, we charge one per alternative.
407
408     ------------ 
409     -- size_up_app is used when there's ONE OR MORE value args
410     size_up_app (App fun arg) args 
411         | isTypeArg arg            = size_up_app fun args
412         | otherwise                = size_up arg  `addSizeNSD`
413                                      size_up_app fun (arg:args)
414     size_up_app (Var fun)     args = size_up_call fun args
415     size_up_app other         args = size_up other `addSizeN` length args
416
417     ------------ 
418     size_up_call :: Id -> [CoreExpr] -> ExprSize
419     size_up_call fun val_args
420        = case idDetails fun of
421            FCallId _        -> sizeN opt_UF_DearOp
422            DataConWorkId dc -> conSize    dc (length val_args)
423            PrimOpId op      -> primOpSize op (length val_args)
424            ClassOpId _      -> classOpSize top_args val_args
425            _                -> funSize top_args fun (length val_args)
426
427     ------------ 
428     size_up_alt (_con, _bndrs, rhs) = size_up rhs `addSizeN` 1
429         -- Don't charge for args, so that wrappers look cheap
430         -- (See comments about wrappers with Case)
431         --
432         -- IMPORATANT: *do* charge 1 for the alternative, else we 
433         -- find that giant case nests are treated as practically free
434         -- A good example is Foreign.C.Error.errrnoToIOError
435
436     ------------
437         -- These addSize things have to be here because
438         -- I don't want to give them bOMB_OUT_SIZE as an argument
439     addSizeN TooBig          _  = TooBig
440     addSizeN (SizeIs n xs d) m  = mkSizeIs bOMB_OUT_SIZE (n +# iUnbox m) xs d
441     
442         -- addAltSize is used to add the sizes of case alternatives
443     addAltSize TooBig            _      = TooBig
444     addAltSize _                 TooBig = TooBig
445     addAltSize (SizeIs n1 xs d1) (SizeIs n2 ys d2) 
446         = mkSizeIs bOMB_OUT_SIZE (n1 +# n2) 
447                                  (xs `unionBags` ys) 
448                                  (d1 +# d2)   -- Note [addAltSize result discounts]
449
450         -- This variant ignores the result discount from its LEFT argument
451         -- It's used when the second argument isn't part of the result
452     addSizeNSD TooBig            _      = TooBig
453     addSizeNSD _                 TooBig = TooBig
454     addSizeNSD (SizeIs n1 xs _) (SizeIs n2 ys d2) 
455         = mkSizeIs bOMB_OUT_SIZE (n1 +# n2) 
456                                  (xs `unionBags` ys) 
457                                  d2  -- Ignore d1
458 \end{code}
459
460 \begin{code}
461 -- | Finds a nominal size of a string literal.
462 litSize :: Literal -> Int
463 -- Used by CoreUnfold.sizeExpr
464 litSize (MachStr str) = 1 + ((lengthFS str + 3) `div` 4)
465         -- If size could be 0 then @f "x"@ might be too small
466         -- [Sept03: make literal strings a bit bigger to avoid fruitless 
467         --  duplication of little strings]
468 litSize _other = 0    -- Must match size of nullary constructors
469                       -- Key point: if  x |-> 4, then x must inline unconditionally
470                       --            (eg via case binding)
471
472 classOpSize :: [Id] -> [CoreExpr] -> ExprSize
473 -- See Note [Conlike is interesting]
474 classOpSize _ [] 
475   = sizeZero
476 classOpSize top_args (arg1 : other_args)
477   = SizeIs (iUnbox size) arg_discount (_ILIT(0))
478   where
479     size = 2 + length other_args
480     -- If the class op is scrutinising a lambda bound dictionary then
481     -- give it a discount, to encourage the inlining of this function
482     -- The actual discount is rather arbitrarily chosen
483     arg_discount = case arg1 of
484                      Var dict | dict `elem` top_args 
485                               -> unitBag (dict, opt_UF_DictDiscount)
486                      _other   -> emptyBag
487                      
488 funSize :: [Id] -> Id -> Int -> ExprSize
489 -- Size for functions that are not constructors or primops
490 -- Note [Function applications]
491 funSize top_args fun n_val_args
492   | fun `hasKey` buildIdKey   = buildSize
493   | fun `hasKey` augmentIdKey = augmentSize
494   | otherwise = SizeIs (iUnbox size) arg_discount (iUnbox res_discount)
495   where
496     some_val_args = n_val_args > 0
497
498     arg_discount | some_val_args && fun `elem` top_args
499                  = unitBag (fun, opt_UF_FunAppDiscount)
500                  | otherwise = emptyBag
501         -- If the function is an argument and is applied
502         -- to some values, give it an arg-discount
503
504     res_discount | idArity fun > n_val_args = opt_UF_FunAppDiscount
505                  | otherwise                = 0
506         -- If the function is partially applied, show a result discount
507
508     size | some_val_args = 1 + n_val_args
509          | otherwise     = 0
510         -- The 1+ is for the function itself
511         -- Add 1 for each non-trivial arg;
512         -- the allocation cost, as in let(rec)
513   
514
515 conSize :: DataCon -> Int -> ExprSize
516 conSize dc n_val_args
517   | n_val_args == 0 = SizeIs (_ILIT(0)) emptyBag (_ILIT(1))     -- Like variables
518
519 -- See Note [Constructor size]
520   | isUnboxedTupleCon dc = SizeIs (_ILIT(0)) emptyBag (iUnbox n_val_args +# _ILIT(1))
521
522 -- See Note [Unboxed tuple result discount]
523 --  | isUnboxedTupleCon dc = SizeIs (_ILIT(0)) emptyBag (_ILIT(0))
524
525 -- See Note [Constructor size]
526   | otherwise = SizeIs (_ILIT(1)) emptyBag (iUnbox n_val_args +# _ILIT(1))
527 \end{code}
528
529 Note [Constructor size]
530 ~~~~~~~~~~~~~~~~~~~~~~~
531 Treat a constructors application as size 1, regardless of how many
532 arguments it has; we are keen to expose them (and we charge separately
533 for their args).  We can't treat them as size zero, else we find that
534 (Just x) has size 0, which is the same as a lone variable; and hence
535 'v' will always be replaced by (Just x), where v is bound to Just x.
536
537 However, unboxed tuples count as size zero. I found occasions where we had 
538         f x y z = case op# x y z of { s -> (# s, () #) }
539 and f wasn't getting inlined.
540
541 Note [Unboxed tuple result discount]
542 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
543 I tried giving unboxed tuples a *result discount* of zero (see the
544 commented-out line).  Why?  When returned as a result they do not
545 allocate, so maybe we don't want to charge so much for them If you
546 have a non-zero discount here, we find that workers often get inlined
547 back into wrappers, because it look like
548     f x = case $wf x of (# a,b #) -> (a,b)
549 and we are keener because of the case.  However while this change
550 shrank binary sizes by 0.5% it also made spectral/boyer allocate 5%
551 more. All other changes were very small. So it's not a big deal but I
552 didn't adopt the idea.
553
554 \begin{code}
555 primOpSize :: PrimOp -> Int -> ExprSize
556 primOpSize op n_val_args
557  | not (primOpIsDupable op) = sizeN opt_UF_DearOp
558  | not (primOpOutOfLine op) = sizeN 1
559         -- Be very keen to inline simple primops.
560         -- We give a discount of 1 for each arg so that (op# x y z) costs 2.
561         -- We can't make it cost 1, else we'll inline let v = (op# x y z) 
562         -- at every use of v, which is excessive.
563         --
564         -- A good example is:
565         --      let x = +# p q in C {x}
566         -- Even though x get's an occurrence of 'many', its RHS looks cheap,
567         -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
568
569  | otherwise = sizeN n_val_args
570
571
572 buildSize :: ExprSize
573 buildSize = SizeIs (_ILIT(0)) emptyBag (_ILIT(4))
574         -- We really want to inline applications of build
575         -- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
576         -- Indeed, we should add a result_discount becuause build is 
577         -- very like a constructor.  We don't bother to check that the
578         -- build is saturated (it usually is).  The "-2" discounts for the \c n, 
579         -- The "4" is rather arbitrary.
580
581 augmentSize :: ExprSize
582 augmentSize = SizeIs (_ILIT(0)) emptyBag (_ILIT(4))
583         -- Ditto (augment t (\cn -> e) ys) should cost only the cost of
584         -- e plus ys. The -2 accounts for the \cn 
585
586 -- When we return a lambda, give a discount if it's used (applied)
587 lamScrutDiscount :: ExprSize -> ExprSize
588 lamScrutDiscount (SizeIs n vs _) = SizeIs n vs (iUnbox opt_UF_FunAppDiscount)
589 lamScrutDiscount TooBig          = TooBig
590 \end{code}
591
592 Note [addAltSize result discounts]
593 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
594 When adding the size of alternatives, we *add* the result discounts
595 too, rather than take the *maximum*.  For a multi-branch case, this
596 gives a discount for each branch that returns a constructor, making us
597 keener to inline.  I did try using 'max' instead, but it makes nofib 
598 'rewrite' and 'puzzle' allocate significantly more, and didn't make
599 binary sizes shrink significantly either.
600
601 Note [Discounts and thresholds]
602 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
603 Constants for discounts and thesholds are defined in main/StaticFlags,
604 all of form opt_UF_xxxx.   They are:
605
606 opt_UF_CreationThreshold (45)
607      At a definition site, if the unfolding is bigger than this, we
608      may discard it altogether
609
610 opt_UF_UseThreshold (6)
611      At a call site, if the unfolding, less discounts, is smaller than
612      this, then it's small enough inline
613
614 opt_UF_KeennessFactor (1.5)
615      Factor by which the discounts are multiplied before 
616      subtracting from size
617
618 opt_UF_DictDiscount (1)
619      The discount for each occurrence of a dictionary argument
620      as an argument of a class method.  Should be pretty small
621      else big functions may get inlined
622
623 opt_UF_FunAppDiscount (6)
624      Discount for a function argument that is applied.  Quite
625      large, because if we inline we avoid the higher-order call.
626
627 opt_UF_DearOp (4)
628      The size of a foreign call or not-dupable PrimOp
629
630
631 Note [Function applications]
632 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
633 In a function application (f a b)
634
635   - If 'f' is an argument to the function being analysed, 
636     and there's at least one value arg, record a FunAppDiscount for f
637
638   - If the application if a PAP (arity > 2 in this example)
639     record a *result* discount (because inlining
640     with "extra" args in the call may mean that we now 
641     get a saturated application)
642
643 Code for manipulating sizes
644
645 \begin{code}
646 data ExprSize = TooBig
647               | SizeIs FastInt          -- Size found
648                        (Bag (Id,Int))   -- Arguments cased herein, and discount for each such
649                        FastInt          -- Size to subtract if result is scrutinised 
650                                         -- by a case expression
651
652 instance Outputable ExprSize where
653   ppr TooBig         = ptext (sLit "TooBig")
654   ppr (SizeIs a _ c) = brackets (int (iBox a) <+> int (iBox c))
655
656 -- subtract the discount before deciding whether to bale out. eg. we
657 -- want to inline a large constructor application into a selector:
658 --      tup = (a_1, ..., a_99)
659 --      x = case tup of ...
660 --
661 mkSizeIs :: FastInt -> FastInt -> Bag (Id, Int) -> FastInt -> ExprSize
662 mkSizeIs max n xs d | (n -# d) ># max = TooBig
663                     | otherwise       = SizeIs n xs d
664  
665 maxSize :: ExprSize -> ExprSize -> ExprSize
666 maxSize TooBig         _                                  = TooBig
667 maxSize _              TooBig                             = TooBig
668 maxSize s1@(SizeIs n1 _ _) s2@(SizeIs n2 _ _) | n1 ># n2  = s1
669                                               | otherwise = s2
670
671 sizeZero :: ExprSize
672 sizeN :: Int -> ExprSize
673
674 sizeZero = SizeIs (_ILIT(0))  emptyBag (_ILIT(0))
675 sizeN n  = SizeIs (iUnbox n) emptyBag (_ILIT(0))
676 \end{code}
677
678
679 %************************************************************************
680 %*                                                                      *
681 \subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
682 %*                                                                      *
683 %************************************************************************
684
685 We use 'couldBeSmallEnoughToInline' to avoid exporting inlinings that
686 we ``couldn't possibly use'' on the other side.  Can be overridden w/
687 flaggery.  Just the same as smallEnoughToInline, except that it has no
688 actual arguments.
689
690 \begin{code}
691 couldBeSmallEnoughToInline :: Int -> CoreExpr -> Bool
692 couldBeSmallEnoughToInline threshold rhs 
693   = case sizeExpr (iUnbox threshold) [] body of
694        TooBig -> False
695        _      -> True
696   where
697     (_, body) = collectBinders rhs
698
699 ----------------
700 smallEnoughToInline :: Unfolding -> Bool
701 smallEnoughToInline (CoreUnfolding {uf_guidance = UnfIfGoodArgs {ug_size = size}})
702   = size <= opt_UF_UseThreshold
703 smallEnoughToInline _
704   = False
705
706 ----------------
707 certainlyWillInline :: Unfolding -> Bool
708   -- Sees if the unfolding is pretty certain to inline  
709 certainlyWillInline (CoreUnfolding { uf_is_cheap = is_cheap, uf_arity = n_vals, uf_guidance = guidance })
710   = case guidance of
711       UnfNever      -> False
712       UnfWhen {}    -> True
713       UnfIfGoodArgs { ug_size = size} 
714                     -> is_cheap && size - (n_vals +1) <= opt_UF_UseThreshold
715
716 certainlyWillInline _
717   = False
718 \end{code}
719
720 %************************************************************************
721 %*                                                                      *
722 \subsection{callSiteInline}
723 %*                                                                      *
724 %************************************************************************
725
726 This is the key function.  It decides whether to inline a variable at a call site
727
728 callSiteInline is used at call sites, so it is a bit more generous.
729 It's a very important function that embodies lots of heuristics.
730 A non-WHNF can be inlined if it doesn't occur inside a lambda,
731 and occurs exactly once or 
732     occurs once in each branch of a case and is small
733
734 If the thing is in WHNF, there's no danger of duplicating work, 
735 so we can inline if it occurs once, or is small
736
737 NOTE: we don't want to inline top-level functions that always diverge.
738 It just makes the code bigger.  Tt turns out that the convenient way to prevent
739 them inlining is to give them a NOINLINE pragma, which we do in 
740 StrictAnal.addStrictnessInfoToTopId
741
742 \begin{code}
743 callSiteInline :: DynFlags
744                -> Id                    -- The Id
745                -> Bool                  -- True <=> unfolding is active
746                -> Bool                  -- True if there are are no arguments at all (incl type args)
747                -> [ArgSummary]          -- One for each value arg; True if it is interesting
748                -> CallCtxt              -- True <=> continuation is interesting
749                -> Maybe CoreExpr        -- Unfolding, if any
750
751 instance Outputable ArgSummary where
752   ppr TrivArg    = ptext (sLit "TrivArg")
753   ppr NonTrivArg = ptext (sLit "NonTrivArg")
754   ppr ValueArg   = ptext (sLit "ValueArg")
755
756 data CallCtxt = BoringCtxt
757
758               | ArgCtxt         -- We are somewhere in the argument of a function
759                         Bool    -- True  <=> we're somewhere in the RHS of function with rules
760                                 -- False <=> we *are* the argument of a function with non-zero
761                                 --           arg discount
762                                 --        OR 
763                                 --           we *are* the RHS of a let  Note [RHS of lets]
764                                 -- In both cases, be a little keener to inline
765
766               | ValAppCtxt      -- We're applied to at least one value arg
767                                 -- This arises when we have ((f x |> co) y)
768                                 -- Then the (f x) has argument 'x' but in a ValAppCtxt
769
770               | CaseCtxt        -- We're the scrutinee of a case
771                                 -- that decomposes its scrutinee
772
773 instance Outputable CallCtxt where
774   ppr BoringCtxt      = ptext (sLit "BoringCtxt")
775   ppr (ArgCtxt rules) = ptext (sLit "ArgCtxt") <+> ppr rules
776   ppr CaseCtxt        = ptext (sLit "CaseCtxt")
777   ppr ValAppCtxt      = ptext (sLit "ValAppCtxt")
778
779 callSiteInline dflags id active_unfolding lone_variable arg_infos cont_info
780   = case idUnfolding id of 
781       -- idUnfolding checks for loop-breakers, returning NoUnfolding
782       -- Things with an INLINE pragma may have an unfolding *and* 
783       -- be a loop breaker  (maybe the knot is not yet untied)
784         CoreUnfolding { uf_tmpl = unf_template, uf_is_top = is_top 
785                       , uf_is_cheap = is_cheap, uf_arity = uf_arity
786                       , uf_guidance = guidance, uf_expandable = is_exp }
787           | active_unfolding -> tryUnfolding dflags id lone_variable 
788                                     arg_infos cont_info unf_template is_top 
789                                     is_cheap is_exp uf_arity guidance
790           | otherwise    -> Nothing
791         NoUnfolding      -> Nothing 
792         OtherCon {}      -> Nothing 
793         DFunUnfolding {} -> Nothing     -- Never unfold a DFun
794
795 tryUnfolding :: DynFlags -> Id -> Bool -> [ArgSummary] -> CallCtxt
796              -> CoreExpr -> Bool -> Bool -> Bool -> Arity -> UnfoldingGuidance
797              -> Maybe CoreExpr  
798 tryUnfolding dflags id lone_variable 
799              arg_infos cont_info unf_template is_top 
800              is_cheap is_exp uf_arity guidance
801                         -- uf_arity will typically be equal to (idArity id), 
802                         -- but may be less for InlineRules
803  | dopt Opt_D_dump_inlinings dflags && dopt Opt_D_verbose_core2core dflags
804  = pprTrace ("Considering inlining: " ++ showSDoc (ppr id))
805                  (vcat [text "arg infos" <+> ppr arg_infos,
806                         text "uf arity" <+> ppr uf_arity,
807                         text "interesting continuation" <+> ppr cont_info,
808                         text "some_benefit" <+> ppr some_benefit,
809                         text "is exp:" <+> ppr is_exp,
810                         text "is cheap:" <+> ppr is_cheap,
811                         text "guidance" <+> ppr guidance,
812                         extra_doc,
813                         text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO"])
814                  result
815   | otherwise  = result
816
817   where
818     n_val_args = length arg_infos
819     saturated  = n_val_args >= uf_arity
820
821     result | yes_or_no = Just unf_template
822            | otherwise = Nothing
823
824     interesting_args = any nonTriv arg_infos 
825         -- NB: (any nonTriv arg_infos) looks at the
826         -- over-saturated args too which is "wrong"; 
827         -- but if over-saturated we inline anyway.
828
829            -- some_benefit is used when the RHS is small enough
830            -- and the call has enough (or too many) value
831            -- arguments (ie n_val_args >= arity). But there must
832            -- be *something* interesting about some argument, or the
833            -- result context, to make it worth inlining
834     some_benefit 
835        | not saturated = interesting_args       -- Under-saturated
836                                         -- Note [Unsaturated applications]
837        | n_val_args > uf_arity = True   -- Over-saturated
838        | otherwise = interesting_args   -- Saturated
839                   || interesting_saturated_call 
840
841     interesting_saturated_call 
842       = case cont_info of
843           BoringCtxt -> not is_top && uf_arity > 0        -- Note [Nested functions]
844           CaseCtxt   -> not (lone_variable && is_cheap)   -- Note [Lone variables]
845           ArgCtxt {} -> uf_arity > 0                      -- Note [Inlining in ArgCtxt]
846           ValAppCtxt -> True                              -- Note [Cast then apply]
847
848     (yes_or_no, extra_doc)
849       = case guidance of
850           UnfNever -> (False, empty)
851
852           UnfWhen unsat_ok boring_ok 
853              -> (enough_args && (boring_ok || some_benefit), empty )
854              where      -- See Note [INLINE for small functions]
855                enough_args = saturated || (unsat_ok && n_val_args > 0)
856
857           UnfIfGoodArgs { ug_args = arg_discounts, ug_res = res_discount, ug_size = size }
858              -> ( is_cheap && some_benefit && small_enough
859                 , (text "discounted size =" <+> int discounted_size) )
860              where
861                discounted_size = size - discount
862                small_enough = discounted_size <= opt_UF_UseThreshold
863                discount = computeDiscount uf_arity arg_discounts 
864                                           res_discount arg_infos cont_info
865 \end{code}
866
867 Note [RHS of lets]
868 ~~~~~~~~~~~~~~~~~~
869 Be a tiny bit keener to inline in the RHS of a let, because that might
870 lead to good thing later
871      f y = (y,y,y)
872      g y = let x = f y in ...(case x of (a,b,c) -> ...) ...
873 We'd inline 'f' if the call was in a case context, and it kind-of-is,
874 only we can't see it.  So we treat the RHS of a let as not-totally-boring.
875     
876 Note [Unsaturated applications]
877 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
878 When a call is not saturated, we *still* inline if one of the
879 arguments has interesting structure.  That's sometimes very important.
880 A good example is the Ord instance for Bool in Base:
881
882  Rec {
883     $fOrdBool =GHC.Classes.D:Ord
884                  @ Bool
885                  ...
886                  $cmin_ajX
887
888     $cmin_ajX [Occ=LoopBreaker] :: Bool -> Bool -> Bool
889     $cmin_ajX = GHC.Classes.$dmmin @ Bool $fOrdBool
890   }
891
892 But the defn of GHC.Classes.$dmmin is:
893
894   $dmmin :: forall a. GHC.Classes.Ord a => a -> a -> a
895     {- Arity: 3, HasNoCafRefs, Strictness: SLL,
896        Unfolding: (\ @ a $dOrd :: GHC.Classes.Ord a x :: a y :: a ->
897                    case @ a GHC.Classes.<= @ a $dOrd x y of wild {
898                      GHC.Types.False -> y GHC.Types.True -> x }) -}
899
900 We *really* want to inline $dmmin, even though it has arity 3, in
901 order to unravel the recursion.
902
903
904 Note [Things to watch]
905 ~~~~~~~~~~~~~~~~~~~~~~
906 *   { y = I# 3; x = y `cast` co; ...case (x `cast` co) of ... }
907     Assume x is exported, so not inlined unconditionally.
908     Then we want x to inline unconditionally; no reason for it 
909     not to, and doing so avoids an indirection.
910
911 *   { x = I# 3; ....f x.... }
912     Make sure that x does not inline unconditionally!  
913     Lest we get extra allocation.
914
915 Note [Inlining an InlineRule]
916 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
917 An InlineRules is used for
918   (a) programmer INLINE pragmas
919   (b) inlinings from worker/wrapper
920
921 For (a) the RHS may be large, and our contract is that we *only* inline
922 when the function is applied to all the arguments on the LHS of the
923 source-code defn.  (The uf_arity in the rule.)
924
925 However for worker/wrapper it may be worth inlining even if the 
926 arity is not satisfied (as we do in the CoreUnfolding case) so we don't
927 require saturation.
928
929
930 Note [Nested functions]
931 ~~~~~~~~~~~~~~~~~~~~~~~
932 If a function has a nested defn we also record some-benefit, on the
933 grounds that we are often able to eliminate the binding, and hence the
934 allocation, for the function altogether; this is good for join points.
935 But this only makes sense for *functions*; inlining a constructor
936 doesn't help allocation unless the result is scrutinised.  UNLESS the
937 constructor occurs just once, albeit possibly in multiple case
938 branches.  Then inlining it doesn't increase allocation, but it does
939 increase the chance that the constructor won't be allocated at all in
940 the branches that don't use it.
941
942 Note [Cast then apply]
943 ~~~~~~~~~~~~~~~~~~~~~~
944 Consider
945    myIndex = __inline_me ( (/\a. <blah>) |> co )
946    co :: (forall a. a -> a) ~ (forall a. T a)
947      ... /\a.\x. case ((myIndex a) |> sym co) x of { ... } ...
948
949 We need to inline myIndex to unravel this; but the actual call (myIndex a) has
950 no value arguments.  The ValAppCtxt gives it enough incentive to inline.
951
952 Note [Inlining in ArgCtxt]
953 ~~~~~~~~~~~~~~~~~~~~~~~~~~
954 The condition (arity > 0) here is very important, because otherwise
955 we end up inlining top-level stuff into useless places; eg
956    x = I# 3#
957    f = \y.  g x
958 This can make a very big difference: it adds 16% to nofib 'integer' allocs,
959 and 20% to 'power'.
960
961 At one stage I replaced this condition by 'True' (leading to the above 
962 slow-down).  The motivation was test eyeball/inline1.hs; but that seems
963 to work ok now.
964
965 NOTE: arguably, we should inline in ArgCtxt only if the result of the
966 call is at least CONLIKE.  At least for the cases where we use ArgCtxt
967 for the RHS of a 'let', we only profit from the inlining if we get a 
968 CONLIKE thing (modulo lets).
969
970 Note [Lone variables]   See also Note [Interaction of exprIsCheap and lone variables]
971 ~~~~~~~~~~~~~~~~~~~~~   which appears below
972 The "lone-variable" case is important.  I spent ages messing about
973 with unsatisfactory varaints, but this is nice.  The idea is that if a
974 variable appears all alone
975
976         as an arg of lazy fn, or rhs    BoringCtxt
977         as scrutinee of a case          CaseCtxt
978         as arg of a fn                  ArgCtxt
979 AND
980         it is bound to a cheap expression
981
982 then we should not inline it (unless there is some other reason,
983 e.g. is is the sole occurrence).  That is what is happening at 
984 the use of 'lone_variable' in 'interesting_saturated_call'.
985
986 Why?  At least in the case-scrutinee situation, turning
987         let x = (a,b) in case x of y -> ...
988 into
989         let x = (a,b) in case (a,b) of y -> ...
990 and thence to 
991         let x = (a,b) in let y = (a,b) in ...
992 is bad if the binding for x will remain.
993
994 Another example: I discovered that strings
995 were getting inlined straight back into applications of 'error'
996 because the latter is strict.
997         s = "foo"
998         f = \x -> ...(error s)...
999
1000 Fundamentally such contexts should not encourage inlining because the
1001 context can ``see'' the unfolding of the variable (e.g. case or a
1002 RULE) so there's no gain.  If the thing is bound to a value.
1003
1004 However, watch out:
1005
1006  * Consider this:
1007         foo = _inline_ (\n. [n])
1008         bar = _inline_ (foo 20)
1009         baz = \n. case bar of { (m:_) -> m + n }
1010    Here we really want to inline 'bar' so that we can inline 'foo'
1011    and the whole thing unravels as it should obviously do.  This is 
1012    important: in the NDP project, 'bar' generates a closure data
1013    structure rather than a list. 
1014
1015    So the non-inlining of lone_variables should only apply if the
1016    unfolding is regarded as cheap; because that is when exprIsConApp_maybe
1017    looks through the unfolding.  Hence the "&& is_cheap" in the
1018    InlineRule branch.
1019
1020  * Even a type application or coercion isn't a lone variable.
1021    Consider
1022         case $fMonadST @ RealWorld of { :DMonad a b c -> c }
1023    We had better inline that sucker!  The case won't see through it.
1024
1025    For now, I'm treating treating a variable applied to types 
1026    in a *lazy* context "lone". The motivating example was
1027         f = /\a. \x. BIG
1028         g = /\a. \y.  h (f a)
1029    There's no advantage in inlining f here, and perhaps
1030    a significant disadvantage.  Hence some_val_args in the Stop case
1031
1032 Note [Interaction of exprIsCheap and lone variables]
1033 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1034 The lone-variable test says "don't inline if a case expression
1035 scrutines a lone variable whose unfolding is cheap".  It's very 
1036 important that, under these circumstances, exprIsConApp_maybe
1037 can spot a constructor application. So, for example, we don't
1038 consider
1039         let x = e in (x,x)
1040 to be cheap, and that's good because exprIsConApp_maybe doesn't
1041 think that expression is a constructor application.
1042
1043 I used to test is_value rather than is_cheap, which was utterly
1044 wrong, because the above expression responds True to exprIsHNF.
1045
1046 This kind of thing can occur if you have
1047
1048         {-# INLINE foo #-}
1049         foo = let x = e in (x,x)
1050
1051 which Roman did.
1052
1053 \begin{code}
1054 computeDiscount :: Int -> [Int] -> Int -> [ArgSummary] -> CallCtxt -> Int
1055 computeDiscount n_vals_wanted arg_discounts res_discount arg_infos cont_info
1056         -- We multiple the raw discounts (args_discount and result_discount)
1057         -- ty opt_UnfoldingKeenessFactor because the former have to do with
1058         --  *size* whereas the discounts imply that there's some extra 
1059         --  *efficiency* to be gained (e.g. beta reductions, case reductions) 
1060         -- by inlining.
1061
1062   = 1           -- Discount of 1 because the result replaces the call
1063                 -- so we count 1 for the function itself
1064
1065     + length (take n_vals_wanted arg_infos)
1066                -- Discount of (un-scaled) 1 for each arg supplied, 
1067                -- because the result replaces the call
1068
1069     + round (opt_UF_KeenessFactor * 
1070              fromIntegral (arg_discount + res_discount'))
1071   where
1072     arg_discount = sum (zipWith mk_arg_discount arg_discounts arg_infos)
1073
1074     mk_arg_discount _        TrivArg    = 0 
1075     mk_arg_discount _        NonTrivArg = 1   
1076     mk_arg_discount discount ValueArg   = discount 
1077
1078     res_discount' = case cont_info of
1079                         BoringCtxt  -> 0
1080                         CaseCtxt    -> res_discount
1081                         _other      -> 4 `min` res_discount
1082                 -- res_discount can be very large when a function returns
1083                 -- constructors; but we only want to invoke that large discount
1084                 -- when there's a case continuation.
1085                 -- Otherwise we, rather arbitrarily, threshold it.  Yuk.
1086                 -- But we want to aovid inlining large functions that return 
1087                 -- constructors into contexts that are simply "interesting"
1088 \end{code}
1089
1090 %************************************************************************
1091 %*                                                                      *
1092         Interesting arguments
1093 %*                                                                      *
1094 %************************************************************************
1095
1096 Note [Interesting arguments]
1097 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1098 An argument is interesting if it deserves a discount for unfoldings
1099 with a discount in that argument position.  The idea is to avoid
1100 unfolding a function that is applied only to variables that have no
1101 unfolding (i.e. they are probably lambda bound): f x y z There is
1102 little point in inlining f here.
1103
1104 Generally, *values* (like (C a b) and (\x.e)) deserve discounts.  But
1105 we must look through lets, eg (let x = e in C a b), because the let will
1106 float, exposing the value, if we inline.  That makes it different to
1107 exprIsHNF.
1108
1109 Before 2009 we said it was interesting if the argument had *any* structure
1110 at all; i.e. (hasSomeUnfolding v).  But does too much inlining; see Trac #3016.
1111
1112 But we don't regard (f x y) as interesting, unless f is unsaturated.
1113 If it's saturated and f hasn't inlined, then it's probably not going
1114 to now!
1115
1116 Note [Conlike is interesting]
1117 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1118 Consider
1119         f d = ...((*) d x y)...
1120         ... f (df d')...
1121 where df is con-like. Then we'd really like to inline 'f' so that the
1122 rule for (*) (df d) can fire.  To do this 
1123   a) we give a discount for being an argument of a class-op (eg (*) d)
1124   b) we say that a con-like argument (eg (df d)) is interesting
1125
1126 \begin{code}
1127 data ArgSummary = TrivArg       -- Nothing interesting
1128                 | NonTrivArg    -- Arg has structure
1129                 | ValueArg      -- Arg is a con-app or PAP
1130                                 -- ..or con-like. Note [Conlike is interesting]
1131
1132 interestingArg :: CoreExpr -> ArgSummary
1133 -- See Note [Interesting arguments]
1134 interestingArg e = go e 0
1135   where
1136     -- n is # value args to which the expression is applied
1137     go (Lit {}) _          = ValueArg
1138     go (Var v)  n
1139        | isConLikeId v     = ValueArg   -- Experimenting with 'conlike' rather that
1140                                         --    data constructors here
1141        | idArity v > n     = ValueArg   -- Catches (eg) primops with arity but no unfolding
1142        | n > 0             = NonTrivArg -- Saturated or unknown call
1143        | conlike_unfolding = ValueArg   -- n==0; look for an interesting unfolding
1144                                         -- See Note [Conlike is interesting]
1145        | otherwise         = TrivArg    -- n==0, no useful unfolding
1146        where
1147          conlike_unfolding = isConLikeUnfolding (idUnfolding v)
1148
1149     go (Type _)          _ = TrivArg
1150     go (App fn (Type _)) n = go fn n    
1151     go (App fn _)        n = go fn (n+1)
1152     go (Note _ a)        n = go a n
1153     go (Cast e _)        n = go e n
1154     go (Lam v e)         n 
1155        | isTyCoVar v       = go e n
1156        | n>0               = go e (n-1)
1157        | otherwise         = ValueArg
1158     go (Let _ e)         n = case go e n of { ValueArg -> ValueArg; _ -> NonTrivArg }
1159     go (Case {})         _ = NonTrivArg
1160
1161 nonTriv ::  ArgSummary -> Bool
1162 nonTriv TrivArg = False
1163 nonTriv _       = True
1164 \end{code}
1165
1166 %************************************************************************
1167 %*                                                                      *
1168          exprIsConApp_maybe
1169 %*                                                                      *
1170 %************************************************************************
1171
1172 Note [exprIsConApp_maybe]
1173 ~~~~~~~~~~~~~~~~~~~~~~~~~
1174 exprIsConApp_maybe is a very important function.  There are two principal
1175 uses:
1176   * case e of { .... }
1177   * cls_op e, where cls_op is a class operation
1178
1179 In both cases you want to know if e is of form (C e1..en) where C is
1180 a data constructor.
1181
1182 However e might not *look* as if 
1183
1184 \begin{code}
1185 -- | Returns @Just (dc, [t1..tk], [x1..xn])@ if the argument expression is 
1186 -- a *saturated* constructor application of the form @dc t1..tk x1 .. xn@,
1187 -- where t1..tk are the *universally-qantified* type args of 'dc'
1188 exprIsConApp_maybe :: IdUnfoldingFun -> CoreExpr -> Maybe (DataCon, [Type], [CoreExpr])
1189
1190 exprIsConApp_maybe id_unf (Note note expr)
1191   | notSccNote note
1192   = exprIsConApp_maybe id_unf expr
1193         -- We ignore all notes except SCCs.  For example,
1194         --      case _scc_ "foo" (C a b) of
1195         --                      C a b -> e
1196         -- should not be optimised away, because we'll lose the
1197         -- entry count on 'foo'; see Trac #4414
1198
1199 exprIsConApp_maybe id_unf (Cast expr co)
1200   =     -- Here we do the KPush reduction rule as described in the FC paper
1201         -- The transformation applies iff we have
1202         --      (C e1 ... en) `cast` co
1203         -- where co :: (T t1 .. tn) ~ to_ty
1204         -- The left-hand one must be a T, because exprIsConApp returned True
1205         -- but the right-hand one might not be.  (Though it usually will.)
1206
1207     case exprIsConApp_maybe id_unf expr of {
1208         Nothing                          -> Nothing ;
1209         Just (dc, _dc_univ_args, dc_args) -> 
1210
1211     let (_from_ty, to_ty) = coercionKind co
1212         dc_tc = dataConTyCon dc
1213     in
1214     case splitTyConApp_maybe to_ty of {
1215         Nothing -> Nothing ;
1216         Just (to_tc, to_tc_arg_tys) 
1217                 | dc_tc /= to_tc -> Nothing
1218                 -- These two Nothing cases are possible; we might see 
1219                 --      (C x y) `cast` (g :: T a ~ S [a]),
1220                 -- where S is a type function.  In fact, exprIsConApp
1221                 -- will probably not be called in such circumstances,
1222                 -- but there't nothing wrong with it 
1223
1224                 | otherwise  ->
1225     let
1226         tc_arity       = tyConArity dc_tc
1227         dc_univ_tyvars = dataConUnivTyVars dc
1228         dc_ex_tyvars   = dataConExTyVars dc
1229         arg_tys        = dataConRepArgTys dc
1230
1231         dc_eqs :: [(Type,Type)]   -- All equalities from the DataCon
1232         dc_eqs = [(mkTyVarTy tv, ty)   | (tv,ty) <- dataConEqSpec dc] ++
1233                  [getEqPredTys eq_pred | eq_pred <- dataConEqTheta dc]
1234
1235         (ex_args, rest1)    = splitAtList dc_ex_tyvars dc_args
1236         (co_args, val_args) = splitAtList dc_eqs rest1
1237
1238         -- Make the "theta" from Fig 3 of the paper
1239         gammas = decomposeCo tc_arity co
1240         theta  = zipOpenTvSubst (dc_univ_tyvars ++ dc_ex_tyvars)
1241                                 (gammas         ++ stripTypeArgs ex_args)
1242
1243           -- Cast the existential coercion arguments
1244         cast_co (ty1, ty2) (Type co) 
1245           = Type $ mkSymCoercion (substTy theta ty1)
1246                    `mkTransCoercion` co
1247                    `mkTransCoercion` (substTy theta ty2)
1248         cast_co _ other_arg = pprPanic "cast_co" (ppr other_arg)
1249         new_co_args = zipWith cast_co dc_eqs co_args
1250   
1251           -- Cast the value arguments (which include dictionaries)
1252         new_val_args = zipWith cast_arg arg_tys val_args
1253         cast_arg arg_ty arg = mkCoerce (substTy theta arg_ty) arg
1254     in
1255 #ifdef DEBUG
1256     let dump_doc = vcat [ppr dc,      ppr dc_univ_tyvars, ppr dc_ex_tyvars,
1257                          ppr arg_tys, ppr dc_args,        ppr _dc_univ_args,
1258                          ppr ex_args, ppr val_args]
1259     in
1260     ASSERT2( coreEqType _from_ty (mkTyConApp dc_tc _dc_univ_args), dump_doc )
1261     ASSERT2( all isTypeArg (ex_args ++ co_args), dump_doc )
1262     ASSERT2( equalLength val_args arg_tys, dump_doc )
1263 #endif
1264
1265     Just (dc, to_tc_arg_tys, ex_args ++ new_co_args ++ new_val_args)
1266     }}
1267
1268 exprIsConApp_maybe id_unf expr 
1269   = analyse expr [] 
1270   where
1271     analyse (App fun arg) args = analyse fun (arg:args)
1272     analyse fun@(Lam {})  args = beta fun [] args 
1273
1274     analyse (Var fun) args
1275         | Just con <- isDataConWorkId_maybe fun
1276         , count isValArg args == idArity fun
1277         , let (univ_ty_args, rest_args) = splitAtList (dataConUnivTyVars con) args
1278         = Just (con, stripTypeArgs univ_ty_args, rest_args)
1279
1280         -- Look through dictionary functions; see Note [Unfolding DFuns]
1281         | DFunUnfolding dfun_nargs con ops <- unfolding
1282         , let sat = length args == dfun_nargs    -- See Note [DFun arity check]
1283           in if sat then True else 
1284              pprTrace "Unsaturated dfun" (ppr fun <+> int dfun_nargs $$ ppr args) False   
1285         , let (dfun_tvs, _n_theta, _cls, dfun_res_tys) = tcSplitDFunTy (idType fun)
1286               subst    = zipOpenTvSubst dfun_tvs (stripTypeArgs (takeList dfun_tvs args))
1287               mk_arg (DFunConstArg e) = e
1288               mk_arg (DFunLamArg i)   = args !! i
1289               mk_arg (DFunPolyArg e)  = mkApps e args
1290         = Just (con, substTys subst dfun_res_tys, map mk_arg ops)
1291
1292         -- Look through unfoldings, but only cheap ones, because
1293         -- we are effectively duplicating the unfolding
1294         | Just rhs <- expandUnfolding_maybe unfolding
1295         = -- pprTrace "expanding" (ppr fun $$ ppr rhs) $
1296           analyse rhs args
1297         where
1298           unfolding = id_unf fun
1299
1300     analyse _ _ = Nothing
1301
1302     -----------
1303     beta (Lam v body) pairs (arg : args) 
1304         | isTypeArg arg
1305         = beta body ((v,arg):pairs) args 
1306
1307     beta (Lam {}) _ _    -- Un-saturated, or not a type lambda
1308         = Nothing
1309
1310     beta fun pairs args
1311         = analyse (substExpr (text "subst-expr-is-con-app") subst fun) args
1312         where
1313           subst = mkOpenSubst (mkInScopeSet (exprFreeVars fun)) pairs
1314           -- doc = vcat [ppr fun, ppr expr, ppr pairs, ppr args]
1315
1316
1317 stripTypeArgs :: [CoreExpr] -> [Type]
1318 stripTypeArgs args = ASSERT2( all isTypeArg args, ppr args )
1319                      [ty | Type ty <- args]
1320 \end{code}
1321
1322 Note [Unfolding DFuns]
1323 ~~~~~~~~~~~~~~~~~~~~~~
1324 DFuns look like
1325
1326   df :: forall a b. (Eq a, Eq b) -> Eq (a,b)
1327   df a b d_a d_b = MkEqD (a,b) ($c1 a b d_a d_b)
1328                                ($c2 a b d_a d_b)
1329
1330 So to split it up we just need to apply the ops $c1, $c2 etc
1331 to the very same args as the dfun.  It takes a little more work
1332 to compute the type arguments to the dictionary constructor.
1333
1334 Note [DFun arity check]
1335 ~~~~~~~~~~~~~~~~~~~~~~~
1336 Here we check that the total number of supplied arguments (inclding 
1337 type args) matches what the dfun is expecting.  This may be *less*
1338 than the ordinary arity of the dfun: see Note [DFun unfoldings] in CoreSyn