OSDN Git Service

(PREFERRED_DEBUGGING_TYPE): Use DWARF2_DEBUG.
[pf3gnuchains/gcc-fork.git] / gcc / cgraphunit.c
1 /* Callgraph based intraprocedural optimizations.
2    Copyright (C) 2003, 2004 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 /* This module implements main driver of compilation process as well as
23    few basic intraprocedural optimizers.
24
25    The main scope of this file is to act as an interface in between
26    tree based frontends and the backend (and middle end)
27
28    The front-end is supposed to use following functionality:
29
30     - cgraph_finalize_function
31
32       This function is called once front-end has parsed whole body of function
33       and it is certain that the function body nor the declaration will change.
34
35       (There is one exception needed for implementing GCC extern inline function.)
36
37     - cgraph_varpool_finalize_variable
38
39       This function has same behavior as the above but is used for static
40       variables.
41
42     - cgraph_finalize_compilation_unit
43
44       This function is called once compilation unit is finalized and it will
45       no longer change.
46
47       In the unit-at-a-time the call-graph construction and local function
48       analysis takes place here.  Bodies of unreachable functions are released
49       to conserve memory usage.
50
51       ???  The compilation unit in this point of view should be compilation
52       unit as defined by the language - for instance C frontend allows multiple
53       compilation units to be parsed at once and it should call function each
54       time parsing is done so we save memory.
55
56     - cgraph_optimize
57
58       In this unit-at-a-time compilation the intra procedural analysis takes
59       place here.  In particular the static functions whose address is never
60       taken are marked as local.  Backend can then use this information to
61       modify calling conventions, do better inlining or similar optimizations.
62
63     - cgraph_assemble_pending_functions
64     - cgraph_varpool_assemble_pending_variables
65
66       In non-unit-at-a-time mode these functions can be used to force compilation
67       of functions or variables that are known to be needed at given stage
68       of compilation
69
70     - cgraph_mark_needed_node
71     - cgraph_varpool_mark_needed_node
72
73       When function or variable is referenced by some hidden way (for instance
74       via assembly code and marked by attribute "used"), the call-graph data structure
75       must be updated accordingly by this function.
76
77     - analyze_expr callback
78
79       This function is responsible for lowering tree nodes not understood by
80       generic code into understandable ones or alternatively marking
81       callgraph and varpool nodes referenced by the as needed.
82
83       ??? On the tree-ssa genericizing should take place here and we will avoid
84       need for these hooks (replacing them by genericizing hook)
85
86     - expand_function callback
87
88       This function is used to expand function and pass it into RTL back-end.
89       Front-end should not make any assumptions about when this function can be
90       called.  In particular cgraph_assemble_pending_functions,
91       cgraph_varpool_assemble_pending_variables, cgraph_finalize_function,
92       cgraph_varpool_finalize_function, cgraph_optimize can cause arbitrarily
93       previously finalized functions to be expanded.
94
95     We implement two compilation modes.
96
97       - unit-at-a-time:  In this mode analyzing of all functions is deferred
98         to cgraph_finalize_compilation_unit and expansion into cgraph_optimize.
99
100         In cgraph_finalize_compilation_unit the reachable functions are
101         analyzed.  During analysis the call-graph edges from reachable
102         functions are constructed and their destinations are marked as
103         reachable.  References to functions and variables are discovered too
104         and variables found to be needed output to the assembly file.  Via
105         mark_referenced call in assemble_variable functions referenced by
106         static variables are noticed too.
107
108         The intra-procedural information is produced and its existence
109         indicated by global_info_ready.  Once this flag is set it is impossible
110         to change function from !reachable to reachable and thus
111         assemble_variable no longer call mark_referenced.
112
113         Finally the call-graph is topologically sorted and all reachable functions
114         that has not been completely inlined or are not external are output.
115
116         ??? It is possible that reference to function or variable is optimized
117         out.  We can not deal with this nicely because topological order is not
118         suitable for it.  For tree-ssa we may consider another pass doing
119         optimization and re-discovering reachable functions.
120
121         ??? Reorganize code so variables are output very last and only if they
122         really has been referenced by produced code, so we catch more cases
123         where reference has been optimized out.
124
125       - non-unit-at-a-time
126
127         All functions are variables are output as early as possible to conserve
128         memory consumption.  This may or may not result in less memory used but
129         it is still needed for some legacy code that rely on particular ordering
130         of things output from the compiler.
131
132         Varpool data structures are not used and variables are output directly.
133
134         Functions are output early using call of
135         cgraph_assemble_pending_function from cgraph_finalize_function.  The
136         decision on whether function is needed is made more conservative so
137         uninlininable static functions are needed too.  During the call-graph
138         construction the edge destinations are not marked as reachable and it
139         is completely relied upn assemble_variable to mark them.
140         
141      Inlining decision heuristics
142         ??? Move this to separate file after tree-ssa merge.
143
144         We separate inlining decisions from the inliner itself and store it
145         inside callgraph as so called inline plan.  Refer to cgraph.c
146         documentation about particular representation of inline plans in the
147         callgraph
148
149         The implementation of particular heuristics is separated from
150         the rest of code to make it easier to replace it with more complicated
151         implementation in the future.  The rest of inlining code acts as a
152         library aimed to modify the callgraph and verify that the parameters
153         on code size growth fits.
154
155         To mark given call inline, use cgraph_mark_inline function, the
156         verification is performed by cgraph_default_inline_p and
157         cgraph_check_inline_limits.
158
159         The heuristics implements simple knapsack style algorithm ordering
160         all functions by their "profitability" (estimated by code size growth)
161         and inlining them in priority order.
162
163         cgraph_decide_inlining implements heuristics taking whole callgraph
164         into account, while cgraph_decide_inlining_incrementally considers
165         only one function at a time and is used in non-unit-at-a-time mode.  */
166
167
168 #include "config.h"
169 #include "system.h"
170 #include "coretypes.h"
171 #include "tm.h"
172 #include "tree.h"
173 #include "rtl.h"
174 #include "tree-flow.h"
175 #include "tree-inline.h"
176 #include "langhooks.h"
177 #include "pointer-set.h"
178 #include "toplev.h"
179 #include "flags.h"
180 #include "ggc.h"
181 #include "debug.h"
182 #include "target.h"
183 #include "cgraph.h"
184 #include "diagnostic.h"
185 #include "timevar.h"
186 #include "params.h"
187 #include "fibheap.h"
188 #include "c-common.h"
189 #include "intl.h"
190 #include "function.h"
191 #include "tree-gimple.h"
192
193 #define INSNS_PER_CALL 10
194
195 static void cgraph_expand_all_functions (void);
196 static void cgraph_mark_functions_to_output (void);
197 static void cgraph_expand_function (struct cgraph_node *);
198 static tree record_call_1 (tree *, int *, void *);
199 static void cgraph_mark_local_functions (void);
200 static bool cgraph_default_inline_p (struct cgraph_node *n);
201 static void cgraph_analyze_function (struct cgraph_node *node);
202 static void cgraph_decide_inlining_incrementally (struct cgraph_node *);
203
204 /* Statistics we collect about inlining algorithm.  */
205 static int ncalls_inlined;
206 static int nfunctions_inlined;
207 static int initial_insns;
208 static int overall_insns;
209
210 /* Records tree nodes seen in cgraph_create_edges.  Simply using
211    walk_tree_without_duplicates doesn't guarantee each node is visited
212    once because it gets a new htab upon each recursive call from
213    record_calls_1.  */
214 static struct pointer_set_t *visited_nodes;
215
216 static FILE *cgraph_dump_file;
217
218 /* Determine if function DECL is needed.  That is, visible to something
219    either outside this translation unit, something magic in the system
220    configury, or (if not doing unit-at-a-time) to something we havn't
221    seen yet.  */
222
223 static bool
224 decide_is_function_needed (struct cgraph_node *node, tree decl)
225 {
226   tree origin;
227
228   /* If we decided it was needed before, but at the time we didn't have
229      the body of the function available, then it's still needed.  We have
230      to go back and re-check its dependencies now.  */
231   if (node->needed)
232     return true;
233
234   /* Externally visible functions must be output.  The exception is
235      COMDAT functions that must be output only when they are needed.  */
236   if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl) && !DECL_EXTERNAL (decl))
237     return true;
238
239   /* Constructors and destructors are reachable from the runtime by
240      some mechanism.  */
241   if (DECL_STATIC_CONSTRUCTOR (decl) || DECL_STATIC_DESTRUCTOR (decl))
242     return true;
243
244   /* If the user told us it is used, then it must be so.  */
245   if (lookup_attribute ("used", DECL_ATTRIBUTES (decl)))
246     return true;
247
248   /* ??? If the assembler name is set by hand, it is possible to assemble
249      the name later after finalizing the function and the fact is noticed
250      in assemble_name then.  This is arguably a bug.  */
251   if (DECL_ASSEMBLER_NAME_SET_P (decl)
252       && TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)))
253     return true;
254
255   if (flag_unit_at_a_time)
256     return false;
257
258   /* If not doing unit at a time, then we'll only defer this function
259      if its marked for inlining.  Otherwise we want to emit it now.  */
260
261   /* "extern inline" functions are never output locally.  */
262   if (DECL_EXTERNAL (decl))
263     return false;
264   /* Nested functions of extern inline function shall not be emit unless
265      we inlined the origin.  */
266   for (origin = decl_function_context (decl); origin;
267        origin = decl_function_context (origin))
268     if (DECL_EXTERNAL (origin))
269       return false;
270   /* We want to emit COMDAT functions only when absolutely necessary.  */
271   if (DECL_COMDAT (decl))
272     return false;
273   if (!DECL_INLINE (decl)
274       || (!node->local.disregard_inline_limits
275           /* When declared inline, defer even the uninlinable functions.
276              This allows them to be eliminated when unused.  */
277           && !DECL_DECLARED_INLINE_P (decl) 
278           && (!node->local.inlinable || !cgraph_default_inline_p (node))))
279     return true;
280
281   return false;
282 }
283
284
285
286 /* When not doing unit-at-a-time, output all functions enqueued.
287    Return true when such a functions were found.  */
288
289 bool
290 cgraph_assemble_pending_functions (void)
291 {
292   bool output = false;
293
294   if (flag_unit_at_a_time)
295     return false;
296
297   while (cgraph_nodes_queue)
298     {
299       struct cgraph_node *n = cgraph_nodes_queue;
300
301       cgraph_nodes_queue = cgraph_nodes_queue->next_needed;
302       n->next_needed = NULL;
303       if (!n->global.inlined_to && !DECL_EXTERNAL (n->decl))
304         {
305           cgraph_expand_function (n);
306           output = true;
307         }
308     }
309
310   return output;
311 }
312
313 /* DECL has been parsed.  Take it, queue it, compile it at the whim of the
314    logic in effect.  If NESTED is true, then our caller cannot stand to have
315    the garbage collector run at the moment.  We would need to either create
316    a new GC context, or just not compile right now.  */
317
318 void
319 cgraph_finalize_function (tree decl, bool nested)
320 {
321   struct cgraph_node *node = cgraph_node (decl);
322
323   if (node->local.finalized)
324     {
325       /* As an GCC extension we allow redefinition of the function.  The
326          semantics when both copies of bodies differ is not well defined.
327          We replace the old body with new body so in unit at a time mode
328          we always use new body, while in normal mode we may end up with
329          old body inlined into some functions and new body expanded and
330          inlined in others.
331          
332          ??? It may make more sense to use one body for inlining and other
333          body for expanding the function but this is difficult to do.  */
334
335       /* If node->output is set, then this is a unit-at-a-time compilation
336          and we have already begun whole-unit analysis.  This is *not*
337          testing for whether we've already emitted the function.  That
338          case can be sort-of legitimately seen with real function 
339          redefinition errors.  I would argue that the front end should
340          never present us with such a case, but don't enforce that for now.  */
341       gcc_assert (!node->output);
342
343       /* Reset our data structures so we can analyze the function again.  */
344       memset (&node->local, 0, sizeof (node->local));
345       memset (&node->global, 0, sizeof (node->global));
346       memset (&node->rtl, 0, sizeof (node->rtl));
347       node->analyzed = false;
348       node->local.redefined_extern_inline = true;
349       while (node->callees)
350         cgraph_remove_edge (node->callees);
351
352       /* We may need to re-queue the node for assembling in case
353          we already proceeded it and ignored as not needed.  */
354       if (node->reachable && !flag_unit_at_a_time)
355         {
356           struct cgraph_node *n;
357
358           for (n = cgraph_nodes_queue; n; n = n->next_needed)
359             if (n == node)
360               break;
361           if (!n)
362             node->reachable = 0;
363         }
364     }
365
366   notice_global_symbol (decl);
367   node->decl = decl;
368   node->local.finalized = true;
369   if (node->nested)
370     lower_nested_functions (decl);
371   gcc_assert (!node->nested);
372
373   /* If not unit at a time, then we need to create the call graph
374      now, so that called functions can be queued and emitted now.  */
375   if (!flag_unit_at_a_time)
376     {
377       cgraph_analyze_function (node);
378       cgraph_decide_inlining_incrementally (node);
379     }
380
381   if (decide_is_function_needed (node, decl))
382     cgraph_mark_needed_node (node);
383
384   /* If not unit at a time, go ahead and emit everything we've found
385      to be reachable at this time.  */
386   if (!nested)
387     {
388       if (!cgraph_assemble_pending_functions ())
389         ggc_collect ();
390     }
391
392   /* If we've not yet emitted decl, tell the debug info about it.  */
393   if (!TREE_ASM_WRITTEN (decl))
394     (*debug_hooks->deferred_inline_function) (decl);
395
396   /* Possibly warn about unused parameters.  */
397   if (warn_unused_parameter)
398     do_warn_unused_parameter (decl);
399 }
400
401 /* Walk tree and record all calls.  Called via walk_tree.  */
402 static tree
403 record_call_1 (tree *tp, int *walk_subtrees, void *data)
404 {
405   tree t = *tp;
406
407   switch (TREE_CODE (t))
408     {
409     case VAR_DECL:
410       /* ??? Really, we should mark this decl as *potentially* referenced
411          by this function and re-examine whether the decl is actually used
412          after rtl has been generated.  */
413       if (TREE_STATIC (t))
414         {
415           cgraph_varpool_mark_needed_node (cgraph_varpool_node (t));
416           if (lang_hooks.callgraph.analyze_expr)
417             return lang_hooks.callgraph.analyze_expr (tp, walk_subtrees, 
418                                                       data);
419         }
420       break;
421
422     case ADDR_EXPR:
423       if (flag_unit_at_a_time)
424         {
425           /* Record dereferences to the functions.  This makes the
426              functions reachable unconditionally.  */
427           tree decl = TREE_OPERAND (*tp, 0);
428           if (TREE_CODE (decl) == FUNCTION_DECL)
429             cgraph_mark_needed_node (cgraph_node (decl));
430         }
431       break;
432
433     case CALL_EXPR:
434       {
435         tree decl = get_callee_fndecl (*tp);
436         if (decl && TREE_CODE (decl) == FUNCTION_DECL)
437           {
438             cgraph_create_edge (data, cgraph_node (decl), *tp);
439
440             /* When we see a function call, we don't want to look at the
441                function reference in the ADDR_EXPR that is hanging from
442                the CALL_EXPR we're examining here, because we would
443                conclude incorrectly that the function's address could be
444                taken by something that is not a function call.  So only
445                walk the function parameter list, skip the other subtrees.  */
446
447             walk_tree (&TREE_OPERAND (*tp, 1), record_call_1, data,
448                        visited_nodes);
449             *walk_subtrees = 0;
450           }
451         break;
452       }
453
454     default:
455       /* Save some cycles by not walking types and declaration as we
456          won't find anything useful there anyway.  */
457       if (IS_TYPE_OR_DECL_P (*tp))
458         {
459           *walk_subtrees = 0;
460           break;
461         }
462
463       if ((unsigned int) TREE_CODE (t) >= LAST_AND_UNUSED_TREE_CODE)
464         return lang_hooks.callgraph.analyze_expr (tp, walk_subtrees, data);
465       break;
466     }
467
468   return NULL;
469 }
470
471 /* Create cgraph edges for function calls inside BODY from NODE.  */
472
473 void
474 cgraph_create_edges (struct cgraph_node *node, tree body)
475 {
476   /* The nodes we're interested in are never shared, so walk
477      the tree ignoring duplicates.  */
478   visited_nodes = pointer_set_create ();
479   walk_tree (&body, record_call_1, node, visited_nodes);
480   pointer_set_destroy (visited_nodes);
481   visited_nodes = NULL;
482 }
483
484 static bool error_found;
485
486 /* Callback of verify_cgraph_node.  Check that all call_exprs have
487    cgraph nodes.  */
488
489 static tree
490 verify_cgraph_node_1 (tree *tp, int *walk_subtrees, void *data)
491 {
492   tree t = *tp;
493   tree decl;
494
495   if (TREE_CODE (t) == CALL_EXPR && (decl = get_callee_fndecl (t)))
496     {
497       struct cgraph_edge *e = cgraph_edge (data, t);
498       if (e)
499         {
500           if (e->aux)
501             {
502               error ("Shared call_expr:");
503               debug_tree (t);
504               error_found = true;
505             }
506           if (e->callee->decl != cgraph_node (decl)->decl)
507             {
508               error ("Edge points to wrong declaration:");
509               debug_tree (e->callee->decl);
510               fprintf (stderr," Instead of:");
511               debug_tree (decl);
512             }
513           e->aux = (void *)1;
514         }
515       else
516         {
517           error ("Missing callgraph edge for call expr:");
518           debug_tree (t);
519           error_found = true;
520         }
521     }
522
523   /* Save some cycles by not walking types and declaration as we
524      won't find anything useful there anyway.  */
525   if (IS_TYPE_OR_DECL_P (*tp))
526     *walk_subtrees = 0;
527
528   return NULL_TREE;
529 }
530
531 /* Verify cgraph nodes of given cgraph node.  */
532 void
533 verify_cgraph_node (struct cgraph_node *node)
534 {
535   struct cgraph_edge *e;
536   struct cgraph_node *main_clone;
537
538   timevar_push (TV_CGRAPH_VERIFY);
539   error_found = false;
540   for (e = node->callees; e; e = e->next_callee)
541     if (e->aux)
542       {
543         error ("Aux field set for edge %s->%s",
544                cgraph_node_name (e->caller), cgraph_node_name (e->callee));
545         error_found = true;
546       }
547   for (e = node->callers; e; e = e->next_caller)
548     {
549       if (!e->inline_failed)
550         {
551           if (node->global.inlined_to
552               != (e->caller->global.inlined_to
553                   ? e->caller->global.inlined_to : e->caller))
554             {
555               error ("Inlined_to pointer is wrong");
556               error_found = true;
557             }
558           if (node->callers->next_caller)
559             {
560               error ("Multiple inline callers");
561               error_found = true;
562             }
563         }
564       else
565         if (node->global.inlined_to)
566           {
567             error ("Inlined_to pointer set for noninline callers");
568             error_found = true;
569           }
570     }
571   if (!node->callers && node->global.inlined_to)
572     {
573       error ("Inlined_to pointer is set but no predecesors found");
574       error_found = true;
575     }
576   if (node->global.inlined_to == node)
577     {
578       error ("Inlined_to pointer reffers to itself");
579       error_found = true;
580     }
581
582   for (main_clone = cgraph_node (node->decl); main_clone;
583        main_clone = main_clone->next_clone)
584     if (main_clone == node)
585       break;
586   if (!node)
587     {
588       error ("Node not found in DECL_ASSEMBLER_NAME hash");
589       error_found = true;
590     }
591   
592   if (node->analyzed
593       && DECL_SAVED_TREE (node->decl) && !TREE_ASM_WRITTEN (node->decl)
594       && (!DECL_EXTERNAL (node->decl) || node->global.inlined_to))
595     {
596       walk_tree_without_duplicates (&DECL_SAVED_TREE (node->decl),
597                                     verify_cgraph_node_1, node);
598       for (e = node->callees; e; e = e->next_callee)
599         {
600           if (!e->aux)
601             {
602               error ("Edge %s->%s has no corresponding call_expr",
603                      cgraph_node_name (e->caller),
604                      cgraph_node_name (e->callee));
605               error_found = true;
606             }
607           e->aux = 0;
608         }
609     }
610   if (error_found)
611     {
612       dump_cgraph_node (stderr, node);
613       internal_error ("verify_cgraph_node failed.");
614     }
615   timevar_pop (TV_CGRAPH_VERIFY);
616 }
617
618 /* Verify whole cgraph structure.  */
619 void
620 verify_cgraph (void)
621 {
622   struct cgraph_node *node;
623
624   if (sorrycount || errorcount)
625     return;
626
627   for (node = cgraph_nodes; node; node = node->next)
628     verify_cgraph_node (node);
629 }
630
631 /* Analyze the function scheduled to be output.  */
632 static void
633 cgraph_analyze_function (struct cgraph_node *node)
634 {
635   tree decl = node->decl;
636   struct cgraph_edge *e;
637
638   current_function_decl = decl;
639
640   /* First kill forward declaration so reverse inlining works properly.  */
641   cgraph_create_edges (node, DECL_SAVED_TREE (decl));
642
643   node->local.inlinable = tree_inlinable_function_p (decl);
644   node->local.self_insns = estimate_num_insns (DECL_SAVED_TREE (decl));
645   if (node->local.inlinable)
646     node->local.disregard_inline_limits
647       = lang_hooks.tree_inlining.disregard_inline_limits (decl);
648   for (e = node->callers; e; e = e->next_caller)
649     {
650       if (node->local.redefined_extern_inline)
651         e->inline_failed = N_("redefined extern inline functions are not "
652                            "considered for inlining");
653       else if (!node->local.inlinable)
654         e->inline_failed = N_("function not inlinable");
655       else
656         e->inline_failed = N_("function not considered for inlining");
657     }
658   if (flag_really_no_inline && !node->local.disregard_inline_limits)
659     node->local.inlinable = 0;
660   /* Inlining characteristics are maintained by the cgraph_mark_inline.  */
661   node->global.insns = node->local.self_insns;
662
663   node->analyzed = true;
664   current_function_decl = NULL;
665 }
666
667 /* Analyze the whole compilation unit once it is parsed completely.  */
668
669 void
670 cgraph_finalize_compilation_unit (void)
671 {
672   struct cgraph_node *node;
673
674   if (!flag_unit_at_a_time)
675     {
676       cgraph_assemble_pending_functions ();
677       return;
678     }
679
680   cgraph_varpool_assemble_pending_decls ();
681   if (!quiet_flag)
682     fprintf (stderr, "\nAnalyzing compilation unit\n");
683
684   timevar_push (TV_CGRAPH);
685   if (cgraph_dump_file)
686     {
687       fprintf (cgraph_dump_file, "Initial entry points:");
688       for (node = cgraph_nodes; node; node = node->next)
689         if (node->needed && DECL_SAVED_TREE (node->decl))
690           fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
691       fprintf (cgraph_dump_file, "\n");
692     }
693
694   /* Propagate reachability flag and lower representation of all reachable
695      functions.  In the future, lowering will introduce new functions and
696      new entry points on the way (by template instantiation and virtual
697      method table generation for instance).  */
698   while (cgraph_nodes_queue)
699     {
700       struct cgraph_edge *edge;
701       tree decl = cgraph_nodes_queue->decl;
702
703       node = cgraph_nodes_queue;
704       cgraph_nodes_queue = cgraph_nodes_queue->next_needed;
705       node->next_needed = NULL;
706
707       /* ??? It is possible to create extern inline function and later using
708          weak alas attribute to kill its body. See
709          gcc.c-torture/compile/20011119-1.c  */
710       if (!DECL_SAVED_TREE (decl))
711         continue;
712
713       gcc_assert (!node->analyzed && node->reachable);
714       gcc_assert (DECL_SAVED_TREE (decl));
715
716       cgraph_analyze_function (node);
717
718       for (edge = node->callees; edge; edge = edge->next_callee)
719         if (!edge->callee->reachable)
720           cgraph_mark_reachable_node (edge->callee);
721
722       cgraph_varpool_assemble_pending_decls ();
723     }
724
725   /* Collect entry points to the unit.  */
726
727   if (cgraph_dump_file)
728     {
729       fprintf (cgraph_dump_file, "Unit entry points:");
730       for (node = cgraph_nodes; node; node = node->next)
731         if (node->needed && DECL_SAVED_TREE (node->decl))
732           fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
733       fprintf (cgraph_dump_file, "\n\nInitial ");
734       dump_cgraph (cgraph_dump_file);
735     }
736
737   if (cgraph_dump_file)
738     fprintf (cgraph_dump_file, "\nReclaiming functions:");
739
740   for (node = cgraph_nodes; node; node = node->next)
741     {
742       tree decl = node->decl;
743
744       if (!node->reachable && DECL_SAVED_TREE (decl))
745         {
746           if (cgraph_dump_file)
747             fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
748           cgraph_remove_node (node);
749         }
750       else
751         node->next_needed = NULL;
752     }
753   if (cgraph_dump_file)
754     {
755       fprintf (cgraph_dump_file, "\n\nReclaimed ");
756       dump_cgraph (cgraph_dump_file);
757     }
758   ggc_collect ();
759   timevar_pop (TV_CGRAPH);
760 }
761 /* Figure out what functions we want to assemble.  */
762
763 static void
764 cgraph_mark_functions_to_output (void)
765 {
766   struct cgraph_node *node;
767
768   for (node = cgraph_nodes; node; node = node->next)
769     {
770       tree decl = node->decl;
771       struct cgraph_edge *e;
772       
773       gcc_assert (!node->output);
774
775       for (e = node->callers; e; e = e->next_caller)
776         if (e->inline_failed)
777           break;
778
779       /* We need to output all local functions that are used and not
780          always inlined, as well as those that are reachable from
781          outside the current compilation unit.  */
782       if (DECL_SAVED_TREE (decl)
783           && !node->global.inlined_to
784           && (node->needed
785               || (e && node->reachable))
786           && !TREE_ASM_WRITTEN (decl)
787           && !DECL_EXTERNAL (decl))
788         node->output = 1;
789       else
790         {
791           /* We should've reclaimed all functions that are not needed.  */
792 #ifdef ENABLE_CHECKING
793           if (!node->global.inlined_to && DECL_SAVED_TREE (decl)
794               && !DECL_EXTERNAL (decl))
795             {
796               dump_cgraph_node (stderr, node);
797               internal_error ("failed to reclaim unneeded function");
798             }
799 #endif
800           gcc_assert (node->global.inlined_to || !DECL_SAVED_TREE (decl)
801                       || DECL_EXTERNAL (decl));
802
803         }
804       
805     }
806 }
807
808 /* Expand function specified by NODE.  */
809
810 static void
811 cgraph_expand_function (struct cgraph_node *node)
812 {
813   tree decl = node->decl;
814
815   /* We ought to not compile any inline clones.  */
816   gcc_assert (!node->global.inlined_to);
817
818   if (flag_unit_at_a_time)
819     announce_function (decl);
820
821   /* Generate RTL for the body of DECL.  */
822   lang_hooks.callgraph.expand_function (decl);
823
824   /* Make sure that BE didn't give up on compiling.  */
825   /* ??? Can happen with nested function of extern inline.  */
826   gcc_assert (TREE_ASM_WRITTEN (node->decl));
827
828   current_function_decl = NULL;
829   if (!cgraph_preserve_function_body_p (node->decl))
830     {
831       DECL_SAVED_TREE (node->decl) = NULL;
832       DECL_STRUCT_FUNCTION (node->decl) = NULL;
833       DECL_INITIAL (node->decl) = error_mark_node;
834       /* Eliminate all call edges.  This is important so the call_expr no longer
835          points to the dead function body.  */
836       while (node->callees)
837         cgraph_remove_edge (node->callees);
838     }
839 }
840
841 /* Fill array order with all nodes with output flag set in the reverse
842    topological order.  */
843
844 static int
845 cgraph_postorder (struct cgraph_node **order)
846 {
847   struct cgraph_node *node, *node2;
848   int stack_size = 0;
849   int order_pos = 0;
850   struct cgraph_edge *edge, last;
851
852   struct cgraph_node **stack =
853     xcalloc (cgraph_n_nodes, sizeof (struct cgraph_node *));
854
855   /* We have to deal with cycles nicely, so use a depth first traversal
856      output algorithm.  Ignore the fact that some functions won't need
857      to be output and put them into order as well, so we get dependencies
858      right through intline functions.  */
859   for (node = cgraph_nodes; node; node = node->next)
860     node->aux = NULL;
861   for (node = cgraph_nodes; node; node = node->next)
862     if (!node->aux)
863       {
864         node2 = node;
865         if (!node->callers)
866           node->aux = &last;
867         else
868           node->aux = node->callers;
869         while (node2)
870           {
871             while (node2->aux != &last)
872               {
873                 edge = node2->aux;
874                 if (edge->next_caller)
875                   node2->aux = edge->next_caller;
876                 else
877                   node2->aux = &last;
878                 if (!edge->caller->aux)
879                   {
880                     if (!edge->caller->callers)
881                       edge->caller->aux = &last;
882                     else
883                       edge->caller->aux = edge->caller->callers;
884                     stack[stack_size++] = node2;
885                     node2 = edge->caller;
886                     break;
887                   }
888               }
889             if (node2->aux == &last)
890               {
891                 order[order_pos++] = node2;
892                 if (stack_size)
893                   node2 = stack[--stack_size];
894                 else
895                   node2 = NULL;
896               }
897           }
898       }
899   free (stack);
900   return order_pos;
901 }
902
903
904 /* Perform reachability analysis and reclaim all unreachable nodes.
905    This function also remove unneeded bodies of extern inline functions
906    and thus needs to be done only after inlining decisions has been made.  */
907 static bool
908 cgraph_remove_unreachable_nodes (void)
909 {
910   struct cgraph_node *first = (void *) 1;
911   struct cgraph_node *node;
912   bool changed = false;
913   int insns = 0;
914
915 #ifdef ENABLE_CHECKING
916   verify_cgraph ();
917 #endif
918   if (cgraph_dump_file)
919     fprintf (cgraph_dump_file, "\nReclaiming functions:");
920 #ifdef ENABLE_CHECKING
921   for (node = cgraph_nodes; node; node = node->next)
922     gcc_assert (!node->aux);
923 #endif
924   for (node = cgraph_nodes; node; node = node->next)
925     if (node->needed && !node->global.inlined_to
926         && (!DECL_EXTERNAL (node->decl) || !node->analyzed))
927       {
928         node->aux = first;
929         first = node;
930       }
931     else
932       gcc_assert (!node->aux);
933
934   /* Perform reachability analysis.  As a special case do not consider
935      extern inline functions not inlined as live because we won't output
936      them at all.  */
937   while (first != (void *) 1)
938     {
939       struct cgraph_edge *e;
940       node = first;
941       first = first->aux;
942
943       for (e = node->callees; e; e = e->next_callee)
944         if (!e->callee->aux
945             && node->analyzed
946             && (!e->inline_failed || !e->callee->analyzed
947                 || !DECL_EXTERNAL (e->callee->decl)))
948           {
949             e->callee->aux = first;
950             first = e->callee;
951           }
952     }
953
954   /* Remove unreachable nodes.  Extern inline functions need special care;
955      Unreachable extern inline functions shall be removed.
956      Reachable extern inline functions we never inlined shall get their bodies
957      eliminated.
958      Reachable extern inline functions we sometimes inlined will be turned into
959      unanalyzed nodes so they look like for true extern functions to the rest
960      of code.  Body of such functions is released via remove_node once the
961      inline clones are eliminated.  */
962   for (node = cgraph_nodes; node; node = node->next)
963     {
964       if (!node->aux)
965         {
966           int local_insns;
967           tree decl = node->decl;
968
969           node->global.inlined_to = NULL;
970           if (DECL_STRUCT_FUNCTION (decl))
971             local_insns = node->local.self_insns;
972           else
973             local_insns = 0;
974           if (cgraph_dump_file)
975             fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
976           if (!node->analyzed || !DECL_EXTERNAL (node->decl))
977             cgraph_remove_node (node);
978           else
979             {
980               struct cgraph_edge *e;
981
982               for (e = node->callers; e; e = e->next_caller)
983                 if (e->caller->aux)
984                   break;
985               if (e || node->needed)
986                 {
987                   struct cgraph_node *clone;
988
989                   for (clone = node->next_clone; clone;
990                        clone = clone->next_clone)
991                     if (clone->aux)
992                       break;
993                   if (!clone)
994                     {
995                       DECL_SAVED_TREE (node->decl) = NULL;
996                       DECL_STRUCT_FUNCTION (node->decl) = NULL;
997                       DECL_INITIAL (node->decl) = error_mark_node;
998                     }
999                   while (node->callees)
1000                     cgraph_remove_edge (node->callees);
1001                   node->analyzed = false;
1002                 }
1003               else
1004                 cgraph_remove_node (node);
1005             }
1006           if (!DECL_SAVED_TREE (decl))
1007             insns += local_insns;
1008           changed = true;
1009         }
1010     }
1011   for (node = cgraph_nodes; node; node = node->next)
1012     node->aux = NULL;
1013   if (cgraph_dump_file)
1014     fprintf (cgraph_dump_file, "\nReclaimed %i insns", insns);
1015   return changed;
1016 }
1017
1018 /* Estimate size of the function after inlining WHAT into TO.  */
1019
1020 static int
1021 cgraph_estimate_size_after_inlining (int times, struct cgraph_node *to,
1022                                      struct cgraph_node *what)
1023 {
1024   return (what->global.insns - INSNS_PER_CALL) * times + to->global.insns;
1025 }
1026
1027 /* Estimate the growth caused by inlining NODE into all callees.  */
1028
1029 static int
1030 cgraph_estimate_growth (struct cgraph_node *node)
1031 {
1032   int growth = 0;
1033   struct cgraph_edge *e;
1034
1035   for (e = node->callers; e; e = e->next_caller)
1036     if (e->inline_failed)
1037       growth += (cgraph_estimate_size_after_inlining (1, e->caller, node)
1038                  - e->caller->global.insns);
1039
1040   /* ??? Wrong for self recursive functions or cases where we decide to not
1041      inline for different reasons, but it is not big deal as in that case
1042      we will keep the body around, but we will also avoid some inlining.  */
1043   if (!node->needed && !DECL_EXTERNAL (node->decl))
1044     growth -= node->global.insns;
1045
1046   return growth;
1047 }
1048
1049 /* E is expected to be an edge being inlined.  Clone destination node of
1050    the edge and redirect it to the new clone.
1051    DUPLICATE is used for bookkeeping on whether we are actually creating new
1052    clones or re-using node originally representing out-of-line function call.
1053    */
1054 void
1055 cgraph_clone_inlined_nodes (struct cgraph_edge *e, bool duplicate)
1056 {
1057   struct cgraph_node *n;
1058
1059   /* We may eliminate the need for out-of-line copy to be output.  In that
1060      case just go ahead and re-use it.  */
1061   if (!e->callee->callers->next_caller
1062       && (!e->callee->needed || DECL_EXTERNAL (e->callee->decl))
1063       && duplicate
1064       && flag_unit_at_a_time)
1065     {
1066       gcc_assert (!e->callee->global.inlined_to);
1067       if (!DECL_EXTERNAL (e->callee->decl))
1068         overall_insns -= e->callee->global.insns, nfunctions_inlined++;
1069       duplicate = 0;
1070     }
1071    else if (duplicate)
1072     {
1073       n = cgraph_clone_node (e->callee);
1074       cgraph_redirect_edge_callee (e, n);
1075     }
1076
1077   if (e->caller->global.inlined_to)
1078     e->callee->global.inlined_to = e->caller->global.inlined_to;
1079   else
1080     e->callee->global.inlined_to = e->caller;
1081
1082   /* Recursively clone all bodies.  */
1083   for (e = e->callee->callees; e; e = e->next_callee)
1084     if (!e->inline_failed)
1085       cgraph_clone_inlined_nodes (e, duplicate);
1086 }
1087
1088 /* Mark edge E as inlined and update callgraph accordingly.  */
1089
1090 void
1091 cgraph_mark_inline_edge (struct cgraph_edge *e)
1092 {
1093   int old_insns = 0, new_insns = 0;
1094   struct cgraph_node *to = NULL, *what;
1095
1096   gcc_assert (e->inline_failed);
1097   e->inline_failed = NULL;
1098
1099   if (!e->callee->global.inlined && flag_unit_at_a_time)
1100     DECL_POSSIBLY_INLINED (e->callee->decl) = true;
1101   e->callee->global.inlined = true;
1102
1103   cgraph_clone_inlined_nodes (e, true);
1104
1105   what = e->callee;
1106
1107   /* Now update size of caller and all functions caller is inlined into.  */
1108   for (;e && !e->inline_failed; e = e->caller->callers)
1109     {
1110       old_insns = e->caller->global.insns;
1111       new_insns = cgraph_estimate_size_after_inlining (1, e->caller,
1112                                                        what);
1113       gcc_assert (new_insns >= 0);
1114       to = e->caller;
1115       to->global.insns = new_insns;
1116     }
1117   gcc_assert (what->global.inlined_to == to);
1118   overall_insns += new_insns - old_insns;
1119   ncalls_inlined++;
1120 }
1121
1122 /* Mark all calls of EDGE->CALLEE inlined into EDGE->CALLER.
1123    Return following unredirected edge in the list of callers
1124    of EDGE->CALLEE  */
1125
1126 static struct cgraph_edge *
1127 cgraph_mark_inline (struct cgraph_edge *edge)
1128 {
1129   struct cgraph_node *to = edge->caller;
1130   struct cgraph_node *what = edge->callee;
1131   struct cgraph_edge *e, *next;
1132   int times = 0;
1133
1134   /* Look for all calls, mark them inline and clone recursively
1135      all inlined functions.  */
1136   for (e = what->callers; e; e = next)
1137     {
1138       next = e->next_caller;
1139       if (e->caller == to && e->inline_failed)
1140         {
1141           cgraph_mark_inline_edge (e);
1142           if (e == edge)
1143             edge = next;
1144           times++;
1145         }
1146     }
1147   gcc_assert (times);
1148   return edge;
1149 }
1150
1151 /* Return false when inlining WHAT into TO is not good idea
1152    as it would cause too large growth of function bodies.  */
1153
1154 static bool
1155 cgraph_check_inline_limits (struct cgraph_node *to, struct cgraph_node *what,
1156                             const char **reason)
1157 {
1158   int times = 0;
1159   struct cgraph_edge *e;
1160   int newsize;
1161   int limit;
1162
1163   if (to->global.inlined_to)
1164     to = to->global.inlined_to;
1165
1166   for (e = to->callees; e; e = e->next_callee)
1167     if (e->callee == what)
1168       times++;
1169
1170   /* When inlining large function body called once into small function,
1171      take the inlined function as base for limiting the growth.  */
1172   if (to->local.self_insns > what->local.self_insns)
1173     limit = to->local.self_insns;
1174   else
1175     limit = what->local.self_insns;
1176
1177   limit += limit * PARAM_VALUE (PARAM_LARGE_FUNCTION_GROWTH) / 100;
1178
1179   newsize = cgraph_estimate_size_after_inlining (times, to, what);
1180   if (newsize > PARAM_VALUE (PARAM_LARGE_FUNCTION_INSNS)
1181       && newsize > limit)
1182     {
1183       if (reason)
1184         *reason = N_("--param large-function-growth limit reached");
1185       return false;
1186     }
1187   return true;
1188 }
1189
1190 /* Return true when function N is small enough to be inlined.  */
1191
1192 static bool
1193 cgraph_default_inline_p (struct cgraph_node *n)
1194 {
1195   if (!DECL_INLINE (n->decl) || !DECL_SAVED_TREE (n->decl))
1196     return false;
1197   if (DECL_DECLARED_INLINE_P (n->decl))
1198     return n->global.insns < MAX_INLINE_INSNS_SINGLE;
1199   else
1200     return n->global.insns < MAX_INLINE_INSNS_AUTO;
1201 }
1202
1203 /* Return true when inlining WHAT would create recursive inlining.
1204    We call recursive inlining all cases where same function appears more than
1205    once in the single recursion nest path in the inline graph.  */
1206
1207 static bool
1208 cgraph_recursive_inlining_p (struct cgraph_node *to,
1209                              struct cgraph_node *what,
1210                              const char **reason)
1211 {
1212   bool recursive;
1213   if (to->global.inlined_to)
1214     recursive = what->decl == to->global.inlined_to->decl;
1215   else
1216     recursive = what->decl == to->decl;
1217   /* Marking recursive function inline has sane semantic and thus we should
1218      not warn on it.  */
1219   if (recursive && reason)
1220     *reason = (what->local.disregard_inline_limits
1221                ? N_("recursive inlining") : "");
1222   return recursive;
1223 }
1224
1225 /* Recompute heap nodes for each of callees.  */
1226 static void
1227 update_callee_keys (fibheap_t heap, struct fibnode **heap_node,
1228                     struct cgraph_node *node)
1229 {
1230   struct cgraph_edge *e;
1231
1232   for (e = node->callees; e; e = e->next_callee)
1233     if (e->inline_failed && heap_node[e->callee->uid])
1234       fibheap_replace_key (heap, heap_node[e->callee->uid],
1235                            cgraph_estimate_growth (e->callee));
1236     else if (!e->inline_failed)
1237       update_callee_keys (heap, heap_node, e->callee);
1238 }
1239
1240 /* Enqueue all recursive calls from NODE into queue linked via aux pointers
1241    in between FIRST and LAST.  WHERE is used for bookkeeping while looking
1242    int calls inlined within NODE.  */
1243 static void
1244 lookup_recursive_calls (struct cgraph_node *node, struct cgraph_node *where,
1245                         struct cgraph_edge **first, struct cgraph_edge **last)
1246 {
1247   struct cgraph_edge *e;
1248   for (e = where->callees; e; e = e->next_callee)
1249     if (e->callee == node)
1250       {
1251         if (!*first)
1252           *first = e;
1253         else
1254           (*last)->aux = e;
1255         *last = e;
1256       }
1257   for (e = where->callees; e; e = e->next_callee)
1258     if (!e->inline_failed)
1259       lookup_recursive_calls (node, e->callee, first, last);
1260 }
1261
1262 /* Decide on recursive inlining: in the case function has recursive calls,
1263    inline until body size reaches given argument.  */
1264 static void
1265 cgraph_decide_recursive_inlining (struct cgraph_node *node)
1266 {
1267   int limit = PARAM_VALUE (PARAM_MAX_INLINE_INSNS_RECURSIVE_AUTO);
1268   int max_depth = PARAM_VALUE (PARAM_MAX_INLINE_RECURSIVE_DEPTH_AUTO);
1269   struct cgraph_edge *first_call = NULL, *last_call = NULL;
1270   struct cgraph_edge *last_in_current_depth;
1271   struct cgraph_edge *e;
1272   struct cgraph_node *master_clone;
1273   int depth = 0;
1274   int n = 0;
1275
1276   if (DECL_DECLARED_INLINE_P (node->decl))
1277     {
1278       limit = PARAM_VALUE (PARAM_MAX_INLINE_INSNS_RECURSIVE);
1279       max_depth = PARAM_VALUE (PARAM_MAX_INLINE_RECURSIVE_DEPTH);
1280     }
1281
1282   /* Make sure that function is small enough to be considered for inlining.  */
1283   if (!max_depth
1284       || cgraph_estimate_size_after_inlining (1, node, node)  >= limit)
1285     return;
1286   lookup_recursive_calls (node, node, &first_call, &last_call);
1287   if (!first_call)
1288     return;
1289
1290   if (cgraph_dump_file)
1291     fprintf (cgraph_dump_file, 
1292              "\nPerforming recursive inlining on %s\n",
1293              cgraph_node_name (node));
1294
1295   /* We need original clone to copy around.  */
1296   master_clone = cgraph_clone_node (node);
1297   master_clone->needed = true;
1298   for (e = master_clone->callees; e; e = e->next_callee)
1299     if (!e->inline_failed)
1300       cgraph_clone_inlined_nodes (e, true);
1301
1302   /* Do the inlining and update list of recursive call during process.  */
1303   last_in_current_depth = last_call;
1304   while (first_call
1305          && cgraph_estimate_size_after_inlining (1, node, master_clone) <= limit)
1306     {
1307       struct cgraph_edge *curr = first_call;
1308
1309       first_call = first_call->aux;
1310       curr->aux = NULL;
1311
1312       cgraph_redirect_edge_callee (curr, master_clone);
1313       cgraph_mark_inline_edge (curr);
1314       lookup_recursive_calls (node, curr->callee, &first_call, &last_call);
1315
1316       if (last_in_current_depth
1317           && ++depth >= max_depth)
1318         break;
1319       n++;
1320     }
1321
1322   /* Cleanup queue pointers.  */
1323   while (first_call)
1324     {
1325       struct cgraph_edge *next = first_call->aux;
1326       first_call->aux = NULL;
1327       first_call = next;
1328     }
1329   if (cgraph_dump_file)
1330     fprintf (cgraph_dump_file, 
1331              "\n   Inlined %i times, body grown from %i to %i insns\n", n,
1332              master_clone->global.insns, node->global.insns);
1333
1334   /* Remove master clone we used for inlining.  We rely that clones inlined
1335      into master clone gets queued just before master clone so we don't
1336      need recursion.  */
1337   for (node = cgraph_nodes; node != master_clone;
1338        node = node->next)
1339     if (node->global.inlined_to == master_clone)
1340       cgraph_remove_node (node);
1341   cgraph_remove_node (master_clone);
1342 }
1343
1344 /* Set inline_failed for all callers of given function to REASON.  */
1345
1346 static void
1347 cgraph_set_inline_failed (struct cgraph_node *node, const char *reason)
1348 {
1349   struct cgraph_edge *e;
1350
1351   if (cgraph_dump_file)
1352     fprintf (cgraph_dump_file, "Inlining failed: %s\n", reason);
1353   for (e = node->callers; e; e = e->next_caller)
1354     if (e->inline_failed)
1355       e->inline_failed = reason;
1356 }
1357
1358 /* We use greedy algorithm for inlining of small functions:
1359    All inline candidates are put into prioritized heap based on estimated
1360    growth of the overall number of instructions and then update the estimates.
1361
1362    INLINED and INLINED_CALEES are just pointers to arrays large enough
1363    to be passed to cgraph_inlined_into and cgraph_inlined_callees.  */
1364
1365 static void
1366 cgraph_decide_inlining_of_small_functions (void)
1367 {
1368   struct cgraph_node *node;
1369   fibheap_t heap = fibheap_new ();
1370   struct fibnode **heap_node =
1371     xcalloc (cgraph_max_uid, sizeof (struct fibnode *));
1372   int max_insns = ((HOST_WIDEST_INT) initial_insns
1373                    * (100 + PARAM_VALUE (PARAM_INLINE_UNIT_GROWTH)) / 100);
1374
1375   /* Put all inline candidates into the heap.  */
1376
1377   for (node = cgraph_nodes; node; node = node->next)
1378     {
1379       if (!node->local.inlinable || !node->callers
1380           || node->local.disregard_inline_limits)
1381         continue;
1382
1383       if (!cgraph_default_inline_p (node))
1384         {
1385           cgraph_set_inline_failed (node,
1386             N_("--param max-inline-insns-single limit reached"));
1387           continue;
1388         }
1389       heap_node[node->uid] =
1390         fibheap_insert (heap, cgraph_estimate_growth (node), node);
1391     }
1392
1393   if (cgraph_dump_file)
1394     fprintf (cgraph_dump_file, "\nDeciding on smaller functions:\n");
1395   while (overall_insns <= max_insns && (node = fibheap_extract_min (heap)))
1396     {
1397       struct cgraph_edge *e, *next;
1398       int old_insns = overall_insns;
1399
1400       heap_node[node->uid] = NULL;
1401       if (cgraph_dump_file)
1402         fprintf (cgraph_dump_file, 
1403                  "\nConsidering %s with %i insns\n"
1404                  " Estimated growth is %+i insns.\n",
1405                  cgraph_node_name (node), node->global.insns,
1406                  cgraph_estimate_growth (node));
1407       if (!cgraph_default_inline_p (node))
1408         {
1409           cgraph_set_inline_failed (node,
1410             N_("--param max-inline-insns-single limit reached after inlining into the callee"));
1411           continue;
1412         }
1413       for (e = node->callers; e; e = next)
1414         {
1415           next = e->next_caller;
1416           if (e->inline_failed)
1417             {
1418               struct cgraph_node *where;
1419
1420               if (cgraph_recursive_inlining_p (e->caller, e->callee,
1421                                                &e->inline_failed)
1422                   || !cgraph_check_inline_limits (e->caller, e->callee,
1423                                                   &e->inline_failed))
1424                 {
1425                   if (cgraph_dump_file)
1426                     fprintf (cgraph_dump_file, " Not inlining into %s:%s.\n",
1427                              cgraph_node_name (e->caller), e->inline_failed);
1428                   continue;
1429                 }
1430               next = cgraph_mark_inline (e);
1431               where = e->caller;
1432               if (where->global.inlined_to)
1433                 where = where->global.inlined_to;
1434
1435               if (heap_node[where->uid])
1436                 fibheap_replace_key (heap, heap_node[where->uid],
1437                                      cgraph_estimate_growth (where));
1438
1439               if (cgraph_dump_file)
1440                 fprintf (cgraph_dump_file, 
1441                          " Inlined into %s which now has %i insns.\n",
1442                          cgraph_node_name (e->caller),
1443                          e->caller->global.insns);
1444             }
1445         }
1446
1447       cgraph_decide_recursive_inlining (node);
1448
1449       /* Similarly all functions called by the function we just inlined
1450          are now called more times; update keys.  */
1451       update_callee_keys (heap, heap_node, node);
1452
1453       if (cgraph_dump_file)
1454         fprintf (cgraph_dump_file, 
1455                  " Inlined for a net change of %+i insns.\n",
1456                  overall_insns - old_insns);
1457     }
1458   while ((node = fibheap_extract_min (heap)) != NULL)
1459     if (!node->local.disregard_inline_limits)
1460       cgraph_set_inline_failed (node, N_("--param inline-unit-growth limit reached"));
1461   fibheap_delete (heap);
1462   free (heap_node);
1463 }
1464
1465 /* Decide on the inlining.  We do so in the topological order to avoid
1466    expenses on updating data structures.  */
1467
1468 static void
1469 cgraph_decide_inlining (void)
1470 {
1471   struct cgraph_node *node;
1472   int nnodes;
1473   struct cgraph_node **order =
1474     xcalloc (cgraph_n_nodes, sizeof (struct cgraph_node *));
1475   int old_insns = 0;
1476   int i;
1477
1478   for (node = cgraph_nodes; node; node = node->next)
1479     initial_insns += node->local.self_insns;
1480   overall_insns = initial_insns;
1481
1482   nnodes = cgraph_postorder (order);
1483
1484   if (cgraph_dump_file)
1485     fprintf (cgraph_dump_file,
1486              "\nDeciding on inlining.  Starting with %i insns.\n",
1487              initial_insns);
1488
1489   for (node = cgraph_nodes; node; node = node->next)
1490     node->aux = 0;
1491
1492   if (cgraph_dump_file)
1493     fprintf (cgraph_dump_file, "\nInlining always_inline functions:\n");
1494
1495   /* In the first pass mark all always_inline edges.  Do this with a priority
1496      so none of our later choices will make this impossible.  */
1497   for (i = nnodes - 1; i >= 0; i--)
1498     {
1499       struct cgraph_edge *e, *next;
1500
1501       node = order[i];
1502
1503       if (!node->local.disregard_inline_limits)
1504         continue;
1505       if (cgraph_dump_file)
1506         fprintf (cgraph_dump_file,
1507                  "\nConsidering %s %i insns (always inline)\n",
1508                  cgraph_node_name (node), node->global.insns);
1509       old_insns = overall_insns;
1510       for (e = node->callers; e; e = next)
1511         {
1512           next = e->next_caller;
1513           if (!e->inline_failed)
1514             continue;
1515           if (cgraph_recursive_inlining_p (e->caller, e->callee,
1516                                            &e->inline_failed))
1517             continue;
1518           cgraph_mark_inline_edge (e);
1519           if (cgraph_dump_file)
1520             fprintf (cgraph_dump_file, 
1521                      " Inlined into %s which now has %i insns.\n",
1522                      cgraph_node_name (e->caller),
1523                      e->caller->global.insns);
1524         }
1525       if (cgraph_dump_file)
1526         fprintf (cgraph_dump_file, 
1527                  " Inlined for a net change of %+i insns.\n",
1528                  overall_insns - old_insns);
1529     }
1530
1531   if (!flag_really_no_inline)
1532     {
1533       cgraph_decide_inlining_of_small_functions ();
1534
1535       if (cgraph_dump_file)
1536         fprintf (cgraph_dump_file, "\nDeciding on functions called once:\n");
1537
1538       /* And finally decide what functions are called once.  */
1539
1540       for (i = nnodes - 1; i >= 0; i--)
1541         {
1542           node = order[i];
1543
1544           if (node->callers && !node->callers->next_caller && !node->needed
1545               && node->local.inlinable && node->callers->inline_failed
1546               && !DECL_EXTERNAL (node->decl) && !DECL_COMDAT (node->decl))
1547             {
1548               bool ok = true;
1549               struct cgraph_node *node1;
1550
1551               /* Verify that we won't duplicate the caller.  */
1552               for (node1 = node->callers->caller;
1553                    node1->callers && !node1->callers->inline_failed
1554                    && ok; node1 = node1->callers->caller)
1555                 if (node1->callers->next_caller || node1->needed)
1556                   ok = false;
1557               if (ok)
1558                 {
1559                   if (cgraph_dump_file)
1560                     fprintf (cgraph_dump_file,
1561                              "\nConsidering %s %i insns.\n"
1562                              " Called once from %s %i insns.\n",
1563                              cgraph_node_name (node), node->global.insns,
1564                              cgraph_node_name (node->callers->caller),
1565                              node->callers->caller->global.insns);
1566
1567                   old_insns = overall_insns;
1568
1569                   if (cgraph_check_inline_limits (node->callers->caller, node,
1570                                                   NULL))
1571                     {
1572                       cgraph_mark_inline (node->callers);
1573                       if (cgraph_dump_file)
1574                         fprintf (cgraph_dump_file,
1575                                  " Inlined into %s which now has %i insns"
1576                                  " for a net change of %+i insns.\n",
1577                                  cgraph_node_name (node->callers->caller),
1578                                  node->callers->caller->global.insns,
1579                                  overall_insns - old_insns);
1580                     }
1581                   else
1582                     {
1583                       if (cgraph_dump_file)
1584                         fprintf (cgraph_dump_file,
1585                                  " Inline limit reached, not inlined.\n");
1586                     }
1587                 }
1588             }
1589         }
1590     }
1591
1592   /* We will never output extern functions we didn't inline. 
1593      ??? Perhaps we can prevent accounting of growth of external
1594      inline functions.  */
1595   cgraph_remove_unreachable_nodes ();
1596
1597   if (cgraph_dump_file)
1598     fprintf (cgraph_dump_file,
1599              "\nInlined %i calls, eliminated %i functions, "
1600              "%i insns turned to %i insns.\n\n",
1601              ncalls_inlined, nfunctions_inlined, initial_insns,
1602              overall_insns);
1603   free (order);
1604 }
1605
1606 /* Decide on the inlining.  We do so in the topological order to avoid
1607    expenses on updating data structures.  */
1608
1609 static void
1610 cgraph_decide_inlining_incrementally (struct cgraph_node *node)
1611 {
1612   struct cgraph_edge *e;
1613
1614   /* First of all look for always inline functions.  */
1615   for (e = node->callees; e; e = e->next_callee)
1616     if (e->callee->local.disregard_inline_limits
1617         && e->inline_failed
1618         && !cgraph_recursive_inlining_p (node, e->callee, &e->inline_failed)
1619         /* ??? It is possible that renaming variable removed the function body
1620            in duplicate_decls. See gcc.c-torture/compile/20011119-2.c  */
1621         && DECL_SAVED_TREE (e->callee->decl))
1622       cgraph_mark_inline (e);
1623
1624   /* Now do the automatic inlining.  */
1625   if (!flag_really_no_inline)
1626     for (e = node->callees; e; e = e->next_callee)
1627       if (e->callee->local.inlinable
1628           && e->inline_failed
1629           && !e->callee->local.disregard_inline_limits
1630           && !cgraph_recursive_inlining_p (node, e->callee, &e->inline_failed)
1631           && cgraph_check_inline_limits (node, e->callee, &e->inline_failed)
1632           && DECL_SAVED_TREE (e->callee->decl))
1633         {
1634           if (cgraph_default_inline_p (e->callee))
1635             cgraph_mark_inline (e);
1636           else
1637             e->inline_failed
1638               = N_("--param max-inline-insns-single limit reached");
1639         }
1640 }
1641
1642
1643 /* Return true when CALLER_DECL should be inlined into CALLEE_DECL.  */
1644
1645 bool
1646 cgraph_inline_p (struct cgraph_edge *e, const char **reason)
1647 {
1648   *reason = e->inline_failed;
1649   return !e->inline_failed;
1650 }
1651
1652
1653
1654 /* Expand all functions that must be output.
1655
1656    Attempt to topologically sort the nodes so function is output when
1657    all called functions are already assembled to allow data to be
1658    propagated across the callgraph.  Use a stack to get smaller distance
1659    between a function and its callees (later we may choose to use a more
1660    sophisticated algorithm for function reordering; we will likely want
1661    to use subsections to make the output functions appear in top-down
1662    order).  */
1663
1664 static void
1665 cgraph_expand_all_functions (void)
1666 {
1667   struct cgraph_node *node;
1668   struct cgraph_node **order =
1669     xcalloc (cgraph_n_nodes, sizeof (struct cgraph_node *));
1670   int order_pos = 0, new_order_pos = 0;
1671   int i;
1672
1673   order_pos = cgraph_postorder (order);
1674   gcc_assert (order_pos == cgraph_n_nodes);
1675
1676   /* Garbage collector may remove inline clones we eliminate during
1677      optimization.  So we must be sure to not reference them.  */
1678   for (i = 0; i < order_pos; i++)
1679     if (order[i]->output)
1680       order[new_order_pos++] = order[i];
1681
1682   for (i = new_order_pos - 1; i >= 0; i--)
1683     {
1684       node = order[i];
1685       if (node->output)
1686         {
1687           gcc_assert (node->reachable);
1688           node->output = 0;
1689           cgraph_expand_function (node);
1690         }
1691     }
1692   free (order);
1693 }
1694
1695 /* Mark all local functions.
1696    
1697    A local function is one whose calls can occur only in the current
1698    compilation unit and all its calls are explicit, so we can change
1699    its calling convention.  We simply mark all static functions whose
1700    address is not taken as local.  */
1701
1702 static void
1703 cgraph_mark_local_functions (void)
1704 {
1705   struct cgraph_node *node;
1706
1707   /* Figure out functions we want to assemble.  */
1708   for (node = cgraph_nodes; node; node = node->next)
1709     {
1710       node->local.local = (!node->needed
1711                            && DECL_SAVED_TREE (node->decl)
1712                            && !TREE_PUBLIC (node->decl));
1713     }
1714
1715   if (cgraph_dump_file)
1716     {
1717       fprintf (cgraph_dump_file, "\nMarking local functions:");
1718       for (node = cgraph_nodes; node; node = node->next)
1719         if (node->local.local)
1720           fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
1721       fprintf (cgraph_dump_file, "\n\n");
1722     }
1723 }
1724
1725 /* Return true when function body of DECL still needs to be kept around
1726    for later re-use.  */
1727 bool
1728 cgraph_preserve_function_body_p (tree decl)
1729 {
1730   struct cgraph_node *node;
1731   /* Keep the body; we're going to dump it.  */
1732   if (dump_enabled_p (TDI_tree_all))
1733     return true;
1734   if (!cgraph_global_info_ready)
1735     return (DECL_INLINE (decl) && !flag_really_no_inline);
1736   /* Look if there is any clone around.  */
1737   for (node = cgraph_node (decl); node; node = node->next_clone)
1738     if (node->global.inlined_to)
1739       return true;
1740   return false;
1741 }
1742
1743 /* Perform simple optimizations based on callgraph.  */
1744
1745 void
1746 cgraph_optimize (void)
1747 {
1748 #ifdef ENABLE_CHECKING
1749   verify_cgraph ();
1750 #endif
1751   if (!flag_unit_at_a_time)
1752     return;
1753
1754   process_pending_assemble_externals ();
1755
1756   timevar_push (TV_CGRAPHOPT);
1757   if (!quiet_flag)
1758     fprintf (stderr, "Performing intraprocedural optimizations\n");
1759
1760   cgraph_mark_local_functions ();
1761   if (cgraph_dump_file)
1762     {
1763       fprintf (cgraph_dump_file, "Marked ");
1764       dump_cgraph (cgraph_dump_file);
1765     }
1766
1767   if (flag_inline_trees)
1768     cgraph_decide_inlining ();
1769   cgraph_global_info_ready = true;
1770   if (cgraph_dump_file)
1771     {
1772       fprintf (cgraph_dump_file, "Optimized ");
1773       dump_cgraph (cgraph_dump_file);
1774     }
1775   timevar_pop (TV_CGRAPHOPT);
1776
1777   /* Output everything.  */
1778   if (!quiet_flag)
1779     fprintf (stderr, "Assembling functions:\n");
1780 #ifdef ENABLE_CHECKING
1781   verify_cgraph ();
1782 #endif
1783   
1784   cgraph_mark_functions_to_output ();
1785   
1786   cgraph_expand_all_functions ();
1787   if (cgraph_dump_file)
1788     {
1789       fprintf (cgraph_dump_file, "\nFinal ");
1790       dump_cgraph (cgraph_dump_file);
1791     }
1792 #ifdef ENABLE_CHECKING
1793   verify_cgraph ();
1794   /* Double check that all inline clones are gone and that all
1795      function bodies have been released from memory.  */
1796   if (flag_unit_at_a_time
1797       && !dump_enabled_p (TDI_tree_all)
1798       && !(sorrycount || errorcount))
1799     {
1800       struct cgraph_node *node;
1801       bool error_found = false;
1802
1803       for (node = cgraph_nodes; node; node = node->next)
1804         if (node->analyzed
1805             && (node->global.inlined_to
1806                 || DECL_SAVED_TREE (node->decl)))
1807           {
1808             error_found = true;
1809             dump_cgraph_node (stderr, node);
1810           }
1811       if (error_found)
1812         internal_error ("Nodes with no released memory found.");
1813     }
1814 #endif
1815 }
1816
1817 /* Generate and emit a static constructor or destructor.  WHICH must be
1818    one of 'I' or 'D'.  BODY should be a STATEMENT_LIST containing 
1819    GENERIC statements.  */
1820
1821 void
1822 cgraph_build_static_cdtor (char which, tree body, int priority)
1823 {
1824   static int counter = 0;
1825   char which_buf[16];
1826   tree decl, name, resdecl;
1827
1828   sprintf (which_buf, "%c_%d", which, counter++);
1829   name = get_file_function_name_long (which_buf);
1830
1831   decl = build_decl (FUNCTION_DECL, name,
1832                      build_function_type (void_type_node, void_list_node));
1833   current_function_decl = decl;
1834
1835   resdecl = build_decl (RESULT_DECL, NULL_TREE, void_type_node);
1836   DECL_ARTIFICIAL (resdecl) = 1;
1837   DECL_IGNORED_P (resdecl) = 1;
1838   DECL_RESULT (decl) = resdecl;
1839
1840   allocate_struct_function (decl);
1841
1842   TREE_STATIC (decl) = 1;
1843   TREE_USED (decl) = 1;
1844   DECL_ARTIFICIAL (decl) = 1;
1845   DECL_IGNORED_P (decl) = 1;
1846   DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (decl) = 1;
1847   DECL_SAVED_TREE (decl) = body;
1848   TREE_PUBLIC (decl) = ! targetm.have_ctors_dtors;
1849   DECL_UNINLINABLE (decl) = 1;
1850
1851   DECL_INITIAL (decl) = make_node (BLOCK);
1852   TREE_USED (DECL_INITIAL (decl)) = 1;
1853
1854   DECL_SOURCE_LOCATION (decl) = input_location;
1855   cfun->function_end_locus = input_location;
1856
1857   switch (which)
1858     {
1859     case 'I':
1860       DECL_STATIC_CONSTRUCTOR (decl) = 1;
1861       break;
1862     case 'D':
1863       DECL_STATIC_DESTRUCTOR (decl) = 1;
1864       break;
1865     default:
1866       gcc_unreachable ();
1867     }
1868
1869   gimplify_function_tree (decl);
1870
1871   /* ??? We will get called LATE in the compilation process.  */
1872   if (cgraph_global_info_ready)
1873     tree_rest_of_compilation (decl);
1874   else
1875     cgraph_finalize_function (decl, 0);
1876   
1877   if (targetm.have_ctors_dtors)
1878     {
1879       void (*fn) (rtx, int);
1880
1881       if (which == 'I')
1882         fn = targetm.asm_out.constructor;
1883       else
1884         fn = targetm.asm_out.destructor;
1885       fn (XEXP (DECL_RTL (decl), 0), priority);
1886     }
1887 }
1888
1889 void
1890 init_cgraph (void)
1891 {
1892   cgraph_dump_file = dump_begin (TDI_cgraph, NULL);
1893 }