OSDN Git Service

* store-motion.c Do not include params.h
[pf3gnuchains/gcc-fork.git] / gcc / cgraphunit.c
1 /* Callgraph based interprocedural optimizations.
2    Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009
3    Free Software Foundation, Inc.
4    Contributed by Jan Hubicka
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* This module implements main driver of compilation process as well as
23    few basic interprocedural 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
36         function.)
37
38     - varpool_finalize_variable
39
40       This function has same behavior as the above but is used for static
41       variables.
42
43     - cgraph_finalize_compilation_unit
44
45       This function is called once (source level) compilation unit is finalized
46       and it will no longer change.
47
48       In the the call-graph construction and local function
49       analysis takes place here.  Bodies of unreachable functions are released
50       to conserve memory usage.
51
52       The function can be called multiple times when multiple source level
53       compilation units are combined (such as in C frontend)
54
55     - cgraph_optimize
56
57       In this unit-at-a-time compilation the intra procedural analysis takes
58       place here.  In particular the static functions whose address is never
59       taken are marked as local.  Backend can then use this information to
60       modify calling conventions, do better inlining or similar optimizations.
61
62     - cgraph_mark_needed_node
63     - varpool_mark_needed_node
64
65       When function or variable is referenced by some hidden way the call-graph
66       data structure must be updated accordingly by this function.
67       There should be little need to call this function and all the references
68       should be made explicit to cgraph code.  At present these functions are
69       used by C++ frontend to explicitly mark the keyed methods.
70
71     - analyze_expr callback
72
73       This function is responsible for lowering tree nodes not understood by
74       generic code into understandable ones or alternatively marking
75       callgraph and varpool nodes referenced by the as needed.
76
77       ??? On the tree-ssa genericizing should take place here and we will avoid
78       need for these hooks (replacing them by genericizing hook)
79
80         Analyzing of all functions is deferred
81         to cgraph_finalize_compilation_unit and expansion into cgraph_optimize.
82
83         In cgraph_finalize_compilation_unit the reachable functions are
84         analyzed.  During analysis the call-graph edges from reachable
85         functions are constructed and their destinations are marked as
86         reachable.  References to functions and variables are discovered too
87         and variables found to be needed output to the assembly file.  Via
88         mark_referenced call in assemble_variable functions referenced by
89         static variables are noticed too.
90
91         The intra-procedural information is produced and its existence
92         indicated by global_info_ready.  Once this flag is set it is impossible
93         to change function from !reachable to reachable and thus
94         assemble_variable no longer call mark_referenced.
95
96         Finally the call-graph is topologically sorted and all reachable functions
97         that has not been completely inlined or are not external are output.
98
99         ??? It is possible that reference to function or variable is optimized
100         out.  We can not deal with this nicely because topological order is not
101         suitable for it.  For tree-ssa we may consider another pass doing
102         optimization and re-discovering reachable functions.
103
104         ??? Reorganize code so variables are output very last and only if they
105         really has been referenced by produced code, so we catch more cases
106         where reference has been optimized out.  */
107
108
109 #include "config.h"
110 #include "system.h"
111 #include "coretypes.h"
112 #include "tm.h"
113 #include "tree.h"
114 #include "rtl.h"
115 #include "tree-flow.h"
116 #include "tree-inline.h"
117 #include "langhooks.h"
118 #include "pointer-set.h"
119 #include "toplev.h"
120 #include "flags.h"
121 #include "ggc.h"
122 #include "debug.h"
123 #include "target.h"
124 #include "cgraph.h"
125 #include "diagnostic.h"
126 #include "timevar.h"
127 #include "params.h"
128 #include "fibheap.h"
129 #include "intl.h"
130 #include "function.h"
131 #include "ipa-prop.h"
132 #include "gimple.h"
133 #include "tree-iterator.h"
134 #include "tree-pass.h"
135 #include "output.h"
136 #include "coverage.h"
137
138 static void cgraph_expand_all_functions (void);
139 static void cgraph_mark_functions_to_output (void);
140 static void cgraph_expand_function (struct cgraph_node *);
141 static void cgraph_output_pending_asms (void);
142
143 static FILE *cgraph_dump_file;
144
145 /* A vector of FUNCTION_DECLs declared as static constructors.  */
146 static GTY (()) VEC(tree, gc) *static_ctors;
147 /* A vector of FUNCTION_DECLs declared as static destructors.  */
148 static GTY (()) VEC(tree, gc) *static_dtors;
149
150 /* When target does not have ctors and dtors, we call all constructor
151    and destructor by special initialization/destruction function
152    recognized by collect2.  
153    
154    When we are going to build this function, collect all constructors and
155    destructors and turn them into normal functions.  */
156
157 static void
158 record_cdtor_fn (tree fndecl)
159 {
160   struct cgraph_node *node;
161   if (targetm.have_ctors_dtors
162       || (!DECL_STATIC_CONSTRUCTOR (fndecl)
163           && !DECL_STATIC_DESTRUCTOR (fndecl)))
164     return;
165
166   if (DECL_STATIC_CONSTRUCTOR (fndecl))
167     {
168       VEC_safe_push (tree, gc, static_ctors, fndecl);
169       DECL_STATIC_CONSTRUCTOR (fndecl) = 0;
170     }
171   if (DECL_STATIC_DESTRUCTOR (fndecl))
172     {
173       VEC_safe_push (tree, gc, static_dtors, fndecl);
174       DECL_STATIC_DESTRUCTOR (fndecl) = 0;
175     }
176   node = cgraph_node (fndecl);
177   node->local.disregard_inline_limits = 1;
178   cgraph_mark_reachable_node (node);
179 }
180
181 /* Define global constructors/destructor functions for the CDTORS, of
182    which they are LEN.  The CDTORS are sorted by initialization
183    priority.  If CTOR_P is true, these are constructors; otherwise,
184    they are destructors.  */
185
186 static void
187 build_cdtor (bool ctor_p, tree *cdtors, size_t len)
188 {
189   size_t i;
190
191   i = 0;
192   while (i < len)
193     {
194       tree body;
195       tree fn;
196       priority_type priority;
197
198       priority = 0;
199       body = NULL_TREE;
200       /* Find the next batch of constructors/destructors with the same
201          initialization priority.  */
202       do
203         {
204           priority_type p;
205           fn = cdtors[i];
206           p = ctor_p ? DECL_INIT_PRIORITY (fn) : DECL_FINI_PRIORITY (fn);
207           if (!body)
208             priority = p;
209           else if (p != priority)
210             break;
211           append_to_statement_list (build_function_call_expr (fn, 0),
212                                     &body);
213           ++i;
214         }
215       while (i < len);
216       gcc_assert (body != NULL_TREE);
217       /* Generate a function to call all the function of like
218          priority.  */
219       cgraph_build_static_cdtor (ctor_p ? 'I' : 'D', body, priority);
220     }
221 }
222
223 /* Comparison function for qsort.  P1 and P2 are actually of type
224    "tree *" and point to static constructors.  DECL_INIT_PRIORITY is
225    used to determine the sort order.  */
226
227 static int
228 compare_ctor (const void *p1, const void *p2)
229 {
230   tree f1;
231   tree f2;
232   int priority1;
233   int priority2;
234
235   f1 = *(const tree *)p1;
236   f2 = *(const tree *)p2;
237   priority1 = DECL_INIT_PRIORITY (f1);
238   priority2 = DECL_INIT_PRIORITY (f2);
239   
240   if (priority1 < priority2)
241     return -1;
242   else if (priority1 > priority2)
243     return 1;
244   else
245     /* Ensure a stable sort.  */
246     return (const tree *)p1 - (const tree *)p2;
247 }
248
249 /* Comparison function for qsort.  P1 and P2 are actually of type
250    "tree *" and point to static destructors.  DECL_FINI_PRIORITY is
251    used to determine the sort order.  */
252
253 static int
254 compare_dtor (const void *p1, const void *p2)
255 {
256   tree f1;
257   tree f2;
258   int priority1;
259   int priority2;
260
261   f1 = *(const tree *)p1;
262   f2 = *(const tree *)p2;
263   priority1 = DECL_FINI_PRIORITY (f1);
264   priority2 = DECL_FINI_PRIORITY (f2);
265   
266   if (priority1 < priority2)
267     return -1;
268   else if (priority1 > priority2)
269     return 1;
270   else
271     /* Ensure a stable sort.  */
272     return (const tree *)p1 - (const tree *)p2;
273 }
274
275 /* Generate functions to call static constructors and destructors
276    for targets that do not support .ctors/.dtors sections.  These
277    functions have magic names which are detected by collect2.  */
278
279 static void
280 cgraph_build_cdtor_fns (void)
281 {
282   if (!VEC_empty (tree, static_ctors))
283     {
284       gcc_assert (!targetm.have_ctors_dtors);
285       qsort (VEC_address (tree, static_ctors),
286              VEC_length (tree, static_ctors), 
287              sizeof (tree),
288              compare_ctor);
289       build_cdtor (/*ctor_p=*/true,
290                    VEC_address (tree, static_ctors),
291                    VEC_length (tree, static_ctors)); 
292       VEC_truncate (tree, static_ctors, 0);
293     }
294
295   if (!VEC_empty (tree, static_dtors))
296     {
297       gcc_assert (!targetm.have_ctors_dtors);
298       qsort (VEC_address (tree, static_dtors),
299              VEC_length (tree, static_dtors), 
300              sizeof (tree),
301              compare_dtor);
302       build_cdtor (/*ctor_p=*/false,
303                    VEC_address (tree, static_dtors),
304                    VEC_length (tree, static_dtors)); 
305       VEC_truncate (tree, static_dtors, 0);
306     }
307 }
308
309 /* Determine if function DECL is needed.  That is, visible to something
310    either outside this translation unit, something magic in the system
311    configury.  */
312
313 static bool
314 decide_is_function_needed (struct cgraph_node *node, tree decl)
315 {
316   if (MAIN_NAME_P (DECL_NAME (decl))
317       && TREE_PUBLIC (decl))
318     {
319       node->local.externally_visible = true;
320       return true;
321     }
322
323   /* If the user told us it is used, then it must be so.  */
324   if (node->local.externally_visible)
325     return true;
326
327   /* ??? If the assembler name is set by hand, it is possible to assemble
328      the name later after finalizing the function and the fact is noticed
329      in assemble_name then.  This is arguably a bug.  */
330   if (DECL_ASSEMBLER_NAME_SET_P (decl)
331       && TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)))
332     return true;
333
334   /* With -fkeep-inline-functions we are keeping all inline functions except
335      for extern inline ones.  */
336   if (flag_keep_inline_functions
337       && DECL_DECLARED_INLINE_P (decl)
338       && !DECL_EXTERNAL (decl)
339       && !lookup_attribute ("always_inline", DECL_ATTRIBUTES (decl)))
340      return true;
341
342   /* If we decided it was needed before, but at the time we didn't have
343      the body of the function available, then it's still needed.  We have
344      to go back and re-check its dependencies now.  */
345   if (node->needed)
346     return true;
347
348   /* Externally visible functions must be output.  The exception is
349      COMDAT functions that must be output only when they are needed.
350
351      When not optimizing, also output the static functions. (see
352      PR24561), but don't do so for always_inline functions, functions
353      declared inline and nested functions.  These was optimized out
354      in the original implementation and it is unclear whether we want
355      to change the behavior here.  */
356   if (((TREE_PUBLIC (decl)
357         || (!optimize && !node->local.disregard_inline_limits
358             && !DECL_DECLARED_INLINE_P (decl)
359             && !node->origin))
360       && !flag_whole_program)
361       && !DECL_COMDAT (decl) && !DECL_EXTERNAL (decl))
362     return true;
363
364   /* Constructors and destructors are reachable from the runtime by
365      some mechanism.  */
366   if (DECL_STATIC_CONSTRUCTOR (decl) || DECL_STATIC_DESTRUCTOR (decl))
367     return true;
368
369   return false;
370 }
371
372 /* Process CGRAPH_NEW_FUNCTIONS and perform actions necessary to add these
373    functions into callgraph in a way so they look like ordinary reachable
374    functions inserted into callgraph already at construction time.  */
375
376 bool
377 cgraph_process_new_functions (void)
378 {
379   bool output = false;
380   tree fndecl;
381   struct cgraph_node *node;
382
383   /*  Note that this queue may grow as its being processed, as the new
384       functions may generate new ones.  */
385   while (cgraph_new_nodes)
386     {
387       node = cgraph_new_nodes;
388       fndecl = node->decl;
389       cgraph_new_nodes = cgraph_new_nodes->next_needed;
390       switch (cgraph_state)
391         {
392         case CGRAPH_STATE_CONSTRUCTION:
393           /* At construction time we just need to finalize function and move
394              it into reachable functions list.  */
395
396           node->next_needed = NULL;
397           cgraph_finalize_function (fndecl, false);
398           cgraph_mark_reachable_node (node);
399           output = true;
400           break;
401
402         case CGRAPH_STATE_IPA:
403         case CGRAPH_STATE_IPA_SSA:
404           /* When IPA optimization already started, do all essential
405              transformations that has been already performed on the whole
406              cgraph but not on this function.  */
407
408           gimple_register_cfg_hooks ();
409           if (!node->analyzed)
410             cgraph_analyze_function (node);
411           push_cfun (DECL_STRUCT_FUNCTION (fndecl));
412           current_function_decl = fndecl;
413           compute_inline_parameters (node);
414           if ((cgraph_state == CGRAPH_STATE_IPA_SSA
415               && !gimple_in_ssa_p (DECL_STRUCT_FUNCTION (fndecl)))
416               /* When not optimizing, be sure we run early local passes anyway
417                  to expand OMP.  */
418               || !optimize)
419             execute_pass_list (pass_early_local_passes.pass.sub);
420           free_dominance_info (CDI_POST_DOMINATORS);
421           free_dominance_info (CDI_DOMINATORS);
422           pop_cfun ();
423           current_function_decl = NULL;
424           break;
425
426         case CGRAPH_STATE_EXPANSION:
427           /* Functions created during expansion shall be compiled
428              directly.  */
429           node->process = 0;
430           cgraph_expand_function (node);
431           break;
432
433         default:
434           gcc_unreachable ();
435           break;
436         }
437       cgraph_call_function_insertion_hooks (node);
438     }
439   return output;
440 }
441
442 /* As an GCC extension we allow redefinition of the function.  The
443    semantics when both copies of bodies differ is not well defined.
444    We replace the old body with new body so in unit at a time mode
445    we always use new body, while in normal mode we may end up with
446    old body inlined into some functions and new body expanded and
447    inlined in others.
448
449    ??? It may make more sense to use one body for inlining and other
450    body for expanding the function but this is difficult to do.  */
451
452 static void
453 cgraph_reset_node (struct cgraph_node *node)
454 {
455   /* If node->process is set, then we have already begun whole-unit analysis.
456      This is *not* testing for whether we've already emitted the function.
457      That case can be sort-of legitimately seen with real function redefinition
458      errors.  I would argue that the front end should never present us with
459      such a case, but don't enforce that for now.  */
460   gcc_assert (!node->process);
461
462   /* Reset our data structures so we can analyze the function again.  */
463   memset (&node->local, 0, sizeof (node->local));
464   memset (&node->global, 0, sizeof (node->global));
465   memset (&node->rtl, 0, sizeof (node->rtl));
466   node->analyzed = false;
467   node->local.redefined_extern_inline = true;
468   node->local.finalized = false;
469
470   cgraph_node_remove_callees (node);
471
472   /* We may need to re-queue the node for assembling in case
473      we already proceeded it and ignored as not needed or got
474      a re-declaration in IMA mode.  */
475   if (node->reachable)
476     {
477       struct cgraph_node *n;
478
479       for (n = cgraph_nodes_queue; n; n = n->next_needed)
480         if (n == node)
481           break;
482       if (!n)
483         node->reachable = 0;
484     }
485 }
486
487 static void
488 cgraph_lower_function (struct cgraph_node *node)
489 {
490   if (node->lowered)
491     return;
492   tree_lowering_passes (node->decl);
493   node->lowered = true;
494 }
495
496 /* DECL has been parsed.  Take it, queue it, compile it at the whim of the
497    logic in effect.  If NESTED is true, then our caller cannot stand to have
498    the garbage collector run at the moment.  We would need to either create
499    a new GC context, or just not compile right now.  */
500
501 void
502 cgraph_finalize_function (tree decl, bool nested)
503 {
504   struct cgraph_node *node = cgraph_node (decl);
505
506   if (node->local.finalized)
507     cgraph_reset_node (node);
508
509   node->pid = cgraph_max_pid ++;
510   notice_global_symbol (decl);
511   node->local.finalized = true;
512   node->lowered = DECL_STRUCT_FUNCTION (decl)->cfg != NULL;
513   record_cdtor_fn (node->decl);
514   if (node->nested)
515     lower_nested_functions (decl);
516   gcc_assert (!node->nested);
517
518   if (decide_is_function_needed (node, decl))
519     cgraph_mark_needed_node (node);
520
521   /* Since we reclaim unreachable nodes at the end of every language
522      level unit, we need to be conservative about possible entry points
523      there.  */
524   if ((TREE_PUBLIC (decl) && !DECL_COMDAT (decl) && !DECL_EXTERNAL (decl)))
525     cgraph_mark_reachable_node (node);
526
527   /* If we've not yet emitted decl, tell the debug info about it.  */
528   if (!TREE_ASM_WRITTEN (decl))
529     (*debug_hooks->deferred_inline_function) (decl);
530
531   /* Possibly warn about unused parameters.  */
532   if (warn_unused_parameter)
533     do_warn_unused_parameter (decl);
534
535   if (!nested)
536     ggc_collect ();
537 }
538
539 /* C99 extern inline keywords allow changing of declaration after function
540    has been finalized.  We need to re-decide if we want to mark the function as
541    needed then.   */
542
543 void
544 cgraph_mark_if_needed (tree decl)
545 {
546   struct cgraph_node *node = cgraph_node (decl);
547   if (node->local.finalized && decide_is_function_needed (node, decl))
548     cgraph_mark_needed_node (node);
549 }
550
551 /* Return TRUE if NODE2 is equivalent to NODE or its clone.  */
552 static bool
553 clone_of_p (struct cgraph_node *node, struct cgraph_node *node2)
554 {
555   while (node != node2 && node2)
556     node2 = node2->clone_of;
557   return node2 != NULL;
558 }
559
560 /* Verify cgraph nodes of given cgraph node.  */
561 void
562 verify_cgraph_node (struct cgraph_node *node)
563 {
564   struct cgraph_edge *e;
565   struct function *this_cfun = DECL_STRUCT_FUNCTION (node->decl);
566   struct function *saved_cfun = cfun;
567   basic_block this_block;
568   gimple_stmt_iterator gsi;
569   bool error_found = false;
570
571   if (errorcount || sorrycount)
572     return;
573
574   timevar_push (TV_CGRAPH_VERIFY);
575   /* debug_generic_stmt needs correct cfun */
576   set_cfun (this_cfun);
577   for (e = node->callees; e; e = e->next_callee)
578     if (e->aux)
579       {
580         error ("aux field set for edge %s->%s",
581                identifier_to_locale (cgraph_node_name (e->caller)),
582                identifier_to_locale (cgraph_node_name (e->callee)));
583         error_found = true;
584       }
585   if (node->count < 0)
586     {
587       error ("Execution count is negative");
588       error_found = true;
589     }
590   for (e = node->callers; e; e = e->next_caller)
591     {
592       if (e->count < 0)
593         {
594           error ("caller edge count is negative");
595           error_found = true;
596         }
597       if (e->frequency < 0)
598         {
599           error ("caller edge frequency is negative");
600           error_found = true;
601         }
602       if (e->frequency > CGRAPH_FREQ_MAX)
603         {
604           error ("caller edge frequency is too large");
605           error_found = true;
606         }
607       if (!e->inline_failed)
608         {
609           if (node->global.inlined_to
610               != (e->caller->global.inlined_to
611                   ? e->caller->global.inlined_to : e->caller))
612             {
613               error ("inlined_to pointer is wrong");
614               error_found = true;
615             }
616           if (node->callers->next_caller)
617             {
618               error ("multiple inline callers");
619               error_found = true;
620             }
621         }
622       else
623         if (node->global.inlined_to)
624           {
625             error ("inlined_to pointer set for noninline callers");
626             error_found = true;
627           }
628     }
629   if (!node->callers && node->global.inlined_to)
630     {
631       error ("inlined_to pointer is set but no predecessors found");
632       error_found = true;
633     }
634   if (node->global.inlined_to == node)
635     {
636       error ("inlined_to pointer refers to itself");
637       error_found = true;
638     }
639
640   if (!cgraph_node (node->decl))
641     {
642       error ("node not found in cgraph_hash");
643       error_found = true;
644     }
645
646   if (node->clone_of)
647     {
648       struct cgraph_node *n;
649       for (n = node->clone_of->clones; n; n = n->next_sibling_clone)
650         if (n == node)
651           break;
652       if (!n)
653         {
654           error ("node has wrong clone_of");
655           error_found = true;
656         }
657     }
658   if (node->clones)
659     {
660       struct cgraph_node *n;
661       for (n = node->clones; n; n = n->next_sibling_clone)
662         if (n->clone_of != node)
663           break;
664       if (n)
665         {
666           error ("node has wrong clone list");
667           error_found = true;
668         }
669     }
670   if ((node->prev_sibling_clone || node->next_sibling_clone) && !node->clone_of)
671     {
672        error ("node is in clone list but it is not clone");
673        error_found = true;
674     }
675   if (!node->prev_sibling_clone && node->clone_of && node->clone_of->clones != node)
676     {
677       error ("node has wrong prev_clone pointer");
678       error_found = true;
679     }
680   if (node->prev_sibling_clone && node->prev_sibling_clone->next_sibling_clone != node)
681     {
682       error ("double linked list of clones corrupted");
683       error_found = true;
684     }
685
686   if (node->analyzed && gimple_has_body_p (node->decl)
687       && !TREE_ASM_WRITTEN (node->decl)
688       && (!DECL_EXTERNAL (node->decl) || node->global.inlined_to))
689     {
690       if (this_cfun->cfg)
691         {
692           /* The nodes we're interested in are never shared, so walk
693              the tree ignoring duplicates.  */
694           struct pointer_set_t *visited_nodes = pointer_set_create ();
695           /* Reach the trees by walking over the CFG, and note the
696              enclosing basic-blocks in the call edges.  */
697           FOR_EACH_BB_FN (this_block, this_cfun)
698             for (gsi = gsi_start_bb (this_block);
699                  !gsi_end_p (gsi);
700                  gsi_next (&gsi))
701               {
702                 gimple stmt = gsi_stmt (gsi);
703                 tree decl;
704                 if (is_gimple_call (stmt) && (decl = gimple_call_fndecl (stmt)))
705                   {
706                     struct cgraph_edge *e = cgraph_edge (node, stmt);
707                     if (e)
708                       {
709                         if (e->aux)
710                           {
711                             error ("shared call_stmt:");
712                             debug_gimple_stmt (stmt);
713                             error_found = true;
714                           }
715                         if (!clone_of_p (cgraph_node (decl), e->callee)
716                             && !e->callee->global.inlined_to)
717                           {
718                             error ("edge points to wrong declaration:");
719                             debug_tree (e->callee->decl);
720                             fprintf (stderr," Instead of:");
721                             debug_tree (decl);
722                           }
723                         e->aux = (void *)1;
724                       }
725                     else
726                       {
727                         error ("missing callgraph edge for call stmt:");
728                         debug_gimple_stmt (stmt);
729                         error_found = true;
730                       }
731                   }
732               }
733           pointer_set_destroy (visited_nodes);
734         }
735       else
736         /* No CFG available?!  */
737         gcc_unreachable ();
738
739       for (e = node->callees; e; e = e->next_callee)
740         {
741           if (!e->aux && !e->indirect_call)
742             {
743               error ("edge %s->%s has no corresponding call_stmt",
744                      identifier_to_locale (cgraph_node_name (e->caller)),
745                      identifier_to_locale (cgraph_node_name (e->callee)));
746               debug_gimple_stmt (e->call_stmt);
747               error_found = true;
748             }
749           e->aux = 0;
750         }
751     }
752   if (error_found)
753     {
754       dump_cgraph_node (stderr, node);
755       internal_error ("verify_cgraph_node failed");
756     }
757   set_cfun (saved_cfun);
758   timevar_pop (TV_CGRAPH_VERIFY);
759 }
760
761 /* Verify whole cgraph structure.  */
762 void
763 verify_cgraph (void)
764 {
765   struct cgraph_node *node;
766
767   if (sorrycount || errorcount)
768     return;
769
770   for (node = cgraph_nodes; node; node = node->next)
771     verify_cgraph_node (node);
772 }
773
774 /* Output all asm statements we have stored up to be output.  */
775
776 static void
777 cgraph_output_pending_asms (void)
778 {
779   struct cgraph_asm_node *can;
780
781   if (errorcount || sorrycount)
782     return;
783
784   for (can = cgraph_asm_nodes; can; can = can->next)
785     assemble_asm (can->asm_str);
786   cgraph_asm_nodes = NULL;
787 }
788
789 /* Analyze the function scheduled to be output.  */
790 void
791 cgraph_analyze_function (struct cgraph_node *node)
792 {
793   tree decl = node->decl;
794
795   current_function_decl = decl;
796   push_cfun (DECL_STRUCT_FUNCTION (decl));
797   cgraph_lower_function (node);
798   node->analyzed = true;
799
800   pop_cfun ();
801   current_function_decl = NULL;
802 }
803
804 /* Look for externally_visible and used attributes and mark cgraph nodes
805    accordingly.
806
807    We cannot mark the nodes at the point the attributes are processed (in
808    handle_*_attribute) because the copy of the declarations available at that
809    point may not be canonical.  For example, in:
810
811     void f();
812     void f() __attribute__((used));
813
814    the declaration we see in handle_used_attribute will be the second
815    declaration -- but the front end will subsequently merge that declaration
816    with the original declaration and discard the second declaration.
817
818    Furthermore, we can't mark these nodes in cgraph_finalize_function because:
819
820     void f() {}
821     void f() __attribute__((externally_visible));
822
823    is valid.
824
825    So, we walk the nodes at the end of the translation unit, applying the
826    attributes at that point.  */
827
828 static void
829 process_function_and_variable_attributes (struct cgraph_node *first,
830                                           struct varpool_node *first_var)
831 {
832   struct cgraph_node *node;
833   struct varpool_node *vnode;
834
835   for (node = cgraph_nodes; node != first; node = node->next)
836     {
837       tree decl = node->decl;
838       if (lookup_attribute ("used", DECL_ATTRIBUTES (decl)))
839         {
840           mark_decl_referenced (decl);
841           if (node->local.finalized)
842              cgraph_mark_needed_node (node);
843         }
844       if (lookup_attribute ("externally_visible", DECL_ATTRIBUTES (decl)))
845         {
846           if (! TREE_PUBLIC (node->decl))
847             warning (OPT_Wattributes,
848                      "%J%<externally_visible%> attribute have effect only on public objects",
849                      node->decl);
850           else
851             {
852               if (node->local.finalized)
853                 cgraph_mark_needed_node (node);
854               node->local.externally_visible = true;
855             }
856         }
857     }
858   for (vnode = varpool_nodes; vnode != first_var; vnode = vnode->next)
859     {
860       tree decl = vnode->decl;
861       if (lookup_attribute ("used", DECL_ATTRIBUTES (decl)))
862         {
863           mark_decl_referenced (decl);
864           if (vnode->finalized)
865             varpool_mark_needed_node (vnode);
866         }
867       if (lookup_attribute ("externally_visible", DECL_ATTRIBUTES (decl)))
868         {
869           if (! TREE_PUBLIC (vnode->decl))
870             warning (OPT_Wattributes,
871                      "%J%<externally_visible%> attribute have effect only on public objects",
872                      vnode->decl);
873           else
874             {
875               if (vnode->finalized)
876                 varpool_mark_needed_node (vnode);
877               vnode->externally_visible = true;
878             }
879         }
880     }
881 }
882
883 /* Process CGRAPH_NODES_NEEDED queue, analyze each function (and transitively
884    each reachable functions) and build cgraph.
885    The function can be called multiple times after inserting new nodes
886    into beginning of queue.  Just the new part of queue is re-scanned then.  */
887
888 static void
889 cgraph_analyze_functions (void)
890 {
891   /* Keep track of already processed nodes when called multiple times for
892      intermodule optimization.  */
893   static struct cgraph_node *first_analyzed;
894   struct cgraph_node *first_processed = first_analyzed;
895   static struct varpool_node *first_analyzed_var;
896   struct cgraph_node *node, *next;
897
898   process_function_and_variable_attributes (first_processed,
899                                             first_analyzed_var);
900   first_processed = cgraph_nodes;
901   first_analyzed_var = varpool_nodes;
902   varpool_analyze_pending_decls ();
903   if (cgraph_dump_file)
904     {
905       fprintf (cgraph_dump_file, "Initial entry points:");
906       for (node = cgraph_nodes; node != first_analyzed; node = node->next)
907         if (node->needed)
908           fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
909       fprintf (cgraph_dump_file, "\n");
910     }
911   cgraph_process_new_functions ();
912
913   /* Propagate reachability flag and lower representation of all reachable
914      functions.  In the future, lowering will introduce new functions and
915      new entry points on the way (by template instantiation and virtual
916      method table generation for instance).  */
917   while (cgraph_nodes_queue)
918     {
919       struct cgraph_edge *edge;
920       tree decl = cgraph_nodes_queue->decl;
921
922       node = cgraph_nodes_queue;
923       cgraph_nodes_queue = cgraph_nodes_queue->next_needed;
924       node->next_needed = NULL;
925
926       /* ??? It is possible to create extern inline function and later using
927          weak alias attribute to kill its body. See
928          gcc.c-torture/compile/20011119-1.c  */
929       if (!DECL_STRUCT_FUNCTION (decl))
930         {
931           cgraph_reset_node (node);
932           continue;
933         }
934
935       gcc_assert (!node->analyzed && node->reachable);
936       gcc_assert (gimple_body (decl));
937
938       cgraph_analyze_function (node);
939
940       for (edge = node->callees; edge; edge = edge->next_callee)
941         if (!edge->callee->reachable)
942           cgraph_mark_reachable_node (edge->callee);
943
944       /* If decl is a clone of an abstract function, mark that abstract
945          function so that we don't release its body. The DECL_INITIAL() of that
946          abstract function declaration will be later needed to output debug info.  */
947       if (DECL_ABSTRACT_ORIGIN (decl))
948         {
949           struct cgraph_node *origin_node = cgraph_node (DECL_ABSTRACT_ORIGIN (decl));
950           origin_node->abstract_and_needed = true;
951         }
952
953       /* We finalize local static variables during constructing callgraph
954          edges.  Process their attributes too.  */
955       process_function_and_variable_attributes (first_processed,
956                                                 first_analyzed_var);
957       first_processed = cgraph_nodes;
958       first_analyzed_var = varpool_nodes;
959       varpool_analyze_pending_decls ();
960       cgraph_process_new_functions ();
961     }
962
963   /* Collect entry points to the unit.  */
964   if (cgraph_dump_file)
965     {
966       fprintf (cgraph_dump_file, "Unit entry points:");
967       for (node = cgraph_nodes; node != first_analyzed; node = node->next)
968         if (node->needed)
969           fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
970       fprintf (cgraph_dump_file, "\n\nInitial ");
971       dump_cgraph (cgraph_dump_file);
972     }
973
974   if (cgraph_dump_file)
975     fprintf (cgraph_dump_file, "\nReclaiming functions:");
976
977   for (node = cgraph_nodes; node != first_analyzed; node = next)
978     {
979       tree decl = node->decl;
980       next = node->next;
981
982       if (node->local.finalized && !gimple_has_body_p (decl))
983         cgraph_reset_node (node);
984
985       if (!node->reachable && gimple_has_body_p (decl))
986         {
987           if (cgraph_dump_file)
988             fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
989           cgraph_remove_node (node);
990           continue;
991         }
992       else
993         node->next_needed = NULL;
994       gcc_assert (!node->local.finalized || gimple_has_body_p (decl));
995       gcc_assert (node->analyzed == node->local.finalized);
996     }
997   if (cgraph_dump_file)
998     {
999       fprintf (cgraph_dump_file, "\n\nReclaimed ");
1000       dump_cgraph (cgraph_dump_file);
1001     }
1002   first_analyzed = cgraph_nodes;
1003   ggc_collect ();
1004 }
1005
1006 /* Analyze the whole compilation unit once it is parsed completely.  */
1007
1008 void
1009 cgraph_finalize_compilation_unit (void)
1010 {
1011   if (errorcount || sorrycount)
1012     return;
1013
1014   finish_aliases_1 ();
1015
1016   if (!quiet_flag)
1017     {
1018       fprintf (stderr, "\nAnalyzing compilation unit\n");
1019       fflush (stderr);
1020     }
1021
1022   timevar_push (TV_CGRAPH);
1023   cgraph_analyze_functions ();
1024   timevar_pop (TV_CGRAPH);
1025 }
1026
1027
1028 /* Figure out what functions we want to assemble.  */
1029
1030 static void
1031 cgraph_mark_functions_to_output (void)
1032 {
1033   struct cgraph_node *node;
1034
1035   for (node = cgraph_nodes; node; node = node->next)
1036     {
1037       tree decl = node->decl;
1038       struct cgraph_edge *e;
1039
1040       gcc_assert (!node->process);
1041
1042       for (e = node->callers; e; e = e->next_caller)
1043         if (e->inline_failed)
1044           break;
1045
1046       /* We need to output all local functions that are used and not
1047          always inlined, as well as those that are reachable from
1048          outside the current compilation unit.  */
1049       if (node->analyzed
1050           && !node->global.inlined_to
1051           && (node->needed
1052               || (e && node->reachable))
1053           && !TREE_ASM_WRITTEN (decl)
1054           && !DECL_EXTERNAL (decl))
1055         node->process = 1;
1056       else
1057         {
1058           /* We should've reclaimed all functions that are not needed.  */
1059 #ifdef ENABLE_CHECKING
1060           if (!node->global.inlined_to
1061               && gimple_has_body_p (decl)
1062               && !DECL_EXTERNAL (decl))
1063             {
1064               dump_cgraph_node (stderr, node);
1065               internal_error ("failed to reclaim unneeded function");
1066             }
1067 #endif
1068           gcc_assert (node->global.inlined_to
1069                       || !gimple_has_body_p (decl)
1070                       || DECL_EXTERNAL (decl));
1071
1072         }
1073
1074     }
1075 }
1076
1077 /* Expand function specified by NODE.  */
1078
1079 static void
1080 cgraph_expand_function (struct cgraph_node *node)
1081 {
1082   tree decl = node->decl;
1083
1084   /* We ought to not compile any inline clones.  */
1085   gcc_assert (!node->global.inlined_to);
1086
1087   announce_function (decl);
1088   node->process = 0;
1089
1090   gcc_assert (node->lowered);
1091
1092   /* Generate RTL for the body of DECL.  */
1093   if (lang_hooks.callgraph.emit_associated_thunks)
1094     lang_hooks.callgraph.emit_associated_thunks (decl);
1095   tree_rest_of_compilation (decl);
1096
1097   /* Make sure that BE didn't give up on compiling.  */
1098   gcc_assert (TREE_ASM_WRITTEN (decl));
1099   current_function_decl = NULL;
1100   gcc_assert (!cgraph_preserve_function_body_p (decl));
1101   cgraph_release_function_body (node);
1102   /* Eliminate all call edges.  This is important so the GIMPLE_CALL no longer
1103      points to the dead function body.  */
1104   cgraph_node_remove_callees (node);
1105
1106   cgraph_function_flags_ready = true;
1107 }
1108
1109 /* Return true when CALLER_DECL should be inlined into CALLEE_DECL.  */
1110
1111 bool
1112 cgraph_inline_p (struct cgraph_edge *e, cgraph_inline_failed_t *reason)
1113 {
1114   *reason = e->inline_failed;
1115   return !e->inline_failed;
1116 }
1117
1118
1119
1120 /* Expand all functions that must be output.
1121
1122    Attempt to topologically sort the nodes so function is output when
1123    all called functions are already assembled to allow data to be
1124    propagated across the callgraph.  Use a stack to get smaller distance
1125    between a function and its callees (later we may choose to use a more
1126    sophisticated algorithm for function reordering; we will likely want
1127    to use subsections to make the output functions appear in top-down
1128    order).  */
1129
1130 static void
1131 cgraph_expand_all_functions (void)
1132 {
1133   struct cgraph_node *node;
1134   struct cgraph_node **order = XCNEWVEC (struct cgraph_node *, cgraph_n_nodes);
1135   int order_pos, new_order_pos = 0;
1136   int i;
1137
1138   order_pos = cgraph_postorder (order);
1139   gcc_assert (order_pos == cgraph_n_nodes);
1140
1141   /* Garbage collector may remove inline clones we eliminate during
1142      optimization.  So we must be sure to not reference them.  */
1143   for (i = 0; i < order_pos; i++)
1144     if (order[i]->process)
1145       order[new_order_pos++] = order[i];
1146
1147   for (i = new_order_pos - 1; i >= 0; i--)
1148     {
1149       node = order[i];
1150       if (node->process)
1151         {
1152           gcc_assert (node->reachable);
1153           node->process = 0;
1154           cgraph_expand_function (node);
1155         }
1156     }
1157   cgraph_process_new_functions ();
1158
1159   free (order);
1160
1161 }
1162
1163 /* This is used to sort the node types by the cgraph order number.  */
1164
1165 enum cgraph_order_sort_kind
1166 {
1167   ORDER_UNDEFINED = 0,
1168   ORDER_FUNCTION,
1169   ORDER_VAR,
1170   ORDER_ASM
1171 };
1172
1173 struct cgraph_order_sort
1174 {
1175   enum cgraph_order_sort_kind kind;
1176   union
1177   {
1178     struct cgraph_node *f;
1179     struct varpool_node *v;
1180     struct cgraph_asm_node *a;
1181   } u;
1182 };
1183
1184 /* Output all functions, variables, and asm statements in the order
1185    according to their order fields, which is the order in which they
1186    appeared in the file.  This implements -fno-toplevel-reorder.  In
1187    this mode we may output functions and variables which don't really
1188    need to be output.  */
1189
1190 static void
1191 cgraph_output_in_order (void)
1192 {
1193   int max;
1194   size_t size;
1195   struct cgraph_order_sort *nodes;
1196   int i;
1197   struct cgraph_node *pf;
1198   struct varpool_node *pv;
1199   struct cgraph_asm_node *pa;
1200
1201   max = cgraph_order;
1202   size = max * sizeof (struct cgraph_order_sort);
1203   nodes = (struct cgraph_order_sort *) alloca (size);
1204   memset (nodes, 0, size);
1205
1206   varpool_analyze_pending_decls ();
1207
1208   for (pf = cgraph_nodes; pf; pf = pf->next)
1209     {
1210       if (pf->process)
1211         {
1212           i = pf->order;
1213           gcc_assert (nodes[i].kind == ORDER_UNDEFINED);
1214           nodes[i].kind = ORDER_FUNCTION;
1215           nodes[i].u.f = pf;
1216         }
1217     }
1218
1219   for (pv = varpool_nodes_queue; pv; pv = pv->next_needed)
1220     {
1221       i = pv->order;
1222       gcc_assert (nodes[i].kind == ORDER_UNDEFINED);
1223       nodes[i].kind = ORDER_VAR;
1224       nodes[i].u.v = pv;
1225     }
1226
1227   for (pa = cgraph_asm_nodes; pa; pa = pa->next)
1228     {
1229       i = pa->order;
1230       gcc_assert (nodes[i].kind == ORDER_UNDEFINED);
1231       nodes[i].kind = ORDER_ASM;
1232       nodes[i].u.a = pa;
1233     }
1234
1235   /* In toplevel reorder mode we output all statics; mark them as needed.  */
1236   for (i = 0; i < max; ++i)
1237     {
1238       if (nodes[i].kind == ORDER_VAR)
1239         {
1240           varpool_mark_needed_node (nodes[i].u.v);
1241         }
1242     }
1243   varpool_empty_needed_queue ();
1244
1245   for (i = 0; i < max; ++i)
1246     {
1247       switch (nodes[i].kind)
1248         {
1249         case ORDER_FUNCTION:
1250           nodes[i].u.f->process = 0;
1251           cgraph_expand_function (nodes[i].u.f);
1252           break;
1253
1254         case ORDER_VAR:
1255           varpool_assemble_decl (nodes[i].u.v);
1256           break;
1257
1258         case ORDER_ASM:
1259           assemble_asm (nodes[i].u.a->asm_str);
1260           break;
1261
1262         case ORDER_UNDEFINED:
1263           break;
1264
1265         default:
1266           gcc_unreachable ();
1267         }
1268     }
1269
1270   cgraph_asm_nodes = NULL;
1271 }
1272
1273 /* Return true when function body of DECL still needs to be kept around
1274    for later re-use.  */
1275 bool
1276 cgraph_preserve_function_body_p (tree decl)
1277 {
1278   struct cgraph_node *node;
1279
1280   gcc_assert (cgraph_global_info_ready);
1281   /* Look if there is any clone around.  */
1282   node = cgraph_node (decl);
1283   if (node->clones)
1284     return true;
1285   return false;
1286 }
1287
1288 static void
1289 ipa_passes (void)
1290 {
1291   set_cfun (NULL);
1292   current_function_decl = NULL;
1293   gimple_register_cfg_hooks ();
1294   bitmap_obstack_initialize (NULL);
1295   execute_ipa_pass_list (all_ipa_passes);
1296
1297   /* Generate coverage variables and constructors.  */
1298   coverage_finish ();
1299
1300   /* Process new functions added.  */
1301   set_cfun (NULL);
1302   current_function_decl = NULL;
1303   cgraph_process_new_functions ();
1304
1305   bitmap_obstack_release (NULL);
1306 }
1307
1308 /* Perform simple optimizations based on callgraph.  */
1309
1310 void
1311 cgraph_optimize (void)
1312 {
1313   if (errorcount || sorrycount)
1314     return;
1315
1316 #ifdef ENABLE_CHECKING
1317   verify_cgraph ();
1318 #endif
1319
1320   /* Call functions declared with the "constructor" or "destructor"
1321      attribute.  */
1322   cgraph_build_cdtor_fns ();
1323
1324   /* Frontend may output common variables after the unit has been finalized.
1325      It is safe to deal with them here as they are always zero initialized.  */
1326   varpool_analyze_pending_decls ();
1327   cgraph_analyze_functions ();
1328
1329   timevar_push (TV_CGRAPHOPT);
1330   if (pre_ipa_mem_report)
1331     {
1332       fprintf (stderr, "Memory consumption before IPA\n");
1333       dump_memory_report (false);
1334     }
1335   if (!quiet_flag)
1336     fprintf (stderr, "Performing interprocedural optimizations\n");
1337   cgraph_state = CGRAPH_STATE_IPA;
1338
1339   /* Don't run the IPA passes if there was any error or sorry messages.  */
1340   if (errorcount == 0 && sorrycount == 0)
1341     ipa_passes ();
1342
1343   /* This pass remove bodies of extern inline functions we never inlined.
1344      Do this later so other IPA passes see what is really going on.  */
1345   cgraph_remove_unreachable_nodes (false, dump_file);
1346   cgraph_global_info_ready = true;
1347   if (cgraph_dump_file)
1348     {
1349       fprintf (cgraph_dump_file, "Optimized ");
1350       dump_cgraph (cgraph_dump_file);
1351       dump_varpool (cgraph_dump_file);
1352     }
1353   if (post_ipa_mem_report)
1354     {
1355       fprintf (stderr, "Memory consumption after IPA\n");
1356       dump_memory_report (false);
1357     }
1358   timevar_pop (TV_CGRAPHOPT);
1359
1360   /* Output everything.  */
1361   if (!quiet_flag)
1362     fprintf (stderr, "Assembling functions:\n");
1363 #ifdef ENABLE_CHECKING
1364   verify_cgraph ();
1365 #endif
1366
1367   cgraph_materialize_all_clones ();
1368   cgraph_mark_functions_to_output ();
1369
1370   cgraph_state = CGRAPH_STATE_EXPANSION;
1371   if (!flag_toplevel_reorder)
1372     cgraph_output_in_order ();
1373   else
1374     {
1375       cgraph_output_pending_asms ();
1376
1377       cgraph_expand_all_functions ();
1378       varpool_remove_unreferenced_decls ();
1379
1380       varpool_assemble_pending_decls ();
1381     }
1382   cgraph_process_new_functions ();
1383   cgraph_state = CGRAPH_STATE_FINISHED;
1384
1385   if (cgraph_dump_file)
1386     {
1387       fprintf (cgraph_dump_file, "\nFinal ");
1388       dump_cgraph (cgraph_dump_file);
1389     }
1390 #ifdef ENABLE_CHECKING
1391   verify_cgraph ();
1392   /* Double check that all inline clones are gone and that all
1393      function bodies have been released from memory.  */
1394   if (!(sorrycount || errorcount))
1395     {
1396       struct cgraph_node *node;
1397       bool error_found = false;
1398
1399       for (node = cgraph_nodes; node; node = node->next)
1400         if (node->analyzed
1401             && (node->global.inlined_to
1402                 || gimple_has_body_p (node->decl)))
1403           {
1404             error_found = true;
1405             dump_cgraph_node (stderr, node);
1406           }
1407       if (error_found)
1408         internal_error ("nodes with unreleased memory found");
1409     }
1410 #endif
1411 }
1412 /* Generate and emit a static constructor or destructor.  WHICH must
1413    be one of 'I' (for a constructor) or 'D' (for a destructor).  BODY
1414    is a STATEMENT_LIST containing GENERIC statements.  PRIORITY is the
1415    initialization priority for this constructor or destructor.  */
1416
1417 void
1418 cgraph_build_static_cdtor (char which, tree body, int priority)
1419 {
1420   static int counter = 0;
1421   char which_buf[16];
1422   tree decl, name, resdecl;
1423
1424   /* The priority is encoded in the constructor or destructor name.
1425      collect2 will sort the names and arrange that they are called at
1426      program startup.  */
1427   sprintf (which_buf, "%c_%.5d_%d", which, priority, counter++);
1428   name = get_file_function_name (which_buf);
1429
1430   decl = build_decl (FUNCTION_DECL, name,
1431                      build_function_type (void_type_node, void_list_node));
1432   current_function_decl = decl;
1433
1434   resdecl = build_decl (RESULT_DECL, NULL_TREE, void_type_node);
1435   DECL_ARTIFICIAL (resdecl) = 1;
1436   DECL_RESULT (decl) = resdecl;
1437   DECL_CONTEXT (resdecl) = decl;
1438
1439   allocate_struct_function (decl, false);
1440
1441   TREE_STATIC (decl) = 1;
1442   TREE_USED (decl) = 1;
1443   DECL_ARTIFICIAL (decl) = 1;
1444   DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (decl) = 1;
1445   DECL_SAVED_TREE (decl) = body;
1446   TREE_PUBLIC (decl) = ! targetm.have_ctors_dtors;
1447   DECL_UNINLINABLE (decl) = 1;
1448
1449   DECL_INITIAL (decl) = make_node (BLOCK);
1450   TREE_USED (DECL_INITIAL (decl)) = 1;
1451
1452   DECL_SOURCE_LOCATION (decl) = input_location;
1453   cfun->function_end_locus = input_location;
1454
1455   switch (which)
1456     {
1457     case 'I':
1458       DECL_STATIC_CONSTRUCTOR (decl) = 1;
1459       decl_init_priority_insert (decl, priority);
1460       break;
1461     case 'D':
1462       DECL_STATIC_DESTRUCTOR (decl) = 1;
1463       decl_fini_priority_insert (decl, priority);
1464       break;
1465     default:
1466       gcc_unreachable ();
1467     }
1468
1469   gimplify_function_tree (decl);
1470
1471   cgraph_add_new_function (decl, false);
1472   cgraph_mark_needed_node (cgraph_node (decl));
1473   set_cfun (NULL);
1474 }
1475
1476 void
1477 init_cgraph (void)
1478 {
1479   cgraph_dump_file = dump_begin (TDI_cgraph, NULL);
1480 }
1481
1482 /* The edges representing the callers of the NEW_VERSION node were
1483    fixed by cgraph_function_versioning (), now the call_expr in their
1484    respective tree code should be updated to call the NEW_VERSION.  */
1485
1486 static void
1487 update_call_expr (struct cgraph_node *new_version)
1488 {
1489   struct cgraph_edge *e;
1490
1491   gcc_assert (new_version);
1492
1493   /* Update the call expr on the edges to call the new version.  */
1494   for (e = new_version->callers; e; e = e->next_caller)
1495     {
1496       struct function *inner_function = DECL_STRUCT_FUNCTION (e->caller->decl);
1497       gimple_call_set_fndecl (e->call_stmt, new_version->decl);
1498       /* Update EH information too, just in case.  */
1499       if (!stmt_could_throw_p (e->call_stmt)
1500           && lookup_stmt_eh_region_fn (inner_function, e->call_stmt))
1501         remove_stmt_from_eh_region_fn (inner_function, e->call_stmt);
1502     }
1503 }
1504
1505
1506 /* Create a new cgraph node which is the new version of
1507    OLD_VERSION node.  REDIRECT_CALLERS holds the callers
1508    edges which should be redirected to point to
1509    NEW_VERSION.  ALL the callees edges of OLD_VERSION
1510    are cloned to the new version node.  Return the new
1511    version node.  */
1512
1513 static struct cgraph_node *
1514 cgraph_copy_node_for_versioning (struct cgraph_node *old_version,
1515                                  tree new_decl,
1516                                  VEC(cgraph_edge_p,heap) *redirect_callers)
1517  {
1518    struct cgraph_node *new_version;
1519    struct cgraph_edge *e, *new_e;
1520    struct cgraph_edge *next_callee;
1521    unsigned i;
1522
1523    gcc_assert (old_version);
1524
1525    new_version = cgraph_node (new_decl);
1526
1527    new_version->analyzed = true;
1528    new_version->local = old_version->local;
1529    new_version->global = old_version->global;
1530    new_version->rtl = new_version->rtl;
1531    new_version->reachable = true;
1532    new_version->count = old_version->count;
1533
1534    /* Clone the old node callees.  Recursive calls are
1535       also cloned.  */
1536    for (e = old_version->callees;e; e=e->next_callee)
1537      {
1538        new_e = cgraph_clone_edge (e, new_version, e->call_stmt, 0, e->frequency,
1539                                   e->loop_nest, true);
1540        new_e->count = e->count;
1541      }
1542    /* Fix recursive calls.
1543       If OLD_VERSION has a recursive call after the
1544       previous edge cloning, the new version will have an edge
1545       pointing to the old version, which is wrong;
1546       Redirect it to point to the new version. */
1547    for (e = new_version->callees ; e; e = next_callee)
1548      {
1549        next_callee = e->next_callee;
1550        if (e->callee == old_version)
1551          cgraph_redirect_edge_callee (e, new_version);
1552
1553        if (!next_callee)
1554          break;
1555      }
1556    for (i = 0; VEC_iterate (cgraph_edge_p, redirect_callers, i, e); i++)
1557      {
1558        /* Redirect calls to the old version node to point to its new
1559           version.  */
1560        cgraph_redirect_edge_callee (e, new_version);
1561      }
1562
1563    return new_version;
1564  }
1565
1566  /* Perform function versioning.
1567     Function versioning includes copying of the tree and
1568     a callgraph update (creating a new cgraph node and updating
1569     its callees and callers).
1570
1571     REDIRECT_CALLERS varray includes the edges to be redirected
1572     to the new version.
1573
1574     TREE_MAP is a mapping of tree nodes we want to replace with
1575     new ones (according to results of prior analysis).
1576     OLD_VERSION_NODE is the node that is versioned.
1577     It returns the new version's cgraph node. 
1578     ARGS_TO_SKIP lists arguments to be omitted from functions
1579     */
1580
1581 struct cgraph_node *
1582 cgraph_function_versioning (struct cgraph_node *old_version_node,
1583                             VEC(cgraph_edge_p,heap) *redirect_callers,
1584                             VEC (ipa_replace_map_p,gc)* tree_map,
1585                             bitmap args_to_skip)
1586 {
1587   tree old_decl = old_version_node->decl;
1588   struct cgraph_node *new_version_node = NULL;
1589   tree new_decl;
1590
1591   if (!tree_versionable_function_p (old_decl))
1592     return NULL;
1593
1594   /* Make a new FUNCTION_DECL tree node for the
1595      new version. */
1596   if (!args_to_skip)
1597     new_decl = copy_node (old_decl);
1598   else
1599     new_decl = build_function_decl_skip_args (old_decl, args_to_skip);
1600
1601   /* Create the new version's call-graph node.
1602      and update the edges of the new node. */
1603   new_version_node =
1604     cgraph_copy_node_for_versioning (old_version_node, new_decl,
1605                                      redirect_callers);
1606
1607   /* Copy the OLD_VERSION_NODE function tree to the new version.  */
1608   tree_function_versioning (old_decl, new_decl, tree_map, false, args_to_skip);
1609
1610   /* Update the new version's properties.
1611      Make The new version visible only within this translation unit.  Make sure
1612      that is not weak also.
1613      ??? We cannot use COMDAT linkage because there is no
1614      ABI support for this.  */
1615   DECL_EXTERNAL (new_version_node->decl) = 0;
1616   DECL_ONE_ONLY (new_version_node->decl) = 0;
1617   TREE_PUBLIC (new_version_node->decl) = 0;
1618   DECL_COMDAT (new_version_node->decl) = 0;
1619   DECL_WEAK (new_version_node->decl) = 0;
1620   DECL_VIRTUAL_P (new_version_node->decl) = 0;
1621   new_version_node->local.externally_visible = 0;
1622   new_version_node->local.local = 1;
1623   new_version_node->lowered = true;
1624
1625   /* Update the call_expr on the edges to call the new version node. */
1626   update_call_expr (new_version_node);
1627   
1628   cgraph_call_function_insertion_hooks (new_version_node);
1629   return new_version_node;
1630 }
1631
1632 /* Produce separate function body for inline clones so the offline copy can be
1633    modified without affecting them.  */
1634 struct cgraph_node *
1635 save_inline_function_body (struct cgraph_node *node)
1636 {
1637   struct cgraph_node *first_clone, *n;
1638
1639   gcc_assert (node == cgraph_node (node->decl));
1640
1641   cgraph_lower_function (node);
1642
1643   first_clone = node->clones;
1644
1645   first_clone->decl = copy_node (node->decl);
1646   cgraph_insert_node_to_hashtable (first_clone);
1647   gcc_assert (first_clone == cgraph_node (first_clone->decl));
1648   if (first_clone->next_sibling_clone)
1649     {
1650       for (n = first_clone->next_sibling_clone; n->next_sibling_clone; n = n->next_sibling_clone)
1651         n->clone_of = first_clone;
1652       n->clone_of = first_clone;
1653       n->next_sibling_clone = first_clone->clones;
1654       if (first_clone->clones)
1655         first_clone->clones->prev_sibling_clone = n;
1656       first_clone->clones = first_clone->next_sibling_clone;
1657       first_clone->next_sibling_clone->prev_sibling_clone = NULL;
1658       first_clone->next_sibling_clone = NULL;
1659       gcc_assert (!first_clone->prev_sibling_clone);
1660     }
1661   first_clone->clone_of = NULL;
1662   node->clones = NULL;
1663
1664   if (first_clone->clones)
1665     for (n = first_clone->clones; n != first_clone;)
1666       {
1667         gcc_assert (n->decl == node->decl);
1668         n->decl = first_clone->decl;
1669         if (n->clones)
1670           n = n->clones;
1671         else if (n->next_sibling_clone)
1672           n = n->next_sibling_clone;
1673         else
1674           {
1675             while (n != first_clone && !n->next_sibling_clone)
1676               n = n->clone_of;
1677             if (n != first_clone)
1678               n = n->next_sibling_clone;
1679           }
1680       }
1681
1682   /* Copy the OLD_VERSION_NODE function tree to the new version.  */
1683   tree_function_versioning (node->decl, first_clone->decl, NULL, true, NULL);
1684
1685   DECL_EXTERNAL (first_clone->decl) = 0;
1686   DECL_ONE_ONLY (first_clone->decl) = 0;
1687   TREE_PUBLIC (first_clone->decl) = 0;
1688   DECL_COMDAT (first_clone->decl) = 0;
1689
1690 #ifdef ENABLE_CHECKING
1691   verify_cgraph_node (first_clone);
1692 #endif
1693   return first_clone;
1694 }
1695
1696 /* Given virtual clone, turn it into actual clone.  */
1697 static void
1698 cgraph_materialize_clone (struct cgraph_node *node)
1699 {
1700   bitmap_obstack_initialize (NULL);
1701   /* Copy the OLD_VERSION_NODE function tree to the new version.  */
1702   tree_function_versioning (node->clone_of->decl, node->decl,
1703                             node->clone.tree_map, true,
1704                             node->clone.args_to_skip);
1705
1706   /* Function is no longer clone.  */
1707   if (node->next_sibling_clone)
1708     node->next_sibling_clone->prev_sibling_clone = node->prev_sibling_clone;
1709   if (node->prev_sibling_clone)
1710     node->prev_sibling_clone->next_sibling_clone = node->next_sibling_clone;
1711   else
1712     node->clone_of->clones = node->next_sibling_clone;
1713   node->next_sibling_clone = NULL;
1714   node->prev_sibling_clone = NULL;
1715   node->clone_of = NULL;
1716   bitmap_obstack_release (NULL);
1717 }
1718
1719 /* Once all functions from compilation unit are in memory, produce all clones
1720    and update all calls.
1721    We might also do this on demand if we don't want to bring all functions to
1722    memory prior compilation, but current WHOPR implementation does that and it is
1723    is bit easier to keep everything right in this order.  */
1724 void
1725 cgraph_materialize_all_clones (void)
1726 {
1727   struct cgraph_node *node;
1728   bool stabilized = false;
1729
1730   if (cgraph_dump_file)
1731     fprintf (cgraph_dump_file, "Materializing clones\n");
1732 #ifdef ENABLE_CHECKING
1733   verify_cgraph ();
1734 #endif
1735
1736   /* We can also do topological order, but number of iterations should be
1737      bounded by number of IPA passes since single IPA pass is probably not
1738      going to create clones of clones it created itself.  */
1739   while (!stabilized)
1740     {
1741       stabilized = true;
1742       for (node = cgraph_nodes; node; node = node->next)
1743         {
1744           if (node->clone_of && node->decl != node->clone_of->decl
1745               && !gimple_has_body_p (node->decl))
1746             {
1747               if (gimple_has_body_p (node->clone_of->decl))
1748                 {
1749                   if (cgraph_dump_file)
1750                     fprintf (cgraph_dump_file, "  clonning %s to %s",
1751                              cgraph_node_name (node->clone_of),
1752                              cgraph_node_name (node));
1753                   cgraph_materialize_clone (node);
1754                 }
1755               else
1756                 stabilized = false;
1757             }
1758         }
1759     }
1760   if (cgraph_dump_file)
1761     fprintf (cgraph_dump_file, "Updating call sites\n");
1762   for (node = cgraph_nodes; node; node = node->next)
1763     if (node->analyzed && gimple_has_body_p (node->decl)
1764         && (!node->clone_of || node->clone_of->decl != node->decl))
1765       {
1766         struct cgraph_edge *e;
1767
1768         current_function_decl = node->decl;
1769         push_cfun (DECL_STRUCT_FUNCTION (node->decl));
1770         for (e = node->callees; e; e = e->next_callee)
1771           {
1772             tree decl = gimple_call_fndecl (e->call_stmt);
1773             /* When function gets inlined, indirect inlining might've invented
1774                new edge for orginally indirect stmt.  Since we are not
1775                preserving clones in the original form, we must not update here
1776                since other inline clones don't need to contain call to the same
1777                call.  Inliner will do the substitution for us later.  */
1778             if (decl && decl != e->callee->decl)
1779               {
1780                 gimple new_stmt;
1781                 gimple_stmt_iterator gsi;
1782                 
1783                 if (cgraph_dump_file)
1784                   {
1785                     fprintf (cgraph_dump_file, "updating call of %s in %s:",
1786                              cgraph_node_name (node),
1787                              cgraph_node_name (e->callee));
1788                     print_gimple_stmt (cgraph_dump_file, e->call_stmt, 0, dump_flags);
1789                   }
1790
1791                 if (e->callee->clone.args_to_skip)
1792                   new_stmt = gimple_call_copy_skip_args (e->call_stmt,
1793                                                          e->callee->clone.args_to_skip);
1794                 else
1795                   new_stmt = e->call_stmt;
1796                 if (gimple_vdef (new_stmt)
1797                     && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
1798                   SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
1799                 gimple_call_set_fndecl (new_stmt, e->callee->decl);
1800
1801                 gsi = gsi_for_stmt (e->call_stmt);
1802                 gsi_replace (&gsi, new_stmt, true);
1803
1804                 /* Update EH information too, just in case.  */
1805                 if (!stmt_could_throw_p (new_stmt)
1806                     && lookup_stmt_eh_region (new_stmt))
1807                   remove_stmt_from_eh_region (new_stmt);
1808
1809                 cgraph_set_call_stmt_including_clones (node, e->call_stmt, new_stmt);
1810
1811                 if (cgraph_dump_file)
1812                   {
1813                     fprintf (cgraph_dump_file, "  updated to:");
1814                     print_gimple_stmt (cgraph_dump_file, e->call_stmt, 0, dump_flags);
1815                   }
1816               }
1817           }
1818         pop_cfun ();
1819         current_function_decl = NULL;
1820 #ifdef ENABLE_CHECKING
1821         verify_cgraph_node (node);
1822 #endif
1823       }
1824 #ifdef ENABLE_CHECKING
1825   verify_cgraph ();
1826 #endif
1827   cgraph_remove_unreachable_nodes (false, cgraph_dump_file);
1828 }
1829
1830 #include "gt-cgraphunit.h"