gcc/
[official-gcc.git] / gcc / ipa-inline.c
blobc0ff329ef0974e86a6da370de3041bbc48593e6d
1 /* Inlining decision heuristics.
2 Copyright (C) 2003-2015 Free Software Foundation, Inc.
3 Contributed by Jan Hubicka
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 /* Inlining decision heuristics
23 The implementation of inliner is organized as follows:
25 inlining heuristics limits
27 can_inline_edge_p allow to check that particular inlining is allowed
28 by the limits specified by user (allowed function growth, growth and so
29 on).
31 Functions are inlined when it is obvious the result is profitable (such
32 as functions called once or when inlining reduce code size).
33 In addition to that we perform inlining of small functions and recursive
34 inlining.
36 inlining heuristics
38 The inliner itself is split into two passes:
40 pass_early_inlining
42 Simple local inlining pass inlining callees into current function.
43 This pass makes no use of whole unit analysis and thus it can do only
44 very simple decisions based on local properties.
46 The strength of the pass is that it is run in topological order
47 (reverse postorder) on the callgraph. Functions are converted into SSA
48 form just before this pass and optimized subsequently. As a result, the
49 callees of the function seen by the early inliner was already optimized
50 and results of early inlining adds a lot of optimization opportunities
51 for the local optimization.
53 The pass handle the obvious inlining decisions within the compilation
54 unit - inlining auto inline functions, inlining for size and
55 flattening.
57 main strength of the pass is the ability to eliminate abstraction
58 penalty in C++ code (via combination of inlining and early
59 optimization) and thus improve quality of analysis done by real IPA
60 optimizers.
62 Because of lack of whole unit knowledge, the pass can not really make
63 good code size/performance tradeoffs. It however does very simple
64 speculative inlining allowing code size to grow by
65 EARLY_INLINING_INSNS when callee is leaf function. In this case the
66 optimizations performed later are very likely to eliminate the cost.
68 pass_ipa_inline
70 This is the real inliner able to handle inlining with whole program
71 knowledge. It performs following steps:
73 1) inlining of small functions. This is implemented by greedy
74 algorithm ordering all inlinable cgraph edges by their badness and
75 inlining them in this order as long as inline limits allows doing so.
77 This heuristics is not very good on inlining recursive calls. Recursive
78 calls can be inlined with results similar to loop unrolling. To do so,
79 special purpose recursive inliner is executed on function when
80 recursive edge is met as viable candidate.
82 2) Unreachable functions are removed from callgraph. Inlining leads
83 to devirtualization and other modification of callgraph so functions
84 may become unreachable during the process. Also functions declared as
85 extern inline or virtual functions are removed, since after inlining
86 we no longer need the offline bodies.
88 3) Functions called once and not exported from the unit are inlined.
89 This should almost always lead to reduction of code size by eliminating
90 the need for offline copy of the function. */
92 #include "config.h"
93 #include "system.h"
94 #include "coretypes.h"
95 #include "tm.h"
96 #include "hash-set.h"
97 #include "machmode.h"
98 #include "vec.h"
99 #include "double-int.h"
100 #include "input.h"
101 #include "alias.h"
102 #include "symtab.h"
103 #include "wide-int.h"
104 #include "inchash.h"
105 #include "tree.h"
106 #include "fold-const.h"
107 #include "trans-mem.h"
108 #include "calls.h"
109 #include "tree-inline.h"
110 #include "langhooks.h"
111 #include "flags.h"
112 #include "diagnostic.h"
113 #include "gimple-pretty-print.h"
114 #include "params.h"
115 #include "intl.h"
116 #include "tree-pass.h"
117 #include "coverage.h"
118 #include "rtl.h"
119 #include "bitmap.h"
120 #include "profile.h"
121 #include "predict.h"
122 #include "hard-reg-set.h"
123 #include "input.h"
124 #include "function.h"
125 #include "basic-block.h"
126 #include "tree-ssa-alias.h"
127 #include "internal-fn.h"
128 #include "gimple-expr.h"
129 #include "is-a.h"
130 #include "gimple.h"
131 #include "gimple-ssa.h"
132 #include "hash-map.h"
133 #include "plugin-api.h"
134 #include "ipa-ref.h"
135 #include "cgraph.h"
136 #include "alloc-pool.h"
137 #include "symbol-summary.h"
138 #include "ipa-prop.h"
139 #include "except.h"
140 #include "target.h"
141 #include "ipa-inline.h"
142 #include "ipa-utils.h"
143 #include "sreal.h"
144 #include "auto-profile.h"
145 #include "cilk.h"
146 #include "builtins.h"
147 #include "fibonacci_heap.h"
148 #include "lto-streamer.h"
150 typedef fibonacci_heap <sreal, cgraph_edge> edge_heap_t;
151 typedef fibonacci_node <sreal, cgraph_edge> edge_heap_node_t;
153 /* Statistics we collect about inlining algorithm. */
154 static int overall_size;
155 static gcov_type max_count;
156 static gcov_type spec_rem;
158 /* Pre-computed constants 1/CGRAPH_FREQ_BASE and 1/100. */
159 static sreal cgraph_freq_base_rec, percent_rec;
161 /* Return false when inlining edge E would lead to violating
162 limits on function unit growth or stack usage growth.
164 The relative function body growth limit is present generally
165 to avoid problems with non-linear behavior of the compiler.
166 To allow inlining huge functions into tiny wrapper, the limit
167 is always based on the bigger of the two functions considered.
169 For stack growth limits we always base the growth in stack usage
170 of the callers. We want to prevent applications from segfaulting
171 on stack overflow when functions with huge stack frames gets
172 inlined. */
174 static bool
175 caller_growth_limits (struct cgraph_edge *e)
177 struct cgraph_node *to = e->caller;
178 struct cgraph_node *what = e->callee->ultimate_alias_target ();
179 int newsize;
180 int limit = 0;
181 HOST_WIDE_INT stack_size_limit = 0, inlined_stack;
182 inline_summary *info, *what_info, *outer_info = inline_summaries->get (to);
184 /* Look for function e->caller is inlined to. While doing
185 so work out the largest function body on the way. As
186 described above, we want to base our function growth
187 limits based on that. Not on the self size of the
188 outer function, not on the self size of inline code
189 we immediately inline to. This is the most relaxed
190 interpretation of the rule "do not grow large functions
191 too much in order to prevent compiler from exploding". */
192 while (true)
194 info = inline_summaries->get (to);
195 if (limit < info->self_size)
196 limit = info->self_size;
197 if (stack_size_limit < info->estimated_self_stack_size)
198 stack_size_limit = info->estimated_self_stack_size;
199 if (to->global.inlined_to)
200 to = to->callers->caller;
201 else
202 break;
205 what_info = inline_summaries->get (what);
207 if (limit < what_info->self_size)
208 limit = what_info->self_size;
210 limit += limit * PARAM_VALUE (PARAM_LARGE_FUNCTION_GROWTH) / 100;
212 /* Check the size after inlining against the function limits. But allow
213 the function to shrink if it went over the limits by forced inlining. */
214 newsize = estimate_size_after_inlining (to, e);
215 if (newsize >= info->size
216 && newsize > PARAM_VALUE (PARAM_LARGE_FUNCTION_INSNS)
217 && newsize > limit)
219 e->inline_failed = CIF_LARGE_FUNCTION_GROWTH_LIMIT;
220 return false;
223 if (!what_info->estimated_stack_size)
224 return true;
226 /* FIXME: Stack size limit often prevents inlining in Fortran programs
227 due to large i/o datastructures used by the Fortran front-end.
228 We ought to ignore this limit when we know that the edge is executed
229 on every invocation of the caller (i.e. its call statement dominates
230 exit block). We do not track this information, yet. */
231 stack_size_limit += ((gcov_type)stack_size_limit
232 * PARAM_VALUE (PARAM_STACK_FRAME_GROWTH) / 100);
234 inlined_stack = (outer_info->stack_frame_offset
235 + outer_info->estimated_self_stack_size
236 + what_info->estimated_stack_size);
237 /* Check new stack consumption with stack consumption at the place
238 stack is used. */
239 if (inlined_stack > stack_size_limit
240 /* If function already has large stack usage from sibling
241 inline call, we can inline, too.
242 This bit overoptimistically assume that we are good at stack
243 packing. */
244 && inlined_stack > info->estimated_stack_size
245 && inlined_stack > PARAM_VALUE (PARAM_LARGE_STACK_FRAME))
247 e->inline_failed = CIF_LARGE_STACK_FRAME_GROWTH_LIMIT;
248 return false;
250 return true;
253 /* Dump info about why inlining has failed. */
255 static void
256 report_inline_failed_reason (struct cgraph_edge *e)
258 if (dump_file)
260 fprintf (dump_file, " not inlinable: %s/%i -> %s/%i, %s\n",
261 xstrdup_for_dump (e->caller->name ()), e->caller->order,
262 xstrdup_for_dump (e->callee->name ()), e->callee->order,
263 cgraph_inline_failed_string (e->inline_failed));
264 if ((e->inline_failed == CIF_TARGET_OPTION_MISMATCH
265 || e->inline_failed == CIF_OPTIMIZATION_MISMATCH)
266 && e->caller->lto_file_data
267 && e->callee->function_symbol ()->lto_file_data)
269 fprintf (dump_file, " LTO objects: %s, %s\n",
270 e->caller->lto_file_data->file_name,
271 e->callee->function_symbol ()->lto_file_data->file_name);
273 if (e->inline_failed == CIF_TARGET_OPTION_MISMATCH)
274 cl_target_option_print_diff
275 (dump_file, 2, target_opts_for_fn (e->caller->decl),
276 target_opts_for_fn (e->callee->ultimate_alias_target ()->decl));
277 if (e->inline_failed == CIF_OPTIMIZATION_MISMATCH)
278 cl_optimization_print_diff
279 (dump_file, 2, opts_for_fn (e->caller->decl),
280 opts_for_fn (e->callee->ultimate_alias_target ()->decl));
284 /* Decide whether sanitizer-related attributes allow inlining. */
286 static bool
287 sanitize_attrs_match_for_inline_p (const_tree caller, const_tree callee)
289 /* Don't care if sanitizer is disabled */
290 if (!(flag_sanitize & SANITIZE_ADDRESS))
291 return true;
293 if (!caller || !callee)
294 return true;
296 return !!lookup_attribute ("no_sanitize_address",
297 DECL_ATTRIBUTES (caller)) ==
298 !!lookup_attribute ("no_sanitize_address",
299 DECL_ATTRIBUTES (callee));
302 /* Decide if we can inline the edge and possibly update
303 inline_failed reason.
304 We check whether inlining is possible at all and whether
305 caller growth limits allow doing so.
307 if REPORT is true, output reason to the dump file.
309 if DISREGARD_LIMITS is true, ignore size limits.*/
311 static bool
312 can_inline_edge_p (struct cgraph_edge *e, bool report,
313 bool disregard_limits = false)
315 bool inlinable = true;
316 enum availability avail;
317 cgraph_node *callee = e->callee->ultimate_alias_target (&avail);
318 cgraph_node *caller = e->caller->global.inlined_to
319 ? e->caller->global.inlined_to : e->caller;
320 tree caller_tree = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (caller->decl);
321 tree callee_tree
322 = callee ? DECL_FUNCTION_SPECIFIC_OPTIMIZATION (callee->decl) : NULL;
323 struct function *caller_fun = caller->get_fun ();
324 struct function *callee_fun = callee ? callee->get_fun () : NULL;
326 gcc_assert (e->inline_failed);
328 if (!callee || !callee->definition)
330 e->inline_failed = CIF_BODY_NOT_AVAILABLE;
331 inlinable = false;
333 else if (callee->calls_comdat_local)
335 e->inline_failed = CIF_USES_COMDAT_LOCAL;
336 inlinable = false;
338 else if (!inline_summaries->get (callee)->inlinable
339 || (caller_fun && fn_contains_cilk_spawn_p (caller_fun)))
341 e->inline_failed = CIF_FUNCTION_NOT_INLINABLE;
342 inlinable = false;
344 else if (avail <= AVAIL_INTERPOSABLE)
346 e->inline_failed = CIF_OVERWRITABLE;
347 inlinable = false;
349 else if (e->call_stmt_cannot_inline_p)
351 if (e->inline_failed != CIF_FUNCTION_NOT_OPTIMIZED)
352 e->inline_failed = CIF_MISMATCHED_ARGUMENTS;
353 inlinable = false;
355 /* Don't inline if the functions have different EH personalities. */
356 else if (DECL_FUNCTION_PERSONALITY (caller->decl)
357 && DECL_FUNCTION_PERSONALITY (callee->decl)
358 && (DECL_FUNCTION_PERSONALITY (caller->decl)
359 != DECL_FUNCTION_PERSONALITY (callee->decl)))
361 e->inline_failed = CIF_EH_PERSONALITY;
362 inlinable = false;
364 /* TM pure functions should not be inlined into non-TM_pure
365 functions. */
366 else if (is_tm_pure (callee->decl)
367 && !is_tm_pure (caller->decl))
369 e->inline_failed = CIF_UNSPECIFIED;
370 inlinable = false;
372 /* Don't inline if the callee can throw non-call exceptions but the
373 caller cannot.
374 FIXME: this is obviously wrong for LTO where STRUCT_FUNCTION is missing.
375 Move the flag into cgraph node or mirror it in the inline summary. */
376 else if (callee_fun && callee_fun->can_throw_non_call_exceptions
377 && !(caller_fun && caller_fun->can_throw_non_call_exceptions))
379 e->inline_failed = CIF_NON_CALL_EXCEPTIONS;
380 inlinable = false;
382 /* Check compatibility of target optimization options. */
383 else if (!targetm.target_option.can_inline_p (caller->decl,
384 callee->decl))
386 e->inline_failed = CIF_TARGET_OPTION_MISMATCH;
387 inlinable = false;
389 /* Don't inline a function with mismatched sanitization attributes. */
390 else if (!sanitize_attrs_match_for_inline_p (caller->decl, callee->decl))
392 e->inline_failed = CIF_ATTRIBUTE_MISMATCH;
393 inlinable = false;
395 /* Check if caller growth allows the inlining. */
396 else if (!DECL_DISREGARD_INLINE_LIMITS (callee->decl)
397 && !disregard_limits
398 && !lookup_attribute ("flatten",
399 DECL_ATTRIBUTES (caller->decl))
400 && !caller_growth_limits (e))
401 inlinable = false;
402 /* Don't inline a function with a higher optimization level than the
403 caller. FIXME: this is really just tip of iceberg of handling
404 optimization attribute. */
405 else if (caller_tree != callee_tree)
407 /* gcc.dg/pr43564.c. Look at forced inline even in -O0. */
408 if (DECL_DISREGARD_INLINE_LIMITS (callee->decl))
410 /* When user added an attribute, honnor it. */
411 else if ((lookup_attribute ("optimize", DECL_ATTRIBUTES (caller->decl))
412 || lookup_attribute ("optimize",
413 DECL_ATTRIBUTES (callee->decl)))
414 && ((opt_for_fn (caller->decl, optimize)
415 > opt_for_fn (callee->decl, optimize))
416 || (opt_for_fn (caller->decl, optimize_size)
417 != opt_for_fn (callee->decl, optimize_size))))
419 e->inline_failed = CIF_OPTIMIZATION_MISMATCH;
420 inlinable = false;
422 /* If mismatch is caused by merging two LTO units with different
423 optimizationflags we want to be bit nicer. However never inline
424 if one of functions is not optimized at all. */
425 else if (!opt_for_fn (callee->decl, optimize)
426 || !opt_for_fn (caller->decl, optimize))
428 e->inline_failed = CIF_OPTIMIZATION_MISMATCH;
429 inlinable = false;
431 /* If callee is optimized for size and caller is not, allow inlining if
432 code shrinks or we are in MAX_INLINE_INSNS_SINGLE limit and callee
433 is inline (and thus likely an unified comdat). This will allow caller
434 to run faster. */
435 else if (opt_for_fn (callee->decl, optimize_size)
436 > opt_for_fn (caller->decl, optimize_size))
438 int growth = estimate_edge_growth (e);
439 if (growth > 0
440 && (!DECL_DECLARED_INLINE_P (callee->decl)
441 && growth >= MAX (MAX_INLINE_INSNS_SINGLE,
442 MAX_INLINE_INSNS_AUTO)))
444 e->inline_failed = CIF_OPTIMIZATION_MISMATCH;
445 inlinable = false;
448 /* If callee is more aggressively optimized for performance than caller,
449 we generally want to inline only cheap (runtime wise) functions. */
450 else if (opt_for_fn (callee->decl, optimize_size)
451 < opt_for_fn (caller->decl, optimize_size)
452 || (opt_for_fn (callee->decl, optimize)
453 >= opt_for_fn (caller->decl, optimize)))
455 if (estimate_edge_time (e)
456 >= 20 + inline_edge_summary (e)->call_stmt_time)
458 e->inline_failed = CIF_OPTIMIZATION_MISMATCH;
459 inlinable = false;
465 if (!inlinable && report)
466 report_inline_failed_reason (e);
467 return inlinable;
471 /* Return true if the edge E is inlinable during early inlining. */
473 static bool
474 can_early_inline_edge_p (struct cgraph_edge *e)
476 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
477 /* Early inliner might get called at WPA stage when IPA pass adds new
478 function. In this case we can not really do any of early inlining
479 because function bodies are missing. */
480 if (!gimple_has_body_p (callee->decl))
482 e->inline_failed = CIF_BODY_NOT_AVAILABLE;
483 return false;
485 /* In early inliner some of callees may not be in SSA form yet
486 (i.e. the callgraph is cyclic and we did not process
487 the callee by early inliner, yet). We don't have CIF code for this
488 case; later we will re-do the decision in the real inliner. */
489 if (!gimple_in_ssa_p (DECL_STRUCT_FUNCTION (e->caller->decl))
490 || !gimple_in_ssa_p (DECL_STRUCT_FUNCTION (callee->decl)))
492 if (dump_file)
493 fprintf (dump_file, " edge not inlinable: not in SSA form\n");
494 return false;
496 if (!can_inline_edge_p (e, true))
497 return false;
498 return true;
502 /* Return number of calls in N. Ignore cheap builtins. */
504 static int
505 num_calls (struct cgraph_node *n)
507 struct cgraph_edge *e;
508 int num = 0;
510 for (e = n->callees; e; e = e->next_callee)
511 if (!is_inexpensive_builtin (e->callee->decl))
512 num++;
513 return num;
517 /* Return true if we are interested in inlining small function. */
519 static bool
520 want_early_inline_function_p (struct cgraph_edge *e)
522 bool want_inline = true;
523 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
525 if (DECL_DISREGARD_INLINE_LIMITS (callee->decl))
527 /* For AutoFDO, we need to make sure that before profile summary, all
528 hot paths' IR look exactly the same as profiled binary. As a result,
529 in einliner, we will disregard size limit and inline those callsites
530 that are:
531 * inlined in the profiled binary, and
532 * the cloned callee has enough samples to be considered "hot". */
533 else if (flag_auto_profile && afdo_callsite_hot_enough_for_early_inline (e))
535 else if (!DECL_DECLARED_INLINE_P (callee->decl)
536 && !opt_for_fn (e->caller->decl, flag_inline_small_functions))
538 e->inline_failed = CIF_FUNCTION_NOT_INLINE_CANDIDATE;
539 report_inline_failed_reason (e);
540 want_inline = false;
542 else
544 int growth = estimate_edge_growth (e);
545 int n;
547 if (growth <= 0)
549 else if (!e->maybe_hot_p ()
550 && growth > 0)
552 if (dump_file)
553 fprintf (dump_file, " will not early inline: %s/%i->%s/%i, "
554 "call is cold and code would grow by %i\n",
555 xstrdup_for_dump (e->caller->name ()),
556 e->caller->order,
557 xstrdup_for_dump (callee->name ()), callee->order,
558 growth);
559 want_inline = false;
561 else if (growth > PARAM_VALUE (PARAM_EARLY_INLINING_INSNS))
563 if (dump_file)
564 fprintf (dump_file, " will not early inline: %s/%i->%s/%i, "
565 "growth %i exceeds --param early-inlining-insns\n",
566 xstrdup_for_dump (e->caller->name ()),
567 e->caller->order,
568 xstrdup_for_dump (callee->name ()), callee->order,
569 growth);
570 want_inline = false;
572 else if ((n = num_calls (callee)) != 0
573 && growth * (n + 1) > PARAM_VALUE (PARAM_EARLY_INLINING_INSNS))
575 if (dump_file)
576 fprintf (dump_file, " will not early inline: %s/%i->%s/%i, "
577 "growth %i exceeds --param early-inlining-insns "
578 "divided by number of calls\n",
579 xstrdup_for_dump (e->caller->name ()),
580 e->caller->order,
581 xstrdup_for_dump (callee->name ()), callee->order,
582 growth);
583 want_inline = false;
586 return want_inline;
589 /* Compute time of the edge->caller + edge->callee execution when inlining
590 does not happen. */
592 inline sreal
593 compute_uninlined_call_time (struct inline_summary *callee_info,
594 struct cgraph_edge *edge)
596 sreal uninlined_call_time = (sreal)callee_info->time;
597 cgraph_node *caller = (edge->caller->global.inlined_to
598 ? edge->caller->global.inlined_to
599 : edge->caller);
601 if (edge->count && caller->count)
602 uninlined_call_time *= (sreal)edge->count / caller->count;
603 if (edge->frequency)
604 uninlined_call_time *= cgraph_freq_base_rec * edge->frequency;
605 else
606 uninlined_call_time = uninlined_call_time >> 11;
608 int caller_time = inline_summaries->get (caller)->time;
609 return uninlined_call_time + caller_time;
612 /* Same as compute_uinlined_call_time but compute time when inlining
613 does happen. */
615 inline sreal
616 compute_inlined_call_time (struct cgraph_edge *edge,
617 int edge_time)
619 cgraph_node *caller = (edge->caller->global.inlined_to
620 ? edge->caller->global.inlined_to
621 : edge->caller);
622 int caller_time = inline_summaries->get (caller)->time;
623 sreal time = edge_time;
625 if (edge->count && caller->count)
626 time *= (sreal)edge->count / caller->count;
627 if (edge->frequency)
628 time *= cgraph_freq_base_rec * edge->frequency;
629 else
630 time = time >> 11;
632 /* This calculation should match one in ipa-inline-analysis.
633 FIXME: Once ipa-inline-analysis is converted to sreal this can be
634 simplified. */
635 time -= (sreal) ((gcov_type) edge->frequency
636 * inline_edge_summary (edge)->call_stmt_time
637 * (INLINE_TIME_SCALE / CGRAPH_FREQ_BASE)) / INLINE_TIME_SCALE;
638 time += caller_time;
639 if (time <= 0)
640 time = ((sreal) 1) >> 8;
641 gcc_checking_assert (time >= 0);
642 return time;
645 /* Return true if the speedup for inlining E is bigger than
646 PARAM_MAX_INLINE_MIN_SPEEDUP. */
648 static bool
649 big_speedup_p (struct cgraph_edge *e)
651 sreal time = compute_uninlined_call_time (inline_summaries->get (e->callee),
653 sreal inlined_time = compute_inlined_call_time (e, estimate_edge_time (e));
655 if (time - inlined_time
656 > (sreal) time * PARAM_VALUE (PARAM_INLINE_MIN_SPEEDUP)
657 * percent_rec)
658 return true;
659 return false;
662 /* Return true if we are interested in inlining small function.
663 When REPORT is true, report reason to dump file. */
665 static bool
666 want_inline_small_function_p (struct cgraph_edge *e, bool report)
668 bool want_inline = true;
669 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
671 if (DECL_DISREGARD_INLINE_LIMITS (callee->decl))
673 else if (!DECL_DECLARED_INLINE_P (callee->decl)
674 && !opt_for_fn (e->caller->decl, flag_inline_small_functions))
676 e->inline_failed = CIF_FUNCTION_NOT_INLINE_CANDIDATE;
677 want_inline = false;
679 /* Do fast and conservative check if the function can be good
680 inline candidate. At the moment we allow inline hints to
681 promote non-inline functions to inline and we increase
682 MAX_INLINE_INSNS_SINGLE 16-fold for inline functions. */
683 else if ((!DECL_DECLARED_INLINE_P (callee->decl)
684 && (!e->count || !e->maybe_hot_p ()))
685 && inline_summaries->get (callee)->min_size
686 - inline_edge_summary (e)->call_stmt_size
687 > MAX (MAX_INLINE_INSNS_SINGLE, MAX_INLINE_INSNS_AUTO))
689 e->inline_failed = CIF_MAX_INLINE_INSNS_AUTO_LIMIT;
690 want_inline = false;
692 else if ((DECL_DECLARED_INLINE_P (callee->decl) || e->count)
693 && inline_summaries->get (callee)->min_size
694 - inline_edge_summary (e)->call_stmt_size
695 > 16 * MAX_INLINE_INSNS_SINGLE)
697 e->inline_failed = (DECL_DECLARED_INLINE_P (callee->decl)
698 ? CIF_MAX_INLINE_INSNS_SINGLE_LIMIT
699 : CIF_MAX_INLINE_INSNS_AUTO_LIMIT);
700 want_inline = false;
702 else
704 int growth = estimate_edge_growth (e);
705 inline_hints hints = estimate_edge_hints (e);
706 bool big_speedup = big_speedup_p (e);
708 if (growth <= 0)
710 /* Apply MAX_INLINE_INSNS_SINGLE limit. Do not do so when
711 hints suggests that inlining given function is very profitable. */
712 else if (DECL_DECLARED_INLINE_P (callee->decl)
713 && growth >= MAX_INLINE_INSNS_SINGLE
714 && ((!big_speedup
715 && !(hints & (INLINE_HINT_indirect_call
716 | INLINE_HINT_known_hot
717 | INLINE_HINT_loop_iterations
718 | INLINE_HINT_array_index
719 | INLINE_HINT_loop_stride)))
720 || growth >= MAX_INLINE_INSNS_SINGLE * 16))
722 e->inline_failed = CIF_MAX_INLINE_INSNS_SINGLE_LIMIT;
723 want_inline = false;
725 else if (!DECL_DECLARED_INLINE_P (callee->decl)
726 && !opt_for_fn (e->caller->decl, flag_inline_functions))
728 /* growth_likely_positive is expensive, always test it last. */
729 if (growth >= MAX_INLINE_INSNS_SINGLE
730 || growth_likely_positive (callee, growth))
732 e->inline_failed = CIF_NOT_DECLARED_INLINED;
733 want_inline = false;
736 /* Apply MAX_INLINE_INSNS_AUTO limit for functions not declared inline
737 Upgrade it to MAX_INLINE_INSNS_SINGLE when hints suggests that
738 inlining given function is very profitable. */
739 else if (!DECL_DECLARED_INLINE_P (callee->decl)
740 && !big_speedup
741 && !(hints & INLINE_HINT_known_hot)
742 && growth >= ((hints & (INLINE_HINT_indirect_call
743 | INLINE_HINT_loop_iterations
744 | INLINE_HINT_array_index
745 | INLINE_HINT_loop_stride))
746 ? MAX (MAX_INLINE_INSNS_AUTO,
747 MAX_INLINE_INSNS_SINGLE)
748 : MAX_INLINE_INSNS_AUTO))
750 /* growth_likely_positive is expensive, always test it last. */
751 if (growth >= MAX_INLINE_INSNS_SINGLE
752 || growth_likely_positive (callee, growth))
754 e->inline_failed = CIF_MAX_INLINE_INSNS_AUTO_LIMIT;
755 want_inline = false;
758 /* If call is cold, do not inline when function body would grow. */
759 else if (!e->maybe_hot_p ()
760 && (growth >= MAX_INLINE_INSNS_SINGLE
761 || growth_likely_positive (callee, growth)))
763 e->inline_failed = CIF_UNLIKELY_CALL;
764 want_inline = false;
767 if (!want_inline && report)
768 report_inline_failed_reason (e);
769 return want_inline;
772 /* EDGE is self recursive edge.
773 We hand two cases - when function A is inlining into itself
774 or when function A is being inlined into another inliner copy of function
775 A within function B.
777 In first case OUTER_NODE points to the toplevel copy of A, while
778 in the second case OUTER_NODE points to the outermost copy of A in B.
780 In both cases we want to be extra selective since
781 inlining the call will just introduce new recursive calls to appear. */
783 static bool
784 want_inline_self_recursive_call_p (struct cgraph_edge *edge,
785 struct cgraph_node *outer_node,
786 bool peeling,
787 int depth)
789 char const *reason = NULL;
790 bool want_inline = true;
791 int caller_freq = CGRAPH_FREQ_BASE;
792 int max_depth = PARAM_VALUE (PARAM_MAX_INLINE_RECURSIVE_DEPTH_AUTO);
794 if (DECL_DECLARED_INLINE_P (edge->caller->decl))
795 max_depth = PARAM_VALUE (PARAM_MAX_INLINE_RECURSIVE_DEPTH);
797 if (!edge->maybe_hot_p ())
799 reason = "recursive call is cold";
800 want_inline = false;
802 else if (max_count && !outer_node->count)
804 reason = "not executed in profile";
805 want_inline = false;
807 else if (depth > max_depth)
809 reason = "--param max-inline-recursive-depth exceeded.";
810 want_inline = false;
813 if (outer_node->global.inlined_to)
814 caller_freq = outer_node->callers->frequency;
816 if (!caller_freq)
818 reason = "function is inlined and unlikely";
819 want_inline = false;
822 if (!want_inline)
824 /* Inlining of self recursive function into copy of itself within other function
825 is transformation similar to loop peeling.
827 Peeling is profitable if we can inline enough copies to make probability
828 of actual call to the self recursive function very small. Be sure that
829 the probability of recursion is small.
831 We ensure that the frequency of recursing is at most 1 - (1/max_depth).
832 This way the expected number of recision is at most max_depth. */
833 else if (peeling)
835 int max_prob = CGRAPH_FREQ_BASE - ((CGRAPH_FREQ_BASE + max_depth - 1)
836 / max_depth);
837 int i;
838 for (i = 1; i < depth; i++)
839 max_prob = max_prob * max_prob / CGRAPH_FREQ_BASE;
840 if (max_count
841 && (edge->count * CGRAPH_FREQ_BASE / outer_node->count
842 >= max_prob))
844 reason = "profile of recursive call is too large";
845 want_inline = false;
847 if (!max_count
848 && (edge->frequency * CGRAPH_FREQ_BASE / caller_freq
849 >= max_prob))
851 reason = "frequency of recursive call is too large";
852 want_inline = false;
855 /* Recursive inlining, i.e. equivalent of unrolling, is profitable if recursion
856 depth is large. We reduce function call overhead and increase chances that
857 things fit in hardware return predictor.
859 Recursive inlining might however increase cost of stack frame setup
860 actually slowing down functions whose recursion tree is wide rather than
861 deep.
863 Deciding reliably on when to do recursive inlining without profile feedback
864 is tricky. For now we disable recursive inlining when probability of self
865 recursion is low.
867 Recursive inlining of self recursive call within loop also results in large loop
868 depths that generally optimize badly. We may want to throttle down inlining
869 in those cases. In particular this seems to happen in one of libstdc++ rb tree
870 methods. */
871 else
873 if (max_count
874 && (edge->count * 100 / outer_node->count
875 <= PARAM_VALUE (PARAM_MIN_INLINE_RECURSIVE_PROBABILITY)))
877 reason = "profile of recursive call is too small";
878 want_inline = false;
880 else if (!max_count
881 && (edge->frequency * 100 / caller_freq
882 <= PARAM_VALUE (PARAM_MIN_INLINE_RECURSIVE_PROBABILITY)))
884 reason = "frequency of recursive call is too small";
885 want_inline = false;
888 if (!want_inline && dump_file)
889 fprintf (dump_file, " not inlining recursively: %s\n", reason);
890 return want_inline;
893 /* Return true when NODE has uninlinable caller;
894 set HAS_HOT_CALL if it has hot call.
895 Worker for cgraph_for_node_and_aliases. */
897 static bool
898 check_callers (struct cgraph_node *node, void *has_hot_call)
900 struct cgraph_edge *e;
901 for (e = node->callers; e; e = e->next_caller)
903 if (!opt_for_fn (e->caller->decl, flag_inline_functions_called_once))
904 return true;
905 if (!can_inline_edge_p (e, true))
906 return true;
907 if (!(*(bool *)has_hot_call) && e->maybe_hot_p ())
908 *(bool *)has_hot_call = true;
910 return false;
913 /* If NODE has a caller, return true. */
915 static bool
916 has_caller_p (struct cgraph_node *node, void *data ATTRIBUTE_UNUSED)
918 if (node->callers)
919 return true;
920 return false;
923 /* Decide if inlining NODE would reduce unit size by eliminating
924 the offline copy of function.
925 When COLD is true the cold calls are considered, too. */
927 static bool
928 want_inline_function_to_all_callers_p (struct cgraph_node *node, bool cold)
930 bool has_hot_call = false;
932 /* Aliases gets inlined along with the function they alias. */
933 if (node->alias)
934 return false;
935 /* Already inlined? */
936 if (node->global.inlined_to)
937 return false;
938 /* Does it have callers? */
939 if (!node->call_for_symbol_thunks_and_aliases (has_caller_p, NULL, true))
940 return false;
941 /* Inlining into all callers would increase size? */
942 if (estimate_growth (node) > 0)
943 return false;
944 /* All inlines must be possible. */
945 if (node->call_for_symbol_thunks_and_aliases (check_callers, &has_hot_call,
946 true))
947 return false;
948 if (!cold && !has_hot_call)
949 return false;
950 return true;
953 /* A cost model driving the inlining heuristics in a way so the edges with
954 smallest badness are inlined first. After each inlining is performed
955 the costs of all caller edges of nodes affected are recomputed so the
956 metrics may accurately depend on values such as number of inlinable callers
957 of the function or function body size. */
959 static sreal
960 edge_badness (struct cgraph_edge *edge, bool dump)
962 sreal badness;
963 int growth, edge_time;
964 struct cgraph_node *callee = edge->callee->ultimate_alias_target ();
965 struct inline_summary *callee_info = inline_summaries->get (callee);
966 inline_hints hints;
967 cgraph_node *caller = (edge->caller->global.inlined_to
968 ? edge->caller->global.inlined_to
969 : edge->caller);
971 growth = estimate_edge_growth (edge);
972 edge_time = estimate_edge_time (edge);
973 hints = estimate_edge_hints (edge);
974 gcc_checking_assert (edge_time >= 0);
975 gcc_checking_assert (edge_time <= callee_info->time);
976 gcc_checking_assert (growth <= callee_info->size);
978 if (dump)
980 fprintf (dump_file, " Badness calculation for %s/%i -> %s/%i\n",
981 xstrdup_for_dump (edge->caller->name ()),
982 edge->caller->order,
983 xstrdup_for_dump (callee->name ()),
984 edge->callee->order);
985 fprintf (dump_file, " size growth %i, time %i ",
986 growth,
987 edge_time);
988 dump_inline_hints (dump_file, hints);
989 if (big_speedup_p (edge))
990 fprintf (dump_file, " big_speedup");
991 fprintf (dump_file, "\n");
994 /* Always prefer inlining saving code size. */
995 if (growth <= 0)
997 badness = (sreal) (-SREAL_MIN_SIG + growth) << (SREAL_MAX_EXP / 256);
998 if (dump)
999 fprintf (dump_file, " %f: Growth %d <= 0\n", badness.to_double (),
1000 growth);
1002 /* Inlining into EXTERNAL functions is not going to change anything unless
1003 they are themselves inlined. */
1004 else if (DECL_EXTERNAL (caller->decl))
1006 if (dump)
1007 fprintf (dump_file, " max: function is external\n");
1008 return sreal::max ();
1010 /* When profile is available. Compute badness as:
1012 time_saved * caller_count
1013 goodness = ---------------------------------
1014 growth_of_caller * overall_growth
1016 badness = - goodness
1018 Again use negative value to make calls with profile appear hotter
1019 then calls without.
1021 else if (opt_for_fn (caller->decl, flag_guess_branch_prob) || caller->count)
1023 sreal numerator, denominator;
1025 numerator = (compute_uninlined_call_time (callee_info, edge)
1026 - compute_inlined_call_time (edge, edge_time));
1027 if (numerator == 0)
1028 numerator = ((sreal) 1 >> 8);
1029 if (caller->count)
1030 numerator *= caller->count;
1031 else if (opt_for_fn (caller->decl, flag_branch_probabilities))
1032 numerator = numerator >> 11;
1033 denominator = growth;
1034 if (callee_info->growth > 0)
1035 denominator *= callee_info->growth;
1037 badness = - numerator / denominator;
1039 if (dump)
1041 fprintf (dump_file,
1042 " %f: guessed profile. frequency %f, count %"PRId64
1043 " caller count %"PRId64
1044 " time w/o inlining %f, time w inlining %f"
1045 " overall growth %i (current) %i (original)\n",
1046 badness.to_double (), (double)edge->frequency / CGRAPH_FREQ_BASE,
1047 edge->count, caller->count,
1048 compute_uninlined_call_time (callee_info, edge).to_double (),
1049 compute_inlined_call_time (edge, edge_time).to_double (),
1050 estimate_growth (callee),
1051 callee_info->growth);
1054 /* When function local profile is not available or it does not give
1055 useful information (ie frequency is zero), base the cost on
1056 loop nest and overall size growth, so we optimize for overall number
1057 of functions fully inlined in program. */
1058 else
1060 int nest = MIN (inline_edge_summary (edge)->loop_depth, 8);
1061 badness = growth;
1063 /* Decrease badness if call is nested. */
1064 if (badness > 0)
1065 badness = badness >> nest;
1066 else
1067 badness = badness << nest;
1068 if (dump)
1069 fprintf (dump_file, " %f: no profile. nest %i\n", badness.to_double (),
1070 nest);
1072 gcc_checking_assert (badness != 0);
1074 if (edge->recursive_p ())
1075 badness = badness.shift (badness > 0 ? 4 : -4);
1076 if ((hints & (INLINE_HINT_indirect_call
1077 | INLINE_HINT_loop_iterations
1078 | INLINE_HINT_array_index
1079 | INLINE_HINT_loop_stride))
1080 || callee_info->growth <= 0)
1081 badness = badness.shift (badness > 0 ? -2 : 2);
1082 if (hints & (INLINE_HINT_same_scc))
1083 badness = badness.shift (badness > 0 ? 3 : -3);
1084 else if (hints & (INLINE_HINT_in_scc))
1085 badness = badness.shift (badness > 0 ? 2 : -2);
1086 else if (hints & (INLINE_HINT_cross_module))
1087 badness = badness.shift (badness > 0 ? 1 : -1);
1088 if (DECL_DISREGARD_INLINE_LIMITS (callee->decl))
1089 badness = badness.shift (badness > 0 ? -4 : 4);
1090 else if ((hints & INLINE_HINT_declared_inline))
1091 badness = badness.shift (badness > 0 ? -3 : 3);
1092 if (dump)
1093 fprintf (dump_file, " Adjusted by hints %f\n", badness.to_double ());
1094 return badness;
1097 /* Recompute badness of EDGE and update its key in HEAP if needed. */
1098 static inline void
1099 update_edge_key (edge_heap_t *heap, struct cgraph_edge *edge)
1101 sreal badness = edge_badness (edge, false);
1102 if (edge->aux)
1104 edge_heap_node_t *n = (edge_heap_node_t *) edge->aux;
1105 gcc_checking_assert (n->get_data () == edge);
1107 /* fibonacci_heap::replace_key does busy updating of the
1108 heap that is unnecesarily expensive.
1109 We do lazy increases: after extracting minimum if the key
1110 turns out to be out of date, it is re-inserted into heap
1111 with correct value. */
1112 if (badness < n->get_key ())
1114 if (dump_file && (dump_flags & TDF_DETAILS))
1116 fprintf (dump_file,
1117 " decreasing badness %s/%i -> %s/%i, %f"
1118 " to %f\n",
1119 xstrdup_for_dump (edge->caller->name ()),
1120 edge->caller->order,
1121 xstrdup_for_dump (edge->callee->name ()),
1122 edge->callee->order,
1123 n->get_key ().to_double (),
1124 badness.to_double ());
1126 heap->decrease_key (n, badness);
1129 else
1131 if (dump_file && (dump_flags & TDF_DETAILS))
1133 fprintf (dump_file,
1134 " enqueuing call %s/%i -> %s/%i, badness %f\n",
1135 xstrdup_for_dump (edge->caller->name ()),
1136 edge->caller->order,
1137 xstrdup_for_dump (edge->callee->name ()),
1138 edge->callee->order,
1139 badness.to_double ());
1141 edge->aux = heap->insert (badness, edge);
1146 /* NODE was inlined.
1147 All caller edges needs to be resetted because
1148 size estimates change. Similarly callees needs reset
1149 because better context may be known. */
1151 static void
1152 reset_edge_caches (struct cgraph_node *node)
1154 struct cgraph_edge *edge;
1155 struct cgraph_edge *e = node->callees;
1156 struct cgraph_node *where = node;
1157 struct ipa_ref *ref;
1159 if (where->global.inlined_to)
1160 where = where->global.inlined_to;
1162 for (edge = where->callers; edge; edge = edge->next_caller)
1163 if (edge->inline_failed)
1164 reset_edge_growth_cache (edge);
1166 FOR_EACH_ALIAS (where, ref)
1167 reset_edge_caches (dyn_cast <cgraph_node *> (ref->referring));
1169 if (!e)
1170 return;
1172 while (true)
1173 if (!e->inline_failed && e->callee->callees)
1174 e = e->callee->callees;
1175 else
1177 if (e->inline_failed)
1178 reset_edge_growth_cache (e);
1179 if (e->next_callee)
1180 e = e->next_callee;
1181 else
1185 if (e->caller == node)
1186 return;
1187 e = e->caller->callers;
1189 while (!e->next_callee);
1190 e = e->next_callee;
1195 /* Recompute HEAP nodes for each of caller of NODE.
1196 UPDATED_NODES track nodes we already visited, to avoid redundant work.
1197 When CHECK_INLINABLITY_FOR is set, re-check for specified edge that
1198 it is inlinable. Otherwise check all edges. */
1200 static void
1201 update_caller_keys (edge_heap_t *heap, struct cgraph_node *node,
1202 bitmap updated_nodes,
1203 struct cgraph_edge *check_inlinablity_for)
1205 struct cgraph_edge *edge;
1206 struct ipa_ref *ref;
1208 if ((!node->alias && !inline_summaries->get (node)->inlinable)
1209 || node->global.inlined_to)
1210 return;
1211 if (!bitmap_set_bit (updated_nodes, node->uid))
1212 return;
1214 FOR_EACH_ALIAS (node, ref)
1216 struct cgraph_node *alias = dyn_cast <cgraph_node *> (ref->referring);
1217 update_caller_keys (heap, alias, updated_nodes, check_inlinablity_for);
1220 for (edge = node->callers; edge; edge = edge->next_caller)
1221 if (edge->inline_failed)
1223 if (!check_inlinablity_for
1224 || check_inlinablity_for == edge)
1226 if (can_inline_edge_p (edge, false)
1227 && want_inline_small_function_p (edge, false))
1228 update_edge_key (heap, edge);
1229 else if (edge->aux)
1231 report_inline_failed_reason (edge);
1232 heap->delete_node ((edge_heap_node_t *) edge->aux);
1233 edge->aux = NULL;
1236 else if (edge->aux)
1237 update_edge_key (heap, edge);
1241 /* Recompute HEAP nodes for each uninlined call in NODE.
1242 This is used when we know that edge badnesses are going only to increase
1243 (we introduced new call site) and thus all we need is to insert newly
1244 created edges into heap. */
1246 static void
1247 update_callee_keys (edge_heap_t *heap, struct cgraph_node *node,
1248 bitmap updated_nodes)
1250 struct cgraph_edge *e = node->callees;
1252 if (!e)
1253 return;
1254 while (true)
1255 if (!e->inline_failed && e->callee->callees)
1256 e = e->callee->callees;
1257 else
1259 enum availability avail;
1260 struct cgraph_node *callee;
1261 /* We do not reset callee growth cache here. Since we added a new call,
1262 growth chould have just increased and consequentely badness metric
1263 don't need updating. */
1264 if (e->inline_failed
1265 && (callee = e->callee->ultimate_alias_target (&avail))
1266 && inline_summaries->get (callee)->inlinable
1267 && avail >= AVAIL_AVAILABLE
1268 && !bitmap_bit_p (updated_nodes, callee->uid))
1270 if (can_inline_edge_p (e, false)
1271 && want_inline_small_function_p (e, false))
1272 update_edge_key (heap, e);
1273 else if (e->aux)
1275 report_inline_failed_reason (e);
1276 heap->delete_node ((edge_heap_node_t *) e->aux);
1277 e->aux = NULL;
1280 if (e->next_callee)
1281 e = e->next_callee;
1282 else
1286 if (e->caller == node)
1287 return;
1288 e = e->caller->callers;
1290 while (!e->next_callee);
1291 e = e->next_callee;
1296 /* Enqueue all recursive calls from NODE into priority queue depending on
1297 how likely we want to recursively inline the call. */
1299 static void
1300 lookup_recursive_calls (struct cgraph_node *node, struct cgraph_node *where,
1301 edge_heap_t *heap)
1303 struct cgraph_edge *e;
1304 enum availability avail;
1306 for (e = where->callees; e; e = e->next_callee)
1307 if (e->callee == node
1308 || (e->callee->ultimate_alias_target (&avail) == node
1309 && avail > AVAIL_INTERPOSABLE))
1311 /* When profile feedback is available, prioritize by expected number
1312 of calls. */
1313 heap->insert (!max_count ? -e->frequency
1314 : -(e->count / ((max_count + (1<<24) - 1) / (1<<24))),
1317 for (e = where->callees; e; e = e->next_callee)
1318 if (!e->inline_failed)
1319 lookup_recursive_calls (node, e->callee, heap);
1322 /* Decide on recursive inlining: in the case function has recursive calls,
1323 inline until body size reaches given argument. If any new indirect edges
1324 are discovered in the process, add them to *NEW_EDGES, unless NEW_EDGES
1325 is NULL. */
1327 static bool
1328 recursive_inlining (struct cgraph_edge *edge,
1329 vec<cgraph_edge *> *new_edges)
1331 int limit = PARAM_VALUE (PARAM_MAX_INLINE_INSNS_RECURSIVE_AUTO);
1332 edge_heap_t heap (sreal::min ());
1333 struct cgraph_node *node;
1334 struct cgraph_edge *e;
1335 struct cgraph_node *master_clone = NULL, *next;
1336 int depth = 0;
1337 int n = 0;
1339 node = edge->caller;
1340 if (node->global.inlined_to)
1341 node = node->global.inlined_to;
1343 if (DECL_DECLARED_INLINE_P (node->decl))
1344 limit = PARAM_VALUE (PARAM_MAX_INLINE_INSNS_RECURSIVE);
1346 /* Make sure that function is small enough to be considered for inlining. */
1347 if (estimate_size_after_inlining (node, edge) >= limit)
1348 return false;
1349 lookup_recursive_calls (node, node, &heap);
1350 if (heap.empty ())
1351 return false;
1353 if (dump_file)
1354 fprintf (dump_file,
1355 " Performing recursive inlining on %s\n",
1356 node->name ());
1358 /* Do the inlining and update list of recursive call during process. */
1359 while (!heap.empty ())
1361 struct cgraph_edge *curr = heap.extract_min ();
1362 struct cgraph_node *cnode, *dest = curr->callee;
1364 if (!can_inline_edge_p (curr, true))
1365 continue;
1367 /* MASTER_CLONE is produced in the case we already started modified
1368 the function. Be sure to redirect edge to the original body before
1369 estimating growths otherwise we will be seeing growths after inlining
1370 the already modified body. */
1371 if (master_clone)
1373 curr->redirect_callee (master_clone);
1374 reset_edge_growth_cache (curr);
1377 if (estimate_size_after_inlining (node, curr) > limit)
1379 curr->redirect_callee (dest);
1380 reset_edge_growth_cache (curr);
1381 break;
1384 depth = 1;
1385 for (cnode = curr->caller;
1386 cnode->global.inlined_to; cnode = cnode->callers->caller)
1387 if (node->decl
1388 == curr->callee->ultimate_alias_target ()->decl)
1389 depth++;
1391 if (!want_inline_self_recursive_call_p (curr, node, false, depth))
1393 curr->redirect_callee (dest);
1394 reset_edge_growth_cache (curr);
1395 continue;
1398 if (dump_file)
1400 fprintf (dump_file,
1401 " Inlining call of depth %i", depth);
1402 if (node->count)
1404 fprintf (dump_file, " called approx. %.2f times per call",
1405 (double)curr->count / node->count);
1407 fprintf (dump_file, "\n");
1409 if (!master_clone)
1411 /* We need original clone to copy around. */
1412 master_clone = node->create_clone (node->decl, node->count,
1413 CGRAPH_FREQ_BASE, false, vNULL,
1414 true, NULL, NULL);
1415 for (e = master_clone->callees; e; e = e->next_callee)
1416 if (!e->inline_failed)
1417 clone_inlined_nodes (e, true, false, NULL, CGRAPH_FREQ_BASE);
1418 curr->redirect_callee (master_clone);
1419 reset_edge_growth_cache (curr);
1422 inline_call (curr, false, new_edges, &overall_size, true);
1423 lookup_recursive_calls (node, curr->callee, &heap);
1424 n++;
1427 if (!heap.empty () && dump_file)
1428 fprintf (dump_file, " Recursive inlining growth limit met.\n");
1430 if (!master_clone)
1431 return false;
1433 if (dump_file)
1434 fprintf (dump_file,
1435 "\n Inlined %i times, "
1436 "body grown from size %i to %i, time %i to %i\n", n,
1437 inline_summaries->get (master_clone)->size, inline_summaries->get (node)->size,
1438 inline_summaries->get (master_clone)->time, inline_summaries->get (node)->time);
1440 /* Remove master clone we used for inlining. We rely that clones inlined
1441 into master clone gets queued just before master clone so we don't
1442 need recursion. */
1443 for (node = symtab->first_function (); node != master_clone;
1444 node = next)
1446 next = symtab->next_function (node);
1447 if (node->global.inlined_to == master_clone)
1448 node->remove ();
1450 master_clone->remove ();
1451 return true;
1455 /* Given whole compilation unit estimate of INSNS, compute how large we can
1456 allow the unit to grow. */
1458 static int
1459 compute_max_insns (int insns)
1461 int max_insns = insns;
1462 if (max_insns < PARAM_VALUE (PARAM_LARGE_UNIT_INSNS))
1463 max_insns = PARAM_VALUE (PARAM_LARGE_UNIT_INSNS);
1465 return ((int64_t) max_insns
1466 * (100 + PARAM_VALUE (PARAM_INLINE_UNIT_GROWTH)) / 100);
1470 /* Compute badness of all edges in NEW_EDGES and add them to the HEAP. */
1472 static void
1473 add_new_edges_to_heap (edge_heap_t *heap, vec<cgraph_edge *> new_edges)
1475 while (new_edges.length () > 0)
1477 struct cgraph_edge *edge = new_edges.pop ();
1479 gcc_assert (!edge->aux);
1480 if (edge->inline_failed
1481 && can_inline_edge_p (edge, true)
1482 && want_inline_small_function_p (edge, true))
1483 edge->aux = heap->insert (edge_badness (edge, false), edge);
1487 /* Remove EDGE from the fibheap. */
1489 static void
1490 heap_edge_removal_hook (struct cgraph_edge *e, void *data)
1492 if (e->aux)
1494 ((edge_heap_t *)data)->delete_node ((edge_heap_node_t *)e->aux);
1495 e->aux = NULL;
1499 /* Return true if speculation of edge E seems useful.
1500 If ANTICIPATE_INLINING is true, be conservative and hope that E
1501 may get inlined. */
1503 bool
1504 speculation_useful_p (struct cgraph_edge *e, bool anticipate_inlining)
1506 enum availability avail;
1507 struct cgraph_node *target = e->callee->ultimate_alias_target (&avail);
1508 struct cgraph_edge *direct, *indirect;
1509 struct ipa_ref *ref;
1511 gcc_assert (e->speculative && !e->indirect_unknown_callee);
1513 if (!e->maybe_hot_p ())
1514 return false;
1516 /* See if IP optimizations found something potentially useful about the
1517 function. For now we look only for CONST/PURE flags. Almost everything
1518 else we propagate is useless. */
1519 if (avail >= AVAIL_AVAILABLE)
1521 int ecf_flags = flags_from_decl_or_type (target->decl);
1522 if (ecf_flags & ECF_CONST)
1524 e->speculative_call_info (direct, indirect, ref);
1525 if (!(indirect->indirect_info->ecf_flags & ECF_CONST))
1526 return true;
1528 else if (ecf_flags & ECF_PURE)
1530 e->speculative_call_info (direct, indirect, ref);
1531 if (!(indirect->indirect_info->ecf_flags & ECF_PURE))
1532 return true;
1535 /* If we did not managed to inline the function nor redirect
1536 to an ipa-cp clone (that are seen by having local flag set),
1537 it is probably pointless to inline it unless hardware is missing
1538 indirect call predictor. */
1539 if (!anticipate_inlining && e->inline_failed && !target->local.local)
1540 return false;
1541 /* For overwritable targets there is not much to do. */
1542 if (e->inline_failed && !can_inline_edge_p (e, false, true))
1543 return false;
1544 /* OK, speculation seems interesting. */
1545 return true;
1548 /* We know that EDGE is not going to be inlined.
1549 See if we can remove speculation. */
1551 static void
1552 resolve_noninline_speculation (edge_heap_t *edge_heap, struct cgraph_edge *edge)
1554 if (edge->speculative && !speculation_useful_p (edge, false))
1556 struct cgraph_node *node = edge->caller;
1557 struct cgraph_node *where = node->global.inlined_to
1558 ? node->global.inlined_to : node;
1559 bitmap updated_nodes = BITMAP_ALLOC (NULL);
1561 spec_rem += edge->count;
1562 edge->resolve_speculation ();
1563 reset_edge_caches (where);
1564 inline_update_overall_summary (where);
1565 update_caller_keys (edge_heap, where,
1566 updated_nodes, NULL);
1567 update_callee_keys (edge_heap, where,
1568 updated_nodes);
1569 BITMAP_FREE (updated_nodes);
1573 /* Return true if NODE should be accounted for overall size estimate.
1574 Skip all nodes optimized for size so we can measure the growth of hot
1575 part of program no matter of the padding. */
1577 bool
1578 inline_account_function_p (struct cgraph_node *node)
1580 return (!DECL_EXTERNAL (node->decl)
1581 && !opt_for_fn (node->decl, optimize_size)
1582 && node->frequency != NODE_FREQUENCY_UNLIKELY_EXECUTED);
1585 /* We use greedy algorithm for inlining of small functions:
1586 All inline candidates are put into prioritized heap ordered in
1587 increasing badness.
1589 The inlining of small functions is bounded by unit growth parameters. */
1591 static void
1592 inline_small_functions (void)
1594 struct cgraph_node *node;
1595 struct cgraph_edge *edge;
1596 edge_heap_t edge_heap (sreal::min ());
1597 bitmap updated_nodes = BITMAP_ALLOC (NULL);
1598 int min_size, max_size;
1599 auto_vec<cgraph_edge *> new_indirect_edges;
1600 int initial_size = 0;
1601 struct cgraph_node **order = XCNEWVEC (cgraph_node *, symtab->cgraph_count);
1602 struct cgraph_edge_hook_list *edge_removal_hook_holder;
1603 new_indirect_edges.create (8);
1605 edge_removal_hook_holder
1606 = symtab->add_edge_removal_hook (&heap_edge_removal_hook, &edge_heap);
1608 /* Compute overall unit size and other global parameters used by badness
1609 metrics. */
1611 max_count = 0;
1612 ipa_reduced_postorder (order, true, true, NULL);
1613 free (order);
1615 FOR_EACH_DEFINED_FUNCTION (node)
1616 if (!node->global.inlined_to)
1618 if (!node->alias && node->analyzed
1619 && (node->has_gimple_body_p () || node->thunk.thunk_p))
1621 struct inline_summary *info = inline_summaries->get (node);
1622 struct ipa_dfs_info *dfs = (struct ipa_dfs_info *) node->aux;
1624 /* Do not account external functions, they will be optimized out
1625 if not inlined. Also only count the non-cold portion of program. */
1626 if (inline_account_function_p (node))
1627 initial_size += info->size;
1628 info->growth = estimate_growth (node);
1629 if (dfs && dfs->next_cycle)
1631 struct cgraph_node *n2;
1632 int id = dfs->scc_no + 1;
1633 for (n2 = node; n2;
1634 n2 = ((struct ipa_dfs_info *) node->aux)->next_cycle)
1636 struct inline_summary *info2 = inline_summaries->get (n2);
1637 if (info2->scc_no)
1638 break;
1639 info2->scc_no = id;
1644 for (edge = node->callers; edge; edge = edge->next_caller)
1645 if (max_count < edge->count)
1646 max_count = edge->count;
1648 ipa_free_postorder_info ();
1649 initialize_growth_caches ();
1651 if (dump_file)
1652 fprintf (dump_file,
1653 "\nDeciding on inlining of small functions. Starting with size %i.\n",
1654 initial_size);
1656 overall_size = initial_size;
1657 max_size = compute_max_insns (overall_size);
1658 min_size = overall_size;
1660 /* Populate the heap with all edges we might inline. */
1662 FOR_EACH_DEFINED_FUNCTION (node)
1664 bool update = false;
1665 struct cgraph_edge *next;
1667 if (dump_file)
1668 fprintf (dump_file, "Enqueueing calls in %s/%i.\n",
1669 node->name (), node->order);
1671 for (edge = node->callees; edge; edge = next)
1673 next = edge->next_callee;
1674 if (edge->inline_failed
1675 && !edge->aux
1676 && can_inline_edge_p (edge, true)
1677 && want_inline_small_function_p (edge, true)
1678 && edge->inline_failed)
1680 gcc_assert (!edge->aux);
1681 update_edge_key (&edge_heap, edge);
1683 if (edge->speculative && !speculation_useful_p (edge, edge->aux != NULL))
1685 edge->resolve_speculation ();
1686 update = true;
1689 if (update)
1691 struct cgraph_node *where = node->global.inlined_to
1692 ? node->global.inlined_to : node;
1693 inline_update_overall_summary (where);
1694 reset_edge_caches (where);
1695 update_caller_keys (&edge_heap, where,
1696 updated_nodes, NULL);
1697 update_callee_keys (&edge_heap, where,
1698 updated_nodes);
1699 bitmap_clear (updated_nodes);
1703 gcc_assert (in_lto_p
1704 || !max_count
1705 || (profile_info && flag_branch_probabilities));
1707 while (!edge_heap.empty ())
1709 int old_size = overall_size;
1710 struct cgraph_node *where, *callee;
1711 sreal badness = edge_heap.min_key ();
1712 sreal current_badness;
1713 int growth;
1715 edge = edge_heap.extract_min ();
1716 gcc_assert (edge->aux);
1717 edge->aux = NULL;
1718 if (!edge->inline_failed || !edge->callee->analyzed)
1719 continue;
1721 #ifdef ENABLE_CHECKING
1722 /* Be sure that caches are maintained consistent. */
1723 sreal cached_badness = edge_badness (edge, false);
1725 int old_size_est = estimate_edge_size (edge);
1726 int old_time_est = estimate_edge_time (edge);
1727 int old_hints_est = estimate_edge_hints (edge);
1729 reset_edge_growth_cache (edge);
1730 gcc_assert (old_size_est == estimate_edge_size (edge));
1731 gcc_assert (old_time_est == estimate_edge_time (edge));
1732 /* FIXME:
1734 gcc_assert (old_hints_est == estimate_edge_hints (edge));
1736 fails with profile feedback because some hints depends on
1737 maybe_hot_edge_p predicate and because callee gets inlined to other
1738 calls, the edge may become cold.
1739 This ought to be fixed by computing relative probabilities
1740 for given invocation but that will be better done once whole
1741 code is converted to sreals. Disable for now and revert to "wrong"
1742 value so enable/disable checking paths agree. */
1743 edge_growth_cache[edge->uid].hints = old_hints_est + 1;
1745 /* When updating the edge costs, we only decrease badness in the keys.
1746 Increases of badness are handled lazilly; when we see key with out
1747 of date value on it, we re-insert it now. */
1748 current_badness = edge_badness (edge, false);
1749 /* Disable checking for profile because roundoff errors may cause slight
1750 deviations in the order. */
1751 gcc_assert (max_count || cached_badness == current_badness);
1752 gcc_assert (current_badness >= badness);
1753 #else
1754 current_badness = edge_badness (edge, false);
1755 #endif
1756 if (current_badness != badness)
1758 if (edge_heap.min () && badness > edge_heap.min_key ())
1760 edge->aux = edge_heap.insert (current_badness, edge);
1761 continue;
1763 else
1764 badness = current_badness;
1767 if (!can_inline_edge_p (edge, true))
1769 resolve_noninline_speculation (&edge_heap, edge);
1770 continue;
1773 callee = edge->callee->ultimate_alias_target ();
1774 growth = estimate_edge_growth (edge);
1775 if (dump_file)
1777 fprintf (dump_file,
1778 "\nConsidering %s/%i with %i size\n",
1779 callee->name (), callee->order,
1780 inline_summaries->get (callee)->size);
1781 fprintf (dump_file,
1782 " to be inlined into %s/%i in %s:%i\n"
1783 " Estimated badness is %f, frequency %.2f.\n",
1784 edge->caller->name (), edge->caller->order,
1785 edge->call_stmt
1786 ? gimple_filename ((const_gimple) edge->call_stmt)
1787 : "unknown",
1788 edge->call_stmt
1789 ? gimple_lineno ((const_gimple) edge->call_stmt)
1790 : -1,
1791 badness.to_double (),
1792 edge->frequency / (double)CGRAPH_FREQ_BASE);
1793 if (edge->count)
1794 fprintf (dump_file," Called %"PRId64"x\n",
1795 edge->count);
1796 if (dump_flags & TDF_DETAILS)
1797 edge_badness (edge, true);
1800 if (overall_size + growth > max_size
1801 && !DECL_DISREGARD_INLINE_LIMITS (callee->decl))
1803 edge->inline_failed = CIF_INLINE_UNIT_GROWTH_LIMIT;
1804 report_inline_failed_reason (edge);
1805 resolve_noninline_speculation (&edge_heap, edge);
1806 continue;
1809 if (!want_inline_small_function_p (edge, true))
1811 resolve_noninline_speculation (&edge_heap, edge);
1812 continue;
1815 /* Heuristics for inlining small functions work poorly for
1816 recursive calls where we do effects similar to loop unrolling.
1817 When inlining such edge seems profitable, leave decision on
1818 specific inliner. */
1819 if (edge->recursive_p ())
1821 where = edge->caller;
1822 if (where->global.inlined_to)
1823 where = where->global.inlined_to;
1824 if (!recursive_inlining (edge,
1825 opt_for_fn (edge->caller->decl,
1826 flag_indirect_inlining)
1827 ? &new_indirect_edges : NULL))
1829 edge->inline_failed = CIF_RECURSIVE_INLINING;
1830 resolve_noninline_speculation (&edge_heap, edge);
1831 continue;
1833 reset_edge_caches (where);
1834 /* Recursive inliner inlines all recursive calls of the function
1835 at once. Consequently we need to update all callee keys. */
1836 if (opt_for_fn (edge->caller->decl, flag_indirect_inlining))
1837 add_new_edges_to_heap (&edge_heap, new_indirect_edges);
1838 update_callee_keys (&edge_heap, where, updated_nodes);
1839 bitmap_clear (updated_nodes);
1841 else
1843 struct cgraph_node *outer_node = NULL;
1844 int depth = 0;
1846 /* Consider the case where self recursive function A is inlined
1847 into B. This is desired optimization in some cases, since it
1848 leads to effect similar of loop peeling and we might completely
1849 optimize out the recursive call. However we must be extra
1850 selective. */
1852 where = edge->caller;
1853 while (where->global.inlined_to)
1855 if (where->decl == callee->decl)
1856 outer_node = where, depth++;
1857 where = where->callers->caller;
1859 if (outer_node
1860 && !want_inline_self_recursive_call_p (edge, outer_node,
1861 true, depth))
1863 edge->inline_failed
1864 = (DECL_DISREGARD_INLINE_LIMITS (edge->callee->decl)
1865 ? CIF_RECURSIVE_INLINING : CIF_UNSPECIFIED);
1866 resolve_noninline_speculation (&edge_heap, edge);
1867 continue;
1869 else if (depth && dump_file)
1870 fprintf (dump_file, " Peeling recursion with depth %i\n", depth);
1872 gcc_checking_assert (!callee->global.inlined_to);
1873 inline_call (edge, true, &new_indirect_edges, &overall_size, true);
1874 add_new_edges_to_heap (&edge_heap, new_indirect_edges);
1876 reset_edge_caches (edge->callee->function_symbol ());
1878 update_callee_keys (&edge_heap, where, updated_nodes);
1880 where = edge->caller;
1881 if (where->global.inlined_to)
1882 where = where->global.inlined_to;
1884 /* Our profitability metric can depend on local properties
1885 such as number of inlinable calls and size of the function body.
1886 After inlining these properties might change for the function we
1887 inlined into (since it's body size changed) and for the functions
1888 called by function we inlined (since number of it inlinable callers
1889 might change). */
1890 update_caller_keys (&edge_heap, where, updated_nodes, NULL);
1891 /* Offline copy count has possibly changed, recompute if profile is
1892 available. */
1893 if (max_count)
1895 struct cgraph_node *n = cgraph_node::get (edge->callee->decl);
1896 if (n != edge->callee && n->analyzed)
1897 update_callee_keys (&edge_heap, n, updated_nodes);
1899 bitmap_clear (updated_nodes);
1901 if (dump_file)
1903 fprintf (dump_file,
1904 " Inlined into %s which now has time %i and size %i,"
1905 "net change of %+i.\n",
1906 edge->caller->name (),
1907 inline_summaries->get (edge->caller)->time,
1908 inline_summaries->get (edge->caller)->size,
1909 overall_size - old_size);
1911 if (min_size > overall_size)
1913 min_size = overall_size;
1914 max_size = compute_max_insns (min_size);
1916 if (dump_file)
1917 fprintf (dump_file, "New minimal size reached: %i\n", min_size);
1921 free_growth_caches ();
1922 if (dump_file)
1923 fprintf (dump_file,
1924 "Unit growth for small function inlining: %i->%i (%i%%)\n",
1925 initial_size, overall_size,
1926 initial_size ? overall_size * 100 / (initial_size) - 100: 0);
1927 BITMAP_FREE (updated_nodes);
1928 symtab->remove_edge_removal_hook (edge_removal_hook_holder);
1931 /* Flatten NODE. Performed both during early inlining and
1932 at IPA inlining time. */
1934 static void
1935 flatten_function (struct cgraph_node *node, bool early)
1937 struct cgraph_edge *e;
1939 /* We shouldn't be called recursively when we are being processed. */
1940 gcc_assert (node->aux == NULL);
1942 node->aux = (void *) node;
1944 for (e = node->callees; e; e = e->next_callee)
1946 struct cgraph_node *orig_callee;
1947 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
1949 /* We've hit cycle? It is time to give up. */
1950 if (callee->aux)
1952 if (dump_file)
1953 fprintf (dump_file,
1954 "Not inlining %s into %s to avoid cycle.\n",
1955 xstrdup_for_dump (callee->name ()),
1956 xstrdup_for_dump (e->caller->name ()));
1957 e->inline_failed = CIF_RECURSIVE_INLINING;
1958 continue;
1961 /* When the edge is already inlined, we just need to recurse into
1962 it in order to fully flatten the leaves. */
1963 if (!e->inline_failed)
1965 flatten_function (callee, early);
1966 continue;
1969 /* Flatten attribute needs to be processed during late inlining. For
1970 extra code quality we however do flattening during early optimization,
1971 too. */
1972 if (!early
1973 ? !can_inline_edge_p (e, true)
1974 : !can_early_inline_edge_p (e))
1975 continue;
1977 if (e->recursive_p ())
1979 if (dump_file)
1980 fprintf (dump_file, "Not inlining: recursive call.\n");
1981 continue;
1984 if (gimple_in_ssa_p (DECL_STRUCT_FUNCTION (node->decl))
1985 != gimple_in_ssa_p (DECL_STRUCT_FUNCTION (callee->decl)))
1987 if (dump_file)
1988 fprintf (dump_file, "Not inlining: SSA form does not match.\n");
1989 continue;
1992 /* Inline the edge and flatten the inline clone. Avoid
1993 recursing through the original node if the node was cloned. */
1994 if (dump_file)
1995 fprintf (dump_file, " Inlining %s into %s.\n",
1996 xstrdup_for_dump (callee->name ()),
1997 xstrdup_for_dump (e->caller->name ()));
1998 orig_callee = callee;
1999 inline_call (e, true, NULL, NULL, false);
2000 if (e->callee != orig_callee)
2001 orig_callee->aux = (void *) node;
2002 flatten_function (e->callee, early);
2003 if (e->callee != orig_callee)
2004 orig_callee->aux = NULL;
2007 node->aux = NULL;
2008 if (!node->global.inlined_to)
2009 inline_update_overall_summary (node);
2012 /* Count number of callers of NODE and store it into DATA (that
2013 points to int. Worker for cgraph_for_node_and_aliases. */
2015 static bool
2016 sum_callers (struct cgraph_node *node, void *data)
2018 struct cgraph_edge *e;
2019 int *num_calls = (int *)data;
2021 for (e = node->callers; e; e = e->next_caller)
2022 (*num_calls)++;
2023 return false;
2026 /* Inline NODE to all callers. Worker for cgraph_for_node_and_aliases.
2027 DATA points to number of calls originally found so we avoid infinite
2028 recursion. */
2030 static bool
2031 inline_to_all_callers (struct cgraph_node *node, void *data)
2033 int *num_calls = (int *)data;
2034 bool callee_removed = false;
2036 while (node->callers && !node->global.inlined_to)
2038 struct cgraph_node *caller = node->callers->caller;
2040 if (dump_file)
2042 fprintf (dump_file,
2043 "\nInlining %s size %i.\n",
2044 node->name (),
2045 inline_summaries->get (node)->size);
2046 fprintf (dump_file,
2047 " Called once from %s %i insns.\n",
2048 node->callers->caller->name (),
2049 inline_summaries->get (node->callers->caller)->size);
2052 inline_call (node->callers, true, NULL, NULL, true, &callee_removed);
2053 if (dump_file)
2054 fprintf (dump_file,
2055 " Inlined into %s which now has %i size\n",
2056 caller->name (),
2057 inline_summaries->get (caller)->size);
2058 if (!(*num_calls)--)
2060 if (dump_file)
2061 fprintf (dump_file, "New calls found; giving up.\n");
2062 return callee_removed;
2064 if (callee_removed)
2065 return true;
2067 return false;
2070 /* Output overall time estimate. */
2071 static void
2072 dump_overall_stats (void)
2074 int64_t sum_weighted = 0, sum = 0;
2075 struct cgraph_node *node;
2077 FOR_EACH_DEFINED_FUNCTION (node)
2078 if (!node->global.inlined_to
2079 && !node->alias)
2081 int time = inline_summaries->get (node)->time;
2082 sum += time;
2083 sum_weighted += time * node->count;
2085 fprintf (dump_file, "Overall time estimate: "
2086 "%"PRId64" weighted by profile: "
2087 "%"PRId64"\n", sum, sum_weighted);
2090 /* Output some useful stats about inlining. */
2092 static void
2093 dump_inline_stats (void)
2095 int64_t inlined_cnt = 0, inlined_indir_cnt = 0;
2096 int64_t inlined_virt_cnt = 0, inlined_virt_indir_cnt = 0;
2097 int64_t noninlined_cnt = 0, noninlined_indir_cnt = 0;
2098 int64_t noninlined_virt_cnt = 0, noninlined_virt_indir_cnt = 0;
2099 int64_t inlined_speculative = 0, inlined_speculative_ply = 0;
2100 int64_t indirect_poly_cnt = 0, indirect_cnt = 0;
2101 int64_t reason[CIF_N_REASONS][3];
2102 int i;
2103 struct cgraph_node *node;
2105 memset (reason, 0, sizeof (reason));
2106 FOR_EACH_DEFINED_FUNCTION (node)
2108 struct cgraph_edge *e;
2109 for (e = node->callees; e; e = e->next_callee)
2111 if (e->inline_failed)
2113 reason[(int) e->inline_failed][0] += e->count;
2114 reason[(int) e->inline_failed][1] += e->frequency;
2115 reason[(int) e->inline_failed][2] ++;
2116 if (DECL_VIRTUAL_P (e->callee->decl))
2118 if (e->indirect_inlining_edge)
2119 noninlined_virt_indir_cnt += e->count;
2120 else
2121 noninlined_virt_cnt += e->count;
2123 else
2125 if (e->indirect_inlining_edge)
2126 noninlined_indir_cnt += e->count;
2127 else
2128 noninlined_cnt += e->count;
2131 else
2133 if (e->speculative)
2135 if (DECL_VIRTUAL_P (e->callee->decl))
2136 inlined_speculative_ply += e->count;
2137 else
2138 inlined_speculative += e->count;
2140 else if (DECL_VIRTUAL_P (e->callee->decl))
2142 if (e->indirect_inlining_edge)
2143 inlined_virt_indir_cnt += e->count;
2144 else
2145 inlined_virt_cnt += e->count;
2147 else
2149 if (e->indirect_inlining_edge)
2150 inlined_indir_cnt += e->count;
2151 else
2152 inlined_cnt += e->count;
2156 for (e = node->indirect_calls; e; e = e->next_callee)
2157 if (e->indirect_info->polymorphic)
2158 indirect_poly_cnt += e->count;
2159 else
2160 indirect_cnt += e->count;
2162 if (max_count)
2164 fprintf (dump_file,
2165 "Inlined %"PRId64 " + speculative "
2166 "%"PRId64 " + speculative polymorphic "
2167 "%"PRId64 " + previously indirect "
2168 "%"PRId64 " + virtual "
2169 "%"PRId64 " + virtual and previously indirect "
2170 "%"PRId64 "\n" "Not inlined "
2171 "%"PRId64 " + previously indirect "
2172 "%"PRId64 " + virtual "
2173 "%"PRId64 " + virtual and previously indirect "
2174 "%"PRId64 " + stil indirect "
2175 "%"PRId64 " + still indirect polymorphic "
2176 "%"PRId64 "\n", inlined_cnt,
2177 inlined_speculative, inlined_speculative_ply,
2178 inlined_indir_cnt, inlined_virt_cnt, inlined_virt_indir_cnt,
2179 noninlined_cnt, noninlined_indir_cnt, noninlined_virt_cnt,
2180 noninlined_virt_indir_cnt, indirect_cnt, indirect_poly_cnt);
2181 fprintf (dump_file,
2182 "Removed speculations %"PRId64 "\n",
2183 spec_rem);
2185 dump_overall_stats ();
2186 fprintf (dump_file, "\nWhy inlining failed?\n");
2187 for (i = 0; i < CIF_N_REASONS; i++)
2188 if (reason[i][2])
2189 fprintf (dump_file, "%-50s: %8i calls, %8i freq, %"PRId64" count\n",
2190 cgraph_inline_failed_string ((cgraph_inline_failed_t) i),
2191 (int) reason[i][2], (int) reason[i][1], reason[i][0]);
2194 /* Decide on the inlining. We do so in the topological order to avoid
2195 expenses on updating data structures. */
2197 static unsigned int
2198 ipa_inline (void)
2200 struct cgraph_node *node;
2201 int nnodes;
2202 struct cgraph_node **order;
2203 int i;
2204 int cold;
2205 bool remove_functions = false;
2207 if (!optimize)
2208 return 0;
2210 cgraph_freq_base_rec = (sreal) 1 / (sreal) CGRAPH_FREQ_BASE;
2211 percent_rec = (sreal) 1 / (sreal) 100;
2213 order = XCNEWVEC (struct cgraph_node *, symtab->cgraph_count);
2215 if (in_lto_p && optimize)
2216 ipa_update_after_lto_read ();
2218 if (dump_file)
2219 dump_inline_summaries (dump_file);
2221 nnodes = ipa_reverse_postorder (order);
2223 FOR_EACH_FUNCTION (node)
2224 node->aux = 0;
2226 if (dump_file)
2227 fprintf (dump_file, "\nFlattening functions:\n");
2229 /* In the first pass handle functions to be flattened. Do this with
2230 a priority so none of our later choices will make this impossible. */
2231 for (i = nnodes - 1; i >= 0; i--)
2233 node = order[i];
2235 /* Handle nodes to be flattened.
2236 Ideally when processing callees we stop inlining at the
2237 entry of cycles, possibly cloning that entry point and
2238 try to flatten itself turning it into a self-recursive
2239 function. */
2240 if (lookup_attribute ("flatten",
2241 DECL_ATTRIBUTES (node->decl)) != NULL)
2243 if (dump_file)
2244 fprintf (dump_file,
2245 "Flattening %s\n", node->name ());
2246 flatten_function (node, false);
2249 if (dump_file)
2250 dump_overall_stats ();
2252 inline_small_functions ();
2254 gcc_assert (symtab->state == IPA_SSA);
2255 symtab->state = IPA_SSA_AFTER_INLINING;
2256 /* Do first after-inlining removal. We want to remove all "stale" extern
2257 inline functions and virtual functions so we really know what is called
2258 once. */
2259 symtab->remove_unreachable_nodes (dump_file);
2260 free (order);
2262 /* Inline functions with a property that after inlining into all callers the
2263 code size will shrink because the out-of-line copy is eliminated.
2264 We do this regardless on the callee size as long as function growth limits
2265 are met. */
2266 if (dump_file)
2267 fprintf (dump_file,
2268 "\nDeciding on functions to be inlined into all callers and "
2269 "removing useless speculations:\n");
2271 /* Inlining one function called once has good chance of preventing
2272 inlining other function into the same callee. Ideally we should
2273 work in priority order, but probably inlining hot functions first
2274 is good cut without the extra pain of maintaining the queue.
2276 ??? this is not really fitting the bill perfectly: inlining function
2277 into callee often leads to better optimization of callee due to
2278 increased context for optimization.
2279 For example if main() function calls a function that outputs help
2280 and then function that does the main optmization, we should inline
2281 the second with priority even if both calls are cold by themselves.
2283 We probably want to implement new predicate replacing our use of
2284 maybe_hot_edge interpreted as maybe_hot_edge || callee is known
2285 to be hot. */
2286 for (cold = 0; cold <= 1; cold ++)
2288 FOR_EACH_DEFINED_FUNCTION (node)
2290 struct cgraph_edge *edge, *next;
2291 bool update=false;
2293 for (edge = node->callees; edge; edge = next)
2295 next = edge->next_callee;
2296 if (edge->speculative && !speculation_useful_p (edge, false))
2298 edge->resolve_speculation ();
2299 spec_rem += edge->count;
2300 update = true;
2301 remove_functions = true;
2304 if (update)
2306 struct cgraph_node *where = node->global.inlined_to
2307 ? node->global.inlined_to : node;
2308 reset_edge_caches (where);
2309 inline_update_overall_summary (where);
2311 if (want_inline_function_to_all_callers_p (node, cold))
2313 int num_calls = 0;
2314 node->call_for_symbol_thunks_and_aliases (sum_callers, &num_calls,
2315 true);
2316 while (node->call_for_symbol_thunks_and_aliases
2317 (inline_to_all_callers, &num_calls, true))
2319 remove_functions = true;
2324 /* Free ipa-prop structures if they are no longer needed. */
2325 if (optimize)
2326 ipa_free_all_structures_after_iinln ();
2328 if (dump_file)
2330 fprintf (dump_file,
2331 "\nInlined %i calls, eliminated %i functions\n\n",
2332 ncalls_inlined, nfunctions_inlined);
2333 dump_inline_stats ();
2336 if (dump_file)
2337 dump_inline_summaries (dump_file);
2338 /* In WPA we use inline summaries for partitioning process. */
2339 if (!flag_wpa)
2340 inline_free_summary ();
2341 return remove_functions ? TODO_remove_functions : 0;
2344 /* Inline always-inline function calls in NODE. */
2346 static bool
2347 inline_always_inline_functions (struct cgraph_node *node)
2349 struct cgraph_edge *e;
2350 bool inlined = false;
2352 for (e = node->callees; e; e = e->next_callee)
2354 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
2355 if (!DECL_DISREGARD_INLINE_LIMITS (callee->decl))
2356 continue;
2358 if (e->recursive_p ())
2360 if (dump_file)
2361 fprintf (dump_file, " Not inlining recursive call to %s.\n",
2362 e->callee->name ());
2363 e->inline_failed = CIF_RECURSIVE_INLINING;
2364 continue;
2367 if (!can_early_inline_edge_p (e))
2369 /* Set inlined to true if the callee is marked "always_inline" but
2370 is not inlinable. This will allow flagging an error later in
2371 expand_call_inline in tree-inline.c. */
2372 if (lookup_attribute ("always_inline",
2373 DECL_ATTRIBUTES (callee->decl)) != NULL)
2374 inlined = true;
2375 continue;
2378 if (dump_file)
2379 fprintf (dump_file, " Inlining %s into %s (always_inline).\n",
2380 xstrdup_for_dump (e->callee->name ()),
2381 xstrdup_for_dump (e->caller->name ()));
2382 inline_call (e, true, NULL, NULL, false);
2383 inlined = true;
2385 if (inlined)
2386 inline_update_overall_summary (node);
2388 return inlined;
2391 /* Decide on the inlining. We do so in the topological order to avoid
2392 expenses on updating data structures. */
2394 static bool
2395 early_inline_small_functions (struct cgraph_node *node)
2397 struct cgraph_edge *e;
2398 bool inlined = false;
2400 for (e = node->callees; e; e = e->next_callee)
2402 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
2403 if (!inline_summaries->get (callee)->inlinable
2404 || !e->inline_failed)
2405 continue;
2407 /* Do not consider functions not declared inline. */
2408 if (!DECL_DECLARED_INLINE_P (callee->decl)
2409 && !opt_for_fn (node->decl, flag_inline_small_functions)
2410 && !opt_for_fn (node->decl, flag_inline_functions))
2411 continue;
2413 if (dump_file)
2414 fprintf (dump_file, "Considering inline candidate %s.\n",
2415 callee->name ());
2417 if (!can_early_inline_edge_p (e))
2418 continue;
2420 if (e->recursive_p ())
2422 if (dump_file)
2423 fprintf (dump_file, " Not inlining: recursive call.\n");
2424 continue;
2427 if (!want_early_inline_function_p (e))
2428 continue;
2430 if (dump_file)
2431 fprintf (dump_file, " Inlining %s into %s.\n",
2432 xstrdup_for_dump (callee->name ()),
2433 xstrdup_for_dump (e->caller->name ()));
2434 inline_call (e, true, NULL, NULL, true);
2435 inlined = true;
2438 return inlined;
2441 unsigned int
2442 early_inliner (function *fun)
2444 struct cgraph_node *node = cgraph_node::get (current_function_decl);
2445 struct cgraph_edge *edge;
2446 unsigned int todo = 0;
2447 int iterations = 0;
2448 bool inlined = false;
2450 if (seen_error ())
2451 return 0;
2453 /* Do nothing if datastructures for ipa-inliner are already computed. This
2454 happens when some pass decides to construct new function and
2455 cgraph_add_new_function calls lowering passes and early optimization on
2456 it. This may confuse ourself when early inliner decide to inline call to
2457 function clone, because function clones don't have parameter list in
2458 ipa-prop matching their signature. */
2459 if (ipa_node_params_sum)
2460 return 0;
2462 #ifdef ENABLE_CHECKING
2463 node->verify ();
2464 #endif
2465 node->remove_all_references ();
2467 /* Even when not optimizing or not inlining inline always-inline
2468 functions. */
2469 inlined = inline_always_inline_functions (node);
2471 if (!optimize
2472 || flag_no_inline
2473 || !flag_early_inlining
2474 /* Never inline regular functions into always-inline functions
2475 during incremental inlining. This sucks as functions calling
2476 always inline functions will get less optimized, but at the
2477 same time inlining of functions calling always inline
2478 function into an always inline function might introduce
2479 cycles of edges to be always inlined in the callgraph.
2481 We might want to be smarter and just avoid this type of inlining. */
2482 || DECL_DISREGARD_INLINE_LIMITS (node->decl))
2484 else if (lookup_attribute ("flatten",
2485 DECL_ATTRIBUTES (node->decl)) != NULL)
2487 /* When the function is marked to be flattened, recursively inline
2488 all calls in it. */
2489 if (dump_file)
2490 fprintf (dump_file,
2491 "Flattening %s\n", node->name ());
2492 flatten_function (node, true);
2493 inlined = true;
2495 else
2497 /* We iterate incremental inlining to get trivial cases of indirect
2498 inlining. */
2499 while (iterations < PARAM_VALUE (PARAM_EARLY_INLINER_MAX_ITERATIONS)
2500 && early_inline_small_functions (node))
2502 timevar_push (TV_INTEGRATION);
2503 todo |= optimize_inline_calls (current_function_decl);
2505 /* Technically we ought to recompute inline parameters so the new
2506 iteration of early inliner works as expected. We however have
2507 values approximately right and thus we only need to update edge
2508 info that might be cleared out for newly discovered edges. */
2509 for (edge = node->callees; edge; edge = edge->next_callee)
2511 /* We have no summary for new bound store calls yet. */
2512 if (inline_edge_summary_vec.length () > (unsigned)edge->uid)
2514 struct inline_edge_summary *es = inline_edge_summary (edge);
2515 es->call_stmt_size
2516 = estimate_num_insns (edge->call_stmt, &eni_size_weights);
2517 es->call_stmt_time
2518 = estimate_num_insns (edge->call_stmt, &eni_time_weights);
2520 if (edge->callee->decl
2521 && !gimple_check_call_matching_types (
2522 edge->call_stmt, edge->callee->decl, false))
2523 edge->call_stmt_cannot_inline_p = true;
2525 if (iterations < PARAM_VALUE (PARAM_EARLY_INLINER_MAX_ITERATIONS) - 1)
2526 inline_update_overall_summary (node);
2527 timevar_pop (TV_INTEGRATION);
2528 iterations++;
2529 inlined = false;
2531 if (dump_file)
2532 fprintf (dump_file, "Iterations: %i\n", iterations);
2535 if (inlined)
2537 timevar_push (TV_INTEGRATION);
2538 todo |= optimize_inline_calls (current_function_decl);
2539 timevar_pop (TV_INTEGRATION);
2542 fun->always_inline_functions_inlined = true;
2544 return todo;
2547 /* Do inlining of small functions. Doing so early helps profiling and other
2548 passes to be somewhat more effective and avoids some code duplication in
2549 later real inlining pass for testcases with very many function calls. */
2551 namespace {
2553 const pass_data pass_data_early_inline =
2555 GIMPLE_PASS, /* type */
2556 "einline", /* name */
2557 OPTGROUP_INLINE, /* optinfo_flags */
2558 TV_EARLY_INLINING, /* tv_id */
2559 PROP_ssa, /* properties_required */
2560 0, /* properties_provided */
2561 0, /* properties_destroyed */
2562 0, /* todo_flags_start */
2563 0, /* todo_flags_finish */
2566 class pass_early_inline : public gimple_opt_pass
2568 public:
2569 pass_early_inline (gcc::context *ctxt)
2570 : gimple_opt_pass (pass_data_early_inline, ctxt)
2573 /* opt_pass methods: */
2574 virtual unsigned int execute (function *);
2576 }; // class pass_early_inline
2578 unsigned int
2579 pass_early_inline::execute (function *fun)
2581 return early_inliner (fun);
2584 } // anon namespace
2586 gimple_opt_pass *
2587 make_pass_early_inline (gcc::context *ctxt)
2589 return new pass_early_inline (ctxt);
2592 namespace {
2594 const pass_data pass_data_ipa_inline =
2596 IPA_PASS, /* type */
2597 "inline", /* name */
2598 OPTGROUP_INLINE, /* optinfo_flags */
2599 TV_IPA_INLINING, /* tv_id */
2600 0, /* properties_required */
2601 0, /* properties_provided */
2602 0, /* properties_destroyed */
2603 0, /* todo_flags_start */
2604 ( TODO_dump_symtab ), /* todo_flags_finish */
2607 class pass_ipa_inline : public ipa_opt_pass_d
2609 public:
2610 pass_ipa_inline (gcc::context *ctxt)
2611 : ipa_opt_pass_d (pass_data_ipa_inline, ctxt,
2612 inline_generate_summary, /* generate_summary */
2613 inline_write_summary, /* write_summary */
2614 inline_read_summary, /* read_summary */
2615 NULL, /* write_optimization_summary */
2616 NULL, /* read_optimization_summary */
2617 NULL, /* stmt_fixup */
2618 0, /* function_transform_todo_flags_start */
2619 inline_transform, /* function_transform */
2620 NULL) /* variable_transform */
2623 /* opt_pass methods: */
2624 virtual unsigned int execute (function *) { return ipa_inline (); }
2626 }; // class pass_ipa_inline
2628 } // anon namespace
2630 ipa_opt_pass_d *
2631 make_pass_ipa_inline (gcc::context *ctxt)
2633 return new pass_ipa_inline (ctxt);