OSDN Git Service

PR c/12553
[pf3gnuchains/gcc-fork.git] / gcc / cgraphunit.c
1 /* Callgraph based intraprocedural optimizations.
2    Copyright (C) 2003 Free Software Foundation, Inc.
3    Contributed by Jan Hubicka
4
5 This file is part of GCC.
6
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 2, or (at your option) any later
10 version.
11
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.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to the Free
19 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "tree-inline.h"
28 #include "langhooks.h"
29 #include "hashtab.h"
30 #include "toplev.h"
31 #include "flags.h"
32 #include "ggc.h"
33 #include "debug.h"
34 #include "target.h"
35 #include "cgraph.h"
36 #include "diagnostic.h"
37 #include "timevar.h"
38 #include "params.h"
39 #include "fibheap.h"
40 #include "c-common.h"
41
42 #define INSNS_PER_CALL 10
43
44 static void cgraph_expand_all_functions (void);
45 static void cgraph_mark_functions_to_output (void);
46 static void cgraph_expand_function (struct cgraph_node *);
47 static tree record_call_1 (tree *, int *, void *);
48 static void cgraph_mark_local_functions (void);
49 static void cgraph_optimize_function (struct cgraph_node *);
50 static bool cgraph_default_inline_p (struct cgraph_node *n);
51 static void cgraph_analyze_function (struct cgraph_node *node);
52 static void cgraph_decide_inlining_incrementally (struct cgraph_node *);
53
54 /* Statistics we collect about inlining algorithm.  */
55 static int ncalls_inlined;
56 static int nfunctions_inlined;
57 static int initial_insns;
58 static int overall_insns;
59
60 /* Records tree nodes seen in cgraph_create_edges.  Simply using
61    walk_tree_without_duplicates doesn't guarantee each node is visited
62    once because it gets a new htab upon each recursive call from
63    record_calls_1.  */
64 static htab_t visited_nodes;
65
66 /* Determine if function DECL is needed.  That is, visible to something
67    either outside this translation unit, something magic in the system
68    configury, or (if not doing unit-at-a-time) to something we havn't
69    seen yet.  */
70
71 static bool
72 decide_is_function_needed (struct cgraph_node *node, tree decl)
73 {
74   /* If we decided it was needed before, but at the time we didn't have
75      the body of the function available, then it's still needed.  We have
76      to go back and re-check its dependencies now.  */
77   if (node->needed)
78     return true;
79
80   /* Externally visible functions must be output.  The exception is
81      COMDAT functions that must be output only when they are needed.  */
82   if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl) && !DECL_EXTERNAL (decl))
83     return true;
84
85   /* Constructors and destructors are reachable from the runtime by
86      some mechanism.  */
87   if (DECL_STATIC_CONSTRUCTOR (decl) || DECL_STATIC_DESTRUCTOR (decl))
88     return true;
89
90   /* If the user told us it is used, then it must be so.  */
91   if (lookup_attribute ("used", DECL_ATTRIBUTES (decl)))
92     return true;
93
94   /* ??? If the assembler name is set by hand, it is possible to assemble
95      the name later after finalizing the function and the fact is noticed
96      in assemble_name then.  This is arguably a bug.  */
97   if (DECL_ASSEMBLER_NAME_SET_P (decl)
98       && TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)))
99     return true;
100
101   if (flag_unit_at_a_time)
102     return false;
103
104   /* If not doing unit at a time, then we'll only defer this function
105      if its marked for inlining.  Otherwise we want to emit it now.  */
106
107   /* "extern inline" functions are never output locally.  */
108   if (DECL_EXTERNAL (decl))
109     return false;
110   /* We want to emit COMDAT functions only when absolutely necessary.  */
111   if (DECL_COMDAT (decl))
112     return false;
113   if (!DECL_INLINE (decl)
114       || (!node->local.disregard_inline_limits
115           /* When declared inline, defer even the uninlinable functions.
116              This allows them to be eliminated when unused.  */
117           && !DECL_DECLARED_INLINE_P (decl) 
118           && (!node->local.inlinable || !cgraph_default_inline_p (node))))
119     return true;
120
121   return false;
122 }
123
124 /* When not doing unit-at-a-time, output all functions enqueued.
125    Return true when such a functions were found.  */
126
127 bool
128 cgraph_assemble_pending_functions (void)
129 {
130   bool output = false;
131
132   if (flag_unit_at_a_time)
133     return false;
134
135   while (cgraph_nodes_queue)
136     {
137       struct cgraph_node *n = cgraph_nodes_queue;
138
139       cgraph_nodes_queue = cgraph_nodes_queue->next_needed;
140       if (!n->origin && !DECL_EXTERNAL (n->decl))
141         {
142           cgraph_expand_function (n);
143           output = true;
144         }
145     }
146
147   return output;
148 }
149
150 /* DECL has been parsed.  Take it, queue it, compile it at the whim of the
151    logic in effect.  If NESTED is true, then our caller cannot stand to have
152    the garbage collector run at the moment.  We would need to either create
153    a new GC context, or just not compile right now.  */
154
155 void
156 cgraph_finalize_function (tree decl, bool nested)
157 {
158   struct cgraph_node *node = cgraph_node (decl);
159
160   if (node->local.finalized)
161     {
162       /* As an GCC extension we allow redefinition of the function.  The
163          semantics when both copies of bodies differ is not well defined.
164          We replace the old body with new body so in unit at a time mode
165          we always use new body, while in normal mode we may end up with
166          old body inlined into some functions and new body expanded and
167          inlined in others.
168          
169          ??? It may make more sense to use one body for inlining and other
170          body for expanding the function but this is difficult to do.  */
171
172       /* If node->output is set, then this is a unit-at-a-time compilation
173          and we have already begun whole-unit analysis.  This is *not*
174          testing for whether we've already emitted the function.  That
175          case can be sort-of legitimately seen with real function 
176          redefinition errors.  I would argue that the front end should
177          never present us with such a case, but don't enforce that for now.  */
178       if (node->output)
179         abort ();
180
181       /* Reset our datastructures so we can analyze the function again.  */
182       memset (&node->local, 0, sizeof (node->local));
183       memset (&node->global, 0, sizeof (node->global));
184       memset (&node->rtl, 0, sizeof (node->rtl));
185       node->analyzed = false;
186       while (node->callees)
187         cgraph_remove_edge (node, node->callees->callee);
188
189       /* We may need to re-queue the node for assembling in case
190          we already proceeded it and ignored as not needed.  */
191       if (node->reachable && !flag_unit_at_a_time)
192         {
193           struct cgraph_node *n;
194
195           for (n = cgraph_nodes_queue; n; n = n->next_needed)
196             if (n == node)
197               break;
198           if (!n)
199             node->reachable = 0;
200         }
201     }
202
203   notice_global_symbol (decl);
204   node->decl = decl;
205   node->local.finalized = true;
206
207   /* If not unit at a time, then we need to create the call graph
208      now, so that called functions can be queued and emitted now.  */
209   if (!flag_unit_at_a_time)
210     {
211       cgraph_analyze_function (node);
212       cgraph_decide_inlining_incrementally (node);
213     }
214
215   if (decide_is_function_needed (node, decl))
216     cgraph_mark_needed_node (node);
217
218   /* If not unit at a time, go ahead and emit everything we've found
219      to be reachable at this time.  */
220   if (!nested)
221     cgraph_assemble_pending_functions ();
222
223   /* If we've not yet emitted decl, tell the debug info about it.  */
224   if (!TREE_ASM_WRITTEN (decl))
225     (*debug_hooks->deferred_inline_function) (decl);
226 }
227
228 /* Walk tree and record all calls.  Called via walk_tree.  */
229 static tree
230 record_call_1 (tree *tp, int *walk_subtrees, void *data)
231 {
232   tree t = *tp;
233
234   switch (TREE_CODE (t))
235     {
236     case VAR_DECL:
237       /* ??? Really, we should mark this decl as *potentially* referenced
238          by this function and re-examine whether the decl is actually used
239          after rtl has been generated.  */
240       if (TREE_STATIC (t))
241         cgraph_varpool_mark_needed_node (cgraph_varpool_node (t));
242       break;
243
244     case ADDR_EXPR:
245       if (flag_unit_at_a_time)
246         {
247           /* Record dereferences to the functions.  This makes the
248              functions reachable unconditionally.  */
249           tree decl = TREE_OPERAND (*tp, 0);
250           if (TREE_CODE (decl) == FUNCTION_DECL)
251             cgraph_mark_needed_node (cgraph_node (decl));
252         }
253       break;
254
255     case CALL_EXPR:
256       {
257         tree decl = get_callee_fndecl (*tp);
258         if (decl && TREE_CODE (decl) == FUNCTION_DECL)
259           {
260             if (DECL_BUILT_IN (decl))
261               return NULL;
262             cgraph_record_call (data, decl);
263
264             /* When we see a function call, we don't want to look at the
265                function reference in the ADDR_EXPR that is hanging from
266                the CALL_EXPR we're examining here, because we would
267                conclude incorrectly that the function's address could be
268                taken by something that is not a function call.  So only
269                walk the function parameter list, skip the other subtrees.  */
270
271             walk_tree (&TREE_OPERAND (*tp, 1), record_call_1, data,
272                        visited_nodes);
273             *walk_subtrees = 0;
274           }
275         break;
276       }
277
278     default:
279       /* Save some cycles by not walking types and declaration as we
280          won't find anything useful there anyway.  */
281       if (DECL_P (*tp) || TYPE_P (*tp))
282         {
283           *walk_subtrees = 0;
284           break;
285         }
286
287       if ((unsigned int) TREE_CODE (t) >= LAST_AND_UNUSED_TREE_CODE)
288         return (*lang_hooks.callgraph.analyze_expr) (tp, walk_subtrees, data);
289       break;
290     }
291
292   return NULL;
293 }
294
295 /* Create cgraph edges for function calls inside BODY from DECL.  */
296
297 void
298 cgraph_create_edges (tree decl, tree body)
299 {
300   /* The nodes we're interested in are never shared, so walk
301      the tree ignoring duplicates.  */
302   visited_nodes = htab_create (37, htab_hash_pointer,
303                                     htab_eq_pointer, NULL);
304   walk_tree (&body, record_call_1, decl, visited_nodes);
305   htab_delete (visited_nodes);
306   visited_nodes = NULL;
307 }
308
309 /* Analyze the function scheduled to be output.  */
310 static void
311 cgraph_analyze_function (struct cgraph_node *node)
312 {
313   tree decl = node->decl;
314
315   current_function_decl = decl;
316
317   /* First kill forward declaration so reverse inlining works properly.  */
318   cgraph_create_edges (decl, DECL_SAVED_TREE (decl));
319
320   node->local.inlinable = tree_inlinable_function_p (decl);
321   if (!DECL_ESTIMATED_INSNS (decl))
322     DECL_ESTIMATED_INSNS (decl)
323       = (*lang_hooks.tree_inlining.estimate_num_insns) (decl);
324   node->local.self_insns = DECL_ESTIMATED_INSNS (decl);
325   if (node->local.inlinable)
326     node->local.disregard_inline_limits
327       = (*lang_hooks.tree_inlining.disregard_inline_limits) (decl);
328
329   /* Inlining characteristics are maintained by the cgraph_mark_inline.  */
330   node->global.insns = node->local.self_insns;
331   if (!DECL_EXTERNAL (decl))
332     {
333       node->global.cloned_times = 1;
334       node->global.will_be_output = true;
335     }
336
337   node->analyzed = true;
338   current_function_decl = NULL;
339 }
340
341 /* Analyze the whole compilation unit once it is parsed completely.  */
342
343 void
344 cgraph_finalize_compilation_unit (void)
345 {
346   struct cgraph_node *node;
347
348   if (!flag_unit_at_a_time)
349     {
350       cgraph_assemble_pending_functions ();
351       return;
352     }
353
354   cgraph_varpool_assemble_pending_decls ();
355   if (!quiet_flag)
356     fprintf (stderr, "\nAnalyzing compilation unit\n");
357
358   timevar_push (TV_CGRAPH);
359   if (cgraph_dump_file)
360     {
361       fprintf (cgraph_dump_file, "Initial entry points:");
362       for (node = cgraph_nodes; node; node = node->next)
363         if (node->needed && DECL_SAVED_TREE (node->decl))
364           fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
365       fprintf (cgraph_dump_file, "\n");
366     }
367
368   /* Propagate reachability flag and lower representation of all reachable
369      functions.  In the future, lowering will introduce new functions and
370      new entry points on the way (by template instantiation and virtual
371      method table generation for instance).  */
372   while (cgraph_nodes_queue)
373     {
374       struct cgraph_edge *edge;
375       tree decl = cgraph_nodes_queue->decl;
376
377       node = cgraph_nodes_queue;
378       cgraph_nodes_queue = cgraph_nodes_queue->next_needed;
379
380       /* ??? It is possible to create extern inline function and later using
381          weak alas attribute to kill it's body. See
382          gcc.c-torture/compile/20011119-1.c  */
383       if (!DECL_SAVED_TREE (decl))
384         continue;
385
386       if (node->analyzed || !node->reachable || !DECL_SAVED_TREE (decl))
387         abort ();
388
389       cgraph_analyze_function (node);
390
391       for (edge = node->callees; edge; edge = edge->next_callee)
392         if (!edge->callee->reachable)
393           cgraph_mark_reachable_node (edge->callee);
394
395       cgraph_varpool_assemble_pending_decls ();
396     }
397
398   /* Collect entry points to the unit.  */
399
400   if (cgraph_dump_file)
401     {
402       fprintf (cgraph_dump_file, "Unit entry points:");
403       for (node = cgraph_nodes; node; node = node->next)
404         if (node->needed && DECL_SAVED_TREE (node->decl))
405           fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
406       fprintf (cgraph_dump_file, "\n\nInitial ");
407       dump_cgraph (cgraph_dump_file);
408     }
409
410   if (cgraph_dump_file)
411     fprintf (cgraph_dump_file, "\nReclaiming functions:");
412
413   for (node = cgraph_nodes; node; node = node->next)
414     {
415       tree decl = node->decl;
416
417       if (!node->reachable && DECL_SAVED_TREE (decl))
418         {
419           cgraph_remove_node (node);
420           if (cgraph_dump_file)
421             fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
422         }
423     }
424   if (cgraph_dump_file)
425     {
426       fprintf (cgraph_dump_file, "\n\nReclaimed ");
427       dump_cgraph (cgraph_dump_file);
428     }
429   ggc_collect ();
430   timevar_pop (TV_CGRAPH);
431 }
432
433 /* Figure out what functions we want to assemble.  */
434
435 static void
436 cgraph_mark_functions_to_output (void)
437 {
438   struct cgraph_node *node;
439
440   for (node = cgraph_nodes; node; node = node->next)
441     {
442       tree decl = node->decl;
443       struct cgraph_edge *e;
444       if (node->output)
445         abort ();
446
447       for (e = node->callers; e; e = e->next_caller)
448         if (!e->inline_call)
449           break;
450
451       /* We need to output all local functions that are used and not
452          always inlined, as well as those that are reachable from
453          outside the current compilation unit.  */
454       if (DECL_SAVED_TREE (decl)
455           && (node->needed
456               || (e && node->reachable))
457           && !TREE_ASM_WRITTEN (decl) && !node->origin
458           && !DECL_EXTERNAL (decl))
459         node->output = 1;
460     }
461 }
462
463 /* Optimize the function before expansion.  */
464
465 static void
466 cgraph_optimize_function (struct cgraph_node *node)
467 {
468   tree decl = node->decl;
469
470   timevar_push (TV_INTEGRATION);
471   /* optimize_inline_calls avoids inlining of current_function_decl.  */
472   current_function_decl = decl;
473   if (flag_inline_trees)
474     optimize_inline_calls (decl);
475   if (node->nested)
476     {
477       for (node = node->nested; node; node = node->next_nested)
478         cgraph_optimize_function (node);
479     }
480   timevar_pop (TV_INTEGRATION);
481 }
482
483 /* Expand function specified by NODE.  */
484
485 static void
486 cgraph_expand_function (struct cgraph_node *node)
487 {
488   tree decl = node->decl;
489   struct cgraph_edge *e;
490
491   if (flag_unit_at_a_time)
492     announce_function (decl);
493
494   cgraph_optimize_function (node);
495
496   /* Generate RTL for the body of DECL.  Nested functions are expanded
497      via lang_expand_decl_stmt.  */
498   (*lang_hooks.callgraph.expand_function) (decl);
499
500   if (!flag_unit_at_a_time)
501     {
502        if (!node->local.inlinable
503            || (!node->local.disregard_inline_limits
504                && !cgraph_default_inline_p (node)))
505          DECL_SAVED_TREE (node->decl) = NULL;
506     }
507   else
508     {
509       for (e = node->callers; e; e = e->next_caller)
510         if (e->inline_call)
511           break;
512       if (!e)
513         DECL_SAVED_TREE (decl) = NULL;
514     }
515   current_function_decl = NULL;
516 }
517
518 /* Fill array order with all nodes with output flag set in the reverse
519    topological order.  */
520 static int
521 cgraph_postorder (struct cgraph_node **order)
522 {
523   struct cgraph_node *node, *node2;
524   int stack_size = 0;
525   int order_pos = 0;
526   struct cgraph_edge *edge, last;
527
528   struct cgraph_node **stack =
529     xcalloc (cgraph_n_nodes, sizeof (struct cgraph_node *));
530
531   /* We have to deal with cycles nicely, so use a depth first traversal
532      output algorithm.  Ignore the fact that some functions won't need
533      to be output and put them into order as well, so we get dependencies
534      right through intline functions.  */
535   for (node = cgraph_nodes; node; node = node->next)
536     node->aux = NULL;
537   for (node = cgraph_nodes; node; node = node->next)
538     if (!node->aux)
539       {
540         node2 = node;
541         if (!node->callers)
542           node->aux = &last;
543         else
544           node->aux = node->callers;
545         while (node2)
546           {
547             while (node2->aux != &last)
548               {
549                 edge = node2->aux;
550                 if (edge->next_caller)
551                   node2->aux = edge->next_caller;
552                 else
553                   node2->aux = &last;
554                 if (!edge->caller->aux)
555                   {
556                     if (!edge->caller->callers)
557                       edge->caller->aux = &last;
558                     else
559                       edge->caller->aux = edge->caller->callers;
560                     stack[stack_size++] = node2;
561                     node2 = edge->caller;
562                     break;
563                   }
564               }
565             if (node2->aux == &last)
566               {
567                 order[order_pos++] = node2;
568                 if (stack_size)
569                   node2 = stack[--stack_size];
570                 else
571                   node2 = NULL;
572               }
573           }
574       }
575   free (stack);
576   return order_pos;
577 }
578
579 #define INLINED_TIMES(node) ((size_t)(node)->aux)
580 #define SET_INLINED_TIMES(node,times) ((node)->aux = (void *)(times))
581
582 /* Return list of nodes we decided to inline NODE into, set their output
583    flag and compute INLINED_TIMES.
584
585    We do simple backtracing to get INLINED_TIMES right.  This should not be
586    expensive as we limit the amount of inlining.  Alternatively we may first
587    discover set of nodes, topologically sort these and propagate
588    INLINED_TIMES  */
589
590 static int
591 cgraph_inlined_into (struct cgraph_node *node, struct cgraph_node **array)
592 {
593   int nfound = 0;
594   struct cgraph_edge **stack;
595   struct cgraph_edge *e, *e1;
596   int sp;
597   int i;
598
599   /* Fast path: since we traverse in mostly topological order, we will likely
600      find no edges.  */
601   for (e = node->callers; e; e = e->next_caller)
602     if (e->inline_call)
603       break;
604
605   if (!e)
606     return 0;
607
608   /* Allocate stack for back-tracking up callgraph.  */
609   stack = xmalloc ((cgraph_n_nodes + 1) * sizeof (struct cgraph_edge));
610   sp = 0;
611
612   /* Push the first edge on to the stack.  */
613   stack[sp++] = e;
614
615   while (sp)
616     {
617       struct cgraph_node *caller;
618
619       /* Look at the edge on the top of the stack.  */
620       e = stack[sp - 1];
621       caller = e->caller;
622
623       /* Check if the caller destination has been visited yet.  */
624       if (!caller->output)
625         {
626           array[nfound++] = e->caller;
627           /* Mark that we have visited the destination.  */
628           caller->output = true;
629           SET_INLINED_TIMES (caller, 0);
630         }
631       SET_INLINED_TIMES (caller, INLINED_TIMES (caller) + 1);
632
633       for (e1 = caller->callers; e1; e1 = e1->next_caller)
634         if (e1->inline_call)
635           break;
636       if (e1)
637         stack[sp++] = e1;
638       else
639         {
640           while (true)
641             {
642               for (e1 = e->next_caller; e1; e1 = e1->next_caller)
643                 if (e1->inline_call)
644                   break;
645
646               if (e1)
647                 {
648                   stack[sp - 1] = e1;
649                   break;
650                 }
651               else
652                 {
653                   sp--;
654                   if (!sp)
655                     break;
656                   e = stack[sp - 1];
657                 }
658             }
659         }
660     }
661
662   free (stack);
663
664
665   if (cgraph_dump_file)
666     {
667       fprintf (cgraph_dump_file, " Found inline predecesors of %s:",
668                cgraph_node_name (node));
669       for (i = 0; i < nfound; i++)
670         {
671           fprintf (cgraph_dump_file, " %s", cgraph_node_name (array[i]));
672           if (INLINED_TIMES (array[i]) != 1)
673             fprintf (cgraph_dump_file, " (%i times)",
674                      (int)INLINED_TIMES (array[i]));
675         }
676       fprintf (cgraph_dump_file, "\n");
677     }
678
679   return nfound;
680 }
681
682 /* Return list of nodes we decided to inline into NODE, set their output
683    flag and compute INLINED_TIMES.
684
685    This function is identical to cgraph_inlined_into with callers and callees
686    nodes swapped.  */
687
688 static int
689 cgraph_inlined_callees (struct cgraph_node *node, struct cgraph_node **array)
690 {
691   int nfound = 0;
692   struct cgraph_edge **stack;
693   struct cgraph_edge *e, *e1;
694   int sp;
695   int i;
696
697   /* Fast path: since we traverse in mostly topological order, we will likely
698      find no edges.  */
699   for (e = node->callees; e; e = e->next_callee)
700     if (e->inline_call)
701       break;
702
703   if (!e)
704     return 0;
705
706   /* Allocate stack for back-tracking up callgraph.  */
707   stack = xmalloc ((cgraph_n_nodes + 1) * sizeof (struct cgraph_edge));
708   sp = 0;
709
710   /* Push the first edge on to the stack.  */
711   stack[sp++] = e;
712
713   while (sp)
714     {
715       struct cgraph_node *callee;
716
717       /* Look at the edge on the top of the stack.  */
718       e = stack[sp - 1];
719       callee = e->callee;
720
721       /* Check if the callee destination has been visited yet.  */
722       if (!callee->output)
723         {
724           array[nfound++] = e->callee;
725           /* Mark that we have visited the destination.  */
726           callee->output = true;
727           SET_INLINED_TIMES (callee, 0);
728         }
729       SET_INLINED_TIMES (callee, INLINED_TIMES (callee) + 1);
730
731       for (e1 = callee->callees; e1; e1 = e1->next_callee)
732         if (e1->inline_call)
733           break;
734       if (e1)
735         stack[sp++] = e1;
736       else
737         {
738           while (true)
739             {
740               for (e1 = e->next_callee; e1; e1 = e1->next_callee)
741                 if (e1->inline_call)
742                   break;
743
744               if (e1)
745                 {
746                   stack[sp - 1] = e1;
747                   break;
748                 }
749               else
750                 {
751                   sp--;
752                   if (!sp)
753                     break;
754                   e = stack[sp - 1];
755                 }
756             }
757         }
758     }
759
760   free (stack);
761
762   if (cgraph_dump_file)
763     {
764       fprintf (cgraph_dump_file, " Found inline successors of %s:",
765                cgraph_node_name (node));
766       for (i = 0; i < nfound; i++)
767         {
768           fprintf (cgraph_dump_file, " %s", cgraph_node_name (array[i]));
769           if (INLINED_TIMES (array[i]) != 1)
770             fprintf (cgraph_dump_file, " (%i times)",
771                      (int)INLINED_TIMES (array[i]));
772         }
773       fprintf (cgraph_dump_file, "\n");
774     }
775
776   return nfound;
777 }
778
779 /* Estimate size of the function after inlining WHAT into TO.  */
780
781 static int
782 cgraph_estimate_size_after_inlining (int times, struct cgraph_node *to,
783                                      struct cgraph_node *what)
784 {
785   return (what->global.insns - INSNS_PER_CALL) * times + to->global.insns;
786 }
787
788 /* Estimate the growth caused by inlining NODE into all callees.  */
789
790 static int
791 cgraph_estimate_growth (struct cgraph_node *node)
792 {
793   int growth = 0;
794   int calls_saved = 0;
795   int clones_added = 0;
796   struct cgraph_edge *e;
797
798   for (e = node->callers; e; e = e->next_caller)
799     if (!e->inline_call)
800       {
801         growth += ((cgraph_estimate_size_after_inlining (1, e->caller, node)
802                     -
803                     e->caller->global.insns) *e->caller->global.cloned_times);
804         calls_saved += e->caller->global.cloned_times;
805         clones_added += e->caller->global.cloned_times;
806       }
807
808   /* ??? Wrong for self recursive functions or cases where we decide to not
809      inline for different reasons, but it is not big deal as in that case
810      we will keep the body around, but we will also avoid some inlining.  */
811   if (!node->needed && !node->origin && !DECL_EXTERNAL (node->decl))
812     growth -= node->global.insns, clones_added--;
813
814   if (!calls_saved)
815     calls_saved = 1;
816
817   return growth;
818 }
819
820 /* Update insn sizes after inlining WHAT into TO that is already inlined into
821    all nodes in INLINED array.  */
822
823 static void
824 cgraph_mark_inline (struct cgraph_node *to, struct cgraph_node *what,
825                     struct cgraph_node **inlined, int ninlined,
826                     struct cgraph_node **inlined_callees,
827                     int ninlined_callees)
828 {
829   int i;
830   int times = 0;
831   int clones = 0;
832   struct cgraph_edge *e;
833   bool called = false;
834   int new_insns;
835
836   for (e = what->callers; e; e = e->next_caller)
837     {
838       if (e->caller == to)
839         {
840           if (e->inline_call)
841             abort ();
842           e->inline_call = true;
843           times++;
844           clones += e->caller->global.cloned_times;
845         }
846       else if (!e->inline_call)
847         called = true;
848     }
849   if (!times)
850     abort ();
851   ncalls_inlined += times;
852
853   new_insns = cgraph_estimate_size_after_inlining (times, to, what);
854   if (to->global.will_be_output)
855     overall_insns += new_insns - to->global.insns;
856   to->global.insns = new_insns;
857
858   if (!called && !what->needed && !what->origin
859       && flag_unit_at_a_time
860       && !DECL_EXTERNAL (what->decl))
861     {
862       if (!what->global.will_be_output)
863         abort ();
864       clones--;
865       nfunctions_inlined++;
866       what->global.will_be_output = 0;
867       overall_insns -= what->global.insns;
868     }
869   what->global.cloned_times += clones;
870   for (i = 0; i < ninlined; i++)
871     {
872       new_insns =
873         cgraph_estimate_size_after_inlining (INLINED_TIMES (inlined[i]) *
874                                              times, inlined[i], what);
875       if (inlined[i]->global.will_be_output)
876         overall_insns += new_insns - inlined[i]->global.insns;
877       inlined[i]->global.insns = new_insns;
878     }
879   for (i = 0; i < ninlined_callees; i++)
880     {
881       inlined_callees[i]->global.cloned_times +=
882         INLINED_TIMES (inlined_callees[i]) * clones;
883     }
884 }
885
886 /* Return false when inlining WHAT into TO is not good idea as it would cause
887    too large growth of function bodies.  */
888
889 static bool
890 cgraph_check_inline_limits (struct cgraph_node *to, struct cgraph_node *what,
891                             struct cgraph_node **inlined, int ninlined)
892 {
893   int i;
894   int times = 0;
895   struct cgraph_edge *e;
896   int newsize;
897   int limit;
898
899   for (e = to->callees; e; e = e->next_callee)
900     if (e->callee == what)
901       times++;
902
903   /* When inlining large function body called once into small function,
904      take the inlined function as base for limiting the growth.  */
905   if (to->local.self_insns > what->local.self_insns)
906     limit = to->local.self_insns;
907   else
908     limit = what->local.self_insns;
909
910   limit += limit * PARAM_VALUE (PARAM_LARGE_FUNCTION_GROWTH) / 100;
911
912   newsize = cgraph_estimate_size_after_inlining (times, to, what);
913   if (newsize > PARAM_VALUE (PARAM_LARGE_FUNCTION_INSNS)
914       && newsize > limit)
915     return false;
916   for (i = 0; i < ninlined; i++)
917     {
918       newsize =
919         cgraph_estimate_size_after_inlining (INLINED_TIMES (inlined[i]) *
920                                              times, inlined[i], what);
921       if (newsize > PARAM_VALUE (PARAM_LARGE_FUNCTION_INSNS)
922           && newsize >
923           inlined[i]->local.self_insns *
924           (100 + PARAM_VALUE (PARAM_LARGE_FUNCTION_GROWTH)) / 100)
925         return false;
926     }
927   return true;
928 }
929
930 /* Return true when function N is small enough to be inlined.  */
931
932 static bool
933 cgraph_default_inline_p (struct cgraph_node *n)
934 {
935   if (!DECL_INLINE (n->decl) || !DECL_SAVED_TREE (n->decl))
936     return false;
937   if (DECL_DECLARED_INLINE_P (n->decl))
938     return n->global.insns < MAX_INLINE_INSNS_SINGLE;
939   else
940     return n->global.insns < MAX_INLINE_INSNS_AUTO;
941 }
942
943 /* We use greedy algorithm for inlining of small functions:
944    All inline candidates are put into prioritized heap based on estimated
945    growth of the overall number of instructions and then update the estimates.
946
947    INLINED and INLINED_CALEES are just pointers to arrays large enought
948    to be passed to cgraph_inlined_into and cgraph_inlined_callees.  */
949
950 static void
951 cgraph_decide_inlining_of_small_functions (struct cgraph_node **inlined,
952                                            struct cgraph_node **inlined_callees)
953 {
954   int i;
955   struct cgraph_node *node;
956   fibheap_t heap = fibheap_new ();
957   struct fibnode **heap_node =
958     xcalloc (cgraph_max_uid, sizeof (struct fibnode *));
959   int ninlined, ninlined_callees;
960   int max_insns = ((HOST_WIDEST_INT) initial_insns
961                    * (100 + PARAM_VALUE (PARAM_INLINE_UNIT_GROWTH)) / 100);
962
963   /* Put all inline candidates into the heap.  */
964
965   for (node = cgraph_nodes; node; node = node->next)
966     {
967       struct cgraph_edge *e;
968
969       if (!node->local.inlinable || !node->callers
970           || !cgraph_default_inline_p (node))
971         continue;
972
973       /* Rule out always_inline functions we dealt with earlier.  */
974       for (e = node->callers; e; e = e->next_caller)
975         if (e->inline_call)
976           break;
977       if (e)
978         continue;
979       heap_node[node->uid] =
980         fibheap_insert (heap, cgraph_estimate_growth (node), node);
981     }
982
983   if (cgraph_dump_file)
984     fprintf (cgraph_dump_file, "\nDeciding on smaller functions:\n");
985   while ((node = fibheap_extract_min (heap)) && overall_insns <= max_insns)
986     {
987       struct cgraph_edge *e;
988       int old_insns = overall_insns;
989
990       heap_node[node->uid] = NULL;
991       if (cgraph_dump_file)
992         fprintf (cgraph_dump_file, 
993                  "\nConsidering %s with %i insns\n"
994                  " Estimated growth is %+i insns.\n",
995                  cgraph_node_name (node), node->global.insns,
996                  cgraph_estimate_growth (node));
997       if (!cgraph_default_inline_p (node))
998         {
999           if (cgraph_dump_file)
1000             fprintf (cgraph_dump_file, " Function too large.\n");
1001           continue;
1002         }
1003       ninlined_callees = cgraph_inlined_callees (node, inlined_callees);
1004       for (e = node->callers; e; e = e->next_caller)
1005         if (!e->inline_call && e->caller != node)
1006           {
1007             ninlined = cgraph_inlined_into (e->caller, inlined);
1008             if (e->callee->output
1009                 || !cgraph_check_inline_limits (e->caller, node, inlined,
1010                                                 ninlined))
1011               {
1012                 for (i = 0; i < ninlined; i++)
1013                   inlined[i]->output = 0, node->aux = 0;
1014                 if (cgraph_dump_file)
1015                   fprintf (cgraph_dump_file, " Not inlining into %s.\n",
1016                            cgraph_node_name (e->caller));
1017                 continue;
1018               }
1019             cgraph_mark_inline (e->caller, node, inlined, ninlined,
1020                                 inlined_callees, ninlined_callees);
1021             if (heap_node[e->caller->uid])
1022               fibheap_replace_key (heap, heap_node[e->caller->uid],
1023                                    cgraph_estimate_growth (e->caller));
1024
1025             /* Size of the functions we updated into has changed, so update
1026                the keys.  */
1027             for (i = 0; i < ninlined; i++)
1028               {
1029                 inlined[i]->output = 0, node->aux = 0;
1030                 if (heap_node[inlined[i]->uid])
1031                   fibheap_replace_key (heap, heap_node[inlined[i]->uid],
1032                                        cgraph_estimate_growth (inlined[i]));
1033               }
1034         if (cgraph_dump_file)
1035           fprintf (cgraph_dump_file, 
1036                    " Inlined into %s which now has %i insns.\n",
1037                    cgraph_node_name (e->caller),
1038                    e->caller->global.insns);
1039
1040           }
1041
1042       /* Similarly all functions called by the function we just inlined
1043          are now called more times; update keys.  */
1044
1045       for (e = node->callees; e; e = e->next_callee)
1046         if (!e->inline_call && heap_node[e->callee->uid])
1047           fibheap_replace_key (heap, heap_node[e->callee->uid],
1048                                cgraph_estimate_growth (e->callee));
1049
1050       for (i = 0; i < ninlined_callees; i++)
1051         {
1052           struct cgraph_edge *e;
1053
1054           for (e = inlined_callees[i]->callees; e; e = e->next_callee)
1055             if (!e->inline_call && heap_node[e->callee->uid])
1056               fibheap_replace_key (heap, heap_node[e->callee->uid],
1057                                    cgraph_estimate_growth (e->callee));
1058
1059           inlined_callees[i]->output = 0, node->aux = 0;
1060         }
1061       if (cgraph_dump_file)
1062         fprintf (cgraph_dump_file, 
1063                  " Inlined %i times for a net change of %+i insns.\n",
1064                  node->global.cloned_times, overall_insns - old_insns);
1065     }
1066   if (cgraph_dump_file && !fibheap_empty (heap))
1067     fprintf (cgraph_dump_file, "\nReached the inline-unit-growth limit.\n");
1068   fibheap_delete (heap);
1069   free (heap_node);
1070 }
1071
1072 /* Decide on the inlining.  We do so in the topological order to avoid
1073    expenses on updating datastructures.  */
1074
1075 static void
1076 cgraph_decide_inlining (void)
1077 {
1078   struct cgraph_node *node;
1079   int nnodes;
1080   struct cgraph_node **order =
1081     xcalloc (cgraph_n_nodes, sizeof (struct cgraph_node *));
1082   struct cgraph_node **inlined =
1083     xcalloc (cgraph_n_nodes, sizeof (struct cgraph_node *));
1084   struct cgraph_node **inlined_callees =
1085     xcalloc (cgraph_n_nodes, sizeof (struct cgraph_node *));
1086   int ninlined;
1087   int ninlined_callees;
1088   int old_insns = 0;
1089   int i, y;
1090
1091   for (node = cgraph_nodes; node; node = node->next)
1092     initial_insns += node->local.self_insns;
1093   overall_insns = initial_insns;
1094
1095   nnodes = cgraph_postorder (order);
1096
1097   if (cgraph_dump_file)
1098     fprintf (cgraph_dump_file,
1099              "\nDeciding on inlining.  Starting with %i insns.\n",
1100              initial_insns);
1101
1102   for (node = cgraph_nodes; node; node = node->next)
1103     node->aux = 0;
1104
1105   if (cgraph_dump_file)
1106     fprintf (cgraph_dump_file, "\nInlining always_inline functions:\n");
1107
1108   /* In the first pass mark all always_inline edges.  Do this with a priority
1109      so none of our later choices will make this impossible.  */
1110   for (i = nnodes - 1; i >= 0; i--)
1111     {
1112       struct cgraph_edge *e;
1113
1114       node = order[i];
1115
1116       for (e = node->callees; e; e = e->next_callee)
1117         if (e->callee->local.disregard_inline_limits)
1118           break;
1119       if (!e)
1120         continue;
1121       if (cgraph_dump_file)
1122         fprintf (cgraph_dump_file,
1123                  "\nConsidering %s %i insns (always inline)\n",
1124                  cgraph_node_name (e->callee), e->callee->global.insns);
1125       ninlined = cgraph_inlined_into (order[i], inlined);
1126       for (; e; e = e->next_callee)
1127         {
1128           old_insns = overall_insns;
1129           if (e->inline_call || !e->callee->local.disregard_inline_limits)
1130             continue;
1131           if (e->callee->output || e->callee == node)
1132             continue;
1133           ninlined_callees =
1134             cgraph_inlined_callees (e->callee, inlined_callees);
1135           cgraph_mark_inline (node, e->callee, inlined, ninlined,
1136                               inlined_callees, ninlined_callees);
1137           for (y = 0; y < ninlined_callees; y++)
1138             inlined_callees[y]->output = 0, node->aux = 0;
1139           if (cgraph_dump_file)
1140             fprintf (cgraph_dump_file, 
1141                      " Inlined into %s which now has %i insns.\n",
1142                      cgraph_node_name (node->callees->caller),
1143                      node->callees->caller->global.insns);
1144         }
1145         if (cgraph_dump_file && node->global.cloned_times > 0)
1146           fprintf (cgraph_dump_file, 
1147                    " Inlined %i times for a net change of %+i insns.\n",
1148                    node->global.cloned_times, overall_insns - old_insns);
1149       for (y = 0; y < ninlined; y++)
1150         inlined[y]->output = 0, node->aux = 0;
1151     }
1152
1153   cgraph_decide_inlining_of_small_functions (inlined, inlined_callees);
1154
1155   if (cgraph_dump_file)
1156     fprintf (cgraph_dump_file, "\nDeciding on functions called once:\n");
1157
1158   /* And finally decide what functions are called once.  */
1159
1160   for (i = nnodes - 1; i >= 0; i--)
1161     {
1162       node = order[i];
1163
1164       if (node->callers && !node->callers->next_caller && !node->needed
1165           && node->local.inlinable && !node->callers->inline_call
1166           && !DECL_EXTERNAL (node->decl) && !DECL_COMDAT (node->decl))
1167         {
1168           bool ok = true;
1169           struct cgraph_node *node1;
1170
1171           /* Verify that we won't duplicate the caller.  */
1172           for (node1 = node->callers->caller;
1173                node1->callers && node1->callers->inline_call
1174                && ok; node1 = node1->callers->caller)
1175             if (node1->callers->next_caller || node1->needed)
1176               ok = false;
1177           if (ok)
1178             {
1179               if (cgraph_dump_file)
1180                 fprintf (cgraph_dump_file,
1181                          "\nConsidering %s %i insns.\n"
1182                          " Called once from %s %i insns.\n",
1183                          cgraph_node_name (node), node->global.insns,
1184                          cgraph_node_name (node->callers->caller),
1185                          node->callers->caller->global.insns);
1186               ninlined = cgraph_inlined_into (node->callers->caller, inlined);
1187               old_insns = overall_insns;
1188               if (cgraph_check_inline_limits
1189                   (node->callers->caller, node, inlined, ninlined))
1190                 {
1191                   ninlined_callees =
1192                     cgraph_inlined_callees (node, inlined_callees);
1193                   cgraph_mark_inline (node->callers->caller, node, inlined,
1194                                       ninlined, inlined_callees,
1195                                       ninlined_callees);
1196                   for (y = 0; y < ninlined_callees; y++)
1197                     inlined_callees[y]->output = 0, node->aux = 0;
1198                   if (cgraph_dump_file)
1199                     fprintf (cgraph_dump_file,
1200                              " Inlined into %s which now has %i insns"
1201                              " for a net change of %+i insns.\n",
1202                              cgraph_node_name (node->callers->caller),
1203                              node->callers->caller->global.insns,
1204                              overall_insns - old_insns);
1205                 }
1206               else
1207                 {
1208                   if (cgraph_dump_file)
1209                     fprintf (cgraph_dump_file,
1210                              " Inline limit reached, not inlined.\n");
1211                 }
1212               for (y = 0; y < ninlined; y++)
1213                 inlined[y]->output = 0, node->aux = 0;
1214             }
1215         }
1216     }
1217
1218   if (cgraph_dump_file)
1219     fprintf (cgraph_dump_file,
1220              "\nInlined %i calls, eliminated %i functions, "
1221              "%i insns turned to %i insns.\n\n",
1222              ncalls_inlined, nfunctions_inlined, initial_insns,
1223              overall_insns);
1224   free (order);
1225   free (inlined);
1226   free (inlined_callees);
1227 }
1228
1229 /* Decide on the inlining.  We do so in the topological order to avoid
1230    expenses on updating datastructures.  */
1231
1232 static void
1233 cgraph_decide_inlining_incrementally (struct cgraph_node *node)
1234 {
1235   struct cgraph_edge *e;
1236   struct cgraph_node **inlined =
1237     xmalloc (sizeof (struct cgraph_node *) * cgraph_n_nodes);
1238   struct cgraph_node **inlined_callees =
1239     xmalloc (sizeof (struct cgraph_node *) * cgraph_n_nodes);
1240   int ninlined;
1241   int ninlined_callees;
1242   int y;
1243
1244   ninlined = cgraph_inlined_into (node, inlined);
1245
1246   /* First of all look for always inline functions.  */
1247   for (e = node->callees; e; e = e->next_callee)
1248     if (e->callee->local.disregard_inline_limits && !e->callee->output
1249         && e->callee != node && !e->inline_call)
1250       {
1251         ninlined_callees = cgraph_inlined_callees (e->callee, inlined_callees);
1252         cgraph_mark_inline (node, e->callee, inlined, ninlined,
1253                             inlined_callees, ninlined_callees);
1254         for (y = 0; y < ninlined_callees; y++)
1255           inlined_callees[y]->output = 0, node->aux = 0;
1256       }
1257
1258   /* Now do the automatic inlining.  */
1259   for (e = node->callees; e; e = e->next_callee)
1260     if (e->callee->local.inlinable && !e->callee->output
1261         && e->callee != node && !e->inline_call
1262         && cgraph_default_inline_p (e->callee)
1263         && cgraph_check_inline_limits (node, e->callee, inlined,
1264                                        ninlined))
1265       {
1266         ninlined_callees = cgraph_inlined_callees (e->callee, inlined_callees);
1267         cgraph_mark_inline (node, e->callee, inlined, ninlined,
1268                             inlined_callees, ninlined_callees);
1269         for (y = 0; y < ninlined_callees; y++)
1270           inlined_callees[y]->output = 0, node->aux = 0;
1271       }
1272
1273   /* Clear the flags set by cgraph_inlined_into.  */
1274   for (y = 0; y < ninlined; y++)
1275     inlined[y]->output = 0, node->aux = 0;
1276
1277   free (inlined);
1278   free (inlined_callees);
1279 }
1280
1281
1282 /* Return true when CALLER_DECL should be inlined into CALLEE_DECL.  */
1283
1284 bool
1285 cgraph_inline_p (tree caller_decl, tree callee_decl)
1286 {
1287   struct cgraph_node *caller = cgraph_node (caller_decl);
1288   struct cgraph_node *callee = cgraph_node (callee_decl);
1289   struct cgraph_edge *e;
1290
1291   for (e = caller->callees; e; e = e->next_callee)
1292     if (e->callee == callee)
1293       return e->inline_call;
1294   /* We do not record builtins in the callgraph.  Perhaps it would make more
1295      sense to do so and then prune out those not overwritten by explicit
1296      function body.  */
1297   return false;
1298 }
1299 /* Expand all functions that must be output.
1300
1301    Attempt to topologically sort the nodes so function is output when
1302    all called functions are already assembled to allow data to be
1303    propagated across the callgraph.  Use a stack to get smaller distance
1304    between a function and it's callees (later we may choose to use a more
1305    sophisticated algorithm for function reordering; we will likely want
1306    to use subsections to make the output functions appear in top-down
1307    order).  */
1308
1309 static void
1310 cgraph_expand_all_functions (void)
1311 {
1312   struct cgraph_node *node;
1313   struct cgraph_node **order =
1314     xcalloc (cgraph_n_nodes, sizeof (struct cgraph_node *));
1315   int order_pos = 0;
1316   int i;
1317
1318   cgraph_mark_functions_to_output ();
1319
1320   order_pos = cgraph_postorder (order);
1321
1322   for (i = order_pos - 1; i >= 0; i--)
1323     {
1324       node = order[i];
1325       if (node->output)
1326         {
1327           if (!node->reachable)
1328             abort ();
1329           node->output = 0;
1330           cgraph_expand_function (node);
1331         }
1332     }
1333   free (order);
1334 }
1335
1336 /* Mark all local functions.
1337
1338    A local function is one whose calls can occur only in the
1339    current compilation unit, so we change its calling convention.
1340    We simply mark all static functions whose address is not taken
1341    as local.  */
1342
1343 static void
1344 cgraph_mark_local_functions (void)
1345 {
1346   struct cgraph_node *node;
1347
1348   if (cgraph_dump_file)
1349     fprintf (cgraph_dump_file, "\nMarking local functions:");
1350
1351   /* Figure out functions we want to assemble.  */
1352   for (node = cgraph_nodes; node; node = node->next)
1353     {
1354       node->local.local = (!node->needed
1355                            && DECL_SAVED_TREE (node->decl)
1356                            && !TREE_PUBLIC (node->decl));
1357       if (cgraph_dump_file && node->local.local)
1358         fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
1359     }
1360   if (cgraph_dump_file)
1361     fprintf (cgraph_dump_file, "\n\n");
1362 }
1363
1364 /* Perform simple optimizations based on callgraph.  */
1365
1366 void
1367 cgraph_optimize (void)
1368 {
1369   if (!flag_unit_at_a_time)
1370     return;
1371   timevar_push (TV_CGRAPHOPT);
1372   if (!quiet_flag)
1373     fprintf (stderr, "Performing intraprocedural optimizations\n");
1374
1375   cgraph_mark_local_functions ();
1376   if (cgraph_dump_file)
1377     {
1378       fprintf (cgraph_dump_file, "Marked ");
1379       dump_cgraph (cgraph_dump_file);
1380     }
1381
1382   cgraph_decide_inlining ();
1383   cgraph_global_info_ready = true;
1384   if (cgraph_dump_file)
1385     {
1386       fprintf (cgraph_dump_file, "Optimized ");
1387       dump_cgraph (cgraph_dump_file);
1388     }
1389   timevar_pop (TV_CGRAPHOPT);
1390
1391   /* Output everything.  */
1392   if (!quiet_flag)
1393     fprintf (stderr, "Assembling functions:\n");
1394   cgraph_expand_all_functions ();
1395   if (cgraph_dump_file)
1396     {
1397       fprintf (cgraph_dump_file, "\nFinal ");
1398       dump_cgraph (cgraph_dump_file);
1399     }
1400 }