2014-06-25 Marc Glisse <marc.glisse@inria.fr>
[official-gcc.git] / gcc / ipa-inline.c
blob82bbd7f14ddce0032bf83bd9104b0b5904d03f1f
1 /* Inlining decision heuristics.
2 Copyright (C) 2003-2014 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 "tree.h"
97 #include "trans-mem.h"
98 #include "calls.h"
99 #include "tree-inline.h"
100 #include "langhooks.h"
101 #include "flags.h"
102 #include "diagnostic.h"
103 #include "gimple-pretty-print.h"
104 #include "params.h"
105 #include "fibheap.h"
106 #include "intl.h"
107 #include "tree-pass.h"
108 #include "coverage.h"
109 #include "rtl.h"
110 #include "bitmap.h"
111 #include "basic-block.h"
112 #include "tree-ssa-alias.h"
113 #include "internal-fn.h"
114 #include "gimple-expr.h"
115 #include "is-a.h"
116 #include "gimple.h"
117 #include "gimple-ssa.h"
118 #include "ipa-prop.h"
119 #include "except.h"
120 #include "target.h"
121 #include "ipa-inline.h"
122 #include "ipa-utils.h"
123 #include "sreal.h"
124 #include "cilk.h"
125 #include "builtins.h"
127 /* Statistics we collect about inlining algorithm. */
128 static int overall_size;
129 static gcov_type max_count;
130 static sreal max_count_real, max_relbenefit_real, half_int_min_real;
131 static gcov_type spec_rem;
133 /* Return false when inlining edge E would lead to violating
134 limits on function unit growth or stack usage growth.
136 The relative function body growth limit is present generally
137 to avoid problems with non-linear behavior of the compiler.
138 To allow inlining huge functions into tiny wrapper, the limit
139 is always based on the bigger of the two functions considered.
141 For stack growth limits we always base the growth in stack usage
142 of the callers. We want to prevent applications from segfaulting
143 on stack overflow when functions with huge stack frames gets
144 inlined. */
146 static bool
147 caller_growth_limits (struct cgraph_edge *e)
149 struct cgraph_node *to = e->caller;
150 struct cgraph_node *what = cgraph_function_or_thunk_node (e->callee, NULL);
151 int newsize;
152 int limit = 0;
153 HOST_WIDE_INT stack_size_limit = 0, inlined_stack;
154 struct inline_summary *info, *what_info, *outer_info = inline_summary (to);
156 /* Look for function e->caller is inlined to. While doing
157 so work out the largest function body on the way. As
158 described above, we want to base our function growth
159 limits based on that. Not on the self size of the
160 outer function, not on the self size of inline code
161 we immediately inline to. This is the most relaxed
162 interpretation of the rule "do not grow large functions
163 too much in order to prevent compiler from exploding". */
164 while (true)
166 info = inline_summary (to);
167 if (limit < info->self_size)
168 limit = info->self_size;
169 if (stack_size_limit < info->estimated_self_stack_size)
170 stack_size_limit = info->estimated_self_stack_size;
171 if (to->global.inlined_to)
172 to = to->callers->caller;
173 else
174 break;
177 what_info = inline_summary (what);
179 if (limit < what_info->self_size)
180 limit = what_info->self_size;
182 limit += limit * PARAM_VALUE (PARAM_LARGE_FUNCTION_GROWTH) / 100;
184 /* Check the size after inlining against the function limits. But allow
185 the function to shrink if it went over the limits by forced inlining. */
186 newsize = estimate_size_after_inlining (to, e);
187 if (newsize >= info->size
188 && newsize > PARAM_VALUE (PARAM_LARGE_FUNCTION_INSNS)
189 && newsize > limit)
191 e->inline_failed = CIF_LARGE_FUNCTION_GROWTH_LIMIT;
192 return false;
195 if (!what_info->estimated_stack_size)
196 return true;
198 /* FIXME: Stack size limit often prevents inlining in Fortran programs
199 due to large i/o datastructures used by the Fortran front-end.
200 We ought to ignore this limit when we know that the edge is executed
201 on every invocation of the caller (i.e. its call statement dominates
202 exit block). We do not track this information, yet. */
203 stack_size_limit += ((gcov_type)stack_size_limit
204 * PARAM_VALUE (PARAM_STACK_FRAME_GROWTH) / 100);
206 inlined_stack = (outer_info->stack_frame_offset
207 + outer_info->estimated_self_stack_size
208 + what_info->estimated_stack_size);
209 /* Check new stack consumption with stack consumption at the place
210 stack is used. */
211 if (inlined_stack > stack_size_limit
212 /* If function already has large stack usage from sibling
213 inline call, we can inline, too.
214 This bit overoptimistically assume that we are good at stack
215 packing. */
216 && inlined_stack > info->estimated_stack_size
217 && inlined_stack > PARAM_VALUE (PARAM_LARGE_STACK_FRAME))
219 e->inline_failed = CIF_LARGE_STACK_FRAME_GROWTH_LIMIT;
220 return false;
222 return true;
225 /* Dump info about why inlining has failed. */
227 static void
228 report_inline_failed_reason (struct cgraph_edge *e)
230 if (dump_file)
232 fprintf (dump_file, " not inlinable: %s/%i -> %s/%i, %s\n",
233 xstrdup (e->caller->name ()), e->caller->order,
234 xstrdup (e->callee->name ()), e->callee->order,
235 cgraph_inline_failed_string (e->inline_failed));
239 /* Decide whether sanitizer-related attributes allow inlining. */
241 static bool
242 sanitize_attrs_match_for_inline_p (const_tree caller, const_tree callee)
244 /* Don't care if sanitizer is disabled */
245 if (!(flag_sanitize & SANITIZE_ADDRESS))
246 return true;
248 if (!caller || !callee)
249 return true;
251 return !!lookup_attribute ("no_sanitize_address",
252 DECL_ATTRIBUTES (caller)) ==
253 !!lookup_attribute ("no_sanitize_address",
254 DECL_ATTRIBUTES (callee));
257 /* Decide if we can inline the edge and possibly update
258 inline_failed reason.
259 We check whether inlining is possible at all and whether
260 caller growth limits allow doing so.
262 if REPORT is true, output reason to the dump file.
264 if DISREGARD_LIMITS is true, ignore size limits.*/
266 static bool
267 can_inline_edge_p (struct cgraph_edge *e, bool report,
268 bool disregard_limits = false)
270 bool inlinable = true;
271 enum availability avail;
272 struct cgraph_node *callee
273 = cgraph_function_or_thunk_node (e->callee, &avail);
274 tree caller_tree = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (e->caller->decl);
275 tree callee_tree
276 = callee ? DECL_FUNCTION_SPECIFIC_OPTIMIZATION (callee->decl) : NULL;
277 struct function *caller_cfun = DECL_STRUCT_FUNCTION (e->caller->decl);
278 struct function *callee_cfun
279 = callee ? DECL_STRUCT_FUNCTION (callee->decl) : NULL;
281 if (!caller_cfun && e->caller->clone_of)
282 caller_cfun = DECL_STRUCT_FUNCTION (e->caller->clone_of->decl);
284 if (!callee_cfun && callee && callee->clone_of)
285 callee_cfun = DECL_STRUCT_FUNCTION (callee->clone_of->decl);
287 gcc_assert (e->inline_failed);
289 if (!callee || !callee->definition)
291 e->inline_failed = CIF_BODY_NOT_AVAILABLE;
292 inlinable = false;
294 else if (callee->calls_comdat_local)
296 e->inline_failed = CIF_USES_COMDAT_LOCAL;
297 inlinable = false;
299 else if (!inline_summary (callee)->inlinable
300 || (caller_cfun && fn_contains_cilk_spawn_p (caller_cfun)))
302 e->inline_failed = CIF_FUNCTION_NOT_INLINABLE;
303 inlinable = false;
305 else if (avail <= AVAIL_OVERWRITABLE)
307 e->inline_failed = CIF_OVERWRITABLE;
308 inlinable = false;
310 else if (e->call_stmt_cannot_inline_p)
312 if (e->inline_failed != CIF_FUNCTION_NOT_OPTIMIZED)
313 e->inline_failed = CIF_MISMATCHED_ARGUMENTS;
314 inlinable = false;
316 /* Don't inline if the functions have different EH personalities. */
317 else if (DECL_FUNCTION_PERSONALITY (e->caller->decl)
318 && DECL_FUNCTION_PERSONALITY (callee->decl)
319 && (DECL_FUNCTION_PERSONALITY (e->caller->decl)
320 != DECL_FUNCTION_PERSONALITY (callee->decl)))
322 e->inline_failed = CIF_EH_PERSONALITY;
323 inlinable = false;
325 /* TM pure functions should not be inlined into non-TM_pure
326 functions. */
327 else if (is_tm_pure (callee->decl)
328 && !is_tm_pure (e->caller->decl))
330 e->inline_failed = CIF_UNSPECIFIED;
331 inlinable = false;
333 /* Don't inline if the callee can throw non-call exceptions but the
334 caller cannot.
335 FIXME: this is obviously wrong for LTO where STRUCT_FUNCTION is missing.
336 Move the flag into cgraph node or mirror it in the inline summary. */
337 else if (callee_cfun && callee_cfun->can_throw_non_call_exceptions
338 && !(caller_cfun && caller_cfun->can_throw_non_call_exceptions))
340 e->inline_failed = CIF_NON_CALL_EXCEPTIONS;
341 inlinable = false;
343 /* Check compatibility of target optimization options. */
344 else if (!targetm.target_option.can_inline_p (e->caller->decl,
345 callee->decl))
347 e->inline_failed = CIF_TARGET_OPTION_MISMATCH;
348 inlinable = false;
350 /* Don't inline a function with mismatched sanitization attributes. */
351 else if (!sanitize_attrs_match_for_inline_p (e->caller->decl, callee->decl))
353 e->inline_failed = CIF_ATTRIBUTE_MISMATCH;
354 inlinable = false;
356 /* Check if caller growth allows the inlining. */
357 else if (!DECL_DISREGARD_INLINE_LIMITS (callee->decl)
358 && !disregard_limits
359 && !lookup_attribute ("flatten",
360 DECL_ATTRIBUTES
361 (e->caller->global.inlined_to
362 ? e->caller->global.inlined_to->decl
363 : e->caller->decl))
364 && !caller_growth_limits (e))
365 inlinable = false;
366 /* Don't inline a function with a higher optimization level than the
367 caller. FIXME: this is really just tip of iceberg of handling
368 optimization attribute. */
369 else if (caller_tree != callee_tree)
371 struct cl_optimization *caller_opt
372 = TREE_OPTIMIZATION ((caller_tree)
373 ? caller_tree
374 : optimization_default_node);
376 struct cl_optimization *callee_opt
377 = TREE_OPTIMIZATION ((callee_tree)
378 ? callee_tree
379 : optimization_default_node);
381 if (((caller_opt->x_optimize > callee_opt->x_optimize)
382 || (caller_opt->x_optimize_size != callee_opt->x_optimize_size))
383 /* gcc.dg/pr43564.c. Look at forced inline even in -O0. */
384 && !DECL_DISREGARD_INLINE_LIMITS (e->callee->decl))
386 e->inline_failed = CIF_OPTIMIZATION_MISMATCH;
387 inlinable = false;
391 if (!inlinable && report)
392 report_inline_failed_reason (e);
393 return inlinable;
397 /* Return true if the edge E is inlinable during early inlining. */
399 static bool
400 can_early_inline_edge_p (struct cgraph_edge *e)
402 struct cgraph_node *callee = cgraph_function_or_thunk_node (e->callee,
403 NULL);
404 /* Early inliner might get called at WPA stage when IPA pass adds new
405 function. In this case we can not really do any of early inlining
406 because function bodies are missing. */
407 if (!gimple_has_body_p (callee->decl))
409 e->inline_failed = CIF_BODY_NOT_AVAILABLE;
410 return false;
412 /* In early inliner some of callees may not be in SSA form yet
413 (i.e. the callgraph is cyclic and we did not process
414 the callee by early inliner, yet). We don't have CIF code for this
415 case; later we will re-do the decision in the real inliner. */
416 if (!gimple_in_ssa_p (DECL_STRUCT_FUNCTION (e->caller->decl))
417 || !gimple_in_ssa_p (DECL_STRUCT_FUNCTION (callee->decl)))
419 if (dump_file)
420 fprintf (dump_file, " edge not inlinable: not in SSA form\n");
421 return false;
423 if (!can_inline_edge_p (e, true))
424 return false;
425 return true;
429 /* Return number of calls in N. Ignore cheap builtins. */
431 static int
432 num_calls (struct cgraph_node *n)
434 struct cgraph_edge *e;
435 int num = 0;
437 for (e = n->callees; e; e = e->next_callee)
438 if (!is_inexpensive_builtin (e->callee->decl))
439 num++;
440 return num;
444 /* Return true if we are interested in inlining small function. */
446 static bool
447 want_early_inline_function_p (struct cgraph_edge *e)
449 bool want_inline = true;
450 struct cgraph_node *callee = cgraph_function_or_thunk_node (e->callee, NULL);
452 if (DECL_DISREGARD_INLINE_LIMITS (callee->decl))
454 else if (!DECL_DECLARED_INLINE_P (callee->decl)
455 && !flag_inline_small_functions)
457 e->inline_failed = CIF_FUNCTION_NOT_INLINE_CANDIDATE;
458 report_inline_failed_reason (e);
459 want_inline = false;
461 else
463 int growth = estimate_edge_growth (e);
464 int n;
466 if (growth <= 0)
468 else if (!cgraph_maybe_hot_edge_p (e)
469 && growth > 0)
471 if (dump_file)
472 fprintf (dump_file, " will not early inline: %s/%i->%s/%i, "
473 "call is cold and code would grow by %i\n",
474 xstrdup (e->caller->name ()),
475 e->caller->order,
476 xstrdup (callee->name ()), callee->order,
477 growth);
478 want_inline = false;
480 else if (growth > PARAM_VALUE (PARAM_EARLY_INLINING_INSNS))
482 if (dump_file)
483 fprintf (dump_file, " will not early inline: %s/%i->%s/%i, "
484 "growth %i exceeds --param early-inlining-insns\n",
485 xstrdup (e->caller->name ()),
486 e->caller->order,
487 xstrdup (callee->name ()), callee->order,
488 growth);
489 want_inline = false;
491 else if ((n = num_calls (callee)) != 0
492 && growth * (n + 1) > PARAM_VALUE (PARAM_EARLY_INLINING_INSNS))
494 if (dump_file)
495 fprintf (dump_file, " will not early inline: %s/%i->%s/%i, "
496 "growth %i exceeds --param early-inlining-insns "
497 "divided by number of calls\n",
498 xstrdup (e->caller->name ()),
499 e->caller->order,
500 xstrdup (callee->name ()), callee->order,
501 growth);
502 want_inline = false;
505 return want_inline;
508 /* Compute time of the edge->caller + edge->callee execution when inlining
509 does not happen. */
511 inline gcov_type
512 compute_uninlined_call_time (struct inline_summary *callee_info,
513 struct cgraph_edge *edge)
515 gcov_type uninlined_call_time =
516 RDIV ((gcov_type)callee_info->time * MAX (edge->frequency, 1),
517 CGRAPH_FREQ_BASE);
518 gcov_type caller_time = inline_summary (edge->caller->global.inlined_to
519 ? edge->caller->global.inlined_to
520 : edge->caller)->time;
521 return uninlined_call_time + caller_time;
524 /* Same as compute_uinlined_call_time but compute time when inlining
525 does happen. */
527 inline gcov_type
528 compute_inlined_call_time (struct cgraph_edge *edge,
529 int edge_time)
531 gcov_type caller_time = inline_summary (edge->caller->global.inlined_to
532 ? edge->caller->global.inlined_to
533 : edge->caller)->time;
534 gcov_type time = (caller_time
535 + RDIV (((gcov_type) edge_time
536 - inline_edge_summary (edge)->call_stmt_time)
537 * MAX (edge->frequency, 1), CGRAPH_FREQ_BASE));
538 /* Possible one roundoff error, but watch for overflows. */
539 gcc_checking_assert (time >= INT_MIN / 2);
540 if (time < 0)
541 time = 0;
542 return time;
545 /* Return true if the speedup for inlining E is bigger than
546 PARAM_MAX_INLINE_MIN_SPEEDUP. */
548 static bool
549 big_speedup_p (struct cgraph_edge *e)
551 gcov_type time = compute_uninlined_call_time (inline_summary (e->callee),
553 gcov_type inlined_time = compute_inlined_call_time (e,
554 estimate_edge_time (e));
555 if (time - inlined_time
556 > RDIV (time * PARAM_VALUE (PARAM_INLINE_MIN_SPEEDUP), 100))
557 return true;
558 return false;
561 /* Return true if we are interested in inlining small function.
562 When REPORT is true, report reason to dump file. */
564 static bool
565 want_inline_small_function_p (struct cgraph_edge *e, bool report)
567 bool want_inline = true;
568 struct cgraph_node *callee = cgraph_function_or_thunk_node (e->callee, NULL);
570 if (DECL_DISREGARD_INLINE_LIMITS (callee->decl))
572 else if (!DECL_DECLARED_INLINE_P (callee->decl)
573 && !flag_inline_small_functions)
575 e->inline_failed = CIF_FUNCTION_NOT_INLINE_CANDIDATE;
576 want_inline = false;
578 /* Do fast and conservative check if the function can be good
579 inline cnadidate. At themoment we allow inline hints to
580 promote non-inline function to inline and we increase
581 MAX_INLINE_INSNS_SINGLE 16fold for inline functions. */
582 else if ((!DECL_DECLARED_INLINE_P (callee->decl)
583 && (!e->count || !cgraph_maybe_hot_edge_p (e)))
584 && inline_summary (callee)->min_size - inline_edge_summary (e)->call_stmt_size
585 > MAX (MAX_INLINE_INSNS_SINGLE, MAX_INLINE_INSNS_AUTO))
587 e->inline_failed = CIF_MAX_INLINE_INSNS_AUTO_LIMIT;
588 want_inline = false;
590 else if ((DECL_DECLARED_INLINE_P (callee->decl) || e->count)
591 && inline_summary (callee)->min_size - inline_edge_summary (e)->call_stmt_size
592 > 16 * MAX_INLINE_INSNS_SINGLE)
594 e->inline_failed = (DECL_DECLARED_INLINE_P (callee->decl)
595 ? CIF_MAX_INLINE_INSNS_SINGLE_LIMIT
596 : CIF_MAX_INLINE_INSNS_AUTO_LIMIT);
597 want_inline = false;
599 else
601 int growth = estimate_edge_growth (e);
602 inline_hints hints = estimate_edge_hints (e);
603 bool big_speedup = big_speedup_p (e);
605 if (growth <= 0)
607 /* Apply MAX_INLINE_INSNS_SINGLE limit. Do not do so when
608 hints suggests that inlining given function is very profitable. */
609 else if (DECL_DECLARED_INLINE_P (callee->decl)
610 && growth >= MAX_INLINE_INSNS_SINGLE
611 && ((!big_speedup
612 && !(hints & (INLINE_HINT_indirect_call
613 | INLINE_HINT_known_hot
614 | INLINE_HINT_loop_iterations
615 | INLINE_HINT_array_index
616 | INLINE_HINT_loop_stride)))
617 || growth >= MAX_INLINE_INSNS_SINGLE * 16))
619 e->inline_failed = CIF_MAX_INLINE_INSNS_SINGLE_LIMIT;
620 want_inline = false;
622 else if (!DECL_DECLARED_INLINE_P (callee->decl)
623 && !flag_inline_functions)
625 /* growth_likely_positive is expensive, always test it last. */
626 if (growth >= MAX_INLINE_INSNS_SINGLE
627 || growth_likely_positive (callee, growth))
629 e->inline_failed = CIF_NOT_DECLARED_INLINED;
630 want_inline = false;
633 /* Apply MAX_INLINE_INSNS_AUTO limit for functions not declared inline
634 Upgrade it to MAX_INLINE_INSNS_SINGLE when hints suggests that
635 inlining given function is very profitable. */
636 else if (!DECL_DECLARED_INLINE_P (callee->decl)
637 && !big_speedup
638 && !(hints & INLINE_HINT_known_hot)
639 && growth >= ((hints & (INLINE_HINT_indirect_call
640 | INLINE_HINT_loop_iterations
641 | INLINE_HINT_array_index
642 | INLINE_HINT_loop_stride))
643 ? MAX (MAX_INLINE_INSNS_AUTO,
644 MAX_INLINE_INSNS_SINGLE)
645 : MAX_INLINE_INSNS_AUTO))
647 /* growth_likely_positive is expensive, always test it last. */
648 if (growth >= MAX_INLINE_INSNS_SINGLE
649 || growth_likely_positive (callee, growth))
651 e->inline_failed = CIF_MAX_INLINE_INSNS_AUTO_LIMIT;
652 want_inline = false;
655 /* If call is cold, do not inline when function body would grow. */
656 else if (!cgraph_maybe_hot_edge_p (e)
657 && (growth >= MAX_INLINE_INSNS_SINGLE
658 || growth_likely_positive (callee, growth)))
660 e->inline_failed = CIF_UNLIKELY_CALL;
661 want_inline = false;
664 if (!want_inline && report)
665 report_inline_failed_reason (e);
666 return want_inline;
669 /* EDGE is self recursive edge.
670 We hand two cases - when function A is inlining into itself
671 or when function A is being inlined into another inliner copy of function
672 A within function B.
674 In first case OUTER_NODE points to the toplevel copy of A, while
675 in the second case OUTER_NODE points to the outermost copy of A in B.
677 In both cases we want to be extra selective since
678 inlining the call will just introduce new recursive calls to appear. */
680 static bool
681 want_inline_self_recursive_call_p (struct cgraph_edge *edge,
682 struct cgraph_node *outer_node,
683 bool peeling,
684 int depth)
686 char const *reason = NULL;
687 bool want_inline = true;
688 int caller_freq = CGRAPH_FREQ_BASE;
689 int max_depth = PARAM_VALUE (PARAM_MAX_INLINE_RECURSIVE_DEPTH_AUTO);
691 if (DECL_DECLARED_INLINE_P (edge->caller->decl))
692 max_depth = PARAM_VALUE (PARAM_MAX_INLINE_RECURSIVE_DEPTH);
694 if (!cgraph_maybe_hot_edge_p (edge))
696 reason = "recursive call is cold";
697 want_inline = false;
699 else if (max_count && !outer_node->count)
701 reason = "not executed in profile";
702 want_inline = false;
704 else if (depth > max_depth)
706 reason = "--param max-inline-recursive-depth exceeded.";
707 want_inline = false;
710 if (outer_node->global.inlined_to)
711 caller_freq = outer_node->callers->frequency;
713 if (!caller_freq)
715 reason = "function is inlined and unlikely";
716 want_inline = false;
719 if (!want_inline)
721 /* Inlining of self recursive function into copy of itself within other function
722 is transformation similar to loop peeling.
724 Peeling is profitable if we can inline enough copies to make probability
725 of actual call to the self recursive function very small. Be sure that
726 the probability of recursion is small.
728 We ensure that the frequency of recursing is at most 1 - (1/max_depth).
729 This way the expected number of recision is at most max_depth. */
730 else if (peeling)
732 int max_prob = CGRAPH_FREQ_BASE - ((CGRAPH_FREQ_BASE + max_depth - 1)
733 / max_depth);
734 int i;
735 for (i = 1; i < depth; i++)
736 max_prob = max_prob * max_prob / CGRAPH_FREQ_BASE;
737 if (max_count
738 && (edge->count * CGRAPH_FREQ_BASE / outer_node->count
739 >= max_prob))
741 reason = "profile of recursive call is too large";
742 want_inline = false;
744 if (!max_count
745 && (edge->frequency * CGRAPH_FREQ_BASE / caller_freq
746 >= max_prob))
748 reason = "frequency of recursive call is too large";
749 want_inline = false;
752 /* Recursive inlining, i.e. equivalent of unrolling, is profitable if recursion
753 depth is large. We reduce function call overhead and increase chances that
754 things fit in hardware return predictor.
756 Recursive inlining might however increase cost of stack frame setup
757 actually slowing down functions whose recursion tree is wide rather than
758 deep.
760 Deciding reliably on when to do recursive inlining without profile feedback
761 is tricky. For now we disable recursive inlining when probability of self
762 recursion is low.
764 Recursive inlining of self recursive call within loop also results in large loop
765 depths that generally optimize badly. We may want to throttle down inlining
766 in those cases. In particular this seems to happen in one of libstdc++ rb tree
767 methods. */
768 else
770 if (max_count
771 && (edge->count * 100 / outer_node->count
772 <= PARAM_VALUE (PARAM_MIN_INLINE_RECURSIVE_PROBABILITY)))
774 reason = "profile of recursive call is too small";
775 want_inline = false;
777 else if (!max_count
778 && (edge->frequency * 100 / caller_freq
779 <= PARAM_VALUE (PARAM_MIN_INLINE_RECURSIVE_PROBABILITY)))
781 reason = "frequency of recursive call is too small";
782 want_inline = false;
785 if (!want_inline && dump_file)
786 fprintf (dump_file, " not inlining recursively: %s\n", reason);
787 return want_inline;
790 /* Return true when NODE has uninlinable caller;
791 set HAS_HOT_CALL if it has hot call.
792 Worker for cgraph_for_node_and_aliases. */
794 static bool
795 check_callers (struct cgraph_node *node, void *has_hot_call)
797 struct cgraph_edge *e;
798 for (e = node->callers; e; e = e->next_caller)
800 if (!can_inline_edge_p (e, true))
801 return true;
802 if (!(*(bool *)has_hot_call) && cgraph_maybe_hot_edge_p (e))
803 *(bool *)has_hot_call = true;
805 return false;
808 /* If NODE has a caller, return true. */
810 static bool
811 has_caller_p (struct cgraph_node *node, void *data ATTRIBUTE_UNUSED)
813 if (node->callers)
814 return true;
815 return false;
818 /* Decide if inlining NODE would reduce unit size by eliminating
819 the offline copy of function.
820 When COLD is true the cold calls are considered, too. */
822 static bool
823 want_inline_function_to_all_callers_p (struct cgraph_node *node, bool cold)
825 struct cgraph_node *function = cgraph_function_or_thunk_node (node, NULL);
826 bool has_hot_call = false;
828 /* Does it have callers? */
829 if (!cgraph_for_node_and_aliases (node, has_caller_p, NULL, true))
830 return false;
831 /* Already inlined? */
832 if (function->global.inlined_to)
833 return false;
834 if (cgraph_function_or_thunk_node (node, NULL) != node)
835 return false;
836 /* Inlining into all callers would increase size? */
837 if (estimate_growth (node) > 0)
838 return false;
839 /* All inlines must be possible. */
840 if (cgraph_for_node_and_aliases (node, check_callers, &has_hot_call, true))
841 return false;
842 if (!cold && !has_hot_call)
843 return false;
844 return true;
847 #define RELATIVE_TIME_BENEFIT_RANGE (INT_MAX / 64)
849 /* Return relative time improvement for inlining EDGE in range
850 1...RELATIVE_TIME_BENEFIT_RANGE */
852 static inline int
853 relative_time_benefit (struct inline_summary *callee_info,
854 struct cgraph_edge *edge,
855 int edge_time)
857 gcov_type relbenefit;
858 gcov_type uninlined_call_time = compute_uninlined_call_time (callee_info, edge);
859 gcov_type inlined_call_time = compute_inlined_call_time (edge, edge_time);
861 /* Inlining into extern inline function is not a win. */
862 if (DECL_EXTERNAL (edge->caller->global.inlined_to
863 ? edge->caller->global.inlined_to->decl
864 : edge->caller->decl))
865 return 1;
867 /* Watch overflows. */
868 gcc_checking_assert (uninlined_call_time >= 0);
869 gcc_checking_assert (inlined_call_time >= 0);
870 gcc_checking_assert (uninlined_call_time >= inlined_call_time);
872 /* Compute relative time benefit, i.e. how much the call becomes faster.
873 ??? perhaps computing how much the caller+calle together become faster
874 would lead to more realistic results. */
875 if (!uninlined_call_time)
876 uninlined_call_time = 1;
877 relbenefit =
878 RDIV (((gcov_type)uninlined_call_time - inlined_call_time) * RELATIVE_TIME_BENEFIT_RANGE,
879 uninlined_call_time);
880 relbenefit = MIN (relbenefit, RELATIVE_TIME_BENEFIT_RANGE);
881 gcc_checking_assert (relbenefit >= 0);
882 relbenefit = MAX (relbenefit, 1);
883 return relbenefit;
887 /* A cost model driving the inlining heuristics in a way so the edges with
888 smallest badness are inlined first. After each inlining is performed
889 the costs of all caller edges of nodes affected are recomputed so the
890 metrics may accurately depend on values such as number of inlinable callers
891 of the function or function body size. */
893 static int
894 edge_badness (struct cgraph_edge *edge, bool dump)
896 gcov_type badness;
897 int growth, edge_time;
898 struct cgraph_node *callee = cgraph_function_or_thunk_node (edge->callee,
899 NULL);
900 struct inline_summary *callee_info = inline_summary (callee);
901 inline_hints hints;
903 if (DECL_DISREGARD_INLINE_LIMITS (callee->decl))
904 return INT_MIN;
906 growth = estimate_edge_growth (edge);
907 edge_time = estimate_edge_time (edge);
908 hints = estimate_edge_hints (edge);
909 gcc_checking_assert (edge_time >= 0);
910 gcc_checking_assert (edge_time <= callee_info->time);
911 gcc_checking_assert (growth <= callee_info->size);
913 if (dump)
915 fprintf (dump_file, " Badness calculation for %s/%i -> %s/%i\n",
916 xstrdup (edge->caller->name ()),
917 edge->caller->order,
918 xstrdup (callee->name ()),
919 edge->callee->order);
920 fprintf (dump_file, " size growth %i, time %i ",
921 growth,
922 edge_time);
923 dump_inline_hints (dump_file, hints);
924 if (big_speedup_p (edge))
925 fprintf (dump_file, " big_speedup");
926 fprintf (dump_file, "\n");
929 /* Always prefer inlining saving code size. */
930 if (growth <= 0)
932 badness = INT_MIN / 2 + growth;
933 if (dump)
934 fprintf (dump_file, " %i: Growth %i <= 0\n", (int) badness,
935 growth);
938 /* When profiling is available, compute badness as:
940 relative_edge_count * relative_time_benefit
941 goodness = -------------------------------------------
942 growth_f_caller
943 badness = -goodness
945 The fraction is upside down, because on edge counts and time beneits
946 the bounds are known. Edge growth is essentially unlimited. */
948 else if (max_count)
950 sreal tmp, relbenefit_real, growth_real;
951 int relbenefit = relative_time_benefit (callee_info, edge, edge_time);
952 /* Capping edge->count to max_count. edge->count can be larger than
953 max_count if an inline adds new edges which increase max_count
954 after max_count is computed. */
955 gcov_type edge_count = edge->count > max_count ? max_count : edge->count;
957 sreal_init (&relbenefit_real, relbenefit, 0);
958 sreal_init (&growth_real, growth, 0);
960 /* relative_edge_count. */
961 sreal_init (&tmp, edge_count, 0);
962 sreal_div (&tmp, &tmp, &max_count_real);
964 /* relative_time_benefit. */
965 sreal_mul (&tmp, &tmp, &relbenefit_real);
966 sreal_div (&tmp, &tmp, &max_relbenefit_real);
968 /* growth_f_caller. */
969 sreal_mul (&tmp, &tmp, &half_int_min_real);
970 sreal_div (&tmp, &tmp, &growth_real);
972 badness = -1 * sreal_to_int (&tmp);
974 if (dump)
976 fprintf (dump_file,
977 " %i (relative %f): profile info. Relative count %f%s"
978 " * Relative benefit %f\n",
979 (int) badness, (double) badness / INT_MIN,
980 (double) edge_count / max_count,
981 edge->count > max_count ? " (capped to max_count)" : "",
982 relbenefit * 100.0 / RELATIVE_TIME_BENEFIT_RANGE);
986 /* When function local profile is available. Compute badness as:
988 relative_time_benefit
989 goodness = ---------------------------------
990 growth_of_caller * overall_growth
992 badness = - goodness
994 compensated by the inline hints.
996 else if (flag_guess_branch_prob)
998 badness = (relative_time_benefit (callee_info, edge, edge_time)
999 * (INT_MIN / 16 / RELATIVE_TIME_BENEFIT_RANGE));
1000 badness /= (MIN (65536/2, growth) * MIN (65536/2, MAX (1, callee_info->growth)));
1001 gcc_checking_assert (badness <=0 && badness >= INT_MIN / 16);
1002 if ((hints & (INLINE_HINT_indirect_call
1003 | INLINE_HINT_loop_iterations
1004 | INLINE_HINT_array_index
1005 | INLINE_HINT_loop_stride))
1006 || callee_info->growth <= 0)
1007 badness *= 8;
1008 if (hints & (INLINE_HINT_same_scc))
1009 badness /= 16;
1010 else if (hints & (INLINE_HINT_in_scc))
1011 badness /= 8;
1012 else if (hints & (INLINE_HINT_cross_module))
1013 badness /= 2;
1014 gcc_checking_assert (badness <= 0 && badness >= INT_MIN / 2);
1015 if ((hints & INLINE_HINT_declared_inline) && badness >= INT_MIN / 32)
1016 badness *= 16;
1017 if (dump)
1019 fprintf (dump_file,
1020 " %i: guessed profile. frequency %f,"
1021 " benefit %f%%, time w/o inlining %i, time w inlining %i"
1022 " overall growth %i (current) %i (original)\n",
1023 (int) badness, (double)edge->frequency / CGRAPH_FREQ_BASE,
1024 relative_time_benefit (callee_info, edge, edge_time) * 100.0
1025 / RELATIVE_TIME_BENEFIT_RANGE,
1026 (int)compute_uninlined_call_time (callee_info, edge),
1027 (int)compute_inlined_call_time (edge, edge_time),
1028 estimate_growth (callee),
1029 callee_info->growth);
1032 /* When function local profile is not available or it does not give
1033 useful information (ie frequency is zero), base the cost on
1034 loop nest and overall size growth, so we optimize for overall number
1035 of functions fully inlined in program. */
1036 else
1038 int nest = MIN (inline_edge_summary (edge)->loop_depth, 8);
1039 badness = growth * 256;
1041 /* Decrease badness if call is nested. */
1042 if (badness > 0)
1043 badness >>= nest;
1044 else
1046 badness <<= nest;
1048 if (dump)
1049 fprintf (dump_file, " %i: no profile. nest %i\n", (int) badness,
1050 nest);
1053 /* Ensure that we did not overflow in all the fixed point math above. */
1054 gcc_assert (badness >= INT_MIN);
1055 gcc_assert (badness <= INT_MAX - 1);
1056 /* Make recursive inlining happen always after other inlining is done. */
1057 if (cgraph_edge_recursive_p (edge))
1058 return badness + 1;
1059 else
1060 return badness;
1063 /* Recompute badness of EDGE and update its key in HEAP if needed. */
1064 static inline void
1065 update_edge_key (fibheap_t heap, struct cgraph_edge *edge)
1067 int badness = edge_badness (edge, false);
1068 if (edge->aux)
1070 fibnode_t n = (fibnode_t) edge->aux;
1071 gcc_checking_assert (n->data == edge);
1073 /* fibheap_replace_key only decrease the keys.
1074 When we increase the key we do not update heap
1075 and instead re-insert the element once it becomes
1076 a minimum of heap. */
1077 if (badness < n->key)
1079 if (dump_file && (dump_flags & TDF_DETAILS))
1081 fprintf (dump_file,
1082 " decreasing badness %s/%i -> %s/%i, %i to %i\n",
1083 xstrdup (edge->caller->name ()),
1084 edge->caller->order,
1085 xstrdup (edge->callee->name ()),
1086 edge->callee->order,
1087 (int)n->key,
1088 badness);
1090 fibheap_replace_key (heap, n, badness);
1091 gcc_checking_assert (n->key == badness);
1094 else
1096 if (dump_file && (dump_flags & TDF_DETAILS))
1098 fprintf (dump_file,
1099 " enqueuing call %s/%i -> %s/%i, badness %i\n",
1100 xstrdup (edge->caller->name ()),
1101 edge->caller->order,
1102 xstrdup (edge->callee->name ()),
1103 edge->callee->order,
1104 badness);
1106 edge->aux = fibheap_insert (heap, badness, edge);
1111 /* NODE was inlined.
1112 All caller edges needs to be resetted because
1113 size estimates change. Similarly callees needs reset
1114 because better context may be known. */
1116 static void
1117 reset_edge_caches (struct cgraph_node *node)
1119 struct cgraph_edge *edge;
1120 struct cgraph_edge *e = node->callees;
1121 struct cgraph_node *where = node;
1122 int i;
1123 struct ipa_ref *ref;
1125 if (where->global.inlined_to)
1126 where = where->global.inlined_to;
1128 /* WHERE body size has changed, the cached growth is invalid. */
1129 reset_node_growth_cache (where);
1131 for (edge = where->callers; edge; edge = edge->next_caller)
1132 if (edge->inline_failed)
1133 reset_edge_growth_cache (edge);
1134 for (i = 0; ipa_ref_list_referring_iterate (&where->ref_list,
1135 i, ref); i++)
1136 if (ref->use == IPA_REF_ALIAS)
1137 reset_edge_caches (ipa_ref_referring_node (ref));
1139 if (!e)
1140 return;
1142 while (true)
1143 if (!e->inline_failed && e->callee->callees)
1144 e = e->callee->callees;
1145 else
1147 if (e->inline_failed)
1148 reset_edge_growth_cache (e);
1149 if (e->next_callee)
1150 e = e->next_callee;
1151 else
1155 if (e->caller == node)
1156 return;
1157 e = e->caller->callers;
1159 while (!e->next_callee);
1160 e = e->next_callee;
1165 /* Recompute HEAP nodes for each of caller of NODE.
1166 UPDATED_NODES track nodes we already visited, to avoid redundant work.
1167 When CHECK_INLINABLITY_FOR is set, re-check for specified edge that
1168 it is inlinable. Otherwise check all edges. */
1170 static void
1171 update_caller_keys (fibheap_t heap, struct cgraph_node *node,
1172 bitmap updated_nodes,
1173 struct cgraph_edge *check_inlinablity_for)
1175 struct cgraph_edge *edge;
1176 int i;
1177 struct ipa_ref *ref;
1179 if ((!node->alias && !inline_summary (node)->inlinable)
1180 || node->global.inlined_to)
1181 return;
1182 if (!bitmap_set_bit (updated_nodes, node->uid))
1183 return;
1185 for (i = 0; ipa_ref_list_referring_iterate (&node->ref_list,
1186 i, ref); i++)
1187 if (ref->use == IPA_REF_ALIAS)
1189 struct cgraph_node *alias = ipa_ref_referring_node (ref);
1190 update_caller_keys (heap, alias, updated_nodes, check_inlinablity_for);
1193 for (edge = node->callers; edge; edge = edge->next_caller)
1194 if (edge->inline_failed)
1196 if (!check_inlinablity_for
1197 || check_inlinablity_for == edge)
1199 if (can_inline_edge_p (edge, false)
1200 && want_inline_small_function_p (edge, false))
1201 update_edge_key (heap, edge);
1202 else if (edge->aux)
1204 report_inline_failed_reason (edge);
1205 fibheap_delete_node (heap, (fibnode_t) edge->aux);
1206 edge->aux = NULL;
1209 else if (edge->aux)
1210 update_edge_key (heap, edge);
1214 /* Recompute HEAP nodes for each uninlined call in NODE.
1215 This is used when we know that edge badnesses are going only to increase
1216 (we introduced new call site) and thus all we need is to insert newly
1217 created edges into heap. */
1219 static void
1220 update_callee_keys (fibheap_t heap, struct cgraph_node *node,
1221 bitmap updated_nodes)
1223 struct cgraph_edge *e = node->callees;
1225 if (!e)
1226 return;
1227 while (true)
1228 if (!e->inline_failed && e->callee->callees)
1229 e = e->callee->callees;
1230 else
1232 enum availability avail;
1233 struct cgraph_node *callee;
1234 /* We do not reset callee growth cache here. Since we added a new call,
1235 growth chould have just increased and consequentely badness metric
1236 don't need updating. */
1237 if (e->inline_failed
1238 && (callee = cgraph_function_or_thunk_node (e->callee, &avail))
1239 && inline_summary (callee)->inlinable
1240 && avail >= AVAIL_AVAILABLE
1241 && !bitmap_bit_p (updated_nodes, callee->uid))
1243 if (can_inline_edge_p (e, false)
1244 && want_inline_small_function_p (e, false))
1245 update_edge_key (heap, e);
1246 else if (e->aux)
1248 report_inline_failed_reason (e);
1249 fibheap_delete_node (heap, (fibnode_t) e->aux);
1250 e->aux = NULL;
1253 if (e->next_callee)
1254 e = e->next_callee;
1255 else
1259 if (e->caller == node)
1260 return;
1261 e = e->caller->callers;
1263 while (!e->next_callee);
1264 e = e->next_callee;
1269 /* Enqueue all recursive calls from NODE into priority queue depending on
1270 how likely we want to recursively inline the call. */
1272 static void
1273 lookup_recursive_calls (struct cgraph_node *node, struct cgraph_node *where,
1274 fibheap_t heap)
1276 struct cgraph_edge *e;
1277 enum availability avail;
1279 for (e = where->callees; e; e = e->next_callee)
1280 if (e->callee == node
1281 || (cgraph_function_or_thunk_node (e->callee, &avail) == node
1282 && avail > AVAIL_OVERWRITABLE))
1284 /* When profile feedback is available, prioritize by expected number
1285 of calls. */
1286 fibheap_insert (heap,
1287 !max_count ? -e->frequency
1288 : -(e->count / ((max_count + (1<<24) - 1) / (1<<24))),
1291 for (e = where->callees; e; e = e->next_callee)
1292 if (!e->inline_failed)
1293 lookup_recursive_calls (node, e->callee, heap);
1296 /* Decide on recursive inlining: in the case function has recursive calls,
1297 inline until body size reaches given argument. If any new indirect edges
1298 are discovered in the process, add them to *NEW_EDGES, unless NEW_EDGES
1299 is NULL. */
1301 static bool
1302 recursive_inlining (struct cgraph_edge *edge,
1303 vec<cgraph_edge_p> *new_edges)
1305 int limit = PARAM_VALUE (PARAM_MAX_INLINE_INSNS_RECURSIVE_AUTO);
1306 fibheap_t heap;
1307 struct cgraph_node *node;
1308 struct cgraph_edge *e;
1309 struct cgraph_node *master_clone = NULL, *next;
1310 int depth = 0;
1311 int n = 0;
1313 node = edge->caller;
1314 if (node->global.inlined_to)
1315 node = node->global.inlined_to;
1317 if (DECL_DECLARED_INLINE_P (node->decl))
1318 limit = PARAM_VALUE (PARAM_MAX_INLINE_INSNS_RECURSIVE);
1320 /* Make sure that function is small enough to be considered for inlining. */
1321 if (estimate_size_after_inlining (node, edge) >= limit)
1322 return false;
1323 heap = fibheap_new ();
1324 lookup_recursive_calls (node, node, heap);
1325 if (fibheap_empty (heap))
1327 fibheap_delete (heap);
1328 return false;
1331 if (dump_file)
1332 fprintf (dump_file,
1333 " Performing recursive inlining on %s\n",
1334 node->name ());
1336 /* Do the inlining and update list of recursive call during process. */
1337 while (!fibheap_empty (heap))
1339 struct cgraph_edge *curr
1340 = (struct cgraph_edge *) fibheap_extract_min (heap);
1341 struct cgraph_node *cnode, *dest = curr->callee;
1343 if (!can_inline_edge_p (curr, true))
1344 continue;
1346 /* MASTER_CLONE is produced in the case we already started modified
1347 the function. Be sure to redirect edge to the original body before
1348 estimating growths otherwise we will be seeing growths after inlining
1349 the already modified body. */
1350 if (master_clone)
1352 cgraph_redirect_edge_callee (curr, master_clone);
1353 reset_edge_growth_cache (curr);
1356 if (estimate_size_after_inlining (node, curr) > limit)
1358 cgraph_redirect_edge_callee (curr, dest);
1359 reset_edge_growth_cache (curr);
1360 break;
1363 depth = 1;
1364 for (cnode = curr->caller;
1365 cnode->global.inlined_to; cnode = cnode->callers->caller)
1366 if (node->decl
1367 == cgraph_function_or_thunk_node (curr->callee, NULL)->decl)
1368 depth++;
1370 if (!want_inline_self_recursive_call_p (curr, node, false, depth))
1372 cgraph_redirect_edge_callee (curr, dest);
1373 reset_edge_growth_cache (curr);
1374 continue;
1377 if (dump_file)
1379 fprintf (dump_file,
1380 " Inlining call of depth %i", depth);
1381 if (node->count)
1383 fprintf (dump_file, " called approx. %.2f times per call",
1384 (double)curr->count / node->count);
1386 fprintf (dump_file, "\n");
1388 if (!master_clone)
1390 /* We need original clone to copy around. */
1391 master_clone = cgraph_clone_node (node, node->decl,
1392 node->count, CGRAPH_FREQ_BASE,
1393 false, vNULL, true, NULL, NULL);
1394 for (e = master_clone->callees; e; e = e->next_callee)
1395 if (!e->inline_failed)
1396 clone_inlined_nodes (e, true, false, NULL, CGRAPH_FREQ_BASE);
1397 cgraph_redirect_edge_callee (curr, master_clone);
1398 reset_edge_growth_cache (curr);
1401 inline_call (curr, false, new_edges, &overall_size, true);
1402 lookup_recursive_calls (node, curr->callee, heap);
1403 n++;
1406 if (!fibheap_empty (heap) && dump_file)
1407 fprintf (dump_file, " Recursive inlining growth limit met.\n");
1408 fibheap_delete (heap);
1410 if (!master_clone)
1411 return false;
1413 if (dump_file)
1414 fprintf (dump_file,
1415 "\n Inlined %i times, "
1416 "body grown from size %i to %i, time %i to %i\n", n,
1417 inline_summary (master_clone)->size, inline_summary (node)->size,
1418 inline_summary (master_clone)->time, inline_summary (node)->time);
1420 /* Remove master clone we used for inlining. We rely that clones inlined
1421 into master clone gets queued just before master clone so we don't
1422 need recursion. */
1423 for (node = cgraph_first_function (); node != master_clone;
1424 node = next)
1426 next = cgraph_next_function (node);
1427 if (node->global.inlined_to == master_clone)
1428 cgraph_remove_node (node);
1430 cgraph_remove_node (master_clone);
1431 return true;
1435 /* Given whole compilation unit estimate of INSNS, compute how large we can
1436 allow the unit to grow. */
1438 static int
1439 compute_max_insns (int insns)
1441 int max_insns = insns;
1442 if (max_insns < PARAM_VALUE (PARAM_LARGE_UNIT_INSNS))
1443 max_insns = PARAM_VALUE (PARAM_LARGE_UNIT_INSNS);
1445 return ((int64_t) max_insns
1446 * (100 + PARAM_VALUE (PARAM_INLINE_UNIT_GROWTH)) / 100);
1450 /* Compute badness of all edges in NEW_EDGES and add them to the HEAP. */
1452 static void
1453 add_new_edges_to_heap (fibheap_t heap, vec<cgraph_edge_p> new_edges)
1455 while (new_edges.length () > 0)
1457 struct cgraph_edge *edge = new_edges.pop ();
1459 gcc_assert (!edge->aux);
1460 if (edge->inline_failed
1461 && can_inline_edge_p (edge, true)
1462 && want_inline_small_function_p (edge, true))
1463 edge->aux = fibheap_insert (heap, edge_badness (edge, false), edge);
1467 /* Remove EDGE from the fibheap. */
1469 static void
1470 heap_edge_removal_hook (struct cgraph_edge *e, void *data)
1472 if (e->callee)
1473 reset_node_growth_cache (e->callee);
1474 if (e->aux)
1476 fibheap_delete_node ((fibheap_t)data, (fibnode_t)e->aux);
1477 e->aux = NULL;
1481 /* Return true if speculation of edge E seems useful.
1482 If ANTICIPATE_INLINING is true, be conservative and hope that E
1483 may get inlined. */
1485 bool
1486 speculation_useful_p (struct cgraph_edge *e, bool anticipate_inlining)
1488 enum availability avail;
1489 struct cgraph_node *target = cgraph_function_or_thunk_node (e->callee, &avail);
1490 struct cgraph_edge *direct, *indirect;
1491 struct ipa_ref *ref;
1493 gcc_assert (e->speculative && !e->indirect_unknown_callee);
1495 if (!cgraph_maybe_hot_edge_p (e))
1496 return false;
1498 /* See if IP optimizations found something potentially useful about the
1499 function. For now we look only for CONST/PURE flags. Almost everything
1500 else we propagate is useless. */
1501 if (avail >= AVAIL_AVAILABLE)
1503 int ecf_flags = flags_from_decl_or_type (target->decl);
1504 if (ecf_flags & ECF_CONST)
1506 cgraph_speculative_call_info (e, direct, indirect, ref);
1507 if (!(indirect->indirect_info->ecf_flags & ECF_CONST))
1508 return true;
1510 else if (ecf_flags & ECF_PURE)
1512 cgraph_speculative_call_info (e, direct, indirect, ref);
1513 if (!(indirect->indirect_info->ecf_flags & ECF_PURE))
1514 return true;
1517 /* If we did not managed to inline the function nor redirect
1518 to an ipa-cp clone (that are seen by having local flag set),
1519 it is probably pointless to inline it unless hardware is missing
1520 indirect call predictor. */
1521 if (!anticipate_inlining && e->inline_failed && !target->local.local)
1522 return false;
1523 /* For overwritable targets there is not much to do. */
1524 if (e->inline_failed && !can_inline_edge_p (e, false, true))
1525 return false;
1526 /* OK, speculation seems interesting. */
1527 return true;
1530 /* We know that EDGE is not going to be inlined.
1531 See if we can remove speculation. */
1533 static void
1534 resolve_noninline_speculation (fibheap_t edge_heap, struct cgraph_edge *edge)
1536 if (edge->speculative && !speculation_useful_p (edge, false))
1538 struct cgraph_node *node = edge->caller;
1539 struct cgraph_node *where = node->global.inlined_to
1540 ? node->global.inlined_to : node;
1541 bitmap updated_nodes = BITMAP_ALLOC (NULL);
1543 spec_rem += edge->count;
1544 cgraph_resolve_speculation (edge, NULL);
1545 reset_edge_caches (where);
1546 inline_update_overall_summary (where);
1547 update_caller_keys (edge_heap, where,
1548 updated_nodes, NULL);
1549 update_callee_keys (edge_heap, where,
1550 updated_nodes);
1551 BITMAP_FREE (updated_nodes);
1555 /* We use greedy algorithm for inlining of small functions:
1556 All inline candidates are put into prioritized heap ordered in
1557 increasing badness.
1559 The inlining of small functions is bounded by unit growth parameters. */
1561 static void
1562 inline_small_functions (void)
1564 struct cgraph_node *node;
1565 struct cgraph_edge *edge;
1566 fibheap_t edge_heap = fibheap_new ();
1567 bitmap updated_nodes = BITMAP_ALLOC (NULL);
1568 int min_size, max_size;
1569 auto_vec<cgraph_edge_p> new_indirect_edges;
1570 int initial_size = 0;
1571 struct cgraph_node **order = XCNEWVEC (struct cgraph_node *, cgraph_n_nodes);
1572 struct cgraph_edge_hook_list *edge_removal_hook_holder;
1574 if (flag_indirect_inlining)
1575 new_indirect_edges.create (8);
1577 edge_removal_hook_holder
1578 = cgraph_add_edge_removal_hook (&heap_edge_removal_hook, edge_heap);
1580 /* Compute overall unit size and other global parameters used by badness
1581 metrics. */
1583 max_count = 0;
1584 ipa_reduced_postorder (order, true, true, NULL);
1585 free (order);
1587 FOR_EACH_DEFINED_FUNCTION (node)
1588 if (!node->global.inlined_to)
1590 if (cgraph_function_with_gimple_body_p (node)
1591 || node->thunk.thunk_p)
1593 struct inline_summary *info = inline_summary (node);
1594 struct ipa_dfs_info *dfs = (struct ipa_dfs_info *) node->aux;
1596 /* Do not account external functions, they will be optimized out
1597 if not inlined. Also only count the non-cold portion of program. */
1598 if (!DECL_EXTERNAL (node->decl)
1599 && node->frequency != NODE_FREQUENCY_UNLIKELY_EXECUTED)
1600 initial_size += info->size;
1601 info->growth = estimate_growth (node);
1602 if (dfs && dfs->next_cycle)
1604 struct cgraph_node *n2;
1605 int id = dfs->scc_no + 1;
1606 for (n2 = node; n2;
1607 n2 = ((struct ipa_dfs_info *) node->aux)->next_cycle)
1609 struct inline_summary *info2 = inline_summary (n2);
1610 if (info2->scc_no)
1611 break;
1612 info2->scc_no = id;
1617 for (edge = node->callers; edge; edge = edge->next_caller)
1618 if (max_count < edge->count)
1619 max_count = edge->count;
1621 sreal_init (&max_count_real, max_count, 0);
1622 sreal_init (&max_relbenefit_real, RELATIVE_TIME_BENEFIT_RANGE, 0);
1623 sreal_init (&half_int_min_real, INT_MAX / 2, 0);
1624 ipa_free_postorder_info ();
1625 initialize_growth_caches ();
1627 if (dump_file)
1628 fprintf (dump_file,
1629 "\nDeciding on inlining of small functions. Starting with size %i.\n",
1630 initial_size);
1632 overall_size = initial_size;
1633 max_size = compute_max_insns (overall_size);
1634 min_size = overall_size;
1636 /* Populate the heap with all edges we might inline. */
1638 FOR_EACH_DEFINED_FUNCTION (node)
1640 bool update = false;
1641 struct cgraph_edge *next;
1643 if (dump_file)
1644 fprintf (dump_file, "Enqueueing calls in %s/%i.\n",
1645 node->name (), node->order);
1647 for (edge = node->callees; edge; edge = next)
1649 next = edge->next_callee;
1650 if (edge->inline_failed
1651 && !edge->aux
1652 && can_inline_edge_p (edge, true)
1653 && want_inline_small_function_p (edge, true)
1654 && edge->inline_failed)
1656 gcc_assert (!edge->aux);
1657 update_edge_key (edge_heap, edge);
1659 if (edge->speculative && !speculation_useful_p (edge, edge->aux != NULL))
1661 cgraph_resolve_speculation (edge, NULL);
1662 update = true;
1665 if (update)
1667 struct cgraph_node *where = node->global.inlined_to
1668 ? node->global.inlined_to : node;
1669 inline_update_overall_summary (where);
1670 reset_node_growth_cache (where);
1671 reset_edge_caches (where);
1672 update_caller_keys (edge_heap, where,
1673 updated_nodes, NULL);
1674 bitmap_clear (updated_nodes);
1678 gcc_assert (in_lto_p
1679 || !max_count
1680 || (profile_info && flag_branch_probabilities));
1682 while (!fibheap_empty (edge_heap))
1684 int old_size = overall_size;
1685 struct cgraph_node *where, *callee;
1686 int badness = fibheap_min_key (edge_heap);
1687 int current_badness;
1688 int cached_badness;
1689 int growth;
1691 edge = (struct cgraph_edge *) fibheap_extract_min (edge_heap);
1692 gcc_assert (edge->aux);
1693 edge->aux = NULL;
1694 if (!edge->inline_failed || !edge->callee->analyzed)
1695 continue;
1697 /* Be sure that caches are maintained consistent.
1698 We can not make this ENABLE_CHECKING only because it cause different
1699 updates of the fibheap queue. */
1700 cached_badness = edge_badness (edge, false);
1701 reset_edge_growth_cache (edge);
1702 reset_node_growth_cache (edge->callee);
1704 /* When updating the edge costs, we only decrease badness in the keys.
1705 Increases of badness are handled lazilly; when we see key with out
1706 of date value on it, we re-insert it now. */
1707 current_badness = edge_badness (edge, false);
1708 gcc_assert (cached_badness == current_badness);
1709 gcc_assert (current_badness >= badness);
1710 if (current_badness != badness)
1712 edge->aux = fibheap_insert (edge_heap, current_badness, edge);
1713 continue;
1716 if (!can_inline_edge_p (edge, true))
1718 resolve_noninline_speculation (edge_heap, edge);
1719 continue;
1722 callee = cgraph_function_or_thunk_node (edge->callee, NULL);
1723 growth = estimate_edge_growth (edge);
1724 if (dump_file)
1726 fprintf (dump_file,
1727 "\nConsidering %s/%i with %i size\n",
1728 callee->name (), callee->order,
1729 inline_summary (callee)->size);
1730 fprintf (dump_file,
1731 " to be inlined into %s/%i in %s:%i\n"
1732 " Estimated badness is %i, frequency %.2f.\n",
1733 edge->caller->name (), edge->caller->order,
1734 flag_wpa ? "unknown"
1735 : gimple_filename ((const_gimple) edge->call_stmt),
1736 flag_wpa ? -1
1737 : gimple_lineno ((const_gimple) edge->call_stmt),
1738 badness,
1739 edge->frequency / (double)CGRAPH_FREQ_BASE);
1740 if (edge->count)
1741 fprintf (dump_file," Called %"PRId64"x\n",
1742 edge->count);
1743 if (dump_flags & TDF_DETAILS)
1744 edge_badness (edge, true);
1747 if (overall_size + growth > max_size
1748 && !DECL_DISREGARD_INLINE_LIMITS (callee->decl))
1750 edge->inline_failed = CIF_INLINE_UNIT_GROWTH_LIMIT;
1751 report_inline_failed_reason (edge);
1752 resolve_noninline_speculation (edge_heap, edge);
1753 continue;
1756 if (!want_inline_small_function_p (edge, true))
1758 resolve_noninline_speculation (edge_heap, edge);
1759 continue;
1762 /* Heuristics for inlining small functions work poorly for
1763 recursive calls where we do effects similar to loop unrolling.
1764 When inlining such edge seems profitable, leave decision on
1765 specific inliner. */
1766 if (cgraph_edge_recursive_p (edge))
1768 where = edge->caller;
1769 if (where->global.inlined_to)
1770 where = where->global.inlined_to;
1771 if (!recursive_inlining (edge,
1772 flag_indirect_inlining
1773 ? &new_indirect_edges : NULL))
1775 edge->inline_failed = CIF_RECURSIVE_INLINING;
1776 resolve_noninline_speculation (edge_heap, edge);
1777 continue;
1779 reset_edge_caches (where);
1780 /* Recursive inliner inlines all recursive calls of the function
1781 at once. Consequently we need to update all callee keys. */
1782 if (flag_indirect_inlining)
1783 add_new_edges_to_heap (edge_heap, new_indirect_edges);
1784 update_callee_keys (edge_heap, where, updated_nodes);
1785 bitmap_clear (updated_nodes);
1787 else
1789 struct cgraph_node *outer_node = NULL;
1790 int depth = 0;
1792 /* Consider the case where self recursive function A is inlined
1793 into B. This is desired optimization in some cases, since it
1794 leads to effect similar of loop peeling and we might completely
1795 optimize out the recursive call. However we must be extra
1796 selective. */
1798 where = edge->caller;
1799 while (where->global.inlined_to)
1801 if (where->decl == callee->decl)
1802 outer_node = where, depth++;
1803 where = where->callers->caller;
1805 if (outer_node
1806 && !want_inline_self_recursive_call_p (edge, outer_node,
1807 true, depth))
1809 edge->inline_failed
1810 = (DECL_DISREGARD_INLINE_LIMITS (edge->callee->decl)
1811 ? CIF_RECURSIVE_INLINING : CIF_UNSPECIFIED);
1812 resolve_noninline_speculation (edge_heap, edge);
1813 continue;
1815 else if (depth && dump_file)
1816 fprintf (dump_file, " Peeling recursion with depth %i\n", depth);
1818 gcc_checking_assert (!callee->global.inlined_to);
1819 inline_call (edge, true, &new_indirect_edges, &overall_size, true);
1820 if (flag_indirect_inlining)
1821 add_new_edges_to_heap (edge_heap, new_indirect_edges);
1823 reset_edge_caches (edge->callee);
1824 reset_node_growth_cache (callee);
1826 update_callee_keys (edge_heap, where, updated_nodes);
1828 where = edge->caller;
1829 if (where->global.inlined_to)
1830 where = where->global.inlined_to;
1832 /* Our profitability metric can depend on local properties
1833 such as number of inlinable calls and size of the function body.
1834 After inlining these properties might change for the function we
1835 inlined into (since it's body size changed) and for the functions
1836 called by function we inlined (since number of it inlinable callers
1837 might change). */
1838 update_caller_keys (edge_heap, where, updated_nodes, NULL);
1839 bitmap_clear (updated_nodes);
1841 if (dump_file)
1843 fprintf (dump_file,
1844 " Inlined into %s which now has time %i and size %i,"
1845 "net change of %+i.\n",
1846 edge->caller->name (),
1847 inline_summary (edge->caller)->time,
1848 inline_summary (edge->caller)->size,
1849 overall_size - old_size);
1851 if (min_size > overall_size)
1853 min_size = overall_size;
1854 max_size = compute_max_insns (min_size);
1856 if (dump_file)
1857 fprintf (dump_file, "New minimal size reached: %i\n", min_size);
1861 free_growth_caches ();
1862 fibheap_delete (edge_heap);
1863 if (dump_file)
1864 fprintf (dump_file,
1865 "Unit growth for small function inlining: %i->%i (%i%%)\n",
1866 initial_size, overall_size,
1867 initial_size ? overall_size * 100 / (initial_size) - 100: 0);
1868 BITMAP_FREE (updated_nodes);
1869 cgraph_remove_edge_removal_hook (edge_removal_hook_holder);
1872 /* Flatten NODE. Performed both during early inlining and
1873 at IPA inlining time. */
1875 static void
1876 flatten_function (struct cgraph_node *node, bool early)
1878 struct cgraph_edge *e;
1880 /* We shouldn't be called recursively when we are being processed. */
1881 gcc_assert (node->aux == NULL);
1883 node->aux = (void *) node;
1885 for (e = node->callees; e; e = e->next_callee)
1887 struct cgraph_node *orig_callee;
1888 struct cgraph_node *callee = cgraph_function_or_thunk_node (e->callee, NULL);
1890 /* We've hit cycle? It is time to give up. */
1891 if (callee->aux)
1893 if (dump_file)
1894 fprintf (dump_file,
1895 "Not inlining %s into %s to avoid cycle.\n",
1896 xstrdup (callee->name ()),
1897 xstrdup (e->caller->name ()));
1898 e->inline_failed = CIF_RECURSIVE_INLINING;
1899 continue;
1902 /* When the edge is already inlined, we just need to recurse into
1903 it in order to fully flatten the leaves. */
1904 if (!e->inline_failed)
1906 flatten_function (callee, early);
1907 continue;
1910 /* Flatten attribute needs to be processed during late inlining. For
1911 extra code quality we however do flattening during early optimization,
1912 too. */
1913 if (!early
1914 ? !can_inline_edge_p (e, true)
1915 : !can_early_inline_edge_p (e))
1916 continue;
1918 if (cgraph_edge_recursive_p (e))
1920 if (dump_file)
1921 fprintf (dump_file, "Not inlining: recursive call.\n");
1922 continue;
1925 if (gimple_in_ssa_p (DECL_STRUCT_FUNCTION (node->decl))
1926 != gimple_in_ssa_p (DECL_STRUCT_FUNCTION (callee->decl)))
1928 if (dump_file)
1929 fprintf (dump_file, "Not inlining: SSA form does not match.\n");
1930 continue;
1933 /* Inline the edge and flatten the inline clone. Avoid
1934 recursing through the original node if the node was cloned. */
1935 if (dump_file)
1936 fprintf (dump_file, " Inlining %s into %s.\n",
1937 xstrdup (callee->name ()),
1938 xstrdup (e->caller->name ()));
1939 orig_callee = callee;
1940 inline_call (e, true, NULL, NULL, false);
1941 if (e->callee != orig_callee)
1942 orig_callee->aux = (void *) node;
1943 flatten_function (e->callee, early);
1944 if (e->callee != orig_callee)
1945 orig_callee->aux = NULL;
1948 node->aux = NULL;
1949 if (!node->global.inlined_to)
1950 inline_update_overall_summary (node);
1953 /* Count number of callers of NODE and store it into DATA (that
1954 points to int. Worker for cgraph_for_node_and_aliases. */
1956 static bool
1957 sum_callers (struct cgraph_node *node, void *data)
1959 struct cgraph_edge *e;
1960 int *num_calls = (int *)data;
1962 for (e = node->callers; e; e = e->next_caller)
1963 (*num_calls)++;
1964 return false;
1967 /* Inline NODE to all callers. Worker for cgraph_for_node_and_aliases.
1968 DATA points to number of calls originally found so we avoid infinite
1969 recursion. */
1971 static bool
1972 inline_to_all_callers (struct cgraph_node *node, void *data)
1974 int *num_calls = (int *)data;
1975 bool callee_removed = false;
1977 while (node->callers && !node->global.inlined_to)
1979 struct cgraph_node *caller = node->callers->caller;
1981 if (dump_file)
1983 fprintf (dump_file,
1984 "\nInlining %s size %i.\n",
1985 node->name (),
1986 inline_summary (node)->size);
1987 fprintf (dump_file,
1988 " Called once from %s %i insns.\n",
1989 node->callers->caller->name (),
1990 inline_summary (node->callers->caller)->size);
1993 inline_call (node->callers, true, NULL, NULL, true, &callee_removed);
1994 if (dump_file)
1995 fprintf (dump_file,
1996 " Inlined into %s which now has %i size\n",
1997 caller->name (),
1998 inline_summary (caller)->size);
1999 if (!(*num_calls)--)
2001 if (dump_file)
2002 fprintf (dump_file, "New calls found; giving up.\n");
2003 return callee_removed;
2005 if (callee_removed)
2006 return true;
2008 return false;
2011 /* Output overall time estimate. */
2012 static void
2013 dump_overall_stats (void)
2015 int64_t sum_weighted = 0, sum = 0;
2016 struct cgraph_node *node;
2018 FOR_EACH_DEFINED_FUNCTION (node)
2019 if (!node->global.inlined_to
2020 && !node->alias)
2022 int time = inline_summary (node)->time;
2023 sum += time;
2024 sum_weighted += time * node->count;
2026 fprintf (dump_file, "Overall time estimate: "
2027 "%"PRId64" weighted by profile: "
2028 "%"PRId64"\n", sum, sum_weighted);
2031 /* Output some useful stats about inlining. */
2033 static void
2034 dump_inline_stats (void)
2036 int64_t inlined_cnt = 0, inlined_indir_cnt = 0;
2037 int64_t inlined_virt_cnt = 0, inlined_virt_indir_cnt = 0;
2038 int64_t noninlined_cnt = 0, noninlined_indir_cnt = 0;
2039 int64_t noninlined_virt_cnt = 0, noninlined_virt_indir_cnt = 0;
2040 int64_t inlined_speculative = 0, inlined_speculative_ply = 0;
2041 int64_t indirect_poly_cnt = 0, indirect_cnt = 0;
2042 int64_t reason[CIF_N_REASONS][3];
2043 int i;
2044 struct cgraph_node *node;
2046 memset (reason, 0, sizeof (reason));
2047 FOR_EACH_DEFINED_FUNCTION (node)
2049 struct cgraph_edge *e;
2050 for (e = node->callees; e; e = e->next_callee)
2052 if (e->inline_failed)
2054 reason[(int) e->inline_failed][0] += e->count;
2055 reason[(int) e->inline_failed][1] += e->frequency;
2056 reason[(int) e->inline_failed][2] ++;
2057 if (DECL_VIRTUAL_P (e->callee->decl))
2059 if (e->indirect_inlining_edge)
2060 noninlined_virt_indir_cnt += e->count;
2061 else
2062 noninlined_virt_cnt += e->count;
2064 else
2066 if (e->indirect_inlining_edge)
2067 noninlined_indir_cnt += e->count;
2068 else
2069 noninlined_cnt += e->count;
2072 else
2074 if (e->speculative)
2076 if (DECL_VIRTUAL_P (e->callee->decl))
2077 inlined_speculative_ply += e->count;
2078 else
2079 inlined_speculative += e->count;
2081 else if (DECL_VIRTUAL_P (e->callee->decl))
2083 if (e->indirect_inlining_edge)
2084 inlined_virt_indir_cnt += e->count;
2085 else
2086 inlined_virt_cnt += e->count;
2088 else
2090 if (e->indirect_inlining_edge)
2091 inlined_indir_cnt += e->count;
2092 else
2093 inlined_cnt += e->count;
2097 for (e = node->indirect_calls; e; e = e->next_callee)
2098 if (e->indirect_info->polymorphic)
2099 indirect_poly_cnt += e->count;
2100 else
2101 indirect_cnt += e->count;
2103 if (max_count)
2105 fprintf (dump_file,
2106 "Inlined %"PRId64 " + speculative "
2107 "%"PRId64 " + speculative polymorphic "
2108 "%"PRId64 " + previously indirect "
2109 "%"PRId64 " + virtual "
2110 "%"PRId64 " + virtual and previously indirect "
2111 "%"PRId64 "\n" "Not inlined "
2112 "%"PRId64 " + previously indirect "
2113 "%"PRId64 " + virtual "
2114 "%"PRId64 " + virtual and previously indirect "
2115 "%"PRId64 " + stil indirect "
2116 "%"PRId64 " + still indirect polymorphic "
2117 "%"PRId64 "\n", inlined_cnt,
2118 inlined_speculative, inlined_speculative_ply,
2119 inlined_indir_cnt, inlined_virt_cnt, inlined_virt_indir_cnt,
2120 noninlined_cnt, noninlined_indir_cnt, noninlined_virt_cnt,
2121 noninlined_virt_indir_cnt, indirect_cnt, indirect_poly_cnt);
2122 fprintf (dump_file,
2123 "Removed speculations %"PRId64 "\n",
2124 spec_rem);
2126 dump_overall_stats ();
2127 fprintf (dump_file, "\nWhy inlining failed?\n");
2128 for (i = 0; i < CIF_N_REASONS; i++)
2129 if (reason[i][2])
2130 fprintf (dump_file, "%-50s: %8i calls, %8i freq, %"PRId64" count\n",
2131 cgraph_inline_failed_string ((cgraph_inline_failed_t) i),
2132 (int) reason[i][2], (int) reason[i][1], reason[i][0]);
2135 /* Decide on the inlining. We do so in the topological order to avoid
2136 expenses on updating data structures. */
2138 static unsigned int
2139 ipa_inline (void)
2141 struct cgraph_node *node;
2142 int nnodes;
2143 struct cgraph_node **order;
2144 int i;
2145 int cold;
2146 bool remove_functions = false;
2148 if (!optimize)
2149 return 0;
2151 order = XCNEWVEC (struct cgraph_node *, cgraph_n_nodes);
2153 if (in_lto_p && optimize)
2154 ipa_update_after_lto_read ();
2156 if (dump_file)
2157 dump_inline_summaries (dump_file);
2159 nnodes = ipa_reverse_postorder (order);
2161 FOR_EACH_FUNCTION (node)
2162 node->aux = 0;
2164 if (dump_file)
2165 fprintf (dump_file, "\nFlattening functions:\n");
2167 /* In the first pass handle functions to be flattened. Do this with
2168 a priority so none of our later choices will make this impossible. */
2169 for (i = nnodes - 1; i >= 0; i--)
2171 node = order[i];
2173 /* Handle nodes to be flattened.
2174 Ideally when processing callees we stop inlining at the
2175 entry of cycles, possibly cloning that entry point and
2176 try to flatten itself turning it into a self-recursive
2177 function. */
2178 if (lookup_attribute ("flatten",
2179 DECL_ATTRIBUTES (node->decl)) != NULL)
2181 if (dump_file)
2182 fprintf (dump_file,
2183 "Flattening %s\n", node->name ());
2184 flatten_function (node, false);
2187 if (dump_file)
2188 dump_overall_stats ();
2190 inline_small_functions ();
2192 /* Do first after-inlining removal. We want to remove all "stale" extern inline
2193 functions and virtual functions so we really know what is called once. */
2194 symtab_remove_unreachable_nodes (false, dump_file);
2195 free (order);
2197 /* Inline functions with a property that after inlining into all callers the
2198 code size will shrink because the out-of-line copy is eliminated.
2199 We do this regardless on the callee size as long as function growth limits
2200 are met. */
2201 if (dump_file)
2202 fprintf (dump_file,
2203 "\nDeciding on functions to be inlined into all callers and removing useless speculations:\n");
2205 /* Inlining one function called once has good chance of preventing
2206 inlining other function into the same callee. Ideally we should
2207 work in priority order, but probably inlining hot functions first
2208 is good cut without the extra pain of maintaining the queue.
2210 ??? this is not really fitting the bill perfectly: inlining function
2211 into callee often leads to better optimization of callee due to
2212 increased context for optimization.
2213 For example if main() function calls a function that outputs help
2214 and then function that does the main optmization, we should inline
2215 the second with priority even if both calls are cold by themselves.
2217 We probably want to implement new predicate replacing our use of
2218 maybe_hot_edge interpreted as maybe_hot_edge || callee is known
2219 to be hot. */
2220 for (cold = 0; cold <= 1; cold ++)
2222 FOR_EACH_DEFINED_FUNCTION (node)
2224 struct cgraph_edge *edge, *next;
2225 bool update=false;
2227 for (edge = node->callees; edge; edge = next)
2229 next = edge->next_callee;
2230 if (edge->speculative && !speculation_useful_p (edge, false))
2232 cgraph_resolve_speculation (edge, NULL);
2233 spec_rem += edge->count;
2234 update = true;
2235 remove_functions = true;
2238 if (update)
2240 struct cgraph_node *where = node->global.inlined_to
2241 ? node->global.inlined_to : node;
2242 reset_node_growth_cache (where);
2243 reset_edge_caches (where);
2244 inline_update_overall_summary (where);
2246 if (flag_inline_functions_called_once
2247 && want_inline_function_to_all_callers_p (node, cold))
2249 int num_calls = 0;
2250 cgraph_for_node_and_aliases (node, sum_callers,
2251 &num_calls, true);
2252 while (cgraph_for_node_and_aliases (node, inline_to_all_callers,
2253 &num_calls, true))
2255 remove_functions = true;
2260 /* Free ipa-prop structures if they are no longer needed. */
2261 if (optimize)
2262 ipa_free_all_structures_after_iinln ();
2264 if (dump_file)
2266 fprintf (dump_file,
2267 "\nInlined %i calls, eliminated %i functions\n\n",
2268 ncalls_inlined, nfunctions_inlined);
2269 dump_inline_stats ();
2272 if (dump_file)
2273 dump_inline_summaries (dump_file);
2274 /* In WPA we use inline summaries for partitioning process. */
2275 if (!flag_wpa)
2276 inline_free_summary ();
2277 return remove_functions ? TODO_remove_functions : 0;
2280 /* Inline always-inline function calls in NODE. */
2282 static bool
2283 inline_always_inline_functions (struct cgraph_node *node)
2285 struct cgraph_edge *e;
2286 bool inlined = false;
2288 for (e = node->callees; e; e = e->next_callee)
2290 struct cgraph_node *callee = cgraph_function_or_thunk_node (e->callee, NULL);
2291 if (!DECL_DISREGARD_INLINE_LIMITS (callee->decl))
2292 continue;
2294 if (cgraph_edge_recursive_p (e))
2296 if (dump_file)
2297 fprintf (dump_file, " Not inlining recursive call to %s.\n",
2298 e->callee->name ());
2299 e->inline_failed = CIF_RECURSIVE_INLINING;
2300 continue;
2303 if (!can_early_inline_edge_p (e))
2305 /* Set inlined to true if the callee is marked "always_inline" but
2306 is not inlinable. This will allow flagging an error later in
2307 expand_call_inline in tree-inline.c. */
2308 if (lookup_attribute ("always_inline",
2309 DECL_ATTRIBUTES (callee->decl)) != NULL)
2310 inlined = true;
2311 continue;
2314 if (dump_file)
2315 fprintf (dump_file, " Inlining %s into %s (always_inline).\n",
2316 xstrdup (e->callee->name ()),
2317 xstrdup (e->caller->name ()));
2318 inline_call (e, true, NULL, NULL, false);
2319 inlined = true;
2321 if (inlined)
2322 inline_update_overall_summary (node);
2324 return inlined;
2327 /* Decide on the inlining. We do so in the topological order to avoid
2328 expenses on updating data structures. */
2330 static bool
2331 early_inline_small_functions (struct cgraph_node *node)
2333 struct cgraph_edge *e;
2334 bool inlined = false;
2336 for (e = node->callees; e; e = e->next_callee)
2338 struct cgraph_node *callee = cgraph_function_or_thunk_node (e->callee, NULL);
2339 if (!inline_summary (callee)->inlinable
2340 || !e->inline_failed)
2341 continue;
2343 /* Do not consider functions not declared inline. */
2344 if (!DECL_DECLARED_INLINE_P (callee->decl)
2345 && !flag_inline_small_functions
2346 && !flag_inline_functions)
2347 continue;
2349 if (dump_file)
2350 fprintf (dump_file, "Considering inline candidate %s.\n",
2351 callee->name ());
2353 if (!can_early_inline_edge_p (e))
2354 continue;
2356 if (cgraph_edge_recursive_p (e))
2358 if (dump_file)
2359 fprintf (dump_file, " Not inlining: recursive call.\n");
2360 continue;
2363 if (!want_early_inline_function_p (e))
2364 continue;
2366 if (dump_file)
2367 fprintf (dump_file, " Inlining %s into %s.\n",
2368 xstrdup (callee->name ()),
2369 xstrdup (e->caller->name ()));
2370 inline_call (e, true, NULL, NULL, true);
2371 inlined = true;
2374 return inlined;
2377 /* Do inlining of small functions. Doing so early helps profiling and other
2378 passes to be somewhat more effective and avoids some code duplication in
2379 later real inlining pass for testcases with very many function calls. */
2381 namespace {
2383 const pass_data pass_data_early_inline =
2385 GIMPLE_PASS, /* type */
2386 "einline", /* name */
2387 OPTGROUP_INLINE, /* optinfo_flags */
2388 true, /* has_execute */
2389 TV_EARLY_INLINING, /* tv_id */
2390 PROP_ssa, /* properties_required */
2391 0, /* properties_provided */
2392 0, /* properties_destroyed */
2393 0, /* todo_flags_start */
2394 0, /* todo_flags_finish */
2397 class pass_early_inline : public gimple_opt_pass
2399 public:
2400 pass_early_inline (gcc::context *ctxt)
2401 : gimple_opt_pass (pass_data_early_inline, ctxt)
2404 /* opt_pass methods: */
2405 virtual unsigned int execute (function *);
2407 }; // class pass_early_inline
2409 unsigned int
2410 pass_early_inline::execute (function *fun)
2412 struct cgraph_node *node = cgraph_get_node (current_function_decl);
2413 struct cgraph_edge *edge;
2414 unsigned int todo = 0;
2415 int iterations = 0;
2416 bool inlined = false;
2418 if (seen_error ())
2419 return 0;
2421 /* Do nothing if datastructures for ipa-inliner are already computed. This
2422 happens when some pass decides to construct new function and
2423 cgraph_add_new_function calls lowering passes and early optimization on
2424 it. This may confuse ourself when early inliner decide to inline call to
2425 function clone, because function clones don't have parameter list in
2426 ipa-prop matching their signature. */
2427 if (ipa_node_params_vector.exists ())
2428 return 0;
2430 #ifdef ENABLE_CHECKING
2431 verify_cgraph_node (node);
2432 #endif
2433 ipa_remove_all_references (&node->ref_list);
2435 /* Even when not optimizing or not inlining inline always-inline
2436 functions. */
2437 inlined = inline_always_inline_functions (node);
2439 if (!optimize
2440 || flag_no_inline
2441 || !flag_early_inlining
2442 /* Never inline regular functions into always-inline functions
2443 during incremental inlining. This sucks as functions calling
2444 always inline functions will get less optimized, but at the
2445 same time inlining of functions calling always inline
2446 function into an always inline function might introduce
2447 cycles of edges to be always inlined in the callgraph.
2449 We might want to be smarter and just avoid this type of inlining. */
2450 || DECL_DISREGARD_INLINE_LIMITS (node->decl))
2452 else if (lookup_attribute ("flatten",
2453 DECL_ATTRIBUTES (node->decl)) != NULL)
2455 /* When the function is marked to be flattened, recursively inline
2456 all calls in it. */
2457 if (dump_file)
2458 fprintf (dump_file,
2459 "Flattening %s\n", node->name ());
2460 flatten_function (node, true);
2461 inlined = true;
2463 else
2465 /* We iterate incremental inlining to get trivial cases of indirect
2466 inlining. */
2467 while (iterations < PARAM_VALUE (PARAM_EARLY_INLINER_MAX_ITERATIONS)
2468 && early_inline_small_functions (node))
2470 timevar_push (TV_INTEGRATION);
2471 todo |= optimize_inline_calls (current_function_decl);
2473 /* Technically we ought to recompute inline parameters so the new
2474 iteration of early inliner works as expected. We however have
2475 values approximately right and thus we only need to update edge
2476 info that might be cleared out for newly discovered edges. */
2477 for (edge = node->callees; edge; edge = edge->next_callee)
2479 struct inline_edge_summary *es = inline_edge_summary (edge);
2480 es->call_stmt_size
2481 = estimate_num_insns (edge->call_stmt, &eni_size_weights);
2482 es->call_stmt_time
2483 = estimate_num_insns (edge->call_stmt, &eni_time_weights);
2484 if (edge->callee->decl
2485 && !gimple_check_call_matching_types (
2486 edge->call_stmt, edge->callee->decl, false))
2487 edge->call_stmt_cannot_inline_p = true;
2489 if (iterations < PARAM_VALUE (PARAM_EARLY_INLINER_MAX_ITERATIONS) - 1)
2490 inline_update_overall_summary (node);
2491 timevar_pop (TV_INTEGRATION);
2492 iterations++;
2493 inlined = false;
2495 if (dump_file)
2496 fprintf (dump_file, "Iterations: %i\n", iterations);
2499 if (inlined)
2501 timevar_push (TV_INTEGRATION);
2502 todo |= optimize_inline_calls (current_function_decl);
2503 timevar_pop (TV_INTEGRATION);
2506 fun->always_inline_functions_inlined = true;
2508 return todo;
2511 } // anon namespace
2513 gimple_opt_pass *
2514 make_pass_early_inline (gcc::context *ctxt)
2516 return new pass_early_inline (ctxt);
2519 namespace {
2521 const pass_data pass_data_ipa_inline =
2523 IPA_PASS, /* type */
2524 "inline", /* name */
2525 OPTGROUP_INLINE, /* optinfo_flags */
2526 true, /* has_execute */
2527 TV_IPA_INLINING, /* tv_id */
2528 0, /* properties_required */
2529 0, /* properties_provided */
2530 0, /* properties_destroyed */
2531 TODO_remove_functions, /* todo_flags_start */
2532 ( TODO_dump_symtab ), /* todo_flags_finish */
2535 class pass_ipa_inline : public ipa_opt_pass_d
2537 public:
2538 pass_ipa_inline (gcc::context *ctxt)
2539 : ipa_opt_pass_d (pass_data_ipa_inline, ctxt,
2540 inline_generate_summary, /* generate_summary */
2541 inline_write_summary, /* write_summary */
2542 inline_read_summary, /* read_summary */
2543 NULL, /* write_optimization_summary */
2544 NULL, /* read_optimization_summary */
2545 NULL, /* stmt_fixup */
2546 0, /* function_transform_todo_flags_start */
2547 inline_transform, /* function_transform */
2548 NULL) /* variable_transform */
2551 /* opt_pass methods: */
2552 virtual unsigned int execute (function *) { return ipa_inline (); }
2554 }; // class pass_ipa_inline
2556 } // anon namespace
2558 ipa_opt_pass_d *
2559 make_pass_ipa_inline (gcc::context *ctxt)
2561 return new pass_ipa_inline (ctxt);