OSDN Git Service

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