OSDN Git Service

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