OSDN Git Service

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