OSDN Git Service

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