OSDN Git Service

In libobjc/:
[pf3gnuchains/gcc-fork.git] / gcc / ipa-cp.c
1 /* Interprocedural constant propagation
2    Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010
3    Free Software Foundation, Inc.
4    Contributed by Razya Ladelsky <RAZYA@il.ibm.com>
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 /* Interprocedural constant propagation.  The aim of interprocedural constant
23    propagation (IPCP) is to find which function's argument has the same
24    constant value in each invocation throughout the whole program. For example,
25    consider the following program:
26
27    int g (int y)
28    {
29      printf ("value is %d",y);
30    }
31
32    int f (int x)
33    {
34      g (x);
35    }
36
37    int h (int y)
38    {
39      g (y);
40    }
41
42    void main (void)
43    {
44      f (3);
45      h (3);
46    }
47
48
49    The IPCP algorithm will find that g's formal argument y is always called
50    with the value 3.
51
52    The algorithm used is based on "Interprocedural Constant Propagation", by
53    Challahan David, Keith D Cooper, Ken Kennedy, Linda Torczon, Comp86, pg
54    152-161
55
56    The optimization is divided into three stages:
57
58    First stage - intraprocedural analysis
59    =======================================
60    This phase computes jump_function and modification flags.
61
62    A jump function for a callsite represents the values passed as an actual
63    arguments of a given callsite. There are three types of values:
64    Pass through - the caller's formal parameter is passed as an actual argument.
65    Constant - a constant is passed as an actual argument.
66    Unknown - neither of the above.
67
68    The jump function info, ipa_jump_func, is stored in ipa_edge_args
69    structure (defined in ipa_prop.h and pointed to by cgraph_node->aux)
70    modified_flags are defined in ipa_node_params structure
71    (defined in ipa_prop.h and pointed to by cgraph_edge->aux).
72
73    -ipcp_generate_summary() is the first stage driver.
74
75    Second stage - interprocedural analysis
76    ========================================
77    This phase does the interprocedural constant propagation.
78    It computes lattices for all formal parameters in the program
79    and their value that may be:
80    TOP - unknown.
81    BOTTOM - non constant.
82    CONSTANT - constant value.
83
84    Lattice describing a formal parameter p will have a constant value if all
85    callsites invoking this function have the same constant value passed to p.
86
87    The lattices are stored in ipcp_lattice which is itself in ipa_node_params
88    structure (defined in ipa_prop.h and pointed to by cgraph_edge->aux).
89
90    -ipcp_iterate_stage() is the second stage driver.
91
92    Third phase - transformation of function code
93    ============================================
94    Propagates the constant-valued formals into the function.
95    For each function whose parameters are constants, we create its clone.
96
97    Then we process the clone in two ways:
98    1. We insert an assignment statement 'parameter = const' at the beginning
99       of the cloned function.
100    2. For read-only parameters that do not live in memory, we replace all their
101       uses with the constant.
102
103    We also need to modify some callsites to call the cloned functions instead
104    of the original ones.  For a callsite passing an argument found to be a
105    constant by IPCP, there are two different cases to handle:
106    1. A constant is passed as an argument.  In this case the callsite in the
107       should be redirected to call the cloned callee.
108    2. A parameter (of the caller) passed as an argument (pass through
109       argument).  In such cases both the caller and the callee have clones and
110       only the callsite in the cloned caller is redirected to call to the
111       cloned callee.
112
113    This update is done in two steps: First all cloned functions are created
114    during a traversal of the call graph, during which all callsites are
115    redirected to call the cloned function.  Then the callsites are traversed
116    and many calls redirected back to fit the description above.
117
118    -ipcp_insert_stage() is the third phase driver.
119
120
121    This pass also performs devirtualization - turns virtual calls into direct
122    ones if it can prove that all invocations of the function call the same
123    callee.  This is achieved by building a list of all base types (actually,
124    their BINFOs) that individual parameters can have in an iterative matter
125    just like propagating scalar constants and then examining whether virtual
126    calls which take a parameter as their object fold to the same target for all
127    these types.  If we cannot enumerate all types or there is a type which does
128    not have any BINFO associated with it, cannot_devirtualize of the associated
129    parameter descriptor is set which is an equivalent of BOTTOM lattice value
130    in standard IPA constant propagation.
131 */
132
133 #include "config.h"
134 #include "system.h"
135 #include "coretypes.h"
136 #include "tree.h"
137 #include "target.h"
138 #include "gimple.h"
139 #include "cgraph.h"
140 #include "ipa-prop.h"
141 #include "tree-flow.h"
142 #include "tree-pass.h"
143 #include "flags.h"
144 #include "timevar.h"
145 #include "diagnostic.h"
146 #include "tree-pretty-print.h"
147 #include "tree-dump.h"
148 #include "tree-inline.h"
149 #include "fibheap.h"
150 #include "params.h"
151
152 /* Number of functions identified as candidates for cloning. When not cloning
153    we can simplify iterate stage not forcing it to go through the decision
154    on what is profitable and what not.  */
155 static int n_cloning_candidates;
156
157 /* Maximal count found in program.  */
158 static gcov_type max_count;
159
160 /* Cgraph nodes that has been completely replaced by cloning during iterate
161  * stage and will be removed after ipcp is finished.  */
162 static bitmap dead_nodes;
163
164 static void ipcp_print_profile_data (FILE *);
165 static void ipcp_function_scale_print (FILE *);
166
167 /* Get the original node field of ipa_node_params associated with node NODE.  */
168 static inline struct cgraph_node *
169 ipcp_get_orig_node (struct cgraph_node *node)
170 {
171   return IPA_NODE_REF (node)->ipcp_orig_node;
172 }
173
174 /* Return true if NODE describes a cloned/versioned function.  */
175 static inline bool
176 ipcp_node_is_clone (struct cgraph_node *node)
177 {
178   return (ipcp_get_orig_node (node) != NULL);
179 }
180
181 /* Create ipa_node_params and its data structures for NEW_NODE.  Set ORIG_NODE
182    as the ipcp_orig_node field in ipa_node_params.  */
183 static void
184 ipcp_init_cloned_node (struct cgraph_node *orig_node,
185                        struct cgraph_node *new_node)
186 {
187   gcc_checking_assert (ipa_node_params_vector
188                        && (VEC_length (ipa_node_params_t,
189                                        ipa_node_params_vector)
190                            > (unsigned) cgraph_max_uid));
191   gcc_checking_assert (IPA_NODE_REF (new_node)->params);
192   IPA_NODE_REF (new_node)->ipcp_orig_node = orig_node;
193 }
194
195 /* Return scale for NODE.  */
196 static inline gcov_type
197 ipcp_get_node_scale (struct cgraph_node *node)
198 {
199   return IPA_NODE_REF (node)->count_scale;
200 }
201
202 /* Set COUNT as scale for NODE.  */
203 static inline void
204 ipcp_set_node_scale (struct cgraph_node *node, gcov_type count)
205 {
206   IPA_NODE_REF (node)->count_scale = count;
207 }
208
209 /* Return whether LAT is a constant lattice.  */
210 static inline bool
211 ipcp_lat_is_const (struct ipcp_lattice *lat)
212 {
213   if (lat->type == IPA_CONST_VALUE)
214     return true;
215   else
216     return false;
217 }
218
219 /* Return whether LAT is a constant lattice that ipa-cp can actually insert
220    into the code (i.e. constants excluding member pointers and pointers).  */
221 static inline bool
222 ipcp_lat_is_insertable (struct ipcp_lattice *lat)
223 {
224   return lat->type == IPA_CONST_VALUE;
225 }
226
227 /* Return true if LAT1 and LAT2 are equal.  */
228 static inline bool
229 ipcp_lats_are_equal (struct ipcp_lattice *lat1, struct ipcp_lattice *lat2)
230 {
231   gcc_assert (ipcp_lat_is_const (lat1) && ipcp_lat_is_const (lat2));
232   if (lat1->type != lat2->type)
233     return false;
234
235   if (TREE_CODE (lat1->constant) ==  ADDR_EXPR
236       && TREE_CODE (lat2->constant) ==  ADDR_EXPR
237       && TREE_CODE (TREE_OPERAND (lat1->constant, 0)) == CONST_DECL
238       && TREE_CODE (TREE_OPERAND (lat2->constant, 0)) == CONST_DECL)
239     return operand_equal_p (DECL_INITIAL (TREE_OPERAND (lat1->constant, 0)),
240                             DECL_INITIAL (TREE_OPERAND (lat2->constant, 0)), 0);
241   else
242     return operand_equal_p (lat1->constant, lat2->constant, 0);
243 }
244
245 /* Compute Meet arithmetics:
246    Meet (IPA_BOTTOM, x) = IPA_BOTTOM
247    Meet (IPA_TOP,x) = x
248    Meet (const_a,const_b) = IPA_BOTTOM,  if const_a != const_b.
249    MEET (const_a,const_b) = const_a, if const_a == const_b.*/
250 static void
251 ipa_lattice_meet (struct ipcp_lattice *res, struct ipcp_lattice *lat1,
252                   struct ipcp_lattice *lat2)
253 {
254   if (lat1->type == IPA_BOTTOM || lat2->type == IPA_BOTTOM)
255     {
256       res->type = IPA_BOTTOM;
257       return;
258     }
259   if (lat1->type == IPA_TOP)
260     {
261       res->type = lat2->type;
262       res->constant = lat2->constant;
263       return;
264     }
265   if (lat2->type == IPA_TOP)
266     {
267       res->type = lat1->type;
268       res->constant = lat1->constant;
269       return;
270     }
271   if (!ipcp_lats_are_equal (lat1, lat2))
272     {
273       res->type = IPA_BOTTOM;
274       return;
275     }
276   res->type = lat1->type;
277   res->constant = lat1->constant;
278 }
279
280 /* Return the lattice corresponding to the Ith formal parameter of the function
281    described by INFO.  */
282 static inline struct ipcp_lattice *
283 ipcp_get_lattice (struct ipa_node_params *info, int i)
284 {
285   return &(info->params[i].ipcp_lattice);
286 }
287
288 /* Given the jump function JFUNC, compute the lattice LAT that describes the
289    value coming down the callsite. INFO describes the caller node so that
290    pass-through jump functions can be evaluated.  */
291 static void
292 ipcp_lattice_from_jfunc (struct ipa_node_params *info, struct ipcp_lattice *lat,
293                          struct ipa_jump_func *jfunc)
294 {
295   if (jfunc->type == IPA_JF_CONST)
296     {
297       lat->type = IPA_CONST_VALUE;
298       lat->constant = jfunc->value.constant;
299     }
300   else if (jfunc->type == IPA_JF_PASS_THROUGH)
301     {
302       struct ipcp_lattice *caller_lat;
303       tree cst;
304
305       caller_lat = ipcp_get_lattice (info, jfunc->value.pass_through.formal_id);
306       lat->type = caller_lat->type;
307       if (caller_lat->type != IPA_CONST_VALUE)
308         return;
309       cst = caller_lat->constant;
310
311       if (jfunc->value.pass_through.operation != NOP_EXPR)
312         {
313           tree restype;
314           if (TREE_CODE_CLASS (jfunc->value.pass_through.operation)
315               == tcc_comparison)
316             restype = boolean_type_node;
317           else
318             restype = TREE_TYPE (cst);
319           cst = fold_binary (jfunc->value.pass_through.operation,
320                              restype, cst, jfunc->value.pass_through.operand);
321         }
322       if (!cst || !is_gimple_ip_invariant (cst))
323         lat->type = IPA_BOTTOM;
324       lat->constant = cst;
325     }
326   else if (jfunc->type == IPA_JF_ANCESTOR)
327     {
328       struct ipcp_lattice *caller_lat;
329       tree t;
330
331       caller_lat = ipcp_get_lattice (info, jfunc->value.ancestor.formal_id);
332       lat->type = caller_lat->type;
333       if (caller_lat->type != IPA_CONST_VALUE)
334         return;
335       if (TREE_CODE (caller_lat->constant) != ADDR_EXPR)
336         {
337           /* This can happen when the constant is a NULL pointer.  */
338           lat->type = IPA_BOTTOM;
339           return;
340         }
341       t = TREE_OPERAND (caller_lat->constant, 0);
342       t = build_ref_for_offset (t, jfunc->value.ancestor.offset,
343                                 jfunc->value.ancestor.type, NULL, false);
344       lat->constant = build_fold_addr_expr (t);
345     }
346   else
347     lat->type = IPA_BOTTOM;
348 }
349
350 /* True when OLD_LAT and NEW_LAT values are not the same.  */
351
352 static bool
353 ipcp_lattice_changed (struct ipcp_lattice *old_lat,
354                       struct ipcp_lattice *new_lat)
355 {
356   if (old_lat->type == new_lat->type)
357     {
358       if (!ipcp_lat_is_const (old_lat))
359         return false;
360       if (ipcp_lats_are_equal (old_lat, new_lat))
361         return false;
362     }
363   return true;
364 }
365
366 /* Print all ipcp_lattices of all functions to F.  */
367 static void
368 ipcp_print_all_lattices (FILE * f)
369 {
370   struct cgraph_node *node;
371   int i, count;
372
373   fprintf (f, "\nLattice:\n");
374   for (node = cgraph_nodes; node; node = node->next)
375     {
376       struct ipa_node_params *info;
377
378       if (!node->analyzed)
379         continue;
380       info = IPA_NODE_REF (node);
381       fprintf (f, "  Node: %s:\n", cgraph_node_name (node));
382       count = ipa_get_param_count (info);
383       for (i = 0; i < count; i++)
384         {
385           struct ipcp_lattice *lat = ipcp_get_lattice (info, i);
386
387           fprintf (f, "    param [%d]: ", i);
388           if (lat->type == IPA_CONST_VALUE)
389             {
390               tree cst = lat->constant;
391               fprintf (f, "type is CONST ");
392               print_generic_expr (f, cst, 0);
393               if (TREE_CODE (cst) == ADDR_EXPR
394                   && TREE_CODE (TREE_OPERAND (cst, 0)) == CONST_DECL)
395                 {
396                   fprintf (f, " -> ");
397                   print_generic_expr (f, DECL_INITIAL (TREE_OPERAND (cst, 0)),
398                                                        0);
399                 }
400             }
401           else if (lat->type == IPA_TOP)
402             fprintf (f, "type is TOP");
403           else
404             fprintf (f, "type is BOTTOM");
405           if (ipa_param_cannot_devirtualize_p (info, i))
406             fprintf (f, " - cannot_devirtualize set\n");
407           else if (ipa_param_types_vec_empty (info, i))
408             fprintf (f, " - type list empty\n");
409           else
410             fprintf (f, "\n");
411         }
412     }
413 }
414
415 /* Return true if ipcp algorithms would allow cloning NODE.  */
416
417 static bool
418 ipcp_versionable_function_p (struct cgraph_node *node)
419 {
420   struct cgraph_edge *edge;
421
422   /* There are a number of generic reasons functions cannot be versioned.  We
423      also cannot remove parameters if there are type attributes such as fnspec
424      present.  */
425   if (!node->local.versionable
426       || TYPE_ATTRIBUTES (TREE_TYPE (node->decl)))
427     return false;
428
429   /* Removing arguments doesn't work if the function takes varargs
430      or use __builtin_apply_args. */
431   for (edge = node->callees; edge; edge = edge->next_callee)
432     {
433       tree t = edge->callee->decl;
434       if (DECL_BUILT_IN_CLASS (t) == BUILT_IN_NORMAL
435           && (DECL_FUNCTION_CODE (t) == BUILT_IN_APPLY_ARGS
436              || DECL_FUNCTION_CODE (t) == BUILT_IN_VA_START))
437         return false;
438     }
439
440   return true;
441 }
442
443 /* Return true if this NODE is viable candidate for cloning.  */
444 static bool
445 ipcp_cloning_candidate_p (struct cgraph_node *node)
446 {
447   int n_calls = 0;
448   int n_hot_calls = 0;
449   gcov_type direct_call_sum = 0;
450   struct cgraph_edge *e;
451
452   /* We never clone functions that are not visible from outside.
453      FIXME: in future we should clone such functions when they are called with
454      different constants, but current ipcp implementation is not good on this.
455      */
456   if (cgraph_only_called_directly_p (node) || !node->analyzed)
457     return false;
458
459   if (cgraph_function_body_availability (node) <= AVAIL_OVERWRITABLE)
460     {
461       if (dump_file)
462         fprintf (dump_file, "Not considering %s for cloning; body is overwrittable.\n",
463                  cgraph_node_name (node));
464       return false;
465     }
466   if (!ipcp_versionable_function_p (node))
467     {
468       if (dump_file)
469         fprintf (dump_file, "Not considering %s for cloning; body is not versionable.\n",
470                  cgraph_node_name (node));
471       return false;
472     }
473   for (e = node->callers; e; e = e->next_caller)
474     {
475       direct_call_sum += e->count;
476       n_calls ++;
477       if (cgraph_maybe_hot_edge_p (e))
478         n_hot_calls ++;
479     }
480
481   if (!n_calls)
482     {
483       if (dump_file)
484         fprintf (dump_file, "Not considering %s for cloning; no direct calls.\n",
485                  cgraph_node_name (node));
486       return false;
487     }
488   if (node->local.inline_summary.self_size < n_calls)
489     {
490       if (dump_file)
491         fprintf (dump_file, "Considering %s for cloning; code would shrink.\n",
492                  cgraph_node_name (node));
493       return true;
494     }
495
496   if (!flag_ipa_cp_clone)
497     {
498       if (dump_file)
499         fprintf (dump_file, "Not considering %s for cloning; -fipa-cp-clone disabled.\n",
500                  cgraph_node_name (node));
501       return false;
502     }
503
504   if (!optimize_function_for_speed_p (DECL_STRUCT_FUNCTION (node->decl)))
505     {
506       if (dump_file)
507         fprintf (dump_file, "Not considering %s for cloning; optimizing it for size.\n",
508                  cgraph_node_name (node));
509       return false;
510     }
511
512   /* When profile is available and function is hot, propagate into it even if
513      calls seems cold; constant propagation can improve function's speed
514      significandly.  */
515   if (max_count)
516     {
517       if (direct_call_sum > node->count * 90 / 100)
518         {
519           if (dump_file)
520             fprintf (dump_file, "Considering %s for cloning; usually called directly.\n",
521                      cgraph_node_name (node));
522           return true;
523         }
524     }
525   if (!n_hot_calls)
526     {
527       if (dump_file)
528         fprintf (dump_file, "Not considering %s for cloning; no hot calls.\n",
529                  cgraph_node_name (node));
530       return false;
531     }
532   if (dump_file)
533     fprintf (dump_file, "Considering %s for cloning.\n",
534              cgraph_node_name (node));
535   return true;
536 }
537
538 /* Mark parameter with index I of function described by INFO as unsuitable for
539    devirtualization.  Return true if it has already been marked so.  */
540
541 static bool
542 ipa_set_param_cannot_devirtualize (struct ipa_node_params *info, int i)
543 {
544   bool ret = info->params[i].cannot_devirtualize;
545   info->params[i].cannot_devirtualize = true;
546   if (info->params[i].types)
547     VEC_free (tree, heap, info->params[i].types);
548   return ret;
549 }
550
551 /* Initialize ipcp_lattices array.  The lattices corresponding to supported
552    types (integers, real types and Fortran constants defined as const_decls)
553    are initialized to IPA_TOP, the rest of them to IPA_BOTTOM.  */
554 static void
555 ipcp_initialize_node_lattices (struct cgraph_node *node)
556 {
557   int i;
558   struct ipa_node_params *info = IPA_NODE_REF (node);
559   enum ipa_lattice_type type;
560
561   if (ipa_is_called_with_var_arguments (info))
562     type = IPA_BOTTOM;
563   else if (cgraph_only_called_directly_p (node))
564     type = IPA_TOP;
565   /* When cloning is allowed, we can assume that externally visible functions
566      are not called.  We will compensate this by cloning later.  */
567   else if (ipcp_cloning_candidate_p (node))
568     type = IPA_TOP, n_cloning_candidates ++;
569   else
570     type = IPA_BOTTOM;
571
572   for (i = 0; i < ipa_get_param_count (info) ; i++)
573     {
574       ipcp_get_lattice (info, i)->type = type;
575       if (type == IPA_BOTTOM)
576         ipa_set_param_cannot_devirtualize (info, i);
577     }
578 }
579
580 /* build INTEGER_CST tree with type TREE_TYPE and value according to LAT.
581    Return the tree.  */
582 static tree
583 build_const_val (struct ipcp_lattice *lat, tree tree_type)
584 {
585   tree val;
586
587   gcc_assert (ipcp_lat_is_const (lat));
588   val = lat->constant;
589
590   if (!useless_type_conversion_p (tree_type, TREE_TYPE (val)))
591     {
592       if (fold_convertible_p (tree_type, val))
593         return fold_build1 (NOP_EXPR, tree_type, val);
594       else
595         return fold_build1 (VIEW_CONVERT_EXPR, tree_type, val);
596     }
597   return val;
598 }
599
600 /* Compute the proper scale for NODE.  It is the ratio between the number of
601    direct calls (represented on the incoming cgraph_edges) and sum of all
602    invocations of NODE (represented as count in cgraph_node).
603
604    FIXME: This code is wrong.  Since the callers can be also clones and
605    the clones are not scaled yet, the sums gets unrealistically high.
606    To properly compute the counts, we would need to do propagation across
607    callgraph (as external call to A might imply call to non-clonned B
608    if A's clone calls clonned B).  */
609 static void
610 ipcp_compute_node_scale (struct cgraph_node *node)
611 {
612   gcov_type sum;
613   struct cgraph_edge *cs;
614
615   sum = 0;
616   /* Compute sum of all counts of callers. */
617   for (cs = node->callers; cs != NULL; cs = cs->next_caller)
618     sum += cs->count;
619   /* Work around the unrealistically high sum problem.  We just don't want
620      the non-cloned body to have negative or very low frequency.  Since
621      majority of execution time will be spent in clones anyway, this should
622      give good enough profile.  */
623   if (sum > node->count * 9 / 10)
624     sum = node->count * 9 / 10;
625   if (node->count == 0)
626     ipcp_set_node_scale (node, 0);
627   else
628     ipcp_set_node_scale (node, sum * REG_BR_PROB_BASE / node->count);
629 }
630
631 /* Return true if there are some formal parameters whose value is IPA_TOP (in
632    the whole compilation unit).  Change their values to IPA_BOTTOM, since they
633    most probably get their values from outside of this compilation unit.  */
634 static bool
635 ipcp_change_tops_to_bottom (void)
636 {
637   int i, count;
638   struct cgraph_node *node;
639   bool prop_again;
640
641   prop_again = false;
642   for (node = cgraph_nodes; node; node = node->next)
643     {
644       struct ipa_node_params *info = IPA_NODE_REF (node);
645       count = ipa_get_param_count (info);
646       for (i = 0; i < count; i++)
647         {
648           struct ipcp_lattice *lat = ipcp_get_lattice (info, i);
649           if (lat->type == IPA_TOP)
650             {
651               prop_again = true;
652               if (dump_file)
653                 {
654                   fprintf (dump_file, "Forcing param ");
655                   print_generic_expr (dump_file, ipa_get_param (info, i), 0);
656                   fprintf (dump_file, " of node %s to bottom.\n",
657                            cgraph_node_name (node));
658                 }
659               lat->type = IPA_BOTTOM;
660             }
661           if (!ipa_param_cannot_devirtualize_p (info, i)
662               && ipa_param_types_vec_empty (info, i))
663             {
664               prop_again = true;
665               ipa_set_param_cannot_devirtualize (info, i);
666               if (dump_file)
667                 {
668                   fprintf (dump_file, "Marking param ");
669                   print_generic_expr (dump_file, ipa_get_param (info, i), 0);
670                   fprintf (dump_file, " of node %s as unusable for "
671                            "devirtualization.\n",
672                            cgraph_node_name (node));
673                 }
674             }
675         }
676     }
677   return prop_again;
678 }
679
680 /* Insert BINFO to the list of known types of parameter number I of the
681    function described by CALLEE_INFO.  Return true iff the type information
682    associated with the callee parameter changed in any way.  */
683
684 static bool
685 ipcp_add_param_type (struct ipa_node_params *callee_info, int i, tree binfo)
686 {
687   int j, count;
688
689   if (ipa_param_cannot_devirtualize_p (callee_info, i))
690     return false;
691
692   if (callee_info->params[i].types)
693     {
694       count = VEC_length (tree, callee_info->params[i].types);
695       for (j = 0; j < count; j++)
696         if (VEC_index (tree, callee_info->params[i].types, j) == binfo)
697           return false;
698     }
699
700   if (VEC_length (tree, callee_info->params[i].types)
701       == (unsigned) PARAM_VALUE (PARAM_DEVIRT_TYPE_LIST_SIZE))
702     return !ipa_set_param_cannot_devirtualize (callee_info, i);
703
704   VEC_safe_push (tree, heap, callee_info->params[i].types, binfo);
705   return true;
706 }
707
708 /* Copy known types information for parameter number CALLEE_IDX of CALLEE_INFO
709    from a parameter of CALLER_INFO as described by JF.  Return true iff the
710    type information changed in any way.  JF must be a pass-through or an
711    ancestor jump function.  */
712
713 static bool
714 ipcp_copy_types (struct ipa_node_params *caller_info,
715                  struct ipa_node_params *callee_info,
716                  int callee_idx, struct ipa_jump_func *jf)
717 {
718   int caller_idx, j, count;
719   bool res;
720
721   if (ipa_param_cannot_devirtualize_p (callee_info, callee_idx))
722     return false;
723
724   if (jf->type == IPA_JF_PASS_THROUGH)
725     {
726       if (jf->value.pass_through.operation != NOP_EXPR)
727         {
728           ipa_set_param_cannot_devirtualize (callee_info, callee_idx);
729           return true;
730         }
731       caller_idx = jf->value.pass_through.formal_id;
732     }
733   else
734     caller_idx = jf->value.ancestor.formal_id;
735
736   if (ipa_param_cannot_devirtualize_p (caller_info, caller_idx))
737     {
738       ipa_set_param_cannot_devirtualize (callee_info, callee_idx);
739       return true;
740     }
741
742   if (!caller_info->params[caller_idx].types)
743     return false;
744
745   res = false;
746   count = VEC_length (tree, caller_info->params[caller_idx].types);
747   for (j = 0; j < count; j++)
748     {
749       tree binfo = VEC_index (tree, caller_info->params[caller_idx].types, j);
750       if (jf->type == IPA_JF_ANCESTOR)
751         {
752           binfo = get_binfo_at_offset (binfo, jf->value.ancestor.offset,
753                                        jf->value.ancestor.type);
754           if (!binfo)
755             {
756               ipa_set_param_cannot_devirtualize (callee_info, callee_idx);
757               return true;
758             }
759         }
760       res |= ipcp_add_param_type (callee_info, callee_idx, binfo);
761     }
762   return res;
763 }
764
765 /* Propagate type information for parameter of CALLEE_INFO number I as
766    described by JF.  CALLER_INFO describes the caller.  Return true iff the
767    type information changed in any way.  */
768
769 static bool
770 ipcp_propagate_types (struct ipa_node_params *caller_info,
771                       struct ipa_node_params *callee_info,
772                       struct ipa_jump_func *jf, int i)
773 {
774   tree cst, binfo;
775
776   switch (jf->type)
777     {
778     case IPA_JF_UNKNOWN:
779     case IPA_JF_CONST_MEMBER_PTR:
780       break;
781
782     case IPA_JF_KNOWN_TYPE:
783       return ipcp_add_param_type (callee_info, i, jf->value.base_binfo);
784
785     case IPA_JF_CONST:
786       cst = jf->value.constant;
787       if (TREE_CODE (cst) != ADDR_EXPR)
788         break;
789       binfo = gimple_get_relevant_ref_binfo (TREE_OPERAND (cst, 0), NULL_TREE);
790       if (!binfo)
791         break;
792       return ipcp_add_param_type (callee_info, i, binfo);
793
794     case IPA_JF_PASS_THROUGH:
795     case IPA_JF_ANCESTOR:
796       return ipcp_copy_types (caller_info, callee_info, i, jf);
797     }
798
799   /* If we reach this we cannot use this parameter for devirtualization.  */
800   return !ipa_set_param_cannot_devirtualize (callee_info, i);
801 }
802
803 /* Interprocedural analysis. The algorithm propagates constants from the
804    caller's parameters to the callee's arguments.  */
805 static void
806 ipcp_propagate_stage (void)
807 {
808   int i;
809   struct ipcp_lattice inc_lat = { IPA_BOTTOM, NULL };
810   struct ipcp_lattice new_lat = { IPA_BOTTOM, NULL };
811   struct ipcp_lattice *dest_lat;
812   struct cgraph_edge *cs;
813   struct ipa_jump_func *jump_func;
814   struct ipa_func_list *wl;
815   int count;
816
817   ipa_check_create_node_params ();
818   ipa_check_create_edge_args ();
819
820   /* Initialize worklist to contain all functions.  */
821   wl = ipa_init_func_list ();
822   while (wl)
823     {
824       struct cgraph_node *node = ipa_pop_func_from_list (&wl);
825       struct ipa_node_params *info = IPA_NODE_REF (node);
826
827       for (cs = node->callees; cs; cs = cs->next_callee)
828         {
829           struct ipa_node_params *callee_info = IPA_NODE_REF (cs->callee);
830           struct ipa_edge_args *args = IPA_EDGE_REF (cs);
831
832           if (ipa_is_called_with_var_arguments (callee_info)
833               || !cs->callee->analyzed
834               || ipa_is_called_with_var_arguments (callee_info))
835             continue;
836
837           count = ipa_get_cs_argument_count (args);
838           for (i = 0; i < count; i++)
839             {
840               jump_func = ipa_get_ith_jump_func (args, i);
841               ipcp_lattice_from_jfunc (info, &inc_lat, jump_func);
842               dest_lat = ipcp_get_lattice (callee_info, i);
843               ipa_lattice_meet (&new_lat, &inc_lat, dest_lat);
844               if (ipcp_lattice_changed (&new_lat, dest_lat))
845                 {
846                   dest_lat->type = new_lat.type;
847                   dest_lat->constant = new_lat.constant;
848                   ipa_push_func_to_list (&wl, cs->callee);
849                 }
850
851               if (ipcp_propagate_types (info, callee_info, jump_func, i))
852                 ipa_push_func_to_list (&wl, cs->callee);
853             }
854         }
855     }
856 }
857
858 /* Call the constant propagation algorithm and re-call it if necessary
859    (if there are undetermined values left).  */
860 static void
861 ipcp_iterate_stage (void)
862 {
863   struct cgraph_node *node;
864   n_cloning_candidates = 0;
865
866   if (dump_file)
867     fprintf (dump_file, "\nIPA iterate stage:\n\n");
868
869   if (in_lto_p)
870     ipa_update_after_lto_read ();
871
872   for (node = cgraph_nodes; node; node = node->next)
873     {
874       ipcp_initialize_node_lattices (node);
875       ipcp_compute_node_scale (node);
876     }
877   if (dump_file && (dump_flags & TDF_DETAILS))
878     {
879       ipcp_print_all_lattices (dump_file);
880       ipcp_function_scale_print (dump_file);
881     }
882
883   ipcp_propagate_stage ();
884   if (ipcp_change_tops_to_bottom ())
885     /* Some lattices have changed from IPA_TOP to IPA_BOTTOM.
886        This change should be propagated.  */
887     {
888       gcc_assert (n_cloning_candidates);
889       ipcp_propagate_stage ();
890     }
891   if (dump_file)
892     {
893       fprintf (dump_file, "\nIPA lattices after propagation:\n");
894       ipcp_print_all_lattices (dump_file);
895       if (dump_flags & TDF_DETAILS)
896         ipcp_print_profile_data (dump_file);
897     }
898 }
899
900 /* Check conditions to forbid constant insertion to function described by
901    NODE.  */
902 static inline bool
903 ipcp_node_modifiable_p (struct cgraph_node *node)
904 {
905   /* Once we will be able to do in-place replacement, we can be more
906      lax here.  */
907   return ipcp_versionable_function_p (node);
908 }
909
910 /* Print count scale data structures.  */
911 static void
912 ipcp_function_scale_print (FILE * f)
913 {
914   struct cgraph_node *node;
915
916   for (node = cgraph_nodes; node; node = node->next)
917     {
918       if (!node->analyzed)
919         continue;
920       fprintf (f, "printing scale for %s: ", cgraph_node_name (node));
921       fprintf (f, "value is  " HOST_WIDE_INT_PRINT_DEC
922                "  \n", (HOST_WIDE_INT) ipcp_get_node_scale (node));
923     }
924 }
925
926 /* Print counts of all cgraph nodes.  */
927 static void
928 ipcp_print_func_profile_counts (FILE * f)
929 {
930   struct cgraph_node *node;
931
932   for (node = cgraph_nodes; node; node = node->next)
933     {
934       fprintf (f, "function %s: ", cgraph_node_name (node));
935       fprintf (f, "count is  " HOST_WIDE_INT_PRINT_DEC
936                "  \n", (HOST_WIDE_INT) node->count);
937     }
938 }
939
940 /* Print counts of all cgraph edges.  */
941 static void
942 ipcp_print_call_profile_counts (FILE * f)
943 {
944   struct cgraph_node *node;
945   struct cgraph_edge *cs;
946
947   for (node = cgraph_nodes; node; node = node->next)
948     {
949       for (cs = node->callees; cs; cs = cs->next_callee)
950         {
951           fprintf (f, "%s -> %s ", cgraph_node_name (cs->caller),
952                    cgraph_node_name (cs->callee));
953           fprintf (f, "count is  " HOST_WIDE_INT_PRINT_DEC "  \n",
954                    (HOST_WIDE_INT) cs->count);
955         }
956     }
957 }
958
959 /* Print profile info for all functions.  */
960 static void
961 ipcp_print_profile_data (FILE * f)
962 {
963   fprintf (f, "\nNODE COUNTS :\n");
964   ipcp_print_func_profile_counts (f);
965   fprintf (f, "\nCS COUNTS stage:\n");
966   ipcp_print_call_profile_counts (f);
967 }
968
969 /* Build and initialize ipa_replace_map struct according to LAT. This struct is
970    processed by versioning, which operates according to the flags set.
971    PARM_TREE is the formal parameter found to be constant.  LAT represents the
972    constant.  */
973 static struct ipa_replace_map *
974 ipcp_create_replace_map (tree parm_tree, struct ipcp_lattice *lat)
975 {
976   struct ipa_replace_map *replace_map;
977   tree const_val;
978
979   replace_map = ggc_alloc_ipa_replace_map ();
980   const_val = build_const_val (lat, TREE_TYPE (parm_tree));
981   if (dump_file)
982     {
983       fprintf (dump_file, "  replacing param ");
984       print_generic_expr (dump_file, parm_tree, 0);
985       fprintf (dump_file, " with const ");
986       print_generic_expr (dump_file, const_val, 0);
987       fprintf (dump_file, "\n");
988     }
989   replace_map->old_tree = parm_tree;
990   replace_map->new_tree = const_val;
991   replace_map->replace_p = true;
992   replace_map->ref_p = false;
993
994   return replace_map;
995 }
996
997 /* Return true if this callsite should be redirected to the original callee
998    (instead of the cloned one).  */
999 static bool
1000 ipcp_need_redirect_p (struct cgraph_edge *cs)
1001 {
1002   struct ipa_node_params *orig_callee_info;
1003   int i, count;
1004   struct cgraph_node *node = cs->callee, *orig;
1005
1006   if (!n_cloning_candidates)
1007     return false;
1008
1009   if ((orig = ipcp_get_orig_node (node)) != NULL)
1010     node = orig;
1011   if (ipcp_get_orig_node (cs->caller))
1012     return false;
1013
1014   orig_callee_info = IPA_NODE_REF (node);
1015   count = ipa_get_param_count (orig_callee_info);
1016   for (i = 0; i < count; i++)
1017     {
1018       struct ipcp_lattice *lat = ipcp_get_lattice (orig_callee_info, i);
1019       struct ipa_jump_func *jump_func;
1020
1021       jump_func = ipa_get_ith_jump_func (IPA_EDGE_REF (cs), i);
1022       if ((ipcp_lat_is_const (lat)
1023            && jump_func->type != IPA_JF_CONST)
1024           || (!ipa_param_cannot_devirtualize_p (orig_callee_info, i)
1025               && !ipa_param_types_vec_empty (orig_callee_info, i)
1026               && jump_func->type != IPA_JF_CONST
1027               && jump_func->type != IPA_JF_KNOWN_TYPE))
1028         return true;
1029     }
1030
1031   return false;
1032 }
1033
1034 /* Fix the callsites and the call graph after function cloning was done.  */
1035 static void
1036 ipcp_update_callgraph (void)
1037 {
1038   struct cgraph_node *node;
1039
1040   for (node = cgraph_nodes; node; node = node->next)
1041     if (node->analyzed && ipcp_node_is_clone (node))
1042       {
1043         bitmap args_to_skip = BITMAP_ALLOC (NULL);
1044         struct cgraph_node *orig_node = ipcp_get_orig_node (node);
1045         struct ipa_node_params *info = IPA_NODE_REF (orig_node);
1046         int i, count = ipa_get_param_count (info);
1047         struct cgraph_edge *cs, *next;
1048
1049         for (i = 0; i < count; i++)
1050           {
1051             struct ipcp_lattice *lat = ipcp_get_lattice (info, i);
1052
1053             /* We can proactively remove obviously unused arguments.  */
1054             if (!ipa_is_param_used (info, i))
1055               {
1056                 bitmap_set_bit (args_to_skip, i);
1057                 continue;
1058               }
1059
1060             if (lat->type == IPA_CONST_VALUE)
1061               bitmap_set_bit (args_to_skip, i);
1062           }
1063         for (cs = node->callers; cs; cs = next)
1064           {
1065             next = cs->next_caller;
1066             if (!ipcp_node_is_clone (cs->caller) && ipcp_need_redirect_p (cs))
1067               {
1068                 if (dump_file)
1069                   fprintf (dump_file, "Redirecting edge %s/%i -> %s/%i "
1070                            "back to %s/%i.",
1071                            cgraph_node_name (cs->caller), cs->caller->uid,
1072                            cgraph_node_name (cs->callee), cs->callee->uid,
1073                            cgraph_node_name (orig_node), orig_node->uid);
1074                 cgraph_redirect_edge_callee (cs, orig_node);
1075               }
1076           }
1077       }
1078 }
1079
1080 /* Update profiling info for versioned functions and the functions they were
1081    versioned from.  */
1082 static void
1083 ipcp_update_profiling (void)
1084 {
1085   struct cgraph_node *node, *orig_node;
1086   gcov_type scale, scale_complement;
1087   struct cgraph_edge *cs;
1088
1089   for (node = cgraph_nodes; node; node = node->next)
1090     {
1091       if (ipcp_node_is_clone (node))
1092         {
1093           orig_node = ipcp_get_orig_node (node);
1094           scale = ipcp_get_node_scale (orig_node);
1095           node->count = orig_node->count * scale / REG_BR_PROB_BASE;
1096           scale_complement = REG_BR_PROB_BASE - scale;
1097           orig_node->count =
1098             orig_node->count * scale_complement / REG_BR_PROB_BASE;
1099           for (cs = node->callees; cs; cs = cs->next_callee)
1100             cs->count = cs->count * scale / REG_BR_PROB_BASE;
1101           for (cs = orig_node->callees; cs; cs = cs->next_callee)
1102             cs->count = cs->count * scale_complement / REG_BR_PROB_BASE;
1103         }
1104     }
1105 }
1106
1107 /* If NODE was cloned, how much would program grow? */
1108 static long
1109 ipcp_estimate_growth (struct cgraph_node *node)
1110 {
1111   struct cgraph_edge *cs;
1112   int redirectable_node_callers = 0;
1113   int removable_args = 0;
1114   bool need_original
1115      = !cgraph_will_be_removed_from_program_if_no_direct_calls (node);
1116   struct ipa_node_params *info;
1117   int i, count;
1118   int growth;
1119
1120   for (cs = node->callers; cs != NULL; cs = cs->next_caller)
1121     if (cs->caller == node || !ipcp_need_redirect_p (cs))
1122       redirectable_node_callers++;
1123     else
1124       need_original = true;
1125
1126   /* If we will be able to fully replace orignal node, we never increase
1127      program size.  */
1128   if (!need_original)
1129     return 0;
1130
1131   info = IPA_NODE_REF (node);
1132   count = ipa_get_param_count (info);
1133   for (i = 0; i < count; i++)
1134     {
1135       struct ipcp_lattice *lat = ipcp_get_lattice (info, i);
1136
1137       /* We can proactively remove obviously unused arguments.  */
1138       if (!ipa_is_param_used (info, i))
1139         removable_args++;
1140
1141       if (lat->type == IPA_CONST_VALUE)
1142         removable_args++;
1143     }
1144
1145   /* We make just very simple estimate of savings for removal of operand from
1146      call site.  Precise cost is dificult to get, as our size metric counts
1147      constants and moves as free.  Generally we are looking for cases that
1148      small function is called very many times.  */
1149   growth = node->local.inline_summary.self_size
1150            - removable_args * redirectable_node_callers;
1151   if (growth < 0)
1152     return 0;
1153   return growth;
1154 }
1155
1156
1157 /* Estimate cost of cloning NODE.  */
1158 static long
1159 ipcp_estimate_cloning_cost (struct cgraph_node *node)
1160 {
1161   int freq_sum = 1;
1162   gcov_type count_sum = 1;
1163   struct cgraph_edge *e;
1164   int cost;
1165
1166   cost = ipcp_estimate_growth (node) * 1000;
1167   if (!cost)
1168     {
1169       if (dump_file)
1170         fprintf (dump_file, "Versioning of %s will save code size\n",
1171                  cgraph_node_name (node));
1172       return 0;
1173     }
1174
1175   for (e = node->callers; e; e = e->next_caller)
1176     if (!bitmap_bit_p (dead_nodes, e->caller->uid)
1177         && !ipcp_need_redirect_p (e))
1178       {
1179         count_sum += e->count;
1180         freq_sum += e->frequency + 1;
1181       }
1182
1183   if (max_count)
1184     cost /= count_sum * 1000 / max_count + 1;
1185   else
1186     cost /= freq_sum * 1000 / REG_BR_PROB_BASE + 1;
1187   if (dump_file)
1188     fprintf (dump_file, "Cost of versioning %s is %i, (size: %i, freq: %i)\n",
1189              cgraph_node_name (node), cost, node->local.inline_summary.self_size,
1190              freq_sum);
1191   return cost + 1;
1192 }
1193
1194 /* Walk indirect calls of NODE and if any polymorphic can be turned into a
1195    direct one now, do so.  */
1196
1197 static void
1198 ipcp_process_devirtualization_opportunities (struct cgraph_node *node)
1199 {
1200   struct ipa_node_params *info = IPA_NODE_REF (node);
1201   struct cgraph_edge *ie, *next_ie;
1202
1203   for (ie = node->indirect_calls; ie; ie = next_ie)
1204     {
1205       int param_index, types_count, j;
1206       HOST_WIDE_INT token;
1207       tree target;
1208
1209       next_ie = ie->next_callee;
1210       if (!ie->indirect_info->polymorphic)
1211         continue;
1212       param_index = ie->indirect_info->param_index;
1213       if (param_index == -1
1214           || ipa_param_cannot_devirtualize_p (info, param_index)
1215           || ipa_param_types_vec_empty (info, param_index))
1216         continue;
1217
1218       token = ie->indirect_info->otr_token;
1219       target = NULL_TREE;
1220       types_count = VEC_length (tree, info->params[param_index].types);
1221       for (j = 0; j < types_count; j++)
1222         {
1223           tree binfo = VEC_index (tree, info->params[param_index].types, j);
1224           tree t = gimple_fold_obj_type_ref_known_binfo (token, binfo);
1225
1226           if (!t)
1227             {
1228               target = NULL_TREE;
1229               break;
1230             }
1231           else if (!target)
1232             target = t;
1233           else if (target != t)
1234             {
1235               target = NULL_TREE;
1236               break;
1237             }
1238         }
1239
1240       if (target)
1241         ipa_make_edge_direct_to_target (ie, target);
1242     }
1243 }
1244
1245 /* Return number of live constant parameters.  */
1246 static int
1247 ipcp_const_param_count (struct cgraph_node *node)
1248 {
1249   int const_param = 0;
1250   struct ipa_node_params *info = IPA_NODE_REF (node);
1251   int count = ipa_get_param_count (info);
1252   int i;
1253
1254   for (i = 0; i < count; i++)
1255     {
1256       struct ipcp_lattice *lat = ipcp_get_lattice (info, i);
1257       if ((ipcp_lat_is_insertable (lat)
1258           /* Do not count obviously unused arguments.  */
1259            && ipa_is_param_used (info, i))
1260           || (!ipa_param_cannot_devirtualize_p (info, i)
1261               && !ipa_param_types_vec_empty (info, i)))
1262         const_param++;
1263     }
1264   return const_param;
1265 }
1266
1267 /* Given that a formal parameter of NODE given by INDEX is known to be constant
1268    CST, try to find any indirect edges that can be made direct and make them
1269    so.  Note that INDEX is the number the parameter at the time of analyzing
1270    parameter uses and parameter removals should not be considered for it.  (In
1271    fact, the parameter itself has just been removed.)  */
1272
1273 static void
1274 ipcp_discover_new_direct_edges (struct cgraph_node *node, int index, tree cst)
1275 {
1276   struct cgraph_edge *ie, *next_ie;
1277
1278   for (ie = node->indirect_calls; ie; ie = next_ie)
1279     {
1280       struct cgraph_indirect_call_info *ici = ie->indirect_info;
1281
1282       next_ie = ie->next_callee;
1283       if (ici->param_index != index)
1284         continue;
1285
1286       if (ici->polymorphic)
1287         {
1288           tree binfo;
1289           HOST_WIDE_INT token;
1290
1291           if (TREE_CODE (cst) != ADDR_EXPR)
1292             continue;
1293
1294           binfo = gimple_get_relevant_ref_binfo (TREE_OPERAND (cst, 0),
1295                                                  NULL_TREE);
1296           if (!binfo)
1297             continue;
1298           gcc_assert (ie->indirect_info->anc_offset == 0);
1299           token = ie->indirect_info->otr_token;
1300           cst = gimple_fold_obj_type_ref_known_binfo (token, binfo);
1301           if (!cst)
1302             continue;
1303         }
1304
1305       ipa_make_edge_direct_to_target (ie, cst);
1306     }
1307 }
1308
1309
1310 /* Propagate the constant parameters found by ipcp_iterate_stage()
1311    to the function's code.  */
1312 static void
1313 ipcp_insert_stage (void)
1314 {
1315   struct cgraph_node *node, *node1 = NULL;
1316   int i;
1317   VEC (cgraph_edge_p, heap) * redirect_callers;
1318   VEC (ipa_replace_map_p,gc)* replace_trees;
1319   int node_callers, count;
1320   tree parm_tree;
1321   struct ipa_replace_map *replace_param;
1322   fibheap_t heap;
1323   long overall_size = 0, new_size = 0;
1324   long max_new_size;
1325
1326   ipa_check_create_node_params ();
1327   ipa_check_create_edge_args ();
1328   if (dump_file)
1329     fprintf (dump_file, "\nIPA insert stage:\n\n");
1330
1331   dead_nodes = BITMAP_ALLOC (NULL);
1332
1333   for (node = cgraph_nodes; node; node = node->next)
1334     if (node->analyzed)
1335       {
1336         if (node->count > max_count)
1337           max_count = node->count;
1338         overall_size += node->local.inline_summary.self_size;
1339       }
1340
1341   max_new_size = overall_size;
1342   if (max_new_size < PARAM_VALUE (PARAM_LARGE_UNIT_INSNS))
1343     max_new_size = PARAM_VALUE (PARAM_LARGE_UNIT_INSNS);
1344   max_new_size = max_new_size * PARAM_VALUE (PARAM_IPCP_UNIT_GROWTH) / 100 + 1;
1345
1346   /* First collect all functions we proved to have constant arguments to
1347      heap.  */
1348   heap = fibheap_new ();
1349   for (node = cgraph_nodes; node; node = node->next)
1350     {
1351       struct ipa_node_params *info;
1352       /* Propagation of the constant is forbidden in certain conditions.  */
1353       if (!node->analyzed || !ipcp_node_modifiable_p (node))
1354           continue;
1355       info = IPA_NODE_REF (node);
1356       if (ipa_is_called_with_var_arguments (info))
1357         continue;
1358       if (ipcp_const_param_count (node))
1359         node->aux = fibheap_insert (heap, ipcp_estimate_cloning_cost (node),
1360                                     node);
1361      }
1362
1363   /* Now clone in priority order until code size growth limits are met or
1364      heap is emptied.  */
1365   while (!fibheap_empty (heap))
1366     {
1367       struct ipa_node_params *info;
1368       int growth = 0;
1369       bitmap args_to_skip;
1370       struct cgraph_edge *cs;
1371
1372       node = (struct cgraph_node *)fibheap_extract_min (heap);
1373       node->aux = NULL;
1374       if (dump_file)
1375         fprintf (dump_file, "considering function %s\n",
1376                  cgraph_node_name (node));
1377
1378       growth = ipcp_estimate_growth (node);
1379
1380       if (new_size + growth > max_new_size)
1381         break;
1382       if (growth
1383           && optimize_function_for_size_p (DECL_STRUCT_FUNCTION (node->decl)))
1384         {
1385           if (dump_file)
1386             fprintf (dump_file, "Not versioning, cold code would grow");
1387           continue;
1388         }
1389
1390       new_size += growth;
1391
1392       /* Look if original function becomes dead after clonning.  */
1393       for (cs = node->callers; cs != NULL; cs = cs->next_caller)
1394         if (cs->caller == node || ipcp_need_redirect_p (cs))
1395           break;
1396       if (!cs && cgraph_will_be_removed_from_program_if_no_direct_calls (node))
1397         bitmap_set_bit (dead_nodes, node->uid);
1398
1399       info = IPA_NODE_REF (node);
1400       count = ipa_get_param_count (info);
1401
1402       replace_trees = VEC_alloc (ipa_replace_map_p, gc, 1);
1403       args_to_skip = BITMAP_GGC_ALLOC ();
1404       for (i = 0; i < count; i++)
1405         {
1406           struct ipcp_lattice *lat = ipcp_get_lattice (info, i);
1407           parm_tree = ipa_get_param (info, i);
1408
1409           /* We can proactively remove obviously unused arguments.  */
1410           if (!ipa_is_param_used (info, i))
1411             {
1412               bitmap_set_bit (args_to_skip, i);
1413               continue;
1414             }
1415
1416           if (lat->type == IPA_CONST_VALUE)
1417             {
1418               replace_param =
1419                 ipcp_create_replace_map (parm_tree, lat);
1420               VEC_safe_push (ipa_replace_map_p, gc, replace_trees, replace_param);
1421               bitmap_set_bit (args_to_skip, i);
1422             }
1423         }
1424
1425       /* Compute how many callers node has.  */
1426       node_callers = 0;
1427       for (cs = node->callers; cs != NULL; cs = cs->next_caller)
1428         node_callers++;
1429       redirect_callers = VEC_alloc (cgraph_edge_p, heap, node_callers);
1430       for (cs = node->callers; cs != NULL; cs = cs->next_caller)
1431         if (!cs->indirect_inlining_edge)
1432           VEC_quick_push (cgraph_edge_p, redirect_callers, cs);
1433
1434       /* Redirecting all the callers of the node to the
1435          new versioned node.  */
1436       node1 =
1437         cgraph_create_virtual_clone (node, redirect_callers, replace_trees,
1438                                      args_to_skip, "constprop");
1439       args_to_skip = NULL;
1440       VEC_free (cgraph_edge_p, heap, redirect_callers);
1441       replace_trees = NULL;
1442
1443       if (node1 == NULL)
1444         continue;
1445       ipcp_process_devirtualization_opportunities (node1);
1446
1447       if (dump_file)
1448         fprintf (dump_file, "versioned function %s with growth %i, overall %i\n",
1449                  cgraph_node_name (node), (int)growth, (int)new_size);
1450       ipcp_init_cloned_node (node, node1);
1451
1452       info = IPA_NODE_REF (node);
1453       for (i = 0; i < count; i++)
1454         {
1455           struct ipcp_lattice *lat = ipcp_get_lattice (info, i);
1456           if (lat->type == IPA_CONST_VALUE)
1457             ipcp_discover_new_direct_edges (node1, i, lat->constant);
1458         }
1459
1460       if (dump_file)
1461         dump_function_to_file (node1->decl, dump_file, dump_flags);
1462
1463       for (cs = node->callees; cs; cs = cs->next_callee)
1464         if (cs->callee->aux)
1465           {
1466             fibheap_delete_node (heap, (fibnode_t) cs->callee->aux);
1467             cs->callee->aux = fibheap_insert (heap,
1468                                               ipcp_estimate_cloning_cost (cs->callee),
1469                                               cs->callee);
1470           }
1471     }
1472
1473   while (!fibheap_empty (heap))
1474     {
1475       if (dump_file)
1476         fprintf (dump_file, "skipping function %s\n",
1477                  cgraph_node_name (node));
1478       node = (struct cgraph_node *) fibheap_extract_min (heap);
1479       node->aux = NULL;
1480     }
1481   fibheap_delete (heap);
1482   BITMAP_FREE (dead_nodes);
1483   ipcp_update_callgraph ();
1484   ipcp_update_profiling ();
1485 }
1486
1487 /* The IPCP driver.  */
1488 static unsigned int
1489 ipcp_driver (void)
1490 {
1491   cgraph_remove_unreachable_nodes (true,dump_file);
1492   if (dump_file)
1493     {
1494       fprintf (dump_file, "\nIPA structures before propagation:\n");
1495       if (dump_flags & TDF_DETAILS)
1496         ipa_print_all_params (dump_file);
1497       ipa_print_all_jump_functions (dump_file);
1498     }
1499   /* 2. Do the interprocedural propagation.  */
1500   ipcp_iterate_stage ();
1501   /* 3. Insert the constants found to the functions.  */
1502   ipcp_insert_stage ();
1503   if (dump_file && (dump_flags & TDF_DETAILS))
1504     {
1505       fprintf (dump_file, "\nProfiling info after insert stage:\n");
1506       ipcp_print_profile_data (dump_file);
1507     }
1508   /* Free all IPCP structures.  */
1509   ipa_free_all_structures_after_ipa_cp ();
1510   if (dump_file)
1511     fprintf (dump_file, "\nIPA constant propagation end\n");
1512   return 0;
1513 }
1514
1515 /* Initialization and computation of IPCP data structures.  This is the initial
1516    intraprocedural analysis of functions, which gathers information to be
1517    propagated later on.  */
1518
1519 static void
1520 ipcp_generate_summary (void)
1521 {
1522   struct cgraph_node *node;
1523
1524   if (dump_file)
1525     fprintf (dump_file, "\nIPA constant propagation start:\n");
1526   ipa_check_create_node_params ();
1527   ipa_check_create_edge_args ();
1528   ipa_register_cgraph_hooks ();
1529
1530   for (node = cgraph_nodes; node; node = node->next)
1531     if (node->analyzed)
1532       {
1533         /* Unreachable nodes should have been eliminated before ipcp.  */
1534         gcc_assert (node->needed || node->reachable);
1535
1536         node->local.versionable = tree_versionable_function_p (node->decl);
1537         ipa_analyze_node (node);
1538       }
1539 }
1540
1541 /* Write ipcp summary for nodes in SET.  */
1542 static void
1543 ipcp_write_summary (cgraph_node_set set,
1544                     varpool_node_set vset ATTRIBUTE_UNUSED)
1545 {
1546   ipa_prop_write_jump_functions (set);
1547 }
1548
1549 /* Read ipcp summary.  */
1550 static void
1551 ipcp_read_summary (void)
1552 {
1553   ipa_prop_read_jump_functions ();
1554 }
1555
1556 /* Gate for IPCP optimization.  */
1557 static bool
1558 cgraph_gate_cp (void)
1559 {
1560   /* FIXME: We should remove the optimize check after we ensure we never run
1561      IPA passes when not optimizng.  */
1562   return flag_ipa_cp && optimize;
1563 }
1564
1565 struct ipa_opt_pass_d pass_ipa_cp =
1566 {
1567  {
1568   IPA_PASS,
1569   "cp",                         /* name */
1570   cgraph_gate_cp,               /* gate */
1571   ipcp_driver,                  /* execute */
1572   NULL,                         /* sub */
1573   NULL,                         /* next */
1574   0,                            /* static_pass_number */
1575   TV_IPA_CONSTANT_PROP,         /* tv_id */
1576   0,                            /* properties_required */
1577   0,                            /* properties_provided */
1578   0,                            /* properties_destroyed */
1579   0,                            /* todo_flags_start */
1580   TODO_dump_cgraph | TODO_dump_func |
1581   TODO_remove_functions | TODO_ggc_collect /* todo_flags_finish */
1582  },
1583  ipcp_generate_summary,                 /* generate_summary */
1584  ipcp_write_summary,                    /* write_summary */
1585  ipcp_read_summary,                     /* read_summary */
1586  NULL,                                  /* write_optimization_summary */
1587  NULL,                                  /* read_optimization_summary */
1588  NULL,                                  /* stmt_fixup */
1589  0,                                     /* TODOs */
1590  NULL,                                  /* function_transform */
1591  NULL,                                  /* variable_transform */
1592 };