OSDN Git Service

2010-04-19 Andrew Haley <aph@redhat.com>
[pf3gnuchains/gcc-fork.git] / gcc / ipa-inline.c
1 /* Inlining decision heuristics.
2    Copyright (C) 2003, 2004, 2007, 2008, 2009, 2010
3    Free Software Foundation, Inc.
4    Contributed by Jan Hubicka
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /*  Inlining decision heuristics
23
24     We separate inlining decisions from the inliner itself and store it
25     inside callgraph as so called inline plan.  Refer to cgraph.c
26     documentation about particular representation of inline plans in the
27     callgraph.
28
29     There are three major parts of this file:
30
31     cgraph_mark_inline implementation
32
33       This function allows to mark given call inline and performs necessary
34       modifications of cgraph (production of the clones and updating overall
35       statistics)
36
37     inlining heuristics limits
38
39       These functions allow to check that particular inlining is allowed
40       by the limits specified by user (allowed function growth, overall unit
41       growth and so on).
42
43     inlining heuristics
44
45       This is implementation of IPA pass aiming to get as much of benefit
46       from inlining obeying the limits checked above.
47
48       The implementation of particular heuristics is separated from
49       the rest of code to make it easier to replace it with more complicated
50       implementation in the future.  The rest of inlining code acts as a
51       library aimed to modify the callgraph and verify that the parameters
52       on code size growth fits.
53
54       To mark given call inline, use cgraph_mark_inline function, the
55       verification is performed by cgraph_default_inline_p and
56       cgraph_check_inline_limits.
57
58       The heuristics implements simple knapsack style algorithm ordering
59       all functions by their "profitability" (estimated by code size growth)
60       and inlining them in priority order.
61
62       cgraph_decide_inlining implements heuristics taking whole callgraph
63       into account, while cgraph_decide_inlining_incrementally considers
64       only one function at a time and is used by early inliner.
65
66    The inliner itself is split into several passes:
67
68    pass_inline_parameters
69
70      This pass computes local properties of functions that are used by inliner:
71      estimated function body size, whether function is inlinable at all and
72      stack frame consumption.
73
74      Before executing any of inliner passes, this local pass has to be applied
75      to each function in the callgraph (ie run as subpass of some earlier
76      IPA pass).  The results are made out of date by any optimization applied
77      on the function body.
78
79    pass_early_inlining
80
81      Simple local inlining pass inlining callees into current function.  This
82      pass makes no global whole compilation unit analysis and this when allowed
83      to do inlining expanding code size it might result in unbounded growth of
84      whole unit.
85
86      The pass is run during conversion into SSA form.  Only functions already
87      converted into SSA form are inlined, so the conversion must happen in
88      topological order on the callgraph (that is maintained by pass manager).
89      The functions after inlining are early optimized so the early inliner sees
90      unoptimized function itself, but all considered callees are already
91      optimized allowing it to unfold abstraction penalty on C++ effectively and
92      cheaply.
93
94    pass_ipa_early_inlining
95
96      With profiling, the early inlining is also necessary to reduce
97      instrumentation costs on program with high abstraction penalty (doing
98      many redundant calls).  This can't happen in parallel with early
99      optimization and profile instrumentation, because we would end up
100      re-instrumenting already instrumented function bodies we brought in via
101      inlining.
102
103      To avoid this, this pass is executed as IPA pass before profiling.  It is
104      simple wrapper to pass_early_inlining and ensures first inlining.
105
106    pass_ipa_inline
107
108      This is the main pass implementing simple greedy algorithm to do inlining
109      of small functions that results in overall growth of compilation unit and
110      inlining of functions called once.  The pass compute just so called inline
111      plan (representation of inlining to be done in callgraph) and unlike early
112      inlining it is not performing the inlining itself.
113
114    pass_apply_inline
115
116      This pass performs actual inlining according to pass_ipa_inline on given
117      function.  Possible the function body before inlining is saved when it is
118      needed for further inlining later.
119  */
120
121 #include "config.h"
122 #include "system.h"
123 #include "coretypes.h"
124 #include "tm.h"
125 #include "tree.h"
126 #include "tree-inline.h"
127 #include "langhooks.h"
128 #include "flags.h"
129 #include "cgraph.h"
130 #include "diagnostic.h"
131 #include "timevar.h"
132 #include "params.h"
133 #include "fibheap.h"
134 #include "intl.h"
135 #include "tree-pass.h"
136 #include "hashtab.h"
137 #include "coverage.h"
138 #include "ggc.h"
139 #include "tree-flow.h"
140 #include "rtl.h"
141 #include "ipa-prop.h"
142 #include "except.h"
143
144 #define MAX_TIME 1000000000
145
146 /* Mode incremental inliner operate on:
147
148    In ALWAYS_INLINE only functions marked
149    always_inline are inlined.  This mode is used after detecting cycle during
150    flattening.
151
152    In SIZE mode, only functions that reduce function body size after inlining
153    are inlined, this is used during early inlining.
154
155    in ALL mode, everything is inlined.  This is used during flattening.  */
156 enum inlining_mode {
157   INLINE_NONE = 0,
158   INLINE_ALWAYS_INLINE,
159   INLINE_SIZE_NORECURSIVE,
160   INLINE_SIZE,
161   INLINE_ALL
162 };
163
164 static bool
165 cgraph_decide_inlining_incrementally (struct cgraph_node *, enum inlining_mode);
166 static void cgraph_flatten (struct cgraph_node *node);
167
168
169 /* Statistics we collect about inlining algorithm.  */
170 static int ncalls_inlined;
171 static int nfunctions_inlined;
172 static int overall_size;
173 static gcov_type max_count, max_benefit;
174
175 /* Holders of ipa cgraph hooks: */
176 static struct cgraph_node_hook_list *function_insertion_hook_holder;
177
178 static inline struct inline_summary *
179 inline_summary (struct cgraph_node *node)
180 {
181   return &node->local.inline_summary;
182 }
183
184 /* Estimate self time of the function after inlining WHAT into TO.  */
185
186 static int
187 cgraph_estimate_time_after_inlining (int frequency, struct cgraph_node *to,
188                                      struct cgraph_node *what)
189 {
190   gcov_type time = (((gcov_type)what->global.time
191                      - inline_summary (what)->time_inlining_benefit)
192                     * frequency + CGRAPH_FREQ_BASE / 2) / CGRAPH_FREQ_BASE
193                     + to->global.time;
194   if (time < 0)
195     time = 0;
196   if (time > MAX_TIME)
197     time = MAX_TIME;
198   return time;
199 }
200
201 /* Estimate self time of the function after inlining WHAT into TO.  */
202
203 static int
204 cgraph_estimate_size_after_inlining (int times, struct cgraph_node *to,
205                                      struct cgraph_node *what)
206 {
207   int size = (what->global.size - inline_summary (what)->size_inlining_benefit) * times + to->global.size;
208   gcc_assert (size >= 0);
209   return size;
210 }
211
212 /* Scale frequency of NODE edges by FREQ_SCALE and increase loop nest
213    by NEST.  */
214
215 static void
216 update_noncloned_frequencies (struct cgraph_node *node,
217                               int freq_scale, int nest)
218 {
219   struct cgraph_edge *e;
220
221   /* We do not want to ignore high loop nest after freq drops to 0.  */
222   if (!freq_scale)
223     freq_scale = 1;
224   for (e = node->callees; e; e = e->next_callee)
225     {
226       e->loop_nest += nest;
227       e->frequency = e->frequency * (gcov_type) freq_scale / CGRAPH_FREQ_BASE;
228       if (e->frequency > CGRAPH_FREQ_MAX)
229         e->frequency = CGRAPH_FREQ_MAX;
230       if (!e->inline_failed)
231         update_noncloned_frequencies (e->callee, freq_scale, nest);
232     }
233 }
234
235 /* E is expected to be an edge being inlined.  Clone destination node of
236    the edge and redirect it to the new clone.
237    DUPLICATE is used for bookkeeping on whether we are actually creating new
238    clones or re-using node originally representing out-of-line function call.
239    */
240 void
241 cgraph_clone_inlined_nodes (struct cgraph_edge *e, bool duplicate,
242                             bool update_original)
243 {
244   HOST_WIDE_INT peak;
245
246   if (duplicate)
247     {
248       /* We may eliminate the need for out-of-line copy to be output.
249          In that case just go ahead and re-use it.  */
250       if (!e->callee->callers->next_caller
251           && cgraph_can_remove_if_no_direct_calls_p (e->callee)
252           /* Don't reuse if more than one function shares a comdat group.
253              If the other function(s) are needed, we need to emit even
254              this function out of line.  */
255           && !e->callee->same_comdat_group
256           && !cgraph_new_nodes)
257         {
258           gcc_assert (!e->callee->global.inlined_to);
259           if (e->callee->analyzed)
260             {
261               overall_size -= e->callee->global.size;
262               nfunctions_inlined++;
263             }
264           duplicate = false;
265           e->callee->local.externally_visible = false;
266           update_noncloned_frequencies (e->callee, e->frequency, e->loop_nest);
267         }
268       else
269         {
270           struct cgraph_node *n;
271           n = cgraph_clone_node (e->callee, e->callee->decl,
272                                  e->count, e->frequency, e->loop_nest,
273                                  update_original, NULL);
274           cgraph_redirect_edge_callee (e, n);
275         }
276     }
277
278   if (e->caller->global.inlined_to)
279     e->callee->global.inlined_to = e->caller->global.inlined_to;
280   else
281     e->callee->global.inlined_to = e->caller;
282   e->callee->global.stack_frame_offset
283     = e->caller->global.stack_frame_offset
284       + inline_summary (e->caller)->estimated_self_stack_size;
285   peak = e->callee->global.stack_frame_offset
286       + inline_summary (e->callee)->estimated_self_stack_size;
287   if (e->callee->global.inlined_to->global.estimated_stack_size < peak)
288     e->callee->global.inlined_to->global.estimated_stack_size = peak;
289   cgraph_propagate_frequency (e->callee);
290
291   /* Recursively clone all bodies.  */
292   for (e = e->callee->callees; e; e = e->next_callee)
293     if (!e->inline_failed)
294       cgraph_clone_inlined_nodes (e, duplicate, update_original);
295 }
296
297 /* Mark edge E as inlined and update callgraph accordingly.  UPDATE_ORIGINAL
298    specify whether profile of original function should be updated.  If any new
299    indirect edges are discovered in the process, add them to NEW_EDGES, unless
300    it is NULL.  Return true iff any new callgraph edges were discovered as a
301    result of inlining.  */
302
303 static bool
304 cgraph_mark_inline_edge (struct cgraph_edge *e, bool update_original,
305                          VEC (cgraph_edge_p, heap) **new_edges)
306 {
307   int old_size = 0, new_size = 0;
308   struct cgraph_node *to = NULL, *what;
309   struct cgraph_edge *curr = e;
310   int freq;
311
312   gcc_assert (e->inline_failed);
313   e->inline_failed = CIF_OK;
314   DECL_POSSIBLY_INLINED (e->callee->decl) = true;
315
316   if (!e->callee->global.inlined)
317     DECL_POSSIBLY_INLINED (e->callee->decl) = true;
318   e->callee->global.inlined = true;
319
320   cgraph_clone_inlined_nodes (e, true, update_original);
321
322   what = e->callee;
323
324   freq = e->frequency;
325   /* Now update size of caller and all functions caller is inlined into.  */
326   for (;e && !e->inline_failed; e = e->caller->callers)
327     {
328       to = e->caller;
329       old_size = e->caller->global.size;
330       new_size = cgraph_estimate_size_after_inlining (1, to, what);
331       to->global.size = new_size;
332       to->global.time = cgraph_estimate_time_after_inlining (freq, to, what);
333     }
334   gcc_assert (what->global.inlined_to == to);
335   if (new_size > old_size)
336     overall_size += new_size - old_size;
337   ncalls_inlined++;
338
339   if (flag_indirect_inlining)
340     return ipa_propagate_indirect_call_infos (curr, new_edges);
341   else
342     return false;
343 }
344
345 /* Mark all calls of EDGE->CALLEE inlined into EDGE->CALLER.  */
346
347 static void
348 cgraph_mark_inline (struct cgraph_edge *edge)
349 {
350   struct cgraph_node *to = edge->caller;
351   struct cgraph_node *what = edge->callee;
352   struct cgraph_edge *e, *next;
353
354   gcc_assert (!edge->call_stmt_cannot_inline_p);
355   /* Look for all calls, mark them inline and clone recursively
356      all inlined functions.  */
357   for (e = what->callers; e; e = next)
358     {
359       next = e->next_caller;
360       if (e->caller == to && e->inline_failed)
361         {
362           cgraph_mark_inline_edge (e, true, NULL);
363           if (e == edge)
364             edge = next;
365         }
366     }
367 }
368
369 /* Estimate the growth caused by inlining NODE into all callees.  */
370
371 static int
372 cgraph_estimate_growth (struct cgraph_node *node)
373 {
374   int growth = 0;
375   struct cgraph_edge *e;
376   bool self_recursive = false;
377
378   if (node->global.estimated_growth != INT_MIN)
379     return node->global.estimated_growth;
380
381   for (e = node->callers; e; e = e->next_caller)
382     {
383       if (e->caller == node)
384         self_recursive = true;
385       if (e->inline_failed)
386         growth += (cgraph_estimate_size_after_inlining (1, e->caller, node)
387                    - e->caller->global.size);
388     }
389
390   /* ??? Wrong for non-trivially self recursive functions or cases where
391      we decide to not inline for different reasons, but it is not big deal
392      as in that case we will keep the body around, but we will also avoid
393      some inlining.  */
394   if (cgraph_only_called_directly_p (node)
395       && !DECL_EXTERNAL (node->decl) && !self_recursive)
396     growth -= node->global.size;
397
398   node->global.estimated_growth = growth;
399   return growth;
400 }
401
402 /* Return false when inlining WHAT into TO is not good idea
403    as it would cause too large growth of function bodies.
404    When ONE_ONLY is true, assume that only one call site is going
405    to be inlined, otherwise figure out how many call sites in
406    TO calls WHAT and verify that all can be inlined.
407    */
408
409 static bool
410 cgraph_check_inline_limits (struct cgraph_node *to, struct cgraph_node *what,
411                             cgraph_inline_failed_t *reason, bool one_only)
412 {
413   int times = 0;
414   struct cgraph_edge *e;
415   int newsize;
416   int limit;
417   HOST_WIDE_INT stack_size_limit, inlined_stack;
418
419   if (one_only)
420     times = 1;
421   else
422     for (e = to->callees; e; e = e->next_callee)
423       if (e->callee == what)
424         times++;
425
426   if (to->global.inlined_to)
427     to = to->global.inlined_to;
428
429   /* When inlining large function body called once into small function,
430      take the inlined function as base for limiting the growth.  */
431   if (inline_summary (to)->self_size > inline_summary(what)->self_size)
432     limit = inline_summary (to)->self_size;
433   else
434     limit = inline_summary (what)->self_size;
435
436   limit += limit * PARAM_VALUE (PARAM_LARGE_FUNCTION_GROWTH) / 100;
437
438   /* Check the size after inlining against the function limits.  But allow
439      the function to shrink if it went over the limits by forced inlining.  */
440   newsize = cgraph_estimate_size_after_inlining (times, to, what);
441   if (newsize >= to->global.size
442       && newsize > PARAM_VALUE (PARAM_LARGE_FUNCTION_INSNS)
443       && newsize > limit)
444     {
445       if (reason)
446         *reason = CIF_LARGE_FUNCTION_GROWTH_LIMIT;
447       return false;
448     }
449
450   stack_size_limit = inline_summary (to)->estimated_self_stack_size;
451
452   stack_size_limit += stack_size_limit * PARAM_VALUE (PARAM_STACK_FRAME_GROWTH) / 100;
453
454   inlined_stack = (to->global.stack_frame_offset
455                    + inline_summary (to)->estimated_self_stack_size
456                    + what->global.estimated_stack_size);
457   if (inlined_stack  > stack_size_limit
458       && inlined_stack > PARAM_VALUE (PARAM_LARGE_STACK_FRAME))
459     {
460       if (reason)
461         *reason = CIF_LARGE_STACK_FRAME_GROWTH_LIMIT;
462       return false;
463     }
464   return true;
465 }
466
467 /* Return true when function N is small enough to be inlined.  */
468
469 static bool
470 cgraph_default_inline_p (struct cgraph_node *n, cgraph_inline_failed_t *reason)
471 {
472   tree decl = n->decl;
473
474   if (n->local.disregard_inline_limits)
475     return true;
476
477   if (!flag_inline_small_functions && !DECL_DECLARED_INLINE_P (decl))
478     {
479       if (reason)
480         *reason = CIF_FUNCTION_NOT_INLINE_CANDIDATE;
481       return false;
482     }
483
484   if (!n->analyzed)
485     {
486       if (reason)
487         *reason = CIF_BODY_NOT_AVAILABLE;
488       return false;
489     }
490
491   if (DECL_DECLARED_INLINE_P (decl))
492     {
493       if (n->global.size >= MAX_INLINE_INSNS_SINGLE)
494         {
495           if (reason)
496             *reason = CIF_MAX_INLINE_INSNS_SINGLE_LIMIT;
497           return false;
498         }
499     }
500   else
501     {
502       if (n->global.size >= MAX_INLINE_INSNS_AUTO)
503         {
504           if (reason)
505             *reason = CIF_MAX_INLINE_INSNS_AUTO_LIMIT;
506           return false;
507         }
508     }
509
510   return true;
511 }
512
513 /* Return true when inlining WHAT would create recursive inlining.
514    We call recursive inlining all cases where same function appears more than
515    once in the single recursion nest path in the inline graph.  */
516
517 static bool
518 cgraph_recursive_inlining_p (struct cgraph_node *to,
519                              struct cgraph_node *what,
520                              cgraph_inline_failed_t *reason)
521 {
522   bool recursive;
523   if (to->global.inlined_to)
524     recursive = what->decl == to->global.inlined_to->decl;
525   else
526     recursive = what->decl == to->decl;
527   /* Marking recursive function inline has sane semantic and thus we should
528      not warn on it.  */
529   if (recursive && reason)
530     *reason = (what->local.disregard_inline_limits
531                ? CIF_RECURSIVE_INLINING : CIF_UNSPECIFIED);
532   return recursive;
533 }
534
535 /* A cost model driving the inlining heuristics in a way so the edges with
536    smallest badness are inlined first.  After each inlining is performed
537    the costs of all caller edges of nodes affected are recomputed so the
538    metrics may accurately depend on values such as number of inlinable callers
539    of the function or function body size.  */
540
541 static int
542 cgraph_edge_badness (struct cgraph_edge *edge, bool dump)
543 {
544   gcov_type badness;
545   int growth =
546     (cgraph_estimate_size_after_inlining (1, edge->caller, edge->callee)
547      - edge->caller->global.size);
548
549   if (dump)
550     {
551       fprintf (dump_file, "    Badness calculcation for %s -> %s\n",
552                cgraph_node_name (edge->caller),
553                cgraph_node_name (edge->callee));
554       fprintf (dump_file, "      growth %i, time %i-%i, size %i-%i\n",
555                growth,
556                edge->callee->global.time,
557                inline_summary (edge->callee)->time_inlining_benefit,
558                edge->callee->global.size,
559                inline_summary (edge->callee)->size_inlining_benefit);
560     }
561
562   /* Always prefer inlining saving code size.  */
563   if (growth <= 0)
564     {
565       badness = INT_MIN - growth;
566       if (dump)
567         fprintf (dump_file, "      %i: Growth %i < 0\n", (int) badness,
568                  growth);
569     }
570
571   /* When profiling is available, base priorities -(#calls / growth).
572      So we optimize for overall number of "executed" inlined calls.  */
573   else if (max_count)
574     {
575       badness =
576         ((int)
577          ((double) edge->count * INT_MIN / max_count / (max_benefit + 1)) *
578          (inline_summary (edge->callee)->time_inlining_benefit + 1)) / growth;
579       if (dump)
580         {
581           fprintf (dump_file,
582                    "      %i (relative %f): profile info. Relative count %f"
583                    " * Relative benefit %f\n",
584                    (int) badness, (double) badness / INT_MIN,
585                    (double) edge->count / max_count,
586                    (double) (inline_summary (edge->callee)->
587                              time_inlining_benefit + 1) / (max_benefit + 1));
588         }
589     }
590
591   /* When function local profile is available, base priorities on
592      growth / frequency, so we optimize for overall frequency of inlined
593      calls.  This is not too accurate since while the call might be frequent
594      within function, the function itself is infrequent.
595
596      Other objective to optimize for is number of different calls inlined.
597      We add the estimated growth after inlining all functions to bias the
598      priorities slightly in this direction (so fewer times called functions
599      of the same size gets priority).  */
600   else if (flag_guess_branch_prob)
601     {
602       int div = edge->frequency * 100 / CGRAPH_FREQ_BASE + 1;
603       int benefitperc;
604       int growth_for_all;
605       badness = growth * 10000;
606       benefitperc =
607         MIN (100 * inline_summary (edge->callee)->time_inlining_benefit /
608              (edge->callee->global.time + 1) +1, 100);
609       div *= benefitperc;
610
611
612       /* Decrease badness if call is nested.  */
613       /* Compress the range so we don't overflow.  */
614       if (div > 10000)
615         div = 10000 + ceil_log2 (div) - 8;
616       if (div < 1)
617         div = 1;
618       if (badness > 0)
619         badness /= div;
620       growth_for_all = cgraph_estimate_growth (edge->callee);
621       badness += growth_for_all;
622       if (badness > INT_MAX)
623         badness = INT_MAX;
624       if (dump)
625         {
626           fprintf (dump_file,
627                    "      %i: guessed profile. frequency %i, overall growth %i,"
628                    " benefit %i%%, divisor %i\n",
629                    (int) badness, edge->frequency, growth_for_all, benefitperc, div);
630         }
631     }
632   /* When function local profile is not available or it does not give
633      useful information (ie frequency is zero), base the cost on
634      loop nest and overall size growth, so we optimize for overall number
635      of functions fully inlined in program.  */
636   else
637     {
638       int nest = MIN (edge->loop_nest, 8);
639       badness = cgraph_estimate_growth (edge->callee) * 256;
640
641       /* Decrease badness if call is nested.  */
642       if (badness > 0)
643         badness >>= nest;
644       else
645         {
646           badness <<= nest;
647         }
648       if (dump)
649         fprintf (dump_file, "      %i: no profile. nest %i\n", (int) badness,
650                  nest);
651     }
652
653   /* Ensure that we did not overflow in all the fixed point math above.  */
654   gcc_assert (badness >= INT_MIN);
655   gcc_assert (badness <= INT_MAX - 1);
656   /* Make recursive inlining happen always after other inlining is done.  */
657   if (cgraph_recursive_inlining_p (edge->caller, edge->callee, NULL))
658     return badness + 1;
659   else
660     return badness;
661 }
662
663 /* Recompute heap nodes for each of caller edge.  */
664
665 static void
666 update_caller_keys (fibheap_t heap, struct cgraph_node *node,
667                     bitmap updated_nodes)
668 {
669   struct cgraph_edge *edge;
670   cgraph_inline_failed_t failed_reason;
671
672   if (!node->local.inlinable
673       || node->global.inlined_to)
674     return;
675   if (bitmap_bit_p (updated_nodes, node->uid))
676     return;
677   bitmap_set_bit (updated_nodes, node->uid);
678   node->global.estimated_growth = INT_MIN;
679
680   if (!node->local.inlinable)
681     return;
682   /* Prune out edges we won't inline into anymore.  */
683   if (!cgraph_default_inline_p (node, &failed_reason))
684     {
685       for (edge = node->callers; edge; edge = edge->next_caller)
686         if (edge->aux)
687           {
688             fibheap_delete_node (heap, (fibnode_t) edge->aux);
689             edge->aux = NULL;
690             if (edge->inline_failed)
691               edge->inline_failed = failed_reason;
692           }
693       return;
694     }
695
696   for (edge = node->callers; edge; edge = edge->next_caller)
697     if (edge->inline_failed)
698       {
699         int badness = cgraph_edge_badness (edge, false);
700         if (edge->aux)
701           {
702             fibnode_t n = (fibnode_t) edge->aux;
703             gcc_assert (n->data == edge);
704             if (n->key == badness)
705               continue;
706
707             /* fibheap_replace_key only increase the keys.  */
708             if (badness < n->key)
709               {
710                 fibheap_replace_key (heap, n, badness);
711                 gcc_assert (n->key == badness);
712                 continue;
713               }
714             fibheap_delete_node (heap, (fibnode_t) edge->aux);
715           }
716         edge->aux = fibheap_insert (heap, badness, edge);
717       }
718 }
719
720 /* Recompute heap nodes for each of caller edges of each of callees.  */
721
722 static void
723 update_callee_keys (fibheap_t heap, struct cgraph_node *node,
724                     bitmap updated_nodes)
725 {
726   struct cgraph_edge *e;
727   node->global.estimated_growth = INT_MIN;
728
729   for (e = node->callees; e; e = e->next_callee)
730     if (e->inline_failed)
731       update_caller_keys (heap, e->callee, updated_nodes);
732     else if (!e->inline_failed)
733       update_callee_keys (heap, e->callee, updated_nodes);
734 }
735
736 /* Enqueue all recursive calls from NODE into priority queue depending on
737    how likely we want to recursively inline the call.  */
738
739 static void
740 lookup_recursive_calls (struct cgraph_node *node, struct cgraph_node *where,
741                         fibheap_t heap)
742 {
743   static int priority;
744   struct cgraph_edge *e;
745   for (e = where->callees; e; e = e->next_callee)
746     if (e->callee == node)
747       {
748         /* When profile feedback is available, prioritize by expected number
749            of calls.  Without profile feedback we maintain simple queue
750            to order candidates via recursive depths.  */
751         fibheap_insert (heap,
752                         !max_count ? priority++
753                         : -(e->count / ((max_count + (1<<24) - 1) / (1<<24))),
754                         e);
755       }
756   for (e = where->callees; e; e = e->next_callee)
757     if (!e->inline_failed)
758       lookup_recursive_calls (node, e->callee, heap);
759 }
760
761 /* Decide on recursive inlining: in the case function has recursive calls,
762    inline until body size reaches given argument.  If any new indirect edges
763    are discovered in the process, add them to *NEW_EDGES, unless NEW_EDGES
764    is NULL.  */
765
766 static bool
767 cgraph_decide_recursive_inlining (struct cgraph_node *node,
768                                   VEC (cgraph_edge_p, heap) **new_edges)
769 {
770   int limit = PARAM_VALUE (PARAM_MAX_INLINE_INSNS_RECURSIVE_AUTO);
771   int max_depth = PARAM_VALUE (PARAM_MAX_INLINE_RECURSIVE_DEPTH_AUTO);
772   int probability = PARAM_VALUE (PARAM_MIN_INLINE_RECURSIVE_PROBABILITY);
773   fibheap_t heap;
774   struct cgraph_edge *e;
775   struct cgraph_node *master_clone, *next;
776   int depth = 0;
777   int n = 0;
778
779   /* It does not make sense to recursively inline always-inline functions
780      as we are going to sorry() on the remaining calls anyway.  */
781   if (node->local.disregard_inline_limits
782       && lookup_attribute ("always_inline", DECL_ATTRIBUTES (node->decl)))
783     return false;
784
785   if (optimize_function_for_size_p (DECL_STRUCT_FUNCTION (node->decl))
786       || (!flag_inline_functions && !DECL_DECLARED_INLINE_P (node->decl)))
787     return false;
788
789   if (DECL_DECLARED_INLINE_P (node->decl))
790     {
791       limit = PARAM_VALUE (PARAM_MAX_INLINE_INSNS_RECURSIVE);
792       max_depth = PARAM_VALUE (PARAM_MAX_INLINE_RECURSIVE_DEPTH);
793     }
794
795   /* Make sure that function is small enough to be considered for inlining.  */
796   if (!max_depth
797       || cgraph_estimate_size_after_inlining (1, node, node)  >= limit)
798     return false;
799   heap = fibheap_new ();
800   lookup_recursive_calls (node, node, heap);
801   if (fibheap_empty (heap))
802     {
803       fibheap_delete (heap);
804       return false;
805     }
806
807   if (dump_file)
808     fprintf (dump_file,
809              "  Performing recursive inlining on %s\n",
810              cgraph_node_name (node));
811
812   /* We need original clone to copy around.  */
813   master_clone = cgraph_clone_node (node, node->decl,
814                                     node->count, CGRAPH_FREQ_BASE, 1,
815                                     false, NULL);
816   master_clone->needed = true;
817   for (e = master_clone->callees; e; e = e->next_callee)
818     if (!e->inline_failed)
819       cgraph_clone_inlined_nodes (e, true, false);
820
821   /* Do the inlining and update list of recursive call during process.  */
822   while (!fibheap_empty (heap)
823          && (cgraph_estimate_size_after_inlining (1, node, master_clone)
824              <= limit))
825     {
826       struct cgraph_edge *curr
827         = (struct cgraph_edge *) fibheap_extract_min (heap);
828       struct cgraph_node *cnode;
829
830       depth = 1;
831       for (cnode = curr->caller;
832            cnode->global.inlined_to; cnode = cnode->callers->caller)
833         if (node->decl == curr->callee->decl)
834           depth++;
835       if (depth > max_depth)
836         {
837           if (dump_file)
838             fprintf (dump_file,
839                      "   maximal depth reached\n");
840           continue;
841         }
842
843       if (max_count)
844         {
845           if (!cgraph_maybe_hot_edge_p (curr))
846             {
847               if (dump_file)
848                 fprintf (dump_file, "   Not inlining cold call\n");
849               continue;
850             }
851           if (curr->count * 100 / node->count < probability)
852             {
853               if (dump_file)
854                 fprintf (dump_file,
855                          "   Probability of edge is too small\n");
856               continue;
857             }
858         }
859
860       if (dump_file)
861         {
862           fprintf (dump_file,
863                    "   Inlining call of depth %i", depth);
864           if (node->count)
865             {
866               fprintf (dump_file, " called approx. %.2f times per call",
867                        (double)curr->count / node->count);
868             }
869           fprintf (dump_file, "\n");
870         }
871       cgraph_redirect_edge_callee (curr, master_clone);
872       cgraph_mark_inline_edge (curr, false, new_edges);
873       lookup_recursive_calls (node, curr->callee, heap);
874       n++;
875     }
876   if (!fibheap_empty (heap) && dump_file)
877     fprintf (dump_file, "    Recursive inlining growth limit met.\n");
878
879   fibheap_delete (heap);
880   if (dump_file)
881     fprintf (dump_file,
882              "\n   Inlined %i times, body grown from size %i to %i, time %i to %i\n", n,
883              master_clone->global.size, node->global.size,
884              master_clone->global.time, node->global.time);
885
886   /* Remove master clone we used for inlining.  We rely that clones inlined
887      into master clone gets queued just before master clone so we don't
888      need recursion.  */
889   for (node = cgraph_nodes; node != master_clone;
890        node = next)
891     {
892       next = node->next;
893       if (node->global.inlined_to == master_clone)
894         cgraph_remove_node (node);
895     }
896   cgraph_remove_node (master_clone);
897   /* FIXME: Recursive inlining actually reduces number of calls of the
898      function.  At this place we should probably walk the function and
899      inline clones and compensate the counts accordingly.  This probably
900      doesn't matter much in practice.  */
901   return n > 0;
902 }
903
904 /* Set inline_failed for all callers of given function to REASON.  */
905
906 static void
907 cgraph_set_inline_failed (struct cgraph_node *node,
908                           cgraph_inline_failed_t reason)
909 {
910   struct cgraph_edge *e;
911
912   if (dump_file)
913     fprintf (dump_file, "Inlining failed: %s\n",
914              cgraph_inline_failed_string (reason));
915   for (e = node->callers; e; e = e->next_caller)
916     if (e->inline_failed)
917       e->inline_failed = reason;
918 }
919
920 /* Given whole compilation unit estimate of INSNS, compute how large we can
921    allow the unit to grow.  */
922 static int
923 compute_max_insns (int insns)
924 {
925   int max_insns = insns;
926   if (max_insns < PARAM_VALUE (PARAM_LARGE_UNIT_INSNS))
927     max_insns = PARAM_VALUE (PARAM_LARGE_UNIT_INSNS);
928
929   return ((HOST_WIDEST_INT) max_insns
930           * (100 + PARAM_VALUE (PARAM_INLINE_UNIT_GROWTH)) / 100);
931 }
932
933 /* Compute badness of all edges in NEW_EDGES and add them to the HEAP.  */
934 static void
935 add_new_edges_to_heap (fibheap_t heap, VEC (cgraph_edge_p, heap) *new_edges)
936 {
937   while (VEC_length (cgraph_edge_p, new_edges) > 0)
938     {
939       struct cgraph_edge *edge = VEC_pop (cgraph_edge_p, new_edges);
940
941       gcc_assert (!edge->aux);
942       edge->aux = fibheap_insert (heap, cgraph_edge_badness (edge, false), edge);
943     }
944 }
945
946
947 /* We use greedy algorithm for inlining of small functions:
948    All inline candidates are put into prioritized heap based on estimated
949    growth of the overall number of instructions and then update the estimates.
950
951    INLINED and INLINED_CALEES are just pointers to arrays large enough
952    to be passed to cgraph_inlined_into and cgraph_inlined_callees.  */
953
954 static void
955 cgraph_decide_inlining_of_small_functions (void)
956 {
957   struct cgraph_node *node;
958   struct cgraph_edge *edge;
959   cgraph_inline_failed_t failed_reason;
960   fibheap_t heap = fibheap_new ();
961   bitmap updated_nodes = BITMAP_ALLOC (NULL);
962   int min_size, max_size;
963   VEC (cgraph_edge_p, heap) *new_indirect_edges = NULL;
964
965   if (flag_indirect_inlining)
966     new_indirect_edges = VEC_alloc (cgraph_edge_p, heap, 8);
967
968   if (dump_file)
969     fprintf (dump_file, "\nDeciding on smaller functions:\n");
970
971   /* Put all inline candidates into the heap.  */
972
973   for (node = cgraph_nodes; node; node = node->next)
974     {
975       if (!node->local.inlinable || !node->callers)
976         continue;
977       if (dump_file)
978         fprintf (dump_file, "Considering inline candidate %s.\n", cgraph_node_name (node));
979
980       node->global.estimated_growth = INT_MIN;
981       if (!cgraph_default_inline_p (node, &failed_reason))
982         {
983           cgraph_set_inline_failed (node, failed_reason);
984           continue;
985         }
986
987       for (edge = node->callers; edge; edge = edge->next_caller)
988         if (edge->inline_failed)
989           {
990             gcc_assert (!edge->aux);
991             edge->aux = fibheap_insert (heap, cgraph_edge_badness (edge, false), edge);
992           }
993     }
994
995   max_size = compute_max_insns (overall_size);
996   min_size = overall_size;
997
998   while (overall_size <= max_size
999          && !fibheap_empty (heap))
1000     {
1001       int old_size = overall_size;
1002       struct cgraph_node *where, *callee;
1003       int badness = fibheap_min_key (heap);
1004       int growth;
1005       cgraph_inline_failed_t not_good = CIF_OK;
1006
1007       edge = (struct cgraph_edge *) fibheap_extract_min (heap);
1008       gcc_assert (edge->aux);
1009       edge->aux = NULL;
1010       if (!edge->inline_failed)
1011         continue;
1012 #ifdef ENABLE_CHECKING
1013       gcc_assert (cgraph_edge_badness (edge, false) == badness);
1014 #endif
1015       callee = edge->callee;
1016
1017       growth = (cgraph_estimate_size_after_inlining (1, edge->caller, edge->callee)
1018                 - edge->caller->global.size);
1019
1020       if (dump_file)
1021         {
1022           fprintf (dump_file,
1023                    "\nConsidering %s with %i size\n",
1024                    cgraph_node_name (edge->callee),
1025                    edge->callee->global.size);
1026           fprintf (dump_file,
1027                    " to be inlined into %s in %s:%i\n"
1028                    " Estimated growth after inlined into all callees is %+i insns.\n"
1029                    " Estimated badness is %i, frequency %.2f.\n",
1030                    cgraph_node_name (edge->caller),
1031                    flag_wpa ? "unknown"
1032                    : gimple_filename ((const_gimple) edge->call_stmt),
1033                    flag_wpa ? -1 : gimple_lineno ((const_gimple) edge->call_stmt),
1034                    cgraph_estimate_growth (edge->callee),
1035                    badness,
1036                    edge->frequency / (double)CGRAPH_FREQ_BASE);
1037           if (edge->count)
1038             fprintf (dump_file," Called "HOST_WIDEST_INT_PRINT_DEC"x\n", edge->count);
1039           if (dump_flags & TDF_DETAILS)
1040             cgraph_edge_badness (edge, true);
1041         }
1042
1043       /* When not having profile info ready we don't weight by any way the
1044          position of call in procedure itself.  This means if call of
1045          function A from function B seems profitable to inline, the recursive
1046          call of function A in inline copy of A in B will look profitable too
1047          and we end up inlining until reaching maximal function growth.  This
1048          is not good idea so prohibit the recursive inlining.
1049
1050          ??? When the frequencies are taken into account we might not need this
1051          restriction.
1052
1053          We need to be cureful here, in some testcases, e.g. directivec.c in
1054          libcpp, we can estimate self recursive function to have negative growth
1055          for inlining completely.
1056          */
1057       if (!edge->count)
1058         {
1059           where = edge->caller;
1060           while (where->global.inlined_to)
1061             {
1062               if (where->decl == edge->callee->decl)
1063                 break;
1064               where = where->callers->caller;
1065             }
1066           if (where->global.inlined_to)
1067             {
1068               edge->inline_failed
1069                 = (edge->callee->local.disregard_inline_limits
1070                    ? CIF_RECURSIVE_INLINING : CIF_UNSPECIFIED);
1071               if (dump_file)
1072                 fprintf (dump_file, " inline_failed:Recursive inlining performed only for function itself.\n");
1073               continue;
1074             }
1075         }
1076
1077       if (edge->callee->local.disregard_inline_limits)
1078         ;
1079       else if (!cgraph_maybe_hot_edge_p (edge))
1080         not_good = CIF_UNLIKELY_CALL;
1081       else if (!flag_inline_functions
1082           && !DECL_DECLARED_INLINE_P (edge->callee->decl))
1083         not_good = CIF_NOT_DECLARED_INLINED;
1084       else if (optimize_function_for_size_p (DECL_STRUCT_FUNCTION(edge->caller->decl)))
1085         not_good = CIF_OPTIMIZING_FOR_SIZE;
1086       if (not_good && growth > 0 && cgraph_estimate_growth (edge->callee) > 0)
1087         {
1088           if (!cgraph_recursive_inlining_p (edge->caller, edge->callee,
1089                                             &edge->inline_failed))
1090             {
1091               edge->inline_failed = not_good;
1092               if (dump_file)
1093                 fprintf (dump_file, " inline_failed:%s.\n",
1094                          cgraph_inline_failed_string (edge->inline_failed));
1095             }
1096           continue;
1097         }
1098       if (!cgraph_default_inline_p (edge->callee, &edge->inline_failed))
1099         {
1100           if (!cgraph_recursive_inlining_p (edge->caller, edge->callee,
1101                                             &edge->inline_failed))
1102             {
1103               if (dump_file)
1104                 fprintf (dump_file, " inline_failed:%s.\n",
1105                          cgraph_inline_failed_string (edge->inline_failed));
1106             }
1107           continue;
1108         }
1109       if (!tree_can_inline_p (edge))
1110         {
1111           if (dump_file)
1112             fprintf (dump_file, " inline_failed:%s.\n",
1113                      cgraph_inline_failed_string (edge->inline_failed));
1114           continue;
1115         }
1116       if (cgraph_recursive_inlining_p (edge->caller, edge->callee,
1117                                        &edge->inline_failed))
1118         {
1119           where = edge->caller;
1120           if (where->global.inlined_to)
1121             where = where->global.inlined_to;
1122           if (!cgraph_decide_recursive_inlining (where,
1123                                                  flag_indirect_inlining
1124                                                  ? &new_indirect_edges : NULL))
1125             continue;
1126           if (flag_indirect_inlining)
1127             add_new_edges_to_heap (heap, new_indirect_edges);
1128           update_callee_keys (heap, where, updated_nodes);
1129         }
1130       else
1131         {
1132           struct cgraph_node *callee;
1133           if (edge->call_stmt_cannot_inline_p
1134               || !cgraph_check_inline_limits (edge->caller, edge->callee,
1135                                               &edge->inline_failed, true))
1136             {
1137               if (dump_file)
1138                 fprintf (dump_file, " Not inlining into %s:%s.\n",
1139                          cgraph_node_name (edge->caller),
1140                          cgraph_inline_failed_string (edge->inline_failed));
1141               continue;
1142             }
1143           callee = edge->callee;
1144           cgraph_mark_inline_edge (edge, true, &new_indirect_edges);
1145           if (flag_indirect_inlining)
1146             add_new_edges_to_heap (heap, new_indirect_edges);
1147
1148           update_callee_keys (heap, callee, updated_nodes);
1149         }
1150       where = edge->caller;
1151       if (where->global.inlined_to)
1152         where = where->global.inlined_to;
1153
1154       /* Our profitability metric can depend on local properties
1155          such as number of inlinable calls and size of the function body.
1156          After inlining these properties might change for the function we
1157          inlined into (since it's body size changed) and for the functions
1158          called by function we inlined (since number of it inlinable callers
1159          might change).  */
1160       update_caller_keys (heap, where, updated_nodes);
1161
1162       /* We removed one call of the function we just inlined.  If offline
1163          copy is still needed, be sure to update the keys.  */
1164       if (callee != where && !callee->global.inlined_to)
1165         update_caller_keys (heap, callee, updated_nodes);
1166       bitmap_clear (updated_nodes);
1167
1168       if (dump_file)
1169         {
1170           fprintf (dump_file,
1171                    " Inlined into %s which now has size %i and self time %i,"
1172                    "net change of %+i.\n",
1173                    cgraph_node_name (edge->caller),
1174                    edge->caller->global.time,
1175                    edge->caller->global.size,
1176                    overall_size - old_size);
1177         }
1178       if (min_size > overall_size)
1179         {
1180           min_size = overall_size;
1181           max_size = compute_max_insns (min_size);
1182
1183           if (dump_file)
1184             fprintf (dump_file, "New minimal size reached: %i\n", min_size);
1185         }
1186     }
1187   while (!fibheap_empty (heap))
1188     {
1189       int badness = fibheap_min_key (heap);
1190
1191       edge = (struct cgraph_edge *) fibheap_extract_min (heap);
1192       gcc_assert (edge->aux);
1193       edge->aux = NULL;
1194       if (!edge->inline_failed)
1195         continue;
1196 #ifdef ENABLE_CHECKING
1197       gcc_assert (cgraph_edge_badness (edge, false) == badness);
1198 #endif
1199       if (dump_file)
1200         {
1201           fprintf (dump_file,
1202                    "\nSkipping %s with %i size\n",
1203                    cgraph_node_name (edge->callee),
1204                    edge->callee->global.size);
1205           fprintf (dump_file,
1206                    " called by %s in %s:%i\n"
1207                    " Estimated growth after inlined into all callees is %+i insns.\n"
1208                    " Estimated badness is %i, frequency %.2f.\n",
1209                    cgraph_node_name (edge->caller),
1210                    flag_wpa ? "unknown"
1211                    : gimple_filename ((const_gimple) edge->call_stmt),
1212                    flag_wpa ? -1 : gimple_lineno ((const_gimple) edge->call_stmt),
1213                    cgraph_estimate_growth (edge->callee),
1214                    badness,
1215                    edge->frequency / (double)CGRAPH_FREQ_BASE);
1216           if (edge->count)
1217             fprintf (dump_file," Called "HOST_WIDEST_INT_PRINT_DEC"x\n", edge->count);
1218           if (dump_flags & TDF_DETAILS)
1219             cgraph_edge_badness (edge, true);
1220         }
1221       if (!edge->callee->local.disregard_inline_limits && edge->inline_failed
1222           && !cgraph_recursive_inlining_p (edge->caller, edge->callee,
1223                                            &edge->inline_failed))
1224         edge->inline_failed = CIF_INLINE_UNIT_GROWTH_LIMIT;
1225     }
1226
1227   if (new_indirect_edges)
1228     VEC_free (cgraph_edge_p, heap, new_indirect_edges);
1229   fibheap_delete (heap);
1230   BITMAP_FREE (updated_nodes);
1231 }
1232
1233 /* Flatten NODE from the IPA inliner.  */
1234
1235 static void
1236 cgraph_flatten (struct cgraph_node *node)
1237 {
1238   struct cgraph_edge *e;
1239
1240   /* We shouldn't be called recursively when we are being processed.  */
1241   gcc_assert (node->aux == NULL);
1242
1243   node->aux = (void *)(size_t) INLINE_ALL;
1244
1245   for (e = node->callees; e; e = e->next_callee)
1246     {
1247       struct cgraph_node *orig_callee;
1248
1249       if (e->call_stmt_cannot_inline_p)
1250         continue;
1251
1252       if (!e->callee->analyzed)
1253         {
1254           if (dump_file)
1255             fprintf (dump_file,
1256                      "Not inlining: Function body not available.\n");
1257           continue;
1258         }
1259
1260       /* We've hit cycle?  It is time to give up.  */
1261       if (e->callee->aux)
1262         {
1263           if (dump_file)
1264             fprintf (dump_file,
1265                      "Not inlining %s into %s to avoid cycle.\n",
1266                      cgraph_node_name (e->callee),
1267                      cgraph_node_name (e->caller));
1268           e->inline_failed = CIF_RECURSIVE_INLINING;
1269           continue;
1270         }
1271
1272       /* When the edge is already inlined, we just need to recurse into
1273          it in order to fully flatten the leaves.  */
1274       if (!e->inline_failed)
1275         {
1276           cgraph_flatten (e->callee);
1277           continue;
1278         }
1279
1280       if (cgraph_recursive_inlining_p (node, e->callee, &e->inline_failed))
1281         {
1282           if (dump_file)
1283             fprintf (dump_file, "Not inlining: recursive call.\n");
1284           continue;
1285         }
1286
1287       if (!tree_can_inline_p (e))
1288         {
1289           if (dump_file)
1290             fprintf (dump_file, "Not inlining: %s",
1291                      cgraph_inline_failed_string (e->inline_failed));
1292           continue;
1293         }
1294
1295       /* Inline the edge and flatten the inline clone.  Avoid
1296          recursing through the original node if the node was cloned.  */
1297       if (dump_file)
1298         fprintf (dump_file, " Inlining %s into %s.\n",
1299                  cgraph_node_name (e->callee),
1300                  cgraph_node_name (e->caller));
1301       orig_callee = e->callee;
1302       cgraph_mark_inline_edge (e, true, NULL);
1303       if (e->callee != orig_callee)
1304         orig_callee->aux = (void *)(size_t) INLINE_ALL;
1305       cgraph_flatten (e->callee);
1306       if (e->callee != orig_callee)
1307         orig_callee->aux = NULL;
1308     }
1309
1310   node->aux = NULL;
1311 }
1312
1313 /* Decide on the inlining.  We do so in the topological order to avoid
1314    expenses on updating data structures.  */
1315
1316 static unsigned int
1317 cgraph_decide_inlining (void)
1318 {
1319   struct cgraph_node *node;
1320   int nnodes;
1321   struct cgraph_node **order =
1322     XCNEWVEC (struct cgraph_node *, cgraph_n_nodes);
1323   int old_size = 0;
1324   int i;
1325   int initial_size = 0;
1326
1327   cgraph_remove_function_insertion_hook (function_insertion_hook_holder);
1328   if (in_lto_p && flag_indirect_inlining)
1329     ipa_update_after_lto_read ();
1330   if (flag_indirect_inlining)
1331     ipa_create_all_structures_for_iinln ();
1332
1333   max_count = 0;
1334   max_benefit = 0;
1335   for (node = cgraph_nodes; node; node = node->next)
1336     if (node->analyzed)
1337       {
1338         struct cgraph_edge *e;
1339
1340         gcc_assert (inline_summary (node)->self_size == node->global.size);
1341         initial_size += node->global.size;
1342         for (e = node->callees; e; e = e->next_callee)
1343           if (max_count < e->count)
1344             max_count = e->count;
1345         if (max_benefit < inline_summary (node)->time_inlining_benefit)
1346           max_benefit = inline_summary (node)->time_inlining_benefit;
1347       }
1348   gcc_assert (in_lto_p
1349               || !max_count
1350               || (profile_info && flag_branch_probabilities));
1351   overall_size = initial_size;
1352
1353   nnodes = cgraph_postorder (order);
1354
1355   if (dump_file)
1356     fprintf (dump_file,
1357              "\nDeciding on inlining.  Starting with size %i.\n",
1358              initial_size);
1359
1360   for (node = cgraph_nodes; node; node = node->next)
1361     node->aux = 0;
1362
1363   if (dump_file)
1364     fprintf (dump_file, "\nFlattening functions:\n");
1365
1366   /* In the first pass handle functions to be flattened.  Do this with
1367      a priority so none of our later choices will make this impossible.  */
1368   for (i = nnodes - 1; i >= 0; i--)
1369     {
1370       node = order[i];
1371
1372       /* Handle nodes to be flattened, but don't update overall unit
1373          size.  Calling the incremental inliner here is lame,
1374          a simple worklist should be enough.  What should be left
1375          here from the early inliner (if it runs) is cyclic cases.
1376          Ideally when processing callees we stop inlining at the
1377          entry of cycles, possibly cloning that entry point and
1378          try to flatten itself turning it into a self-recursive
1379          function.  */
1380       if (lookup_attribute ("flatten",
1381                             DECL_ATTRIBUTES (node->decl)) != NULL)
1382         {
1383           if (dump_file)
1384             fprintf (dump_file,
1385                      "Flattening %s\n", cgraph_node_name (node));
1386           cgraph_flatten (node);
1387         }
1388     }
1389
1390   cgraph_decide_inlining_of_small_functions ();
1391
1392   if (flag_inline_functions_called_once)
1393     {
1394       if (dump_file)
1395         fprintf (dump_file, "\nDeciding on functions called once:\n");
1396
1397       /* And finally decide what functions are called once.  */
1398       for (i = nnodes - 1; i >= 0; i--)
1399         {
1400           node = order[i];
1401
1402           if (node->callers
1403               && !node->callers->next_caller
1404               && cgraph_only_called_directly_p (node)
1405               && node->local.inlinable
1406               && node->callers->inline_failed
1407               && node->callers->caller != node
1408               && node->callers->caller->global.inlined_to != node
1409               && !node->callers->call_stmt_cannot_inline_p
1410               && !DECL_EXTERNAL (node->decl)
1411               && !DECL_COMDAT (node->decl))
1412             {
1413               cgraph_inline_failed_t reason;
1414               old_size = overall_size;
1415               if (dump_file)
1416                 {
1417                   fprintf (dump_file,
1418                            "\nConsidering %s size %i.\n",
1419                            cgraph_node_name (node), node->global.size);
1420                   fprintf (dump_file,
1421                            " Called once from %s %i insns.\n",
1422                            cgraph_node_name (node->callers->caller),
1423                            node->callers->caller->global.size);
1424                 }
1425
1426               if (cgraph_check_inline_limits (node->callers->caller, node,
1427                                               &reason, false))
1428                 {
1429                   struct cgraph_node *caller = node->callers->caller;
1430                   cgraph_mark_inline (node->callers);
1431                   if (dump_file)
1432                     fprintf (dump_file,
1433                              " Inlined into %s which now has %i size"
1434                              " for a net change of %+i size.\n",
1435                              cgraph_node_name (caller),
1436                              caller->global.size,
1437                              overall_size - old_size);
1438                 }
1439               else
1440                 {
1441                   if (dump_file)
1442                     fprintf (dump_file,
1443                              " Not inlining: %s.\n",
1444                              cgraph_inline_failed_string (reason));
1445                 }
1446             }
1447         }
1448     }
1449
1450   /* Free ipa-prop structures if they are no longer needed.  */
1451   if (flag_indirect_inlining)
1452     ipa_free_all_structures_after_iinln ();
1453
1454   if (dump_file)
1455     fprintf (dump_file,
1456              "\nInlined %i calls, eliminated %i functions, "
1457              "size %i turned to %i size.\n\n",
1458              ncalls_inlined, nfunctions_inlined, initial_size,
1459              overall_size);
1460   free (order);
1461   return 0;
1462 }
1463
1464 /* Return true when N is leaf function.  Accept cheap (pure&const) builtins
1465    in leaf functions.  */
1466 static bool
1467 leaf_node_p (struct cgraph_node *n)
1468 {
1469   struct cgraph_edge *e;
1470   for (e = n->callees; e; e = e->next_callee)
1471     if (!DECL_BUILT_IN (e->callee->decl)
1472         || (!TREE_READONLY (e->callee->decl)
1473             || DECL_PURE_P (e->callee->decl)))
1474       return false;
1475   return true;
1476 }
1477
1478 /* Decide on the inlining.  We do so in the topological order to avoid
1479    expenses on updating data structures.  */
1480
1481 static bool
1482 cgraph_decide_inlining_incrementally (struct cgraph_node *node,
1483                                       enum inlining_mode mode)
1484 {
1485   struct cgraph_edge *e;
1486   bool inlined = false;
1487   cgraph_inline_failed_t failed_reason;
1488
1489 #ifdef ENABLE_CHECKING
1490   verify_cgraph_node (node);
1491 #endif
1492
1493   if (mode != INLINE_ALWAYS_INLINE && mode != INLINE_SIZE_NORECURSIVE
1494       && lookup_attribute ("flatten", DECL_ATTRIBUTES (node->decl)) != NULL)
1495     {
1496       if (dump_file)
1497         fprintf (dump_file, "Incrementally flattening %s\n",
1498                  cgraph_node_name (node));
1499       mode = INLINE_ALL;
1500     }
1501
1502   /* First of all look for always inline functions.  */
1503   if (mode != INLINE_SIZE_NORECURSIVE)
1504     for (e = node->callees; e; e = e->next_callee)
1505       {
1506         if (!e->callee->local.disregard_inline_limits
1507             && (mode != INLINE_ALL || !e->callee->local.inlinable))
1508           continue;
1509         if (e->call_stmt_cannot_inline_p)
1510           continue;
1511         if (dump_file)
1512           fprintf (dump_file,
1513                    "Considering to always inline inline candidate %s.\n",
1514                    cgraph_node_name (e->callee));
1515         if (cgraph_recursive_inlining_p (node, e->callee, &e->inline_failed))
1516           {
1517             if (dump_file)
1518               fprintf (dump_file, "Not inlining: recursive call.\n");
1519             continue;
1520           }
1521         if (!tree_can_inline_p (e))
1522           {
1523             if (dump_file)
1524               fprintf (dump_file,
1525                        "Not inlining: %s",
1526                        cgraph_inline_failed_string (e->inline_failed));
1527             continue;
1528           }
1529         if (gimple_in_ssa_p (DECL_STRUCT_FUNCTION (node->decl))
1530             != gimple_in_ssa_p (DECL_STRUCT_FUNCTION (e->callee->decl)))
1531           {
1532             if (dump_file)
1533               fprintf (dump_file, "Not inlining: SSA form does not match.\n");
1534             continue;
1535           }
1536         if (!e->callee->analyzed)
1537           {
1538             if (dump_file)
1539               fprintf (dump_file,
1540                        "Not inlining: Function body no longer available.\n");
1541             continue;
1542           }
1543
1544         if (dump_file)
1545           fprintf (dump_file, " Inlining %s into %s.\n",
1546                    cgraph_node_name (e->callee),
1547                    cgraph_node_name (e->caller));
1548         cgraph_mark_inline (e);
1549         inlined = true;
1550       }
1551
1552   /* Now do the automatic inlining.  */
1553   if (mode != INLINE_ALL && mode != INLINE_ALWAYS_INLINE
1554       /* Never inline regular functions into always-inline functions
1555          during incremental inlining.  */
1556       && !node->local.disregard_inline_limits)
1557     {
1558       bitmap visited = BITMAP_ALLOC (NULL);
1559       for (e = node->callees; e; e = e->next_callee)
1560         {
1561           int allowed_growth = 0;
1562           if (!e->callee->local.inlinable
1563               || !e->inline_failed
1564               || e->callee->local.disregard_inline_limits)
1565             continue;
1566           /* We are inlining a function to all call-sites in node
1567              or to none.  So visit each candidate only once.  */
1568           if (!bitmap_set_bit (visited, e->callee->uid))
1569             continue;
1570           if (dump_file)
1571             fprintf (dump_file, "Considering inline candidate %s.\n",
1572                      cgraph_node_name (e->callee));
1573           if (cgraph_recursive_inlining_p (node, e->callee, &e->inline_failed))
1574             {
1575               if (dump_file)
1576                 fprintf (dump_file, "Not inlining: recursive call.\n");
1577               continue;
1578             }
1579           if (gimple_in_ssa_p (DECL_STRUCT_FUNCTION (node->decl))
1580               != gimple_in_ssa_p (DECL_STRUCT_FUNCTION (e->callee->decl)))
1581             {
1582               if (dump_file)
1583                 fprintf (dump_file,
1584                          "Not inlining: SSA form does not match.\n");
1585               continue;
1586             }
1587
1588           if (cgraph_maybe_hot_edge_p (e) && leaf_node_p (e->callee)
1589               && optimize_function_for_speed_p (cfun))
1590             allowed_growth = PARAM_VALUE (PARAM_EARLY_INLINING_INSNS);
1591
1592           /* When the function body would grow and inlining the function
1593              won't eliminate the need for offline copy of the function,
1594              don't inline.  */
1595           if (((mode == INLINE_SIZE || mode == INLINE_SIZE_NORECURSIVE)
1596                || (!flag_inline_functions
1597                    && !DECL_DECLARED_INLINE_P (e->callee->decl)))
1598               && (cgraph_estimate_size_after_inlining (1, e->caller, e->callee)
1599                   > e->caller->global.size + allowed_growth)
1600               && cgraph_estimate_growth (e->callee) > allowed_growth)
1601             {
1602               if (dump_file)
1603                 fprintf (dump_file,
1604                          "Not inlining: code size would grow by %i.\n",
1605                          cgraph_estimate_size_after_inlining (1, e->caller,
1606                                                               e->callee)
1607                          - e->caller->global.size);
1608               continue;
1609             }
1610           if (!cgraph_check_inline_limits (node, e->callee, &e->inline_failed,
1611                                            false)
1612               || e->call_stmt_cannot_inline_p)
1613             {
1614               if (dump_file)
1615                 fprintf (dump_file, "Not inlining: %s.\n",
1616                          cgraph_inline_failed_string (e->inline_failed));
1617               continue;
1618             }
1619           if (!e->callee->analyzed)
1620             {
1621               if (dump_file)
1622                 fprintf (dump_file,
1623                          "Not inlining: Function body no longer available.\n");
1624               continue;
1625             }
1626           if (!tree_can_inline_p (e))
1627             {
1628               if (dump_file)
1629                 fprintf (dump_file,
1630                          "Not inlining: %s.",
1631                          cgraph_inline_failed_string (e->inline_failed));
1632               continue;
1633             }
1634           if (cgraph_default_inline_p (e->callee, &failed_reason))
1635             {
1636               if (dump_file)
1637                 fprintf (dump_file, " Inlining %s into %s.\n",
1638                          cgraph_node_name (e->callee),
1639                          cgraph_node_name (e->caller));
1640               cgraph_mark_inline (e);
1641               inlined = true;
1642             }
1643         }
1644       BITMAP_FREE (visited);
1645     }
1646   return inlined;
1647 }
1648
1649 /* Because inlining might remove no-longer reachable nodes, we need to
1650    keep the array visible to garbage collector to avoid reading collected
1651    out nodes.  */
1652 static int nnodes;
1653 static GTY ((length ("nnodes"))) struct cgraph_node **order;
1654
1655 /* Do inlining of small functions.  Doing so early helps profiling and other
1656    passes to be somewhat more effective and avoids some code duplication in
1657    later real inlining pass for testcases with very many function calls.  */
1658 static unsigned int
1659 cgraph_early_inlining (void)
1660 {
1661   struct cgraph_node *node = cgraph_node (current_function_decl);
1662   unsigned int todo = 0;
1663   int iterations = 0;
1664
1665   if (sorrycount || errorcount)
1666     return 0;
1667
1668   if (!optimize
1669       || flag_no_inline
1670       || !flag_early_inlining)
1671     {
1672       /* When not optimizing or not inlining inline only always-inline
1673          functions.  */
1674       cgraph_decide_inlining_incrementally (node, INLINE_ALWAYS_INLINE);
1675       timevar_push (TV_INTEGRATION);
1676       todo |= optimize_inline_calls (current_function_decl);
1677       timevar_pop (TV_INTEGRATION);
1678     }
1679   else
1680     {
1681       if (lookup_attribute ("flatten",
1682                             DECL_ATTRIBUTES (node->decl)) != NULL)
1683         {
1684           if (dump_file)
1685             fprintf (dump_file,
1686                      "Flattening %s\n", cgraph_node_name (node));
1687           cgraph_flatten (node);
1688           timevar_push (TV_INTEGRATION);
1689           todo |= optimize_inline_calls (current_function_decl);
1690           timevar_pop (TV_INTEGRATION);
1691         }
1692       /* We iterate incremental inlining to get trivial cases of indirect
1693          inlining.  */
1694       while (iterations < PARAM_VALUE (PARAM_EARLY_INLINER_MAX_ITERATIONS)
1695              && cgraph_decide_inlining_incrementally (node,
1696                                                       iterations
1697                                                       ? INLINE_SIZE_NORECURSIVE
1698                                                       : INLINE_SIZE))
1699         {
1700           timevar_push (TV_INTEGRATION);
1701           todo |= optimize_inline_calls (current_function_decl);
1702           iterations++;
1703           timevar_pop (TV_INTEGRATION);
1704         }
1705       if (dump_file)
1706         fprintf (dump_file, "Iterations: %i\n", iterations);
1707     }
1708
1709   cfun->always_inline_functions_inlined = true;
1710
1711   return todo;
1712 }
1713
1714 struct gimple_opt_pass pass_early_inline =
1715 {
1716  {
1717   GIMPLE_PASS,
1718   "einline",                            /* name */
1719   NULL,                                 /* gate */
1720   cgraph_early_inlining,                /* execute */
1721   NULL,                                 /* sub */
1722   NULL,                                 /* next */
1723   0,                                    /* static_pass_number */
1724   TV_INLINE_HEURISTICS,                 /* tv_id */
1725   0,                                    /* properties_required */
1726   0,                                    /* properties_provided */
1727   0,                                    /* properties_destroyed */
1728   0,                                    /* todo_flags_start */
1729   TODO_dump_func                        /* todo_flags_finish */
1730  }
1731 };
1732
1733 /* When inlining shall be performed.  */
1734 static bool
1735 cgraph_gate_ipa_early_inlining (void)
1736 {
1737   return (flag_early_inlining
1738           && !in_lto_p
1739           && (flag_branch_probabilities || flag_test_coverage
1740               || profile_arc_flag));
1741 }
1742
1743 /* IPA pass wrapper for early inlining pass.  We need to run early inlining
1744    before tree profiling so we have stand alone IPA pass for doing so.  */
1745 struct simple_ipa_opt_pass pass_ipa_early_inline =
1746 {
1747  {
1748   SIMPLE_IPA_PASS,
1749   "einline_ipa",                        /* name */
1750   cgraph_gate_ipa_early_inlining,       /* gate */
1751   NULL,                                 /* execute */
1752   NULL,                                 /* sub */
1753   NULL,                                 /* next */
1754   0,                                    /* static_pass_number */
1755   TV_INLINE_HEURISTICS,                 /* tv_id */
1756   0,                                    /* properties_required */
1757   0,                                    /* properties_provided */
1758   0,                                    /* properties_destroyed */
1759   0,                                    /* todo_flags_start */
1760   TODO_dump_cgraph                      /* todo_flags_finish */
1761  }
1762 };
1763
1764 /* See if statement might disappear after inlining.  We are not terribly
1765    sophisficated, basically looking for simple abstraction penalty wrappers.  */
1766
1767 static bool
1768 likely_eliminated_by_inlining_p (gimple stmt)
1769 {
1770   enum gimple_code code = gimple_code (stmt);
1771   switch (code)
1772     {
1773       case GIMPLE_RETURN:
1774         return true;
1775       case GIMPLE_ASSIGN:
1776         if (gimple_num_ops (stmt) != 2)
1777           return false;
1778
1779         /* Casts of parameters, loads from parameters passed by reference
1780            and stores to return value or parameters are probably free after
1781            inlining.  */
1782         if (gimple_assign_rhs_code (stmt) == CONVERT_EXPR
1783             || gimple_assign_rhs_code (stmt) == NOP_EXPR
1784             || gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR
1785             || gimple_assign_rhs_class (stmt) == GIMPLE_SINGLE_RHS)
1786           {
1787             tree rhs = gimple_assign_rhs1 (stmt);
1788             tree lhs = gimple_assign_lhs (stmt);
1789             tree inner_rhs = rhs;
1790             tree inner_lhs = lhs;
1791             bool rhs_free = false;
1792             bool lhs_free = false;
1793
1794             while (handled_component_p (inner_lhs) || TREE_CODE (inner_lhs) == INDIRECT_REF)
1795               inner_lhs = TREE_OPERAND (inner_lhs, 0);
1796             while (handled_component_p (inner_rhs)
1797                    || TREE_CODE (inner_rhs) == ADDR_EXPR || TREE_CODE (inner_rhs) == INDIRECT_REF)
1798               inner_rhs = TREE_OPERAND (inner_rhs, 0);
1799
1800
1801             if (TREE_CODE (inner_rhs) == PARM_DECL
1802                 || (TREE_CODE (inner_rhs) == SSA_NAME
1803                     && SSA_NAME_IS_DEFAULT_DEF (inner_rhs)
1804                     && TREE_CODE (SSA_NAME_VAR (inner_rhs)) == PARM_DECL))
1805               rhs_free = true;
1806             if (rhs_free && is_gimple_reg (lhs))
1807               lhs_free = true;
1808             if (((TREE_CODE (inner_lhs) == PARM_DECL
1809                   || (TREE_CODE (inner_lhs) == SSA_NAME
1810                       && SSA_NAME_IS_DEFAULT_DEF (inner_lhs)
1811                       && TREE_CODE (SSA_NAME_VAR (inner_lhs)) == PARM_DECL))
1812                  && inner_lhs != lhs)
1813                 || TREE_CODE (inner_lhs) == RESULT_DECL
1814                 || (TREE_CODE (inner_lhs) == SSA_NAME
1815                     && TREE_CODE (SSA_NAME_VAR (inner_lhs)) == RESULT_DECL))
1816               lhs_free = true;
1817             if (lhs_free && (is_gimple_reg (rhs) || is_gimple_min_invariant (rhs)))
1818               rhs_free = true;
1819             if (lhs_free && rhs_free)
1820               return true;
1821           }
1822         return false;
1823       default:
1824         return false;
1825     }
1826 }
1827
1828 /* Compute function body size parameters for NODE.  */
1829
1830 static void
1831 estimate_function_body_sizes (struct cgraph_node *node)
1832 {
1833   gcov_type time = 0;
1834   gcov_type time_inlining_benefit = 0;
1835   int size = 0;
1836   int size_inlining_benefit = 0;
1837   basic_block bb;
1838   gimple_stmt_iterator bsi;
1839   struct function *my_function = DECL_STRUCT_FUNCTION (node->decl);
1840   tree arg;
1841   int freq;
1842   tree funtype = TREE_TYPE (node->decl);
1843
1844   if (node->local.disregard_inline_limits)
1845     {
1846       inline_summary (node)->self_time = 0;
1847       inline_summary (node)->self_size = 0;
1848       inline_summary (node)->time_inlining_benefit = 0;
1849       inline_summary (node)->size_inlining_benefit = 0;
1850     }
1851
1852   if (dump_file)
1853     fprintf (dump_file, "Analyzing function body size: %s\n",
1854              cgraph_node_name (node));
1855
1856   gcc_assert (my_function && my_function->cfg);
1857   FOR_EACH_BB_FN (bb, my_function)
1858     {
1859       freq = compute_call_stmt_bb_frequency (node->decl, bb);
1860       for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1861         {
1862           gimple stmt = gsi_stmt (bsi);
1863           int this_size = estimate_num_insns (stmt, &eni_size_weights);
1864           int this_time = estimate_num_insns (stmt, &eni_time_weights);
1865
1866           if (dump_file && (dump_flags & TDF_DETAILS))
1867             {
1868               fprintf (dump_file, "  freq:%6i size:%3i time:%3i ",
1869                        freq, this_size, this_time);
1870               print_gimple_stmt (dump_file, stmt, 0, 0);
1871             }
1872           this_time *= freq;
1873           time += this_time;
1874           size += this_size;
1875           if (likely_eliminated_by_inlining_p (stmt))
1876             {
1877               size_inlining_benefit += this_size;
1878               time_inlining_benefit += this_time;
1879               if (dump_file && (dump_flags & TDF_DETAILS))
1880                 fprintf (dump_file, "    Likely eliminated\n");
1881             }
1882           gcc_assert (time >= 0);
1883           gcc_assert (size >= 0);
1884         }
1885     }
1886   time = (time + CGRAPH_FREQ_BASE / 2) / CGRAPH_FREQ_BASE;
1887   time_inlining_benefit = ((time_inlining_benefit + CGRAPH_FREQ_BASE / 2)
1888                            / CGRAPH_FREQ_BASE);
1889   if (dump_file)
1890     fprintf (dump_file, "Overall function body time: %i-%i size: %i-%i\n",
1891              (int)time, (int)time_inlining_benefit,
1892              size, size_inlining_benefit);
1893   time_inlining_benefit += eni_time_weights.call_cost;
1894   size_inlining_benefit += eni_size_weights.call_cost;
1895   if (!VOID_TYPE_P (TREE_TYPE (funtype)))
1896     {
1897       int cost = estimate_move_cost (TREE_TYPE (funtype));
1898       time_inlining_benefit += cost;
1899       size_inlining_benefit += cost;
1900     }
1901   for (arg = DECL_ARGUMENTS (node->decl); arg; arg = TREE_CHAIN (arg))
1902     if (!VOID_TYPE_P (TREE_TYPE (arg)))
1903       {
1904         int cost = estimate_move_cost (TREE_TYPE (arg));
1905         time_inlining_benefit += cost;
1906         size_inlining_benefit += cost;
1907       }
1908   if (time_inlining_benefit > MAX_TIME)
1909     time_inlining_benefit = MAX_TIME;
1910   if (time > MAX_TIME)
1911     time = MAX_TIME;
1912   inline_summary (node)->self_time = time;
1913   inline_summary (node)->self_size = size;
1914   if (dump_file)
1915     fprintf (dump_file, "With function call overhead time: %i-%i size: %i-%i\n",
1916              (int)time, (int)time_inlining_benefit,
1917              size, size_inlining_benefit);
1918   inline_summary (node)->time_inlining_benefit = time_inlining_benefit;
1919   inline_summary (node)->size_inlining_benefit = size_inlining_benefit;
1920 }
1921
1922 /* Compute parameters of functions used by inliner.  */
1923 unsigned int
1924 compute_inline_parameters (struct cgraph_node *node)
1925 {
1926   HOST_WIDE_INT self_stack_size;
1927
1928   gcc_assert (!node->global.inlined_to);
1929
1930   /* Estimate the stack size for the function.  But not at -O0
1931      because estimated_stack_frame_size is a quadratic problem.  */
1932   self_stack_size = optimize ? estimated_stack_frame_size () : 0;
1933   inline_summary (node)->estimated_self_stack_size = self_stack_size;
1934   node->global.estimated_stack_size = self_stack_size;
1935   node->global.stack_frame_offset = 0;
1936
1937   /* Can this function be inlined at all?  */
1938   node->local.inlinable = tree_inlinable_function_p (node->decl);
1939   if (node->local.inlinable && !node->local.disregard_inline_limits)
1940     node->local.disregard_inline_limits
1941       = DECL_DISREGARD_INLINE_LIMITS (node->decl);
1942   estimate_function_body_sizes (node);
1943   /* Inlining characteristics are maintained by the cgraph_mark_inline.  */
1944   node->global.time = inline_summary (node)->self_time;
1945   node->global.size = inline_summary (node)->self_size;
1946   return 0;
1947 }
1948
1949
1950 /* Compute parameters of functions used by inliner using
1951    current_function_decl.  */
1952 static unsigned int
1953 compute_inline_parameters_for_current (void)
1954 {
1955   compute_inline_parameters (cgraph_node (current_function_decl));
1956   return 0;
1957 }
1958
1959 struct gimple_opt_pass pass_inline_parameters =
1960 {
1961  {
1962   GIMPLE_PASS,
1963   "inline_param",                       /* name */
1964   NULL,                                 /* gate */
1965   compute_inline_parameters_for_current,/* execute */
1966   NULL,                                 /* sub */
1967   NULL,                                 /* next */
1968   0,                                    /* static_pass_number */
1969   TV_INLINE_HEURISTICS,                 /* tv_id */
1970   0,                                    /* properties_required */
1971   0,                                    /* properties_provided */
1972   0,                                    /* properties_destroyed */
1973   0,                                    /* todo_flags_start */
1974   0                                     /* todo_flags_finish */
1975  }
1976 };
1977
1978 /* This function performs intraprocedural analyzis in NODE that is required to
1979    inline indirect calls.  */
1980 static void
1981 inline_indirect_intraprocedural_analysis (struct cgraph_node *node)
1982 {
1983   struct cgraph_edge *cs;
1984
1985   if (!flag_ipa_cp)
1986     {
1987       ipa_initialize_node_params (node);
1988       ipa_detect_param_modifications (node);
1989     }
1990   ipa_analyze_params_uses (node);
1991
1992   if (!flag_ipa_cp)
1993     for (cs = node->callees; cs; cs = cs->next_callee)
1994       {
1995         ipa_count_arguments (cs);
1996         ipa_compute_jump_functions (cs);
1997       }
1998
1999   if (dump_file)
2000     {
2001       ipa_print_node_params (dump_file, node);
2002       ipa_print_node_jump_functions (dump_file, node);
2003     }
2004 }
2005
2006 /* Note function body size.  */
2007 static void
2008 analyze_function (struct cgraph_node *node)
2009 {
2010   push_cfun (DECL_STRUCT_FUNCTION (node->decl));
2011   current_function_decl = node->decl;
2012
2013   compute_inline_parameters (node);
2014   if (flag_indirect_inlining)
2015     inline_indirect_intraprocedural_analysis (node);
2016
2017   current_function_decl = NULL;
2018   pop_cfun ();
2019 }
2020
2021 /* Called when new function is inserted to callgraph late.  */
2022 static void
2023 add_new_function (struct cgraph_node *node, void *data ATTRIBUTE_UNUSED)
2024 {
2025   analyze_function (node);
2026 }
2027
2028 /* Note function body size.  */
2029 static void
2030 inline_generate_summary (void)
2031 {
2032   struct cgraph_node *node;
2033
2034   function_insertion_hook_holder =
2035       cgraph_add_function_insertion_hook (&add_new_function, NULL);
2036
2037   if (flag_indirect_inlining)
2038     {
2039       ipa_register_cgraph_hooks ();
2040       ipa_check_create_node_params ();
2041       ipa_check_create_edge_args ();
2042     }
2043
2044   for (node = cgraph_nodes; node; node = node->next)
2045     if (node->analyzed)
2046       analyze_function (node);
2047
2048   return;
2049 }
2050
2051 /* Apply inline plan to function.  */
2052 static unsigned int
2053 inline_transform (struct cgraph_node *node)
2054 {
2055   unsigned int todo = 0;
2056   struct cgraph_edge *e;
2057
2058   /* FIXME: Currently the passmanager is adding inline transform more than once to some
2059      clones.  This needs revisiting after WPA cleanups.  */
2060   if (cfun->after_inlining)
2061     return 0;
2062
2063   /* We might need the body of this function so that we can expand
2064      it inline somewhere else.  */
2065   if (cgraph_preserve_function_body_p (node->decl))
2066     save_inline_function_body (node);
2067
2068   for (e = node->callees; e; e = e->next_callee)
2069     if (!e->inline_failed || warn_inline)
2070       break;
2071
2072   if (e)
2073     {
2074       timevar_push (TV_INTEGRATION);
2075       todo = optimize_inline_calls (current_function_decl);
2076       timevar_pop (TV_INTEGRATION);
2077     }
2078   cfun->always_inline_functions_inlined = true;
2079   cfun->after_inlining = true;
2080   return todo | execute_fixup_cfg ();
2081 }
2082
2083 /* Read inline summary.  Jump functions are shared among ipa-cp
2084    and inliner, so when ipa-cp is active, we don't need to write them
2085    twice.  */
2086
2087 static void
2088 inline_read_summary (void)
2089 {
2090   if (flag_indirect_inlining)
2091     {
2092       ipa_register_cgraph_hooks ();
2093       if (!flag_ipa_cp)
2094         ipa_prop_read_jump_functions ();
2095     }
2096   function_insertion_hook_holder =
2097       cgraph_add_function_insertion_hook (&add_new_function, NULL);
2098 }
2099
2100 /* Write inline summary for node in SET.
2101    Jump functions are shared among ipa-cp and inliner, so when ipa-cp is
2102    active, we don't need to write them twice.  */
2103
2104 static void
2105 inline_write_summary (cgraph_node_set set,
2106                       varpool_node_set vset ATTRIBUTE_UNUSED)
2107 {
2108   if (flag_indirect_inlining && !flag_ipa_cp)
2109     ipa_prop_write_jump_functions (set);
2110 }
2111
2112 /* When to run IPA inlining.  Inlining of always-inline functions
2113    happens during early inlining.  */
2114
2115 static bool
2116 gate_cgraph_decide_inlining (void)
2117 {
2118   /* ???  We'd like to skip this if not optimizing or not inlining as
2119      all always-inline functions have been processed by early
2120      inlining already.  But this at least breaks EH with C++ as
2121      we need to unconditionally run fixup_cfg even at -O0.
2122      So leave it on unconditionally for now.  */
2123   return 1;
2124 }
2125
2126 struct ipa_opt_pass_d pass_ipa_inline =
2127 {
2128  {
2129   IPA_PASS,
2130   "inline",                             /* name */
2131   gate_cgraph_decide_inlining,          /* gate */
2132   cgraph_decide_inlining,               /* execute */
2133   NULL,                                 /* sub */
2134   NULL,                                 /* next */
2135   0,                                    /* static_pass_number */
2136   TV_INLINE_HEURISTICS,                 /* tv_id */
2137   0,                                    /* properties_required */
2138   0,                                    /* properties_provided */
2139   0,                                    /* properties_destroyed */
2140   TODO_remove_functions,                /* todo_flags_finish */
2141   TODO_dump_cgraph | TODO_dump_func
2142   | TODO_remove_functions | TODO_ggc_collect    /* todo_flags_finish */
2143  },
2144  inline_generate_summary,               /* generate_summary */
2145  inline_write_summary,                  /* write_summary */
2146  inline_read_summary,                   /* read_summary */
2147  NULL,                                  /* write_optimization_summary */
2148  NULL,                                  /* read_optimization_summary */
2149  NULL,                                  /* stmt_fixup */
2150  0,                                     /* TODOs */
2151  inline_transform,                      /* function_transform */
2152  NULL,                                  /* variable_transform */
2153 };
2154
2155
2156 #include "gt-ipa-inline.h"