libgomp: Use pthread mutexes in the nvptx plugin.
[official-gcc.git] / gcc / ipa-inline.c
blobe9ad2448635396680cf81586696b063feee0aacf
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"
149 typedef fibonacci_heap <sreal, cgraph_edge> edge_heap_t;
150 typedef fibonacci_node <sreal, cgraph_edge> edge_heap_node_t;
152 /* Statistics we collect about inlining algorithm. */
153 static int overall_size;
154 static gcov_type max_count;
155 static gcov_type spec_rem;
157 /* Pre-computed constants 1/CGRAPH_FREQ_BASE and 1/100. */
158 static sreal cgraph_freq_base_rec, percent_rec;
160 /* Return false when inlining edge E would lead to violating
161 limits on function unit growth or stack usage growth.
163 The relative function body growth limit is present generally
164 to avoid problems with non-linear behavior of the compiler.
165 To allow inlining huge functions into tiny wrapper, the limit
166 is always based on the bigger of the two functions considered.
168 For stack growth limits we always base the growth in stack usage
169 of the callers. We want to prevent applications from segfaulting
170 on stack overflow when functions with huge stack frames gets
171 inlined. */
173 static bool
174 caller_growth_limits (struct cgraph_edge *e)
176 struct cgraph_node *to = e->caller;
177 struct cgraph_node *what = e->callee->ultimate_alias_target ();
178 int newsize;
179 int limit = 0;
180 HOST_WIDE_INT stack_size_limit = 0, inlined_stack;
181 inline_summary *info, *what_info, *outer_info = inline_summaries->get (to);
183 /* Look for function e->caller is inlined to. While doing
184 so work out the largest function body on the way. As
185 described above, we want to base our function growth
186 limits based on that. Not on the self size of the
187 outer function, not on the self size of inline code
188 we immediately inline to. This is the most relaxed
189 interpretation of the rule "do not grow large functions
190 too much in order to prevent compiler from exploding". */
191 while (true)
193 info = inline_summaries->get (to);
194 if (limit < info->self_size)
195 limit = info->self_size;
196 if (stack_size_limit < info->estimated_self_stack_size)
197 stack_size_limit = info->estimated_self_stack_size;
198 if (to->global.inlined_to)
199 to = to->callers->caller;
200 else
201 break;
204 what_info = inline_summaries->get (what);
206 if (limit < what_info->self_size)
207 limit = what_info->self_size;
209 limit += limit * PARAM_VALUE (PARAM_LARGE_FUNCTION_GROWTH) / 100;
211 /* Check the size after inlining against the function limits. But allow
212 the function to shrink if it went over the limits by forced inlining. */
213 newsize = estimate_size_after_inlining (to, e);
214 if (newsize >= info->size
215 && newsize > PARAM_VALUE (PARAM_LARGE_FUNCTION_INSNS)
216 && newsize > limit)
218 e->inline_failed = CIF_LARGE_FUNCTION_GROWTH_LIMIT;
219 return false;
222 if (!what_info->estimated_stack_size)
223 return true;
225 /* FIXME: Stack size limit often prevents inlining in Fortran programs
226 due to large i/o datastructures used by the Fortran front-end.
227 We ought to ignore this limit when we know that the edge is executed
228 on every invocation of the caller (i.e. its call statement dominates
229 exit block). We do not track this information, yet. */
230 stack_size_limit += ((gcov_type)stack_size_limit
231 * PARAM_VALUE (PARAM_STACK_FRAME_GROWTH) / 100);
233 inlined_stack = (outer_info->stack_frame_offset
234 + outer_info->estimated_self_stack_size
235 + what_info->estimated_stack_size);
236 /* Check new stack consumption with stack consumption at the place
237 stack is used. */
238 if (inlined_stack > stack_size_limit
239 /* If function already has large stack usage from sibling
240 inline call, we can inline, too.
241 This bit overoptimistically assume that we are good at stack
242 packing. */
243 && inlined_stack > info->estimated_stack_size
244 && inlined_stack > PARAM_VALUE (PARAM_LARGE_STACK_FRAME))
246 e->inline_failed = CIF_LARGE_STACK_FRAME_GROWTH_LIMIT;
247 return false;
249 return true;
252 /* Dump info about why inlining has failed. */
254 static void
255 report_inline_failed_reason (struct cgraph_edge *e)
257 if (dump_file)
259 fprintf (dump_file, " not inlinable: %s/%i -> %s/%i, %s\n",
260 xstrdup_for_dump (e->caller->name ()), e->caller->order,
261 xstrdup_for_dump (e->callee->name ()), e->callee->order,
262 cgraph_inline_failed_string (e->inline_failed));
266 /* Decide whether sanitizer-related attributes allow inlining. */
268 static bool
269 sanitize_attrs_match_for_inline_p (const_tree caller, const_tree callee)
271 /* Don't care if sanitizer is disabled */
272 if (!(flag_sanitize & SANITIZE_ADDRESS))
273 return true;
275 if (!caller || !callee)
276 return true;
278 return !!lookup_attribute ("no_sanitize_address",
279 DECL_ATTRIBUTES (caller)) ==
280 !!lookup_attribute ("no_sanitize_address",
281 DECL_ATTRIBUTES (callee));
284 /* Decide if we can inline the edge and possibly update
285 inline_failed reason.
286 We check whether inlining is possible at all and whether
287 caller growth limits allow doing so.
289 if REPORT is true, output reason to the dump file.
291 if DISREGARD_LIMITS is true, ignore size limits.*/
293 static bool
294 can_inline_edge_p (struct cgraph_edge *e, bool report,
295 bool disregard_limits = false)
297 bool inlinable = true;
298 enum availability avail;
299 cgraph_node *callee = e->callee->ultimate_alias_target (&avail);
300 tree caller_tree = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (e->caller->decl);
301 tree callee_tree
302 = callee ? DECL_FUNCTION_SPECIFIC_OPTIMIZATION (callee->decl) : NULL;
303 struct function *caller_fun = e->caller->get_fun ();
304 struct function *callee_fun = callee ? callee->get_fun () : NULL;
306 gcc_assert (e->inline_failed);
308 if (!callee || !callee->definition)
310 e->inline_failed = CIF_BODY_NOT_AVAILABLE;
311 inlinable = false;
313 else if (callee->calls_comdat_local)
315 e->inline_failed = CIF_USES_COMDAT_LOCAL;
316 inlinable = false;
318 else if (!inline_summaries->get (callee)->inlinable
319 || (caller_fun && fn_contains_cilk_spawn_p (caller_fun)))
321 e->inline_failed = CIF_FUNCTION_NOT_INLINABLE;
322 inlinable = false;
324 else if (avail <= AVAIL_INTERPOSABLE)
326 e->inline_failed = CIF_OVERWRITABLE;
327 inlinable = false;
329 else if (e->call_stmt_cannot_inline_p)
331 if (e->inline_failed != CIF_FUNCTION_NOT_OPTIMIZED)
332 e->inline_failed = CIF_MISMATCHED_ARGUMENTS;
333 inlinable = false;
335 /* Don't inline if the functions have different EH personalities. */
336 else if (DECL_FUNCTION_PERSONALITY (e->caller->decl)
337 && DECL_FUNCTION_PERSONALITY (callee->decl)
338 && (DECL_FUNCTION_PERSONALITY (e->caller->decl)
339 != DECL_FUNCTION_PERSONALITY (callee->decl)))
341 e->inline_failed = CIF_EH_PERSONALITY;
342 inlinable = false;
344 /* TM pure functions should not be inlined into non-TM_pure
345 functions. */
346 else if (is_tm_pure (callee->decl)
347 && !is_tm_pure (e->caller->decl))
349 e->inline_failed = CIF_UNSPECIFIED;
350 inlinable = false;
352 /* Don't inline if the callee can throw non-call exceptions but the
353 caller cannot.
354 FIXME: this is obviously wrong for LTO where STRUCT_FUNCTION is missing.
355 Move the flag into cgraph node or mirror it in the inline summary. */
356 else if (callee_fun && callee_fun->can_throw_non_call_exceptions
357 && !(caller_fun && caller_fun->can_throw_non_call_exceptions))
359 e->inline_failed = CIF_NON_CALL_EXCEPTIONS;
360 inlinable = false;
362 /* Check compatibility of target optimization options. */
363 else if (!targetm.target_option.can_inline_p (e->caller->decl,
364 callee->decl))
366 e->inline_failed = CIF_TARGET_OPTION_MISMATCH;
367 inlinable = false;
369 /* Don't inline a function with mismatched sanitization attributes. */
370 else if (!sanitize_attrs_match_for_inline_p (e->caller->decl, callee->decl))
372 e->inline_failed = CIF_ATTRIBUTE_MISMATCH;
373 inlinable = false;
375 /* Check if caller growth allows the inlining. */
376 else if (!DECL_DISREGARD_INLINE_LIMITS (callee->decl)
377 && !disregard_limits
378 && !lookup_attribute ("flatten",
379 DECL_ATTRIBUTES
380 (e->caller->global.inlined_to
381 ? e->caller->global.inlined_to->decl
382 : e->caller->decl))
383 && !caller_growth_limits (e))
384 inlinable = false;
385 /* Don't inline a function with a higher optimization level than the
386 caller. FIXME: this is really just tip of iceberg of handling
387 optimization attribute. */
388 else if (caller_tree != callee_tree)
390 if (((opt_for_fn (e->caller->decl, optimize)
391 > opt_for_fn (e->callee->decl, optimize))
392 || (opt_for_fn (e->caller->decl, optimize_size)
393 != opt_for_fn (e->callee->decl, optimize_size)))
394 /* gcc.dg/pr43564.c. Look at forced inline even in -O0. */
395 && !DECL_DISREGARD_INLINE_LIMITS (e->callee->decl))
397 e->inline_failed = CIF_OPTIMIZATION_MISMATCH;
398 inlinable = false;
402 if (!inlinable && report)
403 report_inline_failed_reason (e);
404 return inlinable;
408 /* Return true if the edge E is inlinable during early inlining. */
410 static bool
411 can_early_inline_edge_p (struct cgraph_edge *e)
413 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
414 /* Early inliner might get called at WPA stage when IPA pass adds new
415 function. In this case we can not really do any of early inlining
416 because function bodies are missing. */
417 if (!gimple_has_body_p (callee->decl))
419 e->inline_failed = CIF_BODY_NOT_AVAILABLE;
420 return false;
422 /* In early inliner some of callees may not be in SSA form yet
423 (i.e. the callgraph is cyclic and we did not process
424 the callee by early inliner, yet). We don't have CIF code for this
425 case; later we will re-do the decision in the real inliner. */
426 if (!gimple_in_ssa_p (DECL_STRUCT_FUNCTION (e->caller->decl))
427 || !gimple_in_ssa_p (DECL_STRUCT_FUNCTION (callee->decl)))
429 if (dump_file)
430 fprintf (dump_file, " edge not inlinable: not in SSA form\n");
431 return false;
433 if (!can_inline_edge_p (e, true))
434 return false;
435 return true;
439 /* Return number of calls in N. Ignore cheap builtins. */
441 static int
442 num_calls (struct cgraph_node *n)
444 struct cgraph_edge *e;
445 int num = 0;
447 for (e = n->callees; e; e = e->next_callee)
448 if (!is_inexpensive_builtin (e->callee->decl))
449 num++;
450 return num;
454 /* Return true if we are interested in inlining small function. */
456 static bool
457 want_early_inline_function_p (struct cgraph_edge *e)
459 bool want_inline = true;
460 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
462 if (DECL_DISREGARD_INLINE_LIMITS (callee->decl))
464 /* For AutoFDO, we need to make sure that before profile summary, all
465 hot paths' IR look exactly the same as profiled binary. As a result,
466 in einliner, we will disregard size limit and inline those callsites
467 that are:
468 * inlined in the profiled binary, and
469 * the cloned callee has enough samples to be considered "hot". */
470 else if (flag_auto_profile && afdo_callsite_hot_enough_for_early_inline (e))
472 else if (!DECL_DECLARED_INLINE_P (callee->decl)
473 && !opt_for_fn (e->caller->decl, flag_inline_small_functions))
475 e->inline_failed = CIF_FUNCTION_NOT_INLINE_CANDIDATE;
476 report_inline_failed_reason (e);
477 want_inline = false;
479 else
481 int growth = estimate_edge_growth (e);
482 int n;
484 if (growth <= 0)
486 else if (!e->maybe_hot_p ()
487 && growth > 0)
489 if (dump_file)
490 fprintf (dump_file, " will not early inline: %s/%i->%s/%i, "
491 "call is cold and code would grow by %i\n",
492 xstrdup_for_dump (e->caller->name ()),
493 e->caller->order,
494 xstrdup_for_dump (callee->name ()), callee->order,
495 growth);
496 want_inline = false;
498 else if (growth > PARAM_VALUE (PARAM_EARLY_INLINING_INSNS))
500 if (dump_file)
501 fprintf (dump_file, " will not early inline: %s/%i->%s/%i, "
502 "growth %i exceeds --param early-inlining-insns\n",
503 xstrdup_for_dump (e->caller->name ()),
504 e->caller->order,
505 xstrdup_for_dump (callee->name ()), callee->order,
506 growth);
507 want_inline = false;
509 else if ((n = num_calls (callee)) != 0
510 && growth * (n + 1) > PARAM_VALUE (PARAM_EARLY_INLINING_INSNS))
512 if (dump_file)
513 fprintf (dump_file, " will not early inline: %s/%i->%s/%i, "
514 "growth %i exceeds --param early-inlining-insns "
515 "divided by number of calls\n",
516 xstrdup_for_dump (e->caller->name ()),
517 e->caller->order,
518 xstrdup_for_dump (callee->name ()), callee->order,
519 growth);
520 want_inline = false;
523 return want_inline;
526 /* Compute time of the edge->caller + edge->callee execution when inlining
527 does not happen. */
529 inline sreal
530 compute_uninlined_call_time (struct inline_summary *callee_info,
531 struct cgraph_edge *edge)
533 sreal uninlined_call_time = (sreal)callee_info->time
534 * MAX (edge->frequency, 1)
535 * cgraph_freq_base_rec;
536 int caller_time = inline_summaries->get (edge->caller->global.inlined_to
537 ? edge->caller->global.inlined_to
538 : edge->caller)->time;
539 return uninlined_call_time + caller_time;
542 /* Same as compute_uinlined_call_time but compute time when inlining
543 does happen. */
545 inline sreal
546 compute_inlined_call_time (struct cgraph_edge *edge,
547 int edge_time)
549 int caller_time = inline_summaries->get (edge->caller->global.inlined_to
550 ? edge->caller->global.inlined_to
551 : edge->caller)->time;
552 sreal time = (sreal)caller_time
553 + ((sreal) (edge_time - inline_edge_summary (edge)->call_stmt_time)
554 * MAX (edge->frequency, 1)
555 * cgraph_freq_base_rec);
556 gcc_checking_assert (time >= 0);
557 return time;
560 /* Return true if the speedup for inlining E is bigger than
561 PARAM_MAX_INLINE_MIN_SPEEDUP. */
563 static bool
564 big_speedup_p (struct cgraph_edge *e)
566 sreal time = compute_uninlined_call_time (inline_summaries->get (e->callee), e);
567 sreal inlined_time = compute_inlined_call_time (e, estimate_edge_time (e));
568 if (time - inlined_time
569 > (sreal) time * PARAM_VALUE (PARAM_INLINE_MIN_SPEEDUP)
570 * percent_rec)
571 return true;
572 return false;
575 /* Return true if we are interested in inlining small function.
576 When REPORT is true, report reason to dump file. */
578 static bool
579 want_inline_small_function_p (struct cgraph_edge *e, bool report)
581 bool want_inline = true;
582 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
584 if (DECL_DISREGARD_INLINE_LIMITS (callee->decl))
586 else if (!DECL_DECLARED_INLINE_P (callee->decl)
587 && !opt_for_fn (e->caller->decl, flag_inline_small_functions))
589 e->inline_failed = CIF_FUNCTION_NOT_INLINE_CANDIDATE;
590 want_inline = false;
592 /* Do fast and conservative check if the function can be good
593 inline candidate. At the moment we allow inline hints to
594 promote non-inline functions to inline and we increase
595 MAX_INLINE_INSNS_SINGLE 16-fold for inline functions. */
596 else if ((!DECL_DECLARED_INLINE_P (callee->decl)
597 && (!e->count || !e->maybe_hot_p ()))
598 && inline_summaries->get (callee)->min_size
599 - inline_edge_summary (e)->call_stmt_size
600 > MAX (MAX_INLINE_INSNS_SINGLE, MAX_INLINE_INSNS_AUTO))
602 e->inline_failed = CIF_MAX_INLINE_INSNS_AUTO_LIMIT;
603 want_inline = false;
605 else if ((DECL_DECLARED_INLINE_P (callee->decl) || e->count)
606 && inline_summaries->get (callee)->min_size
607 - inline_edge_summary (e)->call_stmt_size
608 > 16 * MAX_INLINE_INSNS_SINGLE)
610 e->inline_failed = (DECL_DECLARED_INLINE_P (callee->decl)
611 ? CIF_MAX_INLINE_INSNS_SINGLE_LIMIT
612 : CIF_MAX_INLINE_INSNS_AUTO_LIMIT);
613 want_inline = false;
615 else
617 int growth = estimate_edge_growth (e);
618 inline_hints hints = estimate_edge_hints (e);
619 bool big_speedup = big_speedup_p (e);
621 if (growth <= 0)
623 /* Apply MAX_INLINE_INSNS_SINGLE limit. Do not do so when
624 hints suggests that inlining given function is very profitable. */
625 else if (DECL_DECLARED_INLINE_P (callee->decl)
626 && growth >= MAX_INLINE_INSNS_SINGLE
627 && ((!big_speedup
628 && !(hints & (INLINE_HINT_indirect_call
629 | INLINE_HINT_known_hot
630 | INLINE_HINT_loop_iterations
631 | INLINE_HINT_array_index
632 | INLINE_HINT_loop_stride)))
633 || growth >= MAX_INLINE_INSNS_SINGLE * 16))
635 e->inline_failed = CIF_MAX_INLINE_INSNS_SINGLE_LIMIT;
636 want_inline = false;
638 else if (!DECL_DECLARED_INLINE_P (callee->decl)
639 && !opt_for_fn (e->caller->decl, flag_inline_functions))
641 /* growth_likely_positive is expensive, always test it last. */
642 if (growth >= MAX_INLINE_INSNS_SINGLE
643 || growth_likely_positive (callee, growth))
645 e->inline_failed = CIF_NOT_DECLARED_INLINED;
646 want_inline = false;
649 /* Apply MAX_INLINE_INSNS_AUTO limit for functions not declared inline
650 Upgrade it to MAX_INLINE_INSNS_SINGLE when hints suggests that
651 inlining given function is very profitable. */
652 else if (!DECL_DECLARED_INLINE_P (callee->decl)
653 && !big_speedup
654 && !(hints & INLINE_HINT_known_hot)
655 && growth >= ((hints & (INLINE_HINT_indirect_call
656 | INLINE_HINT_loop_iterations
657 | INLINE_HINT_array_index
658 | INLINE_HINT_loop_stride))
659 ? MAX (MAX_INLINE_INSNS_AUTO,
660 MAX_INLINE_INSNS_SINGLE)
661 : MAX_INLINE_INSNS_AUTO))
663 /* growth_likely_positive is expensive, always test it last. */
664 if (growth >= MAX_INLINE_INSNS_SINGLE
665 || growth_likely_positive (callee, growth))
667 e->inline_failed = CIF_MAX_INLINE_INSNS_AUTO_LIMIT;
668 want_inline = false;
671 /* If call is cold, do not inline when function body would grow. */
672 else if (!e->maybe_hot_p ()
673 && (growth >= MAX_INLINE_INSNS_SINGLE
674 || growth_likely_positive (callee, growth)))
676 e->inline_failed = CIF_UNLIKELY_CALL;
677 want_inline = false;
680 if (!want_inline && report)
681 report_inline_failed_reason (e);
682 return want_inline;
685 /* EDGE is self recursive edge.
686 We hand two cases - when function A is inlining into itself
687 or when function A is being inlined into another inliner copy of function
688 A within function B.
690 In first case OUTER_NODE points to the toplevel copy of A, while
691 in the second case OUTER_NODE points to the outermost copy of A in B.
693 In both cases we want to be extra selective since
694 inlining the call will just introduce new recursive calls to appear. */
696 static bool
697 want_inline_self_recursive_call_p (struct cgraph_edge *edge,
698 struct cgraph_node *outer_node,
699 bool peeling,
700 int depth)
702 char const *reason = NULL;
703 bool want_inline = true;
704 int caller_freq = CGRAPH_FREQ_BASE;
705 int max_depth = PARAM_VALUE (PARAM_MAX_INLINE_RECURSIVE_DEPTH_AUTO);
707 if (DECL_DECLARED_INLINE_P (edge->caller->decl))
708 max_depth = PARAM_VALUE (PARAM_MAX_INLINE_RECURSIVE_DEPTH);
710 if (!edge->maybe_hot_p ())
712 reason = "recursive call is cold";
713 want_inline = false;
715 else if (max_count && !outer_node->count)
717 reason = "not executed in profile";
718 want_inline = false;
720 else if (depth > max_depth)
722 reason = "--param max-inline-recursive-depth exceeded.";
723 want_inline = false;
726 if (outer_node->global.inlined_to)
727 caller_freq = outer_node->callers->frequency;
729 if (!caller_freq)
731 reason = "function is inlined and unlikely";
732 want_inline = false;
735 if (!want_inline)
737 /* Inlining of self recursive function into copy of itself within other function
738 is transformation similar to loop peeling.
740 Peeling is profitable if we can inline enough copies to make probability
741 of actual call to the self recursive function very small. Be sure that
742 the probability of recursion is small.
744 We ensure that the frequency of recursing is at most 1 - (1/max_depth).
745 This way the expected number of recision is at most max_depth. */
746 else if (peeling)
748 int max_prob = CGRAPH_FREQ_BASE - ((CGRAPH_FREQ_BASE + max_depth - 1)
749 / max_depth);
750 int i;
751 for (i = 1; i < depth; i++)
752 max_prob = max_prob * max_prob / CGRAPH_FREQ_BASE;
753 if (max_count
754 && (edge->count * CGRAPH_FREQ_BASE / outer_node->count
755 >= max_prob))
757 reason = "profile of recursive call is too large";
758 want_inline = false;
760 if (!max_count
761 && (edge->frequency * CGRAPH_FREQ_BASE / caller_freq
762 >= max_prob))
764 reason = "frequency of recursive call is too large";
765 want_inline = false;
768 /* Recursive inlining, i.e. equivalent of unrolling, is profitable if recursion
769 depth is large. We reduce function call overhead and increase chances that
770 things fit in hardware return predictor.
772 Recursive inlining might however increase cost of stack frame setup
773 actually slowing down functions whose recursion tree is wide rather than
774 deep.
776 Deciding reliably on when to do recursive inlining without profile feedback
777 is tricky. For now we disable recursive inlining when probability of self
778 recursion is low.
780 Recursive inlining of self recursive call within loop also results in large loop
781 depths that generally optimize badly. We may want to throttle down inlining
782 in those cases. In particular this seems to happen in one of libstdc++ rb tree
783 methods. */
784 else
786 if (max_count
787 && (edge->count * 100 / outer_node->count
788 <= PARAM_VALUE (PARAM_MIN_INLINE_RECURSIVE_PROBABILITY)))
790 reason = "profile of recursive call is too small";
791 want_inline = false;
793 else if (!max_count
794 && (edge->frequency * 100 / caller_freq
795 <= PARAM_VALUE (PARAM_MIN_INLINE_RECURSIVE_PROBABILITY)))
797 reason = "frequency of recursive call is too small";
798 want_inline = false;
801 if (!want_inline && dump_file)
802 fprintf (dump_file, " not inlining recursively: %s\n", reason);
803 return want_inline;
806 /* Return true when NODE has uninlinable caller;
807 set HAS_HOT_CALL if it has hot call.
808 Worker for cgraph_for_node_and_aliases. */
810 static bool
811 check_callers (struct cgraph_node *node, void *has_hot_call)
813 struct cgraph_edge *e;
814 for (e = node->callers; e; e = e->next_caller)
816 if (!opt_for_fn (e->caller->decl, flag_inline_functions_called_once))
817 return true;
818 if (!can_inline_edge_p (e, true))
819 return true;
820 if (!(*(bool *)has_hot_call) && e->maybe_hot_p ())
821 *(bool *)has_hot_call = true;
823 return false;
826 /* If NODE has a caller, return true. */
828 static bool
829 has_caller_p (struct cgraph_node *node, void *data ATTRIBUTE_UNUSED)
831 if (node->callers)
832 return true;
833 return false;
836 /* Decide if inlining NODE would reduce unit size by eliminating
837 the offline copy of function.
838 When COLD is true the cold calls are considered, too. */
840 static bool
841 want_inline_function_to_all_callers_p (struct cgraph_node *node, bool cold)
843 bool has_hot_call = false;
845 if (node->ultimate_alias_target () != node)
846 return false;
847 /* Already inlined? */
848 if (node->global.inlined_to)
849 return false;
850 /* Does it have callers? */
851 if (!node->call_for_symbol_thunks_and_aliases (has_caller_p, NULL, true))
852 return false;
853 /* Inlining into all callers would increase size? */
854 if (estimate_growth (node) > 0)
855 return false;
856 /* All inlines must be possible. */
857 if (node->call_for_symbol_thunks_and_aliases (check_callers, &has_hot_call,
858 true))
859 return false;
860 if (!cold && !has_hot_call)
861 return false;
862 return true;
865 #define RELATIVE_TIME_BENEFIT_RANGE (INT_MAX / 64)
867 /* Return relative time improvement for inlining EDGE in range
868 as value NUMERATOR/DENOMINATOR. */
870 static inline void
871 relative_time_benefit (struct inline_summary *callee_info,
872 struct cgraph_edge *edge,
873 int edge_time,
874 sreal *numerator,
875 sreal *denominator)
877 /* Inlining into extern inline function is not a win. */
878 if (DECL_EXTERNAL (edge->caller->global.inlined_to
879 ? edge->caller->global.inlined_to->decl
880 : edge->caller->decl))
882 *numerator = (sreal) 1;
883 *denominator = (sreal) 1024;
884 return;
887 sreal uninlined_call_time = compute_uninlined_call_time (callee_info, edge);
888 sreal inlined_call_time = compute_inlined_call_time (edge, edge_time);
890 /* Compute relative time benefit, i.e. how much the call becomes faster.
891 ??? perhaps computing how much the caller+calle together become faster
892 would lead to more realistic results. */
893 if (uninlined_call_time == (sreal) 0)
894 uninlined_call_time = 1;
896 /* Avoid zeros, these are not useful later in calculations. */
897 if (uninlined_call_time == inlined_call_time)
898 *numerator = ((sreal) 1)>>8;
899 else
900 *numerator = uninlined_call_time - inlined_call_time;
901 *denominator = uninlined_call_time;
902 #ifdef ENABLE_CHECKING
903 gcc_checking_assert (*numerator >= 0);
904 gcc_checking_assert (*denominator >= 0);
905 #endif
908 /* A cost model driving the inlining heuristics in a way so the edges with
909 smallest badness are inlined first. After each inlining is performed
910 the costs of all caller edges of nodes affected are recomputed so the
911 metrics may accurately depend on values such as number of inlinable callers
912 of the function or function body size. */
914 static sreal
915 edge_badness (struct cgraph_edge *edge, bool dump)
917 sreal badness;
918 int growth, edge_time;
919 struct cgraph_node *callee = edge->callee->ultimate_alias_target ();
920 struct inline_summary *callee_info = inline_summaries->get (callee);
921 inline_hints hints;
923 if (DECL_DISREGARD_INLINE_LIMITS (callee->decl))
924 return sreal::min ();
926 growth = estimate_edge_growth (edge);
927 edge_time = estimate_edge_time (edge);
928 hints = estimate_edge_hints (edge);
929 gcc_checking_assert (edge_time >= 0);
930 gcc_checking_assert (edge_time <= callee_info->time);
931 gcc_checking_assert (growth <= callee_info->size);
933 if (dump)
935 fprintf (dump_file, " Badness calculation for %s/%i -> %s/%i\n",
936 xstrdup_for_dump (edge->caller->name ()),
937 edge->caller->order,
938 xstrdup_for_dump (callee->name ()),
939 edge->callee->order);
940 fprintf (dump_file, " size growth %i, time %i ",
941 growth,
942 edge_time);
943 dump_inline_hints (dump_file, hints);
944 if (big_speedup_p (edge))
945 fprintf (dump_file, " big_speedup");
946 fprintf (dump_file, "\n");
949 /* Always prefer inlining saving code size. */
950 if (growth <= 0)
952 badness = (sreal) (-SREAL_MIN_SIG + growth) << (SREAL_MAX_EXP / 256);
953 if (dump)
954 fprintf (dump_file, " %f: Growth %d <= 0\n", badness.to_double (),
955 growth);
958 /* When profiling is available, compute badness as:
960 edge_count * relative_time_benefit
961 goodness = -------------------------------------------
962 growth_of_caller
963 badness = - goodness
965 The fraction is upside down, because on edge counts and time beneits
966 the bounds are known. Edge growth is essentially unlimited. */
968 else if (max_count)
970 sreal numerator, denominator;
971 relative_time_benefit (callee_info, edge, edge_time, &numerator,
972 &denominator);
974 if (edge->count)
975 numerator *= edge->count;
976 denominator *= growth;
978 badness = - numerator / denominator;
980 if (dump)
982 sreal num,den;
983 relative_time_benefit (callee_info, edge, edge_time, &num, &den);
984 fprintf (dump_file,
985 " %f: profile info. count %"PRId64
986 " * Relative benefit %f / growth %i\n",
987 badness.to_double (), (int64_t)edge->count,
988 (num / den * 100).to_double (), growth);
992 /* When function local profile is available. Compute badness as:
994 relative_time_benefit
995 goodness = ---------------------------------
996 growth_of_caller * overall_growth
998 badness = - goodness
1000 compensated by the inline hints.
1002 /* TODO: We ought suport mixing units where some functions are profiled
1003 and some not. */
1004 else if (flag_guess_branch_prob)
1006 sreal numerator, denominator;
1007 relative_time_benefit (callee_info, edge, edge_time, &numerator,
1008 &denominator);
1009 denominator *= growth;
1010 if (callee_info->growth > 0)
1011 denominator *= callee_info->growth;
1013 badness = - numerator / denominator;
1015 if (dump)
1017 sreal num,den;
1018 relative_time_benefit (callee_info, edge, edge_time, &num, &den);
1019 fprintf (dump_file,
1020 " %f: guessed profile. frequency %f,"
1021 " benefit %f%%, time w/o inlining %f, time w inlining %f"
1022 " overall growth %i (current) %i (original)\n",
1023 badness.to_double (), (double)edge->frequency / CGRAPH_FREQ_BASE,
1024 (num/den).to_double () * 100,
1025 compute_uninlined_call_time (callee_info, edge).to_double (),
1026 compute_inlined_call_time (edge, edge_time).to_double (),
1027 estimate_growth (callee),
1028 callee_info->growth);
1031 /* When function local profile is not available or it does not give
1032 useful information (ie frequency is zero), base the cost on
1033 loop nest and overall size growth, so we optimize for overall number
1034 of functions fully inlined in program. */
1035 else
1037 int nest = MIN (inline_edge_summary (edge)->loop_depth, 8);
1038 badness = growth;
1040 /* Decrease badness if call is nested. */
1041 if (badness > 0)
1042 badness = badness >> nest;
1043 else
1044 badness = badness << nest;
1045 if (dump)
1046 fprintf (dump_file, " %f: no profile. nest %i\n", badness.to_double (),
1047 nest);
1049 gcc_checking_assert (badness != 0);
1051 if (edge->recursive_p ())
1052 badness = badness.shift (badness > 0 ? 4 : -4);
1053 if ((hints & (INLINE_HINT_indirect_call
1054 | INLINE_HINT_loop_iterations
1055 | INLINE_HINT_array_index
1056 | INLINE_HINT_loop_stride))
1057 || callee_info->growth <= 0)
1058 badness = badness.shift (badness > 0 ? -2 : 2);
1059 if (hints & (INLINE_HINT_same_scc))
1060 badness = badness.shift (badness > 0 ? 3 : -3);
1061 else if (hints & (INLINE_HINT_in_scc))
1062 badness = badness.shift (badness > 0 ? 2 : -2);
1063 else if (hints & (INLINE_HINT_cross_module))
1064 badness = badness.shift (badness > 0 ? 1 : -1);
1065 if ((hints & INLINE_HINT_declared_inline))
1066 badness = badness.shift (badness > 0 ? -3 : 3);
1067 if (dump)
1068 fprintf (dump_file, " Adjusted by hints %f\n", badness.to_double ());
1069 return badness;
1072 /* Recompute badness of EDGE and update its key in HEAP if needed. */
1073 static inline void
1074 update_edge_key (edge_heap_t *heap, struct cgraph_edge *edge)
1076 sreal badness = edge_badness (edge, false);
1077 if (edge->aux)
1079 edge_heap_node_t *n = (edge_heap_node_t *) edge->aux;
1080 gcc_checking_assert (n->get_data () == edge);
1082 /* fibonacci_heap::replace_key does busy updating of the
1083 heap that is unnecesarily expensive.
1084 We do lazy increases: after extracting minimum if the key
1085 turns out to be out of date, it is re-inserted into heap
1086 with correct value. */
1087 if (badness < n->get_key ())
1089 if (dump_file && (dump_flags & TDF_DETAILS))
1091 fprintf (dump_file,
1092 " decreasing badness %s/%i -> %s/%i, %f"
1093 " to %f\n",
1094 xstrdup_for_dump (edge->caller->name ()),
1095 edge->caller->order,
1096 xstrdup_for_dump (edge->callee->name ()),
1097 edge->callee->order,
1098 n->get_key ().to_double (),
1099 badness.to_double ());
1101 heap->decrease_key (n, badness);
1104 else
1106 if (dump_file && (dump_flags & TDF_DETAILS))
1108 fprintf (dump_file,
1109 " enqueuing call %s/%i -> %s/%i, badness %f\n",
1110 xstrdup_for_dump (edge->caller->name ()),
1111 edge->caller->order,
1112 xstrdup_for_dump (edge->callee->name ()),
1113 edge->callee->order,
1114 badness.to_double ());
1116 edge->aux = heap->insert (badness, edge);
1121 /* NODE was inlined.
1122 All caller edges needs to be resetted because
1123 size estimates change. Similarly callees needs reset
1124 because better context may be known. */
1126 static void
1127 reset_edge_caches (struct cgraph_node *node)
1129 struct cgraph_edge *edge;
1130 struct cgraph_edge *e = node->callees;
1131 struct cgraph_node *where = node;
1132 struct ipa_ref *ref;
1134 if (where->global.inlined_to)
1135 where = where->global.inlined_to;
1137 /* WHERE body size has changed, the cached growth is invalid. */
1138 reset_node_growth_cache (where);
1140 for (edge = where->callers; edge; edge = edge->next_caller)
1141 if (edge->inline_failed)
1142 reset_edge_growth_cache (edge);
1144 FOR_EACH_ALIAS (where, ref)
1145 reset_edge_caches (dyn_cast <cgraph_node *> (ref->referring));
1147 if (!e)
1148 return;
1150 while (true)
1151 if (!e->inline_failed && e->callee->callees)
1152 e = e->callee->callees;
1153 else
1155 if (e->inline_failed)
1156 reset_edge_growth_cache (e);
1157 if (e->next_callee)
1158 e = e->next_callee;
1159 else
1163 if (e->caller == node)
1164 return;
1165 e = e->caller->callers;
1167 while (!e->next_callee);
1168 e = e->next_callee;
1173 /* Recompute HEAP nodes for each of caller of NODE.
1174 UPDATED_NODES track nodes we already visited, to avoid redundant work.
1175 When CHECK_INLINABLITY_FOR is set, re-check for specified edge that
1176 it is inlinable. Otherwise check all edges. */
1178 static void
1179 update_caller_keys (edge_heap_t *heap, struct cgraph_node *node,
1180 bitmap updated_nodes,
1181 struct cgraph_edge *check_inlinablity_for)
1183 struct cgraph_edge *edge;
1184 struct ipa_ref *ref;
1186 if ((!node->alias && !inline_summaries->get (node)->inlinable)
1187 || node->global.inlined_to)
1188 return;
1189 if (!bitmap_set_bit (updated_nodes, node->uid))
1190 return;
1192 FOR_EACH_ALIAS (node, ref)
1194 struct cgraph_node *alias = dyn_cast <cgraph_node *> (ref->referring);
1195 update_caller_keys (heap, alias, updated_nodes, check_inlinablity_for);
1198 for (edge = node->callers; edge; edge = edge->next_caller)
1199 if (edge->inline_failed)
1201 if (!check_inlinablity_for
1202 || check_inlinablity_for == edge)
1204 if (can_inline_edge_p (edge, false)
1205 && want_inline_small_function_p (edge, false))
1206 update_edge_key (heap, edge);
1207 else if (edge->aux)
1209 report_inline_failed_reason (edge);
1210 heap->delete_node ((edge_heap_node_t *) edge->aux);
1211 edge->aux = NULL;
1214 else if (edge->aux)
1215 update_edge_key (heap, edge);
1219 /* Recompute HEAP nodes for each uninlined call in NODE.
1220 This is used when we know that edge badnesses are going only to increase
1221 (we introduced new call site) and thus all we need is to insert newly
1222 created edges into heap. */
1224 static void
1225 update_callee_keys (edge_heap_t *heap, struct cgraph_node *node,
1226 bitmap updated_nodes)
1228 struct cgraph_edge *e = node->callees;
1230 if (!e)
1231 return;
1232 while (true)
1233 if (!e->inline_failed && e->callee->callees)
1234 e = e->callee->callees;
1235 else
1237 enum availability avail;
1238 struct cgraph_node *callee;
1239 /* We do not reset callee growth cache here. Since we added a new call,
1240 growth chould have just increased and consequentely badness metric
1241 don't need updating. */
1242 if (e->inline_failed
1243 && (callee = e->callee->ultimate_alias_target (&avail))
1244 && inline_summaries->get (callee)->inlinable
1245 && avail >= AVAIL_AVAILABLE
1246 && !bitmap_bit_p (updated_nodes, callee->uid))
1248 if (can_inline_edge_p (e, false)
1249 && want_inline_small_function_p (e, false))
1250 update_edge_key (heap, e);
1251 else if (e->aux)
1253 report_inline_failed_reason (e);
1254 heap->delete_node ((edge_heap_node_t *) e->aux);
1255 e->aux = NULL;
1258 if (e->next_callee)
1259 e = e->next_callee;
1260 else
1264 if (e->caller == node)
1265 return;
1266 e = e->caller->callers;
1268 while (!e->next_callee);
1269 e = e->next_callee;
1274 /* Enqueue all recursive calls from NODE into priority queue depending on
1275 how likely we want to recursively inline the call. */
1277 static void
1278 lookup_recursive_calls (struct cgraph_node *node, struct cgraph_node *where,
1279 edge_heap_t *heap)
1281 struct cgraph_edge *e;
1282 enum availability avail;
1284 for (e = where->callees; e; e = e->next_callee)
1285 if (e->callee == node
1286 || (e->callee->ultimate_alias_target (&avail) == node
1287 && avail > AVAIL_INTERPOSABLE))
1289 /* When profile feedback is available, prioritize by expected number
1290 of calls. */
1291 heap->insert (!max_count ? -e->frequency
1292 : -(e->count / ((max_count + (1<<24) - 1) / (1<<24))),
1295 for (e = where->callees; e; e = e->next_callee)
1296 if (!e->inline_failed)
1297 lookup_recursive_calls (node, e->callee, heap);
1300 /* Decide on recursive inlining: in the case function has recursive calls,
1301 inline until body size reaches given argument. If any new indirect edges
1302 are discovered in the process, add them to *NEW_EDGES, unless NEW_EDGES
1303 is NULL. */
1305 static bool
1306 recursive_inlining (struct cgraph_edge *edge,
1307 vec<cgraph_edge *> *new_edges)
1309 int limit = PARAM_VALUE (PARAM_MAX_INLINE_INSNS_RECURSIVE_AUTO);
1310 edge_heap_t heap (sreal::min ());
1311 struct cgraph_node *node;
1312 struct cgraph_edge *e;
1313 struct cgraph_node *master_clone = NULL, *next;
1314 int depth = 0;
1315 int n = 0;
1317 node = edge->caller;
1318 if (node->global.inlined_to)
1319 node = node->global.inlined_to;
1321 if (DECL_DECLARED_INLINE_P (node->decl))
1322 limit = PARAM_VALUE (PARAM_MAX_INLINE_INSNS_RECURSIVE);
1324 /* Make sure that function is small enough to be considered for inlining. */
1325 if (estimate_size_after_inlining (node, edge) >= limit)
1326 return false;
1327 lookup_recursive_calls (node, node, &heap);
1328 if (heap.empty ())
1329 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 (!heap.empty ())
1339 struct cgraph_edge *curr = heap.extract_min ();
1340 struct cgraph_node *cnode, *dest = curr->callee;
1342 if (!can_inline_edge_p (curr, true))
1343 continue;
1345 /* MASTER_CLONE is produced in the case we already started modified
1346 the function. Be sure to redirect edge to the original body before
1347 estimating growths otherwise we will be seeing growths after inlining
1348 the already modified body. */
1349 if (master_clone)
1351 curr->redirect_callee (master_clone);
1352 reset_edge_growth_cache (curr);
1355 if (estimate_size_after_inlining (node, curr) > limit)
1357 curr->redirect_callee (dest);
1358 reset_edge_growth_cache (curr);
1359 break;
1362 depth = 1;
1363 for (cnode = curr->caller;
1364 cnode->global.inlined_to; cnode = cnode->callers->caller)
1365 if (node->decl
1366 == curr->callee->ultimate_alias_target ()->decl)
1367 depth++;
1369 if (!want_inline_self_recursive_call_p (curr, node, false, depth))
1371 curr->redirect_callee (dest);
1372 reset_edge_growth_cache (curr);
1373 continue;
1376 if (dump_file)
1378 fprintf (dump_file,
1379 " Inlining call of depth %i", depth);
1380 if (node->count)
1382 fprintf (dump_file, " called approx. %.2f times per call",
1383 (double)curr->count / node->count);
1385 fprintf (dump_file, "\n");
1387 if (!master_clone)
1389 /* We need original clone to copy around. */
1390 master_clone = node->create_clone (node->decl, node->count,
1391 CGRAPH_FREQ_BASE, false, vNULL,
1392 true, NULL, NULL);
1393 for (e = master_clone->callees; e; e = e->next_callee)
1394 if (!e->inline_failed)
1395 clone_inlined_nodes (e, true, false, NULL, CGRAPH_FREQ_BASE);
1396 curr->redirect_callee (master_clone);
1397 reset_edge_growth_cache (curr);
1400 inline_call (curr, false, new_edges, &overall_size, true);
1401 lookup_recursive_calls (node, curr->callee, &heap);
1402 n++;
1405 if (!heap.empty () && dump_file)
1406 fprintf (dump_file, " Recursive inlining growth limit met.\n");
1408 if (!master_clone)
1409 return false;
1411 if (dump_file)
1412 fprintf (dump_file,
1413 "\n Inlined %i times, "
1414 "body grown from size %i to %i, time %i to %i\n", n,
1415 inline_summaries->get (master_clone)->size, inline_summaries->get (node)->size,
1416 inline_summaries->get (master_clone)->time, inline_summaries->get (node)->time);
1418 /* Remove master clone we used for inlining. We rely that clones inlined
1419 into master clone gets queued just before master clone so we don't
1420 need recursion. */
1421 for (node = symtab->first_function (); node != master_clone;
1422 node = next)
1424 next = symtab->next_function (node);
1425 if (node->global.inlined_to == master_clone)
1426 node->remove ();
1428 master_clone->remove ();
1429 return true;
1433 /* Given whole compilation unit estimate of INSNS, compute how large we can
1434 allow the unit to grow. */
1436 static int
1437 compute_max_insns (int insns)
1439 int max_insns = insns;
1440 if (max_insns < PARAM_VALUE (PARAM_LARGE_UNIT_INSNS))
1441 max_insns = PARAM_VALUE (PARAM_LARGE_UNIT_INSNS);
1443 return ((int64_t) max_insns
1444 * (100 + PARAM_VALUE (PARAM_INLINE_UNIT_GROWTH)) / 100);
1448 /* Compute badness of all edges in NEW_EDGES and add them to the HEAP. */
1450 static void
1451 add_new_edges_to_heap (edge_heap_t *heap, vec<cgraph_edge *> new_edges)
1453 while (new_edges.length () > 0)
1455 struct cgraph_edge *edge = new_edges.pop ();
1457 gcc_assert (!edge->aux);
1458 if (edge->inline_failed
1459 && can_inline_edge_p (edge, true)
1460 && want_inline_small_function_p (edge, true))
1461 edge->aux = heap->insert (edge_badness (edge, false), edge);
1465 /* Remove EDGE from the fibheap. */
1467 static void
1468 heap_edge_removal_hook (struct cgraph_edge *e, void *data)
1470 if (e->callee)
1471 reset_node_growth_cache (e->callee);
1472 if (e->aux)
1474 ((edge_heap_t *)data)->delete_node ((edge_heap_node_t *)e->aux);
1475 e->aux = NULL;
1479 /* Return true if speculation of edge E seems useful.
1480 If ANTICIPATE_INLINING is true, be conservative and hope that E
1481 may get inlined. */
1483 bool
1484 speculation_useful_p (struct cgraph_edge *e, bool anticipate_inlining)
1486 enum availability avail;
1487 struct cgraph_node *target = e->callee->ultimate_alias_target (&avail);
1488 struct cgraph_edge *direct, *indirect;
1489 struct ipa_ref *ref;
1491 gcc_assert (e->speculative && !e->indirect_unknown_callee);
1493 if (!e->maybe_hot_p ())
1494 return false;
1496 /* See if IP optimizations found something potentially useful about the
1497 function. For now we look only for CONST/PURE flags. Almost everything
1498 else we propagate is useless. */
1499 if (avail >= AVAIL_AVAILABLE)
1501 int ecf_flags = flags_from_decl_or_type (target->decl);
1502 if (ecf_flags & ECF_CONST)
1504 e->speculative_call_info (direct, indirect, ref);
1505 if (!(indirect->indirect_info->ecf_flags & ECF_CONST))
1506 return true;
1508 else if (ecf_flags & ECF_PURE)
1510 e->speculative_call_info (direct, indirect, ref);
1511 if (!(indirect->indirect_info->ecf_flags & ECF_PURE))
1512 return true;
1515 /* If we did not managed to inline the function nor redirect
1516 to an ipa-cp clone (that are seen by having local flag set),
1517 it is probably pointless to inline it unless hardware is missing
1518 indirect call predictor. */
1519 if (!anticipate_inlining && e->inline_failed && !target->local.local)
1520 return false;
1521 /* For overwritable targets there is not much to do. */
1522 if (e->inline_failed && !can_inline_edge_p (e, false, true))
1523 return false;
1524 /* OK, speculation seems interesting. */
1525 return true;
1528 /* We know that EDGE is not going to be inlined.
1529 See if we can remove speculation. */
1531 static void
1532 resolve_noninline_speculation (edge_heap_t *edge_heap, struct cgraph_edge *edge)
1534 if (edge->speculative && !speculation_useful_p (edge, false))
1536 struct cgraph_node *node = edge->caller;
1537 struct cgraph_node *where = node->global.inlined_to
1538 ? node->global.inlined_to : node;
1539 bitmap updated_nodes = BITMAP_ALLOC (NULL);
1541 spec_rem += edge->count;
1542 edge->resolve_speculation ();
1543 reset_edge_caches (where);
1544 inline_update_overall_summary (where);
1545 update_caller_keys (edge_heap, where,
1546 updated_nodes, NULL);
1547 update_callee_keys (edge_heap, where,
1548 updated_nodes);
1549 BITMAP_FREE (updated_nodes);
1553 /* We use greedy algorithm for inlining of small functions:
1554 All inline candidates are put into prioritized heap ordered in
1555 increasing badness.
1557 The inlining of small functions is bounded by unit growth parameters. */
1559 static void
1560 inline_small_functions (void)
1562 struct cgraph_node *node;
1563 struct cgraph_edge *edge;
1564 edge_heap_t edge_heap (sreal::min ());
1565 bitmap updated_nodes = BITMAP_ALLOC (NULL);
1566 int min_size, max_size;
1567 auto_vec<cgraph_edge *> new_indirect_edges;
1568 int initial_size = 0;
1569 struct cgraph_node **order = XCNEWVEC (cgraph_node *, symtab->cgraph_count);
1570 struct cgraph_edge_hook_list *edge_removal_hook_holder;
1571 new_indirect_edges.create (8);
1573 edge_removal_hook_holder
1574 = symtab->add_edge_removal_hook (&heap_edge_removal_hook, &edge_heap);
1576 /* Compute overall unit size and other global parameters used by badness
1577 metrics. */
1579 max_count = 0;
1580 ipa_reduced_postorder (order, true, true, NULL);
1581 free (order);
1583 FOR_EACH_DEFINED_FUNCTION (node)
1584 if (!node->global.inlined_to)
1586 if (node->has_gimple_body_p ()
1587 || node->thunk.thunk_p)
1589 struct inline_summary *info = inline_summaries->get (node);
1590 struct ipa_dfs_info *dfs = (struct ipa_dfs_info *) node->aux;
1592 /* Do not account external functions, they will be optimized out
1593 if not inlined. Also only count the non-cold portion of program. */
1594 if (!DECL_EXTERNAL (node->decl)
1595 && node->frequency != NODE_FREQUENCY_UNLIKELY_EXECUTED)
1596 initial_size += info->size;
1597 info->growth = estimate_growth (node);
1598 if (dfs && dfs->next_cycle)
1600 struct cgraph_node *n2;
1601 int id = dfs->scc_no + 1;
1602 for (n2 = node; n2;
1603 n2 = ((struct ipa_dfs_info *) node->aux)->next_cycle)
1605 struct inline_summary *info2 = inline_summaries->get (n2);
1606 if (info2->scc_no)
1607 break;
1608 info2->scc_no = id;
1613 for (edge = node->callers; edge; edge = edge->next_caller)
1614 if (max_count < edge->count)
1615 max_count = edge->count;
1617 ipa_free_postorder_info ();
1618 initialize_growth_caches ();
1620 if (dump_file)
1621 fprintf (dump_file,
1622 "\nDeciding on inlining of small functions. Starting with size %i.\n",
1623 initial_size);
1625 overall_size = initial_size;
1626 max_size = compute_max_insns (overall_size);
1627 min_size = overall_size;
1629 /* Populate the heap with all edges we might inline. */
1631 FOR_EACH_DEFINED_FUNCTION (node)
1633 bool update = false;
1634 struct cgraph_edge *next;
1636 if (dump_file)
1637 fprintf (dump_file, "Enqueueing calls in %s/%i.\n",
1638 node->name (), node->order);
1640 for (edge = node->callees; edge; edge = next)
1642 next = edge->next_callee;
1643 if (edge->inline_failed
1644 && !edge->aux
1645 && can_inline_edge_p (edge, true)
1646 && want_inline_small_function_p (edge, true)
1647 && edge->inline_failed)
1649 gcc_assert (!edge->aux);
1650 update_edge_key (&edge_heap, edge);
1652 if (edge->speculative && !speculation_useful_p (edge, edge->aux != NULL))
1654 edge->resolve_speculation ();
1655 update = true;
1658 if (update)
1660 struct cgraph_node *where = node->global.inlined_to
1661 ? node->global.inlined_to : node;
1662 inline_update_overall_summary (where);
1663 reset_node_growth_cache (where);
1664 reset_edge_caches (where);
1665 update_caller_keys (&edge_heap, where,
1666 updated_nodes, NULL);
1667 bitmap_clear (updated_nodes);
1671 gcc_assert (in_lto_p
1672 || !max_count
1673 || (profile_info && flag_branch_probabilities));
1675 while (!edge_heap.empty ())
1677 int old_size = overall_size;
1678 struct cgraph_node *where, *callee;
1679 sreal badness = edge_heap.min_key ();
1680 sreal current_badness;
1681 int growth;
1683 edge = edge_heap.extract_min ();
1684 gcc_assert (edge->aux);
1685 edge->aux = NULL;
1686 if (!edge->inline_failed || !edge->callee->analyzed)
1687 continue;
1689 #ifdef ENABLE_CHECKING
1690 /* Be sure that caches are maintained consistent. */
1691 sreal cached_badness = edge_badness (edge, false);
1692 reset_edge_growth_cache (edge);
1693 reset_node_growth_cache (edge->callee);
1695 /* When updating the edge costs, we only decrease badness in the keys.
1696 Increases of badness are handled lazilly; when we see key with out
1697 of date value on it, we re-insert it now. */
1698 current_badness = edge_badness (edge, false);
1699 gcc_assert (cached_badness == current_badness);
1700 gcc_assert (current_badness >= badness);
1701 #else
1702 current_badness = edge_badness (edge, false);
1703 #endif
1704 if (current_badness != badness)
1706 if (edge_heap.min () && badness > edge_heap.min_key ())
1708 edge->aux = edge_heap.insert (current_badness, edge);
1709 continue;
1711 else
1712 badness = current_badness;
1715 if (!can_inline_edge_p (edge, true))
1717 resolve_noninline_speculation (&edge_heap, edge);
1718 continue;
1721 callee = edge->callee->ultimate_alias_target ();
1722 growth = estimate_edge_growth (edge);
1723 if (dump_file)
1725 fprintf (dump_file,
1726 "\nConsidering %s/%i with %i size\n",
1727 callee->name (), callee->order,
1728 inline_summaries->get (callee)->size);
1729 fprintf (dump_file,
1730 " to be inlined into %s/%i in %s:%i\n"
1731 " Estimated badness is %f, frequency %.2f.\n",
1732 edge->caller->name (), edge->caller->order,
1733 edge->call_stmt ? "unknown"
1734 : gimple_filename ((const_gimple) edge->call_stmt),
1735 edge->call_stmt ? -1
1736 : gimple_lineno ((const_gimple) edge->call_stmt),
1737 badness.to_double (),
1738 edge->frequency / (double)CGRAPH_FREQ_BASE);
1739 if (edge->count)
1740 fprintf (dump_file," Called %"PRId64"x\n",
1741 edge->count);
1742 if (dump_flags & TDF_DETAILS)
1743 edge_badness (edge, true);
1746 if (overall_size + growth > max_size
1747 && !DECL_DISREGARD_INLINE_LIMITS (callee->decl))
1749 edge->inline_failed = CIF_INLINE_UNIT_GROWTH_LIMIT;
1750 report_inline_failed_reason (edge);
1751 resolve_noninline_speculation (&edge_heap, edge);
1752 continue;
1755 if (!want_inline_small_function_p (edge, true))
1757 resolve_noninline_speculation (&edge_heap, edge);
1758 continue;
1761 /* Heuristics for inlining small functions work poorly for
1762 recursive calls where we do effects similar to loop unrolling.
1763 When inlining such edge seems profitable, leave decision on
1764 specific inliner. */
1765 if (edge->recursive_p ())
1767 where = edge->caller;
1768 if (where->global.inlined_to)
1769 where = where->global.inlined_to;
1770 if (!recursive_inlining (edge,
1771 opt_for_fn (edge->caller->decl,
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 (opt_for_fn (edge->caller->decl, 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 add_new_edges_to_heap (&edge_heap, new_indirect_edges);
1822 reset_edge_caches (edge->callee);
1823 reset_node_growth_cache (callee);
1825 update_callee_keys (&edge_heap, where, updated_nodes);
1827 where = edge->caller;
1828 if (where->global.inlined_to)
1829 where = where->global.inlined_to;
1831 /* Our profitability metric can depend on local properties
1832 such as number of inlinable calls and size of the function body.
1833 After inlining these properties might change for the function we
1834 inlined into (since it's body size changed) and for the functions
1835 called by function we inlined (since number of it inlinable callers
1836 might change). */
1837 update_caller_keys (&edge_heap, where, updated_nodes, NULL);
1838 bitmap_clear (updated_nodes);
1840 if (dump_file)
1842 fprintf (dump_file,
1843 " Inlined into %s which now has time %i and size %i,"
1844 "net change of %+i.\n",
1845 edge->caller->name (),
1846 inline_summaries->get (edge->caller)->time,
1847 inline_summaries->get (edge->caller)->size,
1848 overall_size - old_size);
1850 if (min_size > overall_size)
1852 min_size = overall_size;
1853 max_size = compute_max_insns (min_size);
1855 if (dump_file)
1856 fprintf (dump_file, "New minimal size reached: %i\n", min_size);
1860 free_growth_caches ();
1861 if (dump_file)
1862 fprintf (dump_file,
1863 "Unit growth for small function inlining: %i->%i (%i%%)\n",
1864 initial_size, overall_size,
1865 initial_size ? overall_size * 100 / (initial_size) - 100: 0);
1866 BITMAP_FREE (updated_nodes);
1867 symtab->remove_edge_removal_hook (edge_removal_hook_holder);
1870 /* Flatten NODE. Performed both during early inlining and
1871 at IPA inlining time. */
1873 static void
1874 flatten_function (struct cgraph_node *node, bool early)
1876 struct cgraph_edge *e;
1878 /* We shouldn't be called recursively when we are being processed. */
1879 gcc_assert (node->aux == NULL);
1881 node->aux = (void *) node;
1883 for (e = node->callees; e; e = e->next_callee)
1885 struct cgraph_node *orig_callee;
1886 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
1888 /* We've hit cycle? It is time to give up. */
1889 if (callee->aux)
1891 if (dump_file)
1892 fprintf (dump_file,
1893 "Not inlining %s into %s to avoid cycle.\n",
1894 xstrdup_for_dump (callee->name ()),
1895 xstrdup_for_dump (e->caller->name ()));
1896 e->inline_failed = CIF_RECURSIVE_INLINING;
1897 continue;
1900 /* When the edge is already inlined, we just need to recurse into
1901 it in order to fully flatten the leaves. */
1902 if (!e->inline_failed)
1904 flatten_function (callee, early);
1905 continue;
1908 /* Flatten attribute needs to be processed during late inlining. For
1909 extra code quality we however do flattening during early optimization,
1910 too. */
1911 if (!early
1912 ? !can_inline_edge_p (e, true)
1913 : !can_early_inline_edge_p (e))
1914 continue;
1916 if (e->recursive_p ())
1918 if (dump_file)
1919 fprintf (dump_file, "Not inlining: recursive call.\n");
1920 continue;
1923 if (gimple_in_ssa_p (DECL_STRUCT_FUNCTION (node->decl))
1924 != gimple_in_ssa_p (DECL_STRUCT_FUNCTION (callee->decl)))
1926 if (dump_file)
1927 fprintf (dump_file, "Not inlining: SSA form does not match.\n");
1928 continue;
1931 /* Inline the edge and flatten the inline clone. Avoid
1932 recursing through the original node if the node was cloned. */
1933 if (dump_file)
1934 fprintf (dump_file, " Inlining %s into %s.\n",
1935 xstrdup_for_dump (callee->name ()),
1936 xstrdup_for_dump (e->caller->name ()));
1937 orig_callee = callee;
1938 inline_call (e, true, NULL, NULL, false);
1939 if (e->callee != orig_callee)
1940 orig_callee->aux = (void *) node;
1941 flatten_function (e->callee, early);
1942 if (e->callee != orig_callee)
1943 orig_callee->aux = NULL;
1946 node->aux = NULL;
1947 if (!node->global.inlined_to)
1948 inline_update_overall_summary (node);
1951 /* Count number of callers of NODE and store it into DATA (that
1952 points to int. Worker for cgraph_for_node_and_aliases. */
1954 static bool
1955 sum_callers (struct cgraph_node *node, void *data)
1957 struct cgraph_edge *e;
1958 int *num_calls = (int *)data;
1960 for (e = node->callers; e; e = e->next_caller)
1961 (*num_calls)++;
1962 return false;
1965 /* Inline NODE to all callers. Worker for cgraph_for_node_and_aliases.
1966 DATA points to number of calls originally found so we avoid infinite
1967 recursion. */
1969 static bool
1970 inline_to_all_callers (struct cgraph_node *node, void *data)
1972 int *num_calls = (int *)data;
1973 bool callee_removed = false;
1975 while (node->callers && !node->global.inlined_to)
1977 struct cgraph_node *caller = node->callers->caller;
1979 if (dump_file)
1981 fprintf (dump_file,
1982 "\nInlining %s size %i.\n",
1983 node->name (),
1984 inline_summaries->get (node)->size);
1985 fprintf (dump_file,
1986 " Called once from %s %i insns.\n",
1987 node->callers->caller->name (),
1988 inline_summaries->get (node->callers->caller)->size);
1991 inline_call (node->callers, true, NULL, NULL, true, &callee_removed);
1992 if (dump_file)
1993 fprintf (dump_file,
1994 " Inlined into %s which now has %i size\n",
1995 caller->name (),
1996 inline_summaries->get (caller)->size);
1997 if (!(*num_calls)--)
1999 if (dump_file)
2000 fprintf (dump_file, "New calls found; giving up.\n");
2001 return callee_removed;
2003 if (callee_removed)
2004 return true;
2006 return false;
2009 /* Output overall time estimate. */
2010 static void
2011 dump_overall_stats (void)
2013 int64_t sum_weighted = 0, sum = 0;
2014 struct cgraph_node *node;
2016 FOR_EACH_DEFINED_FUNCTION (node)
2017 if (!node->global.inlined_to
2018 && !node->alias)
2020 int time = inline_summaries->get (node)->time;
2021 sum += time;
2022 sum_weighted += time * node->count;
2024 fprintf (dump_file, "Overall time estimate: "
2025 "%"PRId64" weighted by profile: "
2026 "%"PRId64"\n", sum, sum_weighted);
2029 /* Output some useful stats about inlining. */
2031 static void
2032 dump_inline_stats (void)
2034 int64_t inlined_cnt = 0, inlined_indir_cnt = 0;
2035 int64_t inlined_virt_cnt = 0, inlined_virt_indir_cnt = 0;
2036 int64_t noninlined_cnt = 0, noninlined_indir_cnt = 0;
2037 int64_t noninlined_virt_cnt = 0, noninlined_virt_indir_cnt = 0;
2038 int64_t inlined_speculative = 0, inlined_speculative_ply = 0;
2039 int64_t indirect_poly_cnt = 0, indirect_cnt = 0;
2040 int64_t reason[CIF_N_REASONS][3];
2041 int i;
2042 struct cgraph_node *node;
2044 memset (reason, 0, sizeof (reason));
2045 FOR_EACH_DEFINED_FUNCTION (node)
2047 struct cgraph_edge *e;
2048 for (e = node->callees; e; e = e->next_callee)
2050 if (e->inline_failed)
2052 reason[(int) e->inline_failed][0] += e->count;
2053 reason[(int) e->inline_failed][1] += e->frequency;
2054 reason[(int) e->inline_failed][2] ++;
2055 if (DECL_VIRTUAL_P (e->callee->decl))
2057 if (e->indirect_inlining_edge)
2058 noninlined_virt_indir_cnt += e->count;
2059 else
2060 noninlined_virt_cnt += e->count;
2062 else
2064 if (e->indirect_inlining_edge)
2065 noninlined_indir_cnt += e->count;
2066 else
2067 noninlined_cnt += e->count;
2070 else
2072 if (e->speculative)
2074 if (DECL_VIRTUAL_P (e->callee->decl))
2075 inlined_speculative_ply += e->count;
2076 else
2077 inlined_speculative += e->count;
2079 else if (DECL_VIRTUAL_P (e->callee->decl))
2081 if (e->indirect_inlining_edge)
2082 inlined_virt_indir_cnt += e->count;
2083 else
2084 inlined_virt_cnt += e->count;
2086 else
2088 if (e->indirect_inlining_edge)
2089 inlined_indir_cnt += e->count;
2090 else
2091 inlined_cnt += e->count;
2095 for (e = node->indirect_calls; e; e = e->next_callee)
2096 if (e->indirect_info->polymorphic)
2097 indirect_poly_cnt += e->count;
2098 else
2099 indirect_cnt += e->count;
2101 if (max_count)
2103 fprintf (dump_file,
2104 "Inlined %"PRId64 " + speculative "
2105 "%"PRId64 " + speculative polymorphic "
2106 "%"PRId64 " + previously indirect "
2107 "%"PRId64 " + virtual "
2108 "%"PRId64 " + virtual and previously indirect "
2109 "%"PRId64 "\n" "Not inlined "
2110 "%"PRId64 " + previously indirect "
2111 "%"PRId64 " + virtual "
2112 "%"PRId64 " + virtual and previously indirect "
2113 "%"PRId64 " + stil indirect "
2114 "%"PRId64 " + still indirect polymorphic "
2115 "%"PRId64 "\n", inlined_cnt,
2116 inlined_speculative, inlined_speculative_ply,
2117 inlined_indir_cnt, inlined_virt_cnt, inlined_virt_indir_cnt,
2118 noninlined_cnt, noninlined_indir_cnt, noninlined_virt_cnt,
2119 noninlined_virt_indir_cnt, indirect_cnt, indirect_poly_cnt);
2120 fprintf (dump_file,
2121 "Removed speculations %"PRId64 "\n",
2122 spec_rem);
2124 dump_overall_stats ();
2125 fprintf (dump_file, "\nWhy inlining failed?\n");
2126 for (i = 0; i < CIF_N_REASONS; i++)
2127 if (reason[i][2])
2128 fprintf (dump_file, "%-50s: %8i calls, %8i freq, %"PRId64" count\n",
2129 cgraph_inline_failed_string ((cgraph_inline_failed_t) i),
2130 (int) reason[i][2], (int) reason[i][1], reason[i][0]);
2133 /* Decide on the inlining. We do so in the topological order to avoid
2134 expenses on updating data structures. */
2136 static unsigned int
2137 ipa_inline (void)
2139 struct cgraph_node *node;
2140 int nnodes;
2141 struct cgraph_node **order;
2142 int i;
2143 int cold;
2144 bool remove_functions = false;
2146 if (!optimize)
2147 return 0;
2149 cgraph_freq_base_rec = (sreal) 1 / (sreal) CGRAPH_FREQ_BASE;
2150 percent_rec = (sreal) 1 / (sreal) 100;
2152 order = XCNEWVEC (struct cgraph_node *, symtab->cgraph_count);
2154 if (in_lto_p && optimize)
2155 ipa_update_after_lto_read ();
2157 if (dump_file)
2158 dump_inline_summaries (dump_file);
2160 nnodes = ipa_reverse_postorder (order);
2162 FOR_EACH_FUNCTION (node)
2163 node->aux = 0;
2165 if (dump_file)
2166 fprintf (dump_file, "\nFlattening functions:\n");
2168 /* In the first pass handle functions to be flattened. Do this with
2169 a priority so none of our later choices will make this impossible. */
2170 for (i = nnodes - 1; i >= 0; i--)
2172 node = order[i];
2174 /* Handle nodes to be flattened.
2175 Ideally when processing callees we stop inlining at the
2176 entry of cycles, possibly cloning that entry point and
2177 try to flatten itself turning it into a self-recursive
2178 function. */
2179 if (lookup_attribute ("flatten",
2180 DECL_ATTRIBUTES (node->decl)) != NULL)
2182 if (dump_file)
2183 fprintf (dump_file,
2184 "Flattening %s\n", node->name ());
2185 flatten_function (node, false);
2188 if (dump_file)
2189 dump_overall_stats ();
2191 inline_small_functions ();
2193 gcc_assert (symtab->state == IPA_SSA);
2194 symtab->state = IPA_SSA_AFTER_INLINING;
2195 /* Do first after-inlining removal. We want to remove all "stale" extern
2196 inline functions and virtual functions so we really know what is called
2197 once. */
2198 symtab->remove_unreachable_nodes (dump_file);
2199 free (order);
2201 /* Inline functions with a property that after inlining into all callers the
2202 code size will shrink because the out-of-line copy is eliminated.
2203 We do this regardless on the callee size as long as function growth limits
2204 are met. */
2205 if (dump_file)
2206 fprintf (dump_file,
2207 "\nDeciding on functions to be inlined into all callers and "
2208 "removing useless speculations:\n");
2210 /* Inlining one function called once has good chance of preventing
2211 inlining other function into the same callee. Ideally we should
2212 work in priority order, but probably inlining hot functions first
2213 is good cut without the extra pain of maintaining the queue.
2215 ??? this is not really fitting the bill perfectly: inlining function
2216 into callee often leads to better optimization of callee due to
2217 increased context for optimization.
2218 For example if main() function calls a function that outputs help
2219 and then function that does the main optmization, we should inline
2220 the second with priority even if both calls are cold by themselves.
2222 We probably want to implement new predicate replacing our use of
2223 maybe_hot_edge interpreted as maybe_hot_edge || callee is known
2224 to be hot. */
2225 for (cold = 0; cold <= 1; cold ++)
2227 FOR_EACH_DEFINED_FUNCTION (node)
2229 struct cgraph_edge *edge, *next;
2230 bool update=false;
2232 for (edge = node->callees; edge; edge = next)
2234 next = edge->next_callee;
2235 if (edge->speculative && !speculation_useful_p (edge, false))
2237 edge->resolve_speculation ();
2238 spec_rem += edge->count;
2239 update = true;
2240 remove_functions = true;
2243 if (update)
2245 struct cgraph_node *where = node->global.inlined_to
2246 ? node->global.inlined_to : node;
2247 reset_node_growth_cache (where);
2248 reset_edge_caches (where);
2249 inline_update_overall_summary (where);
2251 if (want_inline_function_to_all_callers_p (node, cold))
2253 int num_calls = 0;
2254 node->call_for_symbol_thunks_and_aliases (sum_callers, &num_calls,
2255 true);
2256 while (node->call_for_symbol_thunks_and_aliases
2257 (inline_to_all_callers, &num_calls, true))
2259 remove_functions = true;
2264 /* Free ipa-prop structures if they are no longer needed. */
2265 if (optimize)
2266 ipa_free_all_structures_after_iinln ();
2268 if (dump_file)
2270 fprintf (dump_file,
2271 "\nInlined %i calls, eliminated %i functions\n\n",
2272 ncalls_inlined, nfunctions_inlined);
2273 dump_inline_stats ();
2276 if (dump_file)
2277 dump_inline_summaries (dump_file);
2278 /* In WPA we use inline summaries for partitioning process. */
2279 if (!flag_wpa)
2280 inline_free_summary ();
2281 return remove_functions ? TODO_remove_functions : 0;
2284 /* Inline always-inline function calls in NODE. */
2286 static bool
2287 inline_always_inline_functions (struct cgraph_node *node)
2289 struct cgraph_edge *e;
2290 bool inlined = false;
2292 for (e = node->callees; e; e = e->next_callee)
2294 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
2295 if (!DECL_DISREGARD_INLINE_LIMITS (callee->decl))
2296 continue;
2298 if (e->recursive_p ())
2300 if (dump_file)
2301 fprintf (dump_file, " Not inlining recursive call to %s.\n",
2302 e->callee->name ());
2303 e->inline_failed = CIF_RECURSIVE_INLINING;
2304 continue;
2307 if (!can_early_inline_edge_p (e))
2309 /* Set inlined to true if the callee is marked "always_inline" but
2310 is not inlinable. This will allow flagging an error later in
2311 expand_call_inline in tree-inline.c. */
2312 if (lookup_attribute ("always_inline",
2313 DECL_ATTRIBUTES (callee->decl)) != NULL)
2314 inlined = true;
2315 continue;
2318 if (dump_file)
2319 fprintf (dump_file, " Inlining %s into %s (always_inline).\n",
2320 xstrdup_for_dump (e->callee->name ()),
2321 xstrdup_for_dump (e->caller->name ()));
2322 inline_call (e, true, NULL, NULL, false);
2323 inlined = true;
2325 if (inlined)
2326 inline_update_overall_summary (node);
2328 return inlined;
2331 /* Decide on the inlining. We do so in the topological order to avoid
2332 expenses on updating data structures. */
2334 static bool
2335 early_inline_small_functions (struct cgraph_node *node)
2337 struct cgraph_edge *e;
2338 bool inlined = false;
2340 for (e = node->callees; e; e = e->next_callee)
2342 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
2343 if (!inline_summaries->get (callee)->inlinable
2344 || !e->inline_failed)
2345 continue;
2347 /* Do not consider functions not declared inline. */
2348 if (!DECL_DECLARED_INLINE_P (callee->decl)
2349 && !opt_for_fn (node->decl, flag_inline_small_functions)
2350 && !opt_for_fn (node->decl, flag_inline_functions))
2351 continue;
2353 if (dump_file)
2354 fprintf (dump_file, "Considering inline candidate %s.\n",
2355 callee->name ());
2357 if (!can_early_inline_edge_p (e))
2358 continue;
2360 if (e->recursive_p ())
2362 if (dump_file)
2363 fprintf (dump_file, " Not inlining: recursive call.\n");
2364 continue;
2367 if (!want_early_inline_function_p (e))
2368 continue;
2370 if (dump_file)
2371 fprintf (dump_file, " Inlining %s into %s.\n",
2372 xstrdup_for_dump (callee->name ()),
2373 xstrdup_for_dump (e->caller->name ()));
2374 inline_call (e, true, NULL, NULL, true);
2375 inlined = true;
2378 return inlined;
2381 unsigned int
2382 early_inliner (function *fun)
2384 struct cgraph_node *node = cgraph_node::get (current_function_decl);
2385 struct cgraph_edge *edge;
2386 unsigned int todo = 0;
2387 int iterations = 0;
2388 bool inlined = false;
2390 if (seen_error ())
2391 return 0;
2393 /* Do nothing if datastructures for ipa-inliner are already computed. This
2394 happens when some pass decides to construct new function and
2395 cgraph_add_new_function calls lowering passes and early optimization on
2396 it. This may confuse ourself when early inliner decide to inline call to
2397 function clone, because function clones don't have parameter list in
2398 ipa-prop matching their signature. */
2399 if (ipa_node_params_sum)
2400 return 0;
2402 #ifdef ENABLE_CHECKING
2403 node->verify ();
2404 #endif
2405 node->remove_all_references ();
2407 /* Even when not optimizing or not inlining inline always-inline
2408 functions. */
2409 inlined = inline_always_inline_functions (node);
2411 if (!optimize
2412 || flag_no_inline
2413 || !flag_early_inlining
2414 /* Never inline regular functions into always-inline functions
2415 during incremental inlining. This sucks as functions calling
2416 always inline functions will get less optimized, but at the
2417 same time inlining of functions calling always inline
2418 function into an always inline function might introduce
2419 cycles of edges to be always inlined in the callgraph.
2421 We might want to be smarter and just avoid this type of inlining. */
2422 || DECL_DISREGARD_INLINE_LIMITS (node->decl))
2424 else if (lookup_attribute ("flatten",
2425 DECL_ATTRIBUTES (node->decl)) != NULL)
2427 /* When the function is marked to be flattened, recursively inline
2428 all calls in it. */
2429 if (dump_file)
2430 fprintf (dump_file,
2431 "Flattening %s\n", node->name ());
2432 flatten_function (node, true);
2433 inlined = true;
2435 else
2437 /* We iterate incremental inlining to get trivial cases of indirect
2438 inlining. */
2439 while (iterations < PARAM_VALUE (PARAM_EARLY_INLINER_MAX_ITERATIONS)
2440 && early_inline_small_functions (node))
2442 timevar_push (TV_INTEGRATION);
2443 todo |= optimize_inline_calls (current_function_decl);
2445 /* Technically we ought to recompute inline parameters so the new
2446 iteration of early inliner works as expected. We however have
2447 values approximately right and thus we only need to update edge
2448 info that might be cleared out for newly discovered edges. */
2449 for (edge = node->callees; edge; edge = edge->next_callee)
2451 /* We have no summary for new bound store calls yet. */
2452 if (inline_edge_summary_vec.length () > (unsigned)edge->uid)
2454 struct inline_edge_summary *es = inline_edge_summary (edge);
2455 es->call_stmt_size
2456 = estimate_num_insns (edge->call_stmt, &eni_size_weights);
2457 es->call_stmt_time
2458 = estimate_num_insns (edge->call_stmt, &eni_time_weights);
2460 if (edge->callee->decl
2461 && !gimple_check_call_matching_types (
2462 edge->call_stmt, edge->callee->decl, false))
2463 edge->call_stmt_cannot_inline_p = true;
2465 if (iterations < PARAM_VALUE (PARAM_EARLY_INLINER_MAX_ITERATIONS) - 1)
2466 inline_update_overall_summary (node);
2467 timevar_pop (TV_INTEGRATION);
2468 iterations++;
2469 inlined = false;
2471 if (dump_file)
2472 fprintf (dump_file, "Iterations: %i\n", iterations);
2475 if (inlined)
2477 timevar_push (TV_INTEGRATION);
2478 todo |= optimize_inline_calls (current_function_decl);
2479 timevar_pop (TV_INTEGRATION);
2482 fun->always_inline_functions_inlined = true;
2484 return todo;
2487 /* Do inlining of small functions. Doing so early helps profiling and other
2488 passes to be somewhat more effective and avoids some code duplication in
2489 later real inlining pass for testcases with very many function calls. */
2491 namespace {
2493 const pass_data pass_data_early_inline =
2495 GIMPLE_PASS, /* type */
2496 "einline", /* name */
2497 OPTGROUP_INLINE, /* optinfo_flags */
2498 TV_EARLY_INLINING, /* tv_id */
2499 PROP_ssa, /* properties_required */
2500 0, /* properties_provided */
2501 0, /* properties_destroyed */
2502 0, /* todo_flags_start */
2503 0, /* todo_flags_finish */
2506 class pass_early_inline : public gimple_opt_pass
2508 public:
2509 pass_early_inline (gcc::context *ctxt)
2510 : gimple_opt_pass (pass_data_early_inline, ctxt)
2513 /* opt_pass methods: */
2514 virtual unsigned int execute (function *);
2516 }; // class pass_early_inline
2518 unsigned int
2519 pass_early_inline::execute (function *fun)
2521 return early_inliner (fun);
2524 } // anon namespace
2526 gimple_opt_pass *
2527 make_pass_early_inline (gcc::context *ctxt)
2529 return new pass_early_inline (ctxt);
2532 namespace {
2534 const pass_data pass_data_ipa_inline =
2536 IPA_PASS, /* type */
2537 "inline", /* name */
2538 OPTGROUP_INLINE, /* optinfo_flags */
2539 TV_IPA_INLINING, /* tv_id */
2540 0, /* properties_required */
2541 0, /* properties_provided */
2542 0, /* properties_destroyed */
2543 0, /* todo_flags_start */
2544 ( TODO_dump_symtab ), /* todo_flags_finish */
2547 class pass_ipa_inline : public ipa_opt_pass_d
2549 public:
2550 pass_ipa_inline (gcc::context *ctxt)
2551 : ipa_opt_pass_d (pass_data_ipa_inline, ctxt,
2552 inline_generate_summary, /* generate_summary */
2553 inline_write_summary, /* write_summary */
2554 inline_read_summary, /* read_summary */
2555 NULL, /* write_optimization_summary */
2556 NULL, /* read_optimization_summary */
2557 NULL, /* stmt_fixup */
2558 0, /* function_transform_todo_flags_start */
2559 inline_transform, /* function_transform */
2560 NULL) /* variable_transform */
2563 /* opt_pass methods: */
2564 virtual unsigned int execute (function *) { return ipa_inline (); }
2566 }; // class pass_ipa_inline
2568 } // anon namespace
2570 ipa_opt_pass_d *
2571 make_pass_ipa_inline (gcc::context *ctxt)
2573 return new pass_ipa_inline (ctxt);