OSDN Git Service

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