Update gcc-50 to SVN version 222321 (gcc-5-branch)
[dragonfly.git] / contrib / gcc-5.0 / gcc / ipa-inline-analysis.c
1 /* Inlining decision heuristics.
2    Copyright (C) 2003-2015 Free Software Foundation, Inc.
3    Contributed by Jan Hubicka
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 /* Analysis used by the inliner and other passes limiting code size growth.
22
23    We estimate for each function
24      - function body size
25      - average function execution time
26      - inlining size benefit (that is how much of function body size
27        and its call sequence is expected to disappear by inlining)
28      - inlining time benefit
29      - function frame size
30    For each call
31      - call statement size and time
32
33    inlinie_summary datastructures store above information locally (i.e.
34    parameters of the function itself) and globally (i.e. parameters of
35    the function created by applying all the inline decisions already
36    present in the callgraph).
37
38    We provide accestor to the inline_summary datastructure and
39    basic logic updating the parameters when inlining is performed. 
40
41    The summaries are context sensitive.  Context means
42      1) partial assignment of known constant values of operands
43      2) whether function is inlined into the call or not.
44    It is easy to add more variants.  To represent function size and time
45    that depends on context (i.e. it is known to be optimized away when
46    context is known either by inlining or from IP-CP and clonning),
47    we use predicates. Predicates are logical formulas in
48    conjunctive-disjunctive form consisting of clauses. Clauses are bitmaps
49    specifying what conditions must be true. Conditions are simple test
50    of the form described above.
51
52    In order to make predicate (possibly) true, all of its clauses must
53    be (possibly) true. To make clause (possibly) true, one of conditions
54    it mentions must be (possibly) true.  There are fixed bounds on
55    number of clauses and conditions and all the manipulation functions
56    are conservative in positive direction. I.e. we may lose precision
57    by thinking that predicate may be true even when it is not.
58
59    estimate_edge_size and estimate_edge_growth can be used to query
60    function size/time in the given context.  inline_merge_summary merges
61    properties of caller and callee after inlining.
62
63    Finally pass_inline_parameters is exported.  This is used to drive
64    computation of function parameters used by the early inliner. IPA
65    inlined performs analysis via its analyze_function method. */
66
67 #include "config.h"
68 #include "system.h"
69 #include "coretypes.h"
70 #include "tm.h"
71 #include "hash-set.h"
72 #include "machmode.h"
73 #include "vec.h"
74 #include "double-int.h"
75 #include "input.h"
76 #include "alias.h"
77 #include "symtab.h"
78 #include "wide-int.h"
79 #include "inchash.h"
80 #include "real.h"
81 #include "tree.h"
82 #include "fold-const.h"
83 #include "stor-layout.h"
84 #include "stringpool.h"
85 #include "print-tree.h"
86 #include "tree-inline.h"
87 #include "langhooks.h"
88 #include "flags.h"
89 #include "diagnostic.h"
90 #include "gimple-pretty-print.h"
91 #include "params.h"
92 #include "tree-pass.h"
93 #include "coverage.h"
94 #include "predict.h"
95 #include "hard-reg-set.h"
96 #include "input.h"
97 #include "function.h"
98 #include "dominance.h"
99 #include "cfg.h"
100 #include "cfganal.h"
101 #include "basic-block.h"
102 #include "tree-ssa-alias.h"
103 #include "internal-fn.h"
104 #include "gimple-expr.h"
105 #include "is-a.h"
106 #include "gimple.h"
107 #include "gimple-iterator.h"
108 #include "gimple-ssa.h"
109 #include "tree-cfg.h"
110 #include "tree-phinodes.h"
111 #include "ssa-iterators.h"
112 #include "tree-ssanames.h"
113 #include "tree-ssa-loop-niter.h"
114 #include "tree-ssa-loop.h"
115 #include "hash-map.h"
116 #include "plugin-api.h"
117 #include "ipa-ref.h"
118 #include "cgraph.h"
119 #include "alloc-pool.h"
120 #include "symbol-summary.h"
121 #include "ipa-prop.h"
122 #include "lto-streamer.h"
123 #include "data-streamer.h"
124 #include "tree-streamer.h"
125 #include "ipa-inline.h"
126 #include "cfgloop.h"
127 #include "tree-scalar-evolution.h"
128 #include "ipa-utils.h"
129 #include "cilk.h"
130 #include "cfgexpand.h"
131
132 /* Estimate runtime of function can easilly run into huge numbers with many
133    nested loops.  Be sure we can compute time * INLINE_SIZE_SCALE * 2 in an
134    integer.  For anything larger we use gcov_type.  */
135 #define MAX_TIME 500000
136
137 /* Number of bits in integer, but we really want to be stable across different
138    hosts.  */
139 #define NUM_CONDITIONS 32
140
141 enum predicate_conditions
142 {
143   predicate_false_condition = 0,
144   predicate_not_inlined_condition = 1,
145   predicate_first_dynamic_condition = 2
146 };
147
148 /* Special condition code we use to represent test that operand is compile time
149    constant.  */
150 #define IS_NOT_CONSTANT ERROR_MARK
151 /* Special condition code we use to represent test that operand is not changed
152    across invocation of the function.  When operand IS_NOT_CONSTANT it is always
153    CHANGED, however i.e. loop invariants can be NOT_CHANGED given percentage
154    of executions even when they are not compile time constants.  */
155 #define CHANGED IDENTIFIER_NODE
156
157 /* Holders of ipa cgraph hooks: */
158 static struct cgraph_2edge_hook_list *edge_duplication_hook_holder;
159 static struct cgraph_edge_hook_list *edge_removal_hook_holder;
160 static void inline_edge_removal_hook (struct cgraph_edge *, void *);
161 static void inline_edge_duplication_hook (struct cgraph_edge *,
162                                           struct cgraph_edge *, void *);
163
164 /* VECtor holding inline summaries.  
165    In GGC memory because conditions might point to constant trees.  */
166 function_summary <inline_summary *> *inline_summaries;
167 vec<inline_edge_summary_t> inline_edge_summary_vec;
168
169 /* Cached node/edge growths.  */
170 vec<edge_growth_cache_entry> edge_growth_cache;
171
172 /* Edge predicates goes here.  */
173 static alloc_pool edge_predicate_pool;
174
175 /* Return true predicate (tautology).
176    We represent it by empty list of clauses.  */
177
178 static inline struct predicate
179 true_predicate (void)
180 {
181   struct predicate p;
182   p.clause[0] = 0;
183   return p;
184 }
185
186
187 /* Return predicate testing single condition number COND.  */
188
189 static inline struct predicate
190 single_cond_predicate (int cond)
191 {
192   struct predicate p;
193   p.clause[0] = 1 << cond;
194   p.clause[1] = 0;
195   return p;
196 }
197
198
199 /* Return false predicate.  First clause require false condition.  */
200
201 static inline struct predicate
202 false_predicate (void)
203 {
204   return single_cond_predicate (predicate_false_condition);
205 }
206
207
208 /* Return true if P is (true).  */
209
210 static inline bool
211 true_predicate_p (struct predicate *p)
212 {
213   return !p->clause[0];
214 }
215
216
217 /* Return true if P is (false).  */
218
219 static inline bool
220 false_predicate_p (struct predicate *p)
221 {
222   if (p->clause[0] == (1 << predicate_false_condition))
223     {
224       gcc_checking_assert (!p->clause[1]
225                            && p->clause[0] == 1 << predicate_false_condition);
226       return true;
227     }
228   return false;
229 }
230
231
232 /* Return predicate that is set true when function is not inlined.  */
233
234 static inline struct predicate
235 not_inlined_predicate (void)
236 {
237   return single_cond_predicate (predicate_not_inlined_condition);
238 }
239
240 /* Simple description of whether a memory load or a condition refers to a load
241    from an aggregate and if so, how and where from in the aggregate.
242    Individual fields have the same meaning like fields with the same name in
243    struct condition.  */
244
245 struct agg_position_info
246 {
247   HOST_WIDE_INT offset;
248   bool agg_contents;
249   bool by_ref;
250 };
251
252 /* Add condition to condition list CONDS.  AGGPOS describes whether the used
253    oprand is loaded from an aggregate and where in the aggregate it is.  It can
254    be NULL, which means this not a load from an aggregate.  */
255
256 static struct predicate
257 add_condition (struct inline_summary *summary, int operand_num,
258                struct agg_position_info *aggpos,
259                enum tree_code code, tree val)
260 {
261   int i;
262   struct condition *c;
263   struct condition new_cond;
264   HOST_WIDE_INT offset;
265   bool agg_contents, by_ref;
266
267   if (aggpos)
268     {
269       offset = aggpos->offset;
270       agg_contents = aggpos->agg_contents;
271       by_ref = aggpos->by_ref;
272     }
273   else
274     {
275       offset = 0;
276       agg_contents = false;
277       by_ref = false;
278     }
279
280   gcc_checking_assert (operand_num >= 0);
281   for (i = 0; vec_safe_iterate (summary->conds, i, &c); i++)
282     {
283       if (c->operand_num == operand_num
284           && c->code == code
285           && c->val == val
286           && c->agg_contents == agg_contents
287           && (!agg_contents || (c->offset == offset && c->by_ref == by_ref)))
288         return single_cond_predicate (i + predicate_first_dynamic_condition);
289     }
290   /* Too many conditions.  Give up and return constant true.  */
291   if (i == NUM_CONDITIONS - predicate_first_dynamic_condition)
292     return true_predicate ();
293
294   new_cond.operand_num = operand_num;
295   new_cond.code = code;
296   new_cond.val = val;
297   new_cond.agg_contents = agg_contents;
298   new_cond.by_ref = by_ref;
299   new_cond.offset = offset;
300   vec_safe_push (summary->conds, new_cond);
301   return single_cond_predicate (i + predicate_first_dynamic_condition);
302 }
303
304
305 /* Add clause CLAUSE into the predicate P.  */
306
307 static inline void
308 add_clause (conditions conditions, struct predicate *p, clause_t clause)
309 {
310   int i;
311   int i2;
312   int insert_here = -1;
313   int c1, c2;
314
315   /* True clause.  */
316   if (!clause)
317     return;
318
319   /* False clause makes the whole predicate false.  Kill the other variants.  */
320   if (clause == (1 << predicate_false_condition))
321     {
322       p->clause[0] = (1 << predicate_false_condition);
323       p->clause[1] = 0;
324       return;
325     }
326   if (false_predicate_p (p))
327     return;
328
329   /* No one should be silly enough to add false into nontrivial clauses.  */
330   gcc_checking_assert (!(clause & (1 << predicate_false_condition)));
331
332   /* Look where to insert the clause.  At the same time prune out
333      clauses of P that are implied by the new clause and thus
334      redundant.  */
335   for (i = 0, i2 = 0; i <= MAX_CLAUSES; i++)
336     {
337       p->clause[i2] = p->clause[i];
338
339       if (!p->clause[i])
340         break;
341
342       /* If p->clause[i] implies clause, there is nothing to add.  */
343       if ((p->clause[i] & clause) == p->clause[i])
344         {
345           /* We had nothing to add, none of clauses should've become
346              redundant.  */
347           gcc_checking_assert (i == i2);
348           return;
349         }
350
351       if (p->clause[i] < clause && insert_here < 0)
352         insert_here = i2;
353
354       /* If clause implies p->clause[i], then p->clause[i] becomes redundant.
355          Otherwise the p->clause[i] has to stay.  */
356       if ((p->clause[i] & clause) != clause)
357         i2++;
358     }
359
360   /* Look for clauses that are obviously true.  I.e.
361      op0 == 5 || op0 != 5.  */
362   for (c1 = predicate_first_dynamic_condition; c1 < NUM_CONDITIONS; c1++)
363     {
364       condition *cc1;
365       if (!(clause & (1 << c1)))
366         continue;
367       cc1 = &(*conditions)[c1 - predicate_first_dynamic_condition];
368       /* We have no way to represent !CHANGED and !IS_NOT_CONSTANT
369          and thus there is no point for looking for them.  */
370       if (cc1->code == CHANGED || cc1->code == IS_NOT_CONSTANT)
371         continue;
372       for (c2 = c1 + 1; c2 < NUM_CONDITIONS; c2++)
373         if (clause & (1 << c2))
374           {
375             condition *cc1 =
376               &(*conditions)[c1 - predicate_first_dynamic_condition];
377             condition *cc2 =
378               &(*conditions)[c2 - predicate_first_dynamic_condition];
379             if (cc1->operand_num == cc2->operand_num
380                 && cc1->val == cc2->val
381                 && cc2->code != IS_NOT_CONSTANT
382                 && cc2->code != CHANGED
383                 && cc1->code == invert_tree_comparison (cc2->code,
384                                                         HONOR_NANS (cc1->val)))
385               return;
386           }
387     }
388
389
390   /* We run out of variants.  Be conservative in positive direction.  */
391   if (i2 == MAX_CLAUSES)
392     return;
393   /* Keep clauses in decreasing order. This makes equivalence testing easy.  */
394   p->clause[i2 + 1] = 0;
395   if (insert_here >= 0)
396     for (; i2 > insert_here; i2--)
397       p->clause[i2] = p->clause[i2 - 1];
398   else
399     insert_here = i2;
400   p->clause[insert_here] = clause;
401 }
402
403
404 /* Return P & P2.  */
405
406 static struct predicate
407 and_predicates (conditions conditions,
408                 struct predicate *p, struct predicate *p2)
409 {
410   struct predicate out = *p;
411   int i;
412
413   /* Avoid busy work.  */
414   if (false_predicate_p (p2) || true_predicate_p (p))
415     return *p2;
416   if (false_predicate_p (p) || true_predicate_p (p2))
417     return *p;
418
419   /* See how far predicates match.  */
420   for (i = 0; p->clause[i] && p->clause[i] == p2->clause[i]; i++)
421     {
422       gcc_checking_assert (i < MAX_CLAUSES);
423     }
424
425   /* Combine the predicates rest.  */
426   for (; p2->clause[i]; i++)
427     {
428       gcc_checking_assert (i < MAX_CLAUSES);
429       add_clause (conditions, &out, p2->clause[i]);
430     }
431   return out;
432 }
433
434
435 /* Return true if predicates are obviously equal.  */
436
437 static inline bool
438 predicates_equal_p (struct predicate *p, struct predicate *p2)
439 {
440   int i;
441   for (i = 0; p->clause[i]; i++)
442     {
443       gcc_checking_assert (i < MAX_CLAUSES);
444       gcc_checking_assert (p->clause[i] > p->clause[i + 1]);
445       gcc_checking_assert (!p2->clause[i]
446                            || p2->clause[i] > p2->clause[i + 1]);
447       if (p->clause[i] != p2->clause[i])
448         return false;
449     }
450   return !p2->clause[i];
451 }
452
453
454 /* Return P | P2.  */
455
456 static struct predicate
457 or_predicates (conditions conditions,
458                struct predicate *p, struct predicate *p2)
459 {
460   struct predicate out = true_predicate ();
461   int i, j;
462
463   /* Avoid busy work.  */
464   if (false_predicate_p (p2) || true_predicate_p (p))
465     return *p;
466   if (false_predicate_p (p) || true_predicate_p (p2))
467     return *p2;
468   if (predicates_equal_p (p, p2))
469     return *p;
470
471   /* OK, combine the predicates.  */
472   for (i = 0; p->clause[i]; i++)
473     for (j = 0; p2->clause[j]; j++)
474       {
475         gcc_checking_assert (i < MAX_CLAUSES && j < MAX_CLAUSES);
476         add_clause (conditions, &out, p->clause[i] | p2->clause[j]);
477       }
478   return out;
479 }
480
481
482 /* Having partial truth assignment in POSSIBLE_TRUTHS, return false
483    if predicate P is known to be false.  */
484
485 static bool
486 evaluate_predicate (struct predicate *p, clause_t possible_truths)
487 {
488   int i;
489
490   /* True remains true.  */
491   if (true_predicate_p (p))
492     return true;
493
494   gcc_assert (!(possible_truths & (1 << predicate_false_condition)));
495
496   /* See if we can find clause we can disprove.  */
497   for (i = 0; p->clause[i]; i++)
498     {
499       gcc_checking_assert (i < MAX_CLAUSES);
500       if (!(p->clause[i] & possible_truths))
501         return false;
502     }
503   return true;
504 }
505
506 /* Return the probability in range 0...REG_BR_PROB_BASE that the predicated
507    instruction will be recomputed per invocation of the inlined call.  */
508
509 static int
510 predicate_probability (conditions conds,
511                        struct predicate *p, clause_t possible_truths,
512                        vec<inline_param_summary> inline_param_summary)
513 {
514   int i;
515   int combined_prob = REG_BR_PROB_BASE;
516
517   /* True remains true.  */
518   if (true_predicate_p (p))
519     return REG_BR_PROB_BASE;
520
521   if (false_predicate_p (p))
522     return 0;
523
524   gcc_assert (!(possible_truths & (1 << predicate_false_condition)));
525
526   /* See if we can find clause we can disprove.  */
527   for (i = 0; p->clause[i]; i++)
528     {
529       gcc_checking_assert (i < MAX_CLAUSES);
530       if (!(p->clause[i] & possible_truths))
531         return 0;
532       else
533         {
534           int this_prob = 0;
535           int i2;
536           if (!inline_param_summary.exists ())
537             return REG_BR_PROB_BASE;
538           for (i2 = 0; i2 < NUM_CONDITIONS; i2++)
539             if ((p->clause[i] & possible_truths) & (1 << i2))
540               {
541                 if (i2 >= predicate_first_dynamic_condition)
542                   {
543                     condition *c =
544                       &(*conds)[i2 - predicate_first_dynamic_condition];
545                     if (c->code == CHANGED
546                         && (c->operand_num <
547                             (int) inline_param_summary.length ()))
548                       {
549                         int iprob =
550                           inline_param_summary[c->operand_num].change_prob;
551                         this_prob = MAX (this_prob, iprob);
552                       }
553                     else
554                       this_prob = REG_BR_PROB_BASE;
555                   }
556                 else
557                   this_prob = REG_BR_PROB_BASE;
558               }
559           combined_prob = MIN (this_prob, combined_prob);
560           if (!combined_prob)
561             return 0;
562         }
563     }
564   return combined_prob;
565 }
566
567
568 /* Dump conditional COND.  */
569
570 static void
571 dump_condition (FILE *f, conditions conditions, int cond)
572 {
573   condition *c;
574   if (cond == predicate_false_condition)
575     fprintf (f, "false");
576   else if (cond == predicate_not_inlined_condition)
577     fprintf (f, "not inlined");
578   else
579     {
580       c = &(*conditions)[cond - predicate_first_dynamic_condition];
581       fprintf (f, "op%i", c->operand_num);
582       if (c->agg_contents)
583         fprintf (f, "[%soffset: " HOST_WIDE_INT_PRINT_DEC "]",
584                  c->by_ref ? "ref " : "", c->offset);
585       if (c->code == IS_NOT_CONSTANT)
586         {
587           fprintf (f, " not constant");
588           return;
589         }
590       if (c->code == CHANGED)
591         {
592           fprintf (f, " changed");
593           return;
594         }
595       fprintf (f, " %s ", op_symbol_code (c->code));
596       print_generic_expr (f, c->val, 1);
597     }
598 }
599
600
601 /* Dump clause CLAUSE.  */
602
603 static void
604 dump_clause (FILE *f, conditions conds, clause_t clause)
605 {
606   int i;
607   bool found = false;
608   fprintf (f, "(");
609   if (!clause)
610     fprintf (f, "true");
611   for (i = 0; i < NUM_CONDITIONS; i++)
612     if (clause & (1 << i))
613       {
614         if (found)
615           fprintf (f, " || ");
616         found = true;
617         dump_condition (f, conds, i);
618       }
619   fprintf (f, ")");
620 }
621
622
623 /* Dump predicate PREDICATE.  */
624
625 static void
626 dump_predicate (FILE *f, conditions conds, struct predicate *pred)
627 {
628   int i;
629   if (true_predicate_p (pred))
630     dump_clause (f, conds, 0);
631   else
632     for (i = 0; pred->clause[i]; i++)
633       {
634         if (i)
635           fprintf (f, " && ");
636         dump_clause (f, conds, pred->clause[i]);
637       }
638   fprintf (f, "\n");
639 }
640
641
642 /* Dump inline hints.  */
643 void
644 dump_inline_hints (FILE *f, inline_hints hints)
645 {
646   if (!hints)
647     return;
648   fprintf (f, "inline hints:");
649   if (hints & INLINE_HINT_indirect_call)
650     {
651       hints &= ~INLINE_HINT_indirect_call;
652       fprintf (f, " indirect_call");
653     }
654   if (hints & INLINE_HINT_loop_iterations)
655     {
656       hints &= ~INLINE_HINT_loop_iterations;
657       fprintf (f, " loop_iterations");
658     }
659   if (hints & INLINE_HINT_loop_stride)
660     {
661       hints &= ~INLINE_HINT_loop_stride;
662       fprintf (f, " loop_stride");
663     }
664   if (hints & INLINE_HINT_same_scc)
665     {
666       hints &= ~INLINE_HINT_same_scc;
667       fprintf (f, " same_scc");
668     }
669   if (hints & INLINE_HINT_in_scc)
670     {
671       hints &= ~INLINE_HINT_in_scc;
672       fprintf (f, " in_scc");
673     }
674   if (hints & INLINE_HINT_cross_module)
675     {
676       hints &= ~INLINE_HINT_cross_module;
677       fprintf (f, " cross_module");
678     }
679   if (hints & INLINE_HINT_declared_inline)
680     {
681       hints &= ~INLINE_HINT_declared_inline;
682       fprintf (f, " declared_inline");
683     }
684   if (hints & INLINE_HINT_array_index)
685     {
686       hints &= ~INLINE_HINT_array_index;
687       fprintf (f, " array_index");
688     }
689   if (hints & INLINE_HINT_known_hot)
690     {
691       hints &= ~INLINE_HINT_known_hot;
692       fprintf (f, " known_hot");
693     }
694   gcc_assert (!hints);
695 }
696
697
698 /* Record SIZE and TIME under condition PRED into the inline summary.  */
699
700 static void
701 account_size_time (struct inline_summary *summary, int size, int time,
702                    struct predicate *pred)
703 {
704   size_time_entry *e;
705   bool found = false;
706   int i;
707
708   if (false_predicate_p (pred))
709     return;
710
711   /* We need to create initial empty unconitional clause, but otherwie
712      we don't need to account empty times and sizes.  */
713   if (!size && !time && summary->entry)
714     return;
715
716   /* Watch overflow that might result from insane profiles.  */
717   if (time > MAX_TIME * INLINE_TIME_SCALE)
718     time = MAX_TIME * INLINE_TIME_SCALE;
719   gcc_assert (time >= 0);
720
721   for (i = 0; vec_safe_iterate (summary->entry, i, &e); i++)
722     if (predicates_equal_p (&e->predicate, pred))
723       {
724         found = true;
725         break;
726       }
727   if (i == 256)
728     {
729       i = 0;
730       found = true;
731       e = &(*summary->entry)[0];
732       gcc_assert (!e->predicate.clause[0]);
733       if (dump_file && (dump_flags & TDF_DETAILS))
734         fprintf (dump_file,
735                  "\t\tReached limit on number of entries, "
736                  "ignoring the predicate.");
737     }
738   if (dump_file && (dump_flags & TDF_DETAILS) && (time || size))
739     {
740       fprintf (dump_file,
741                "\t\tAccounting size:%3.2f, time:%3.2f on %spredicate:",
742                ((double) size) / INLINE_SIZE_SCALE,
743                ((double) time) / INLINE_TIME_SCALE, found ? "" : "new ");
744       dump_predicate (dump_file, summary->conds, pred);
745     }
746   if (!found)
747     {
748       struct size_time_entry new_entry;
749       new_entry.size = size;
750       new_entry.time = time;
751       new_entry.predicate = *pred;
752       vec_safe_push (summary->entry, new_entry);
753     }
754   else
755     {
756       e->size += size;
757       e->time += time;
758       if (e->time > MAX_TIME * INLINE_TIME_SCALE)
759         e->time = MAX_TIME * INLINE_TIME_SCALE;
760     }
761 }
762
763 /* We proved E to be unreachable, redirect it to __bultin_unreachable.  */
764
765 static struct cgraph_edge *
766 redirect_to_unreachable (struct cgraph_edge *e)
767 {
768   struct cgraph_node *callee = !e->inline_failed ? e->callee : NULL;
769   struct cgraph_node *target = cgraph_node::get_create
770                       (builtin_decl_implicit (BUILT_IN_UNREACHABLE));
771
772   if (e->speculative)
773     e = e->resolve_speculation (target->decl);
774   else if (!e->callee)
775     e->make_direct (target);
776   else
777     e->redirect_callee (target);
778   struct inline_edge_summary *es = inline_edge_summary (e);
779   e->inline_failed = CIF_UNREACHABLE;
780   e->frequency = 0;
781   e->count = 0;
782   es->call_stmt_size = 0;
783   es->call_stmt_time = 0;
784   if (callee)
785     callee->remove_symbol_and_inline_clones ();
786   return e;
787 }
788
789 /* Set predicate for edge E.  */
790
791 static void
792 edge_set_predicate (struct cgraph_edge *e, struct predicate *predicate)
793 {
794   /* If the edge is determined to be never executed, redirect it
795      to BUILTIN_UNREACHABLE to save inliner from inlining into it.  */
796   if (predicate && false_predicate_p (predicate)
797       /* When handling speculative edges, we need to do the redirection
798          just once.  Do it always on the direct edge, so we do not
799          attempt to resolve speculation while duplicating the edge.  */
800       && (!e->speculative || e->callee))
801     e = redirect_to_unreachable (e);
802
803   struct inline_edge_summary *es = inline_edge_summary (e);
804   if (predicate && !true_predicate_p (predicate))
805     {
806       if (!es->predicate)
807         es->predicate = (struct predicate *) pool_alloc (edge_predicate_pool);
808       *es->predicate = *predicate;
809     }
810   else
811     {
812       if (es->predicate)
813         pool_free (edge_predicate_pool, es->predicate);
814       es->predicate = NULL;
815     }
816 }
817
818 /* Set predicate for hint *P.  */
819
820 static void
821 set_hint_predicate (struct predicate **p, struct predicate new_predicate)
822 {
823   if (false_predicate_p (&new_predicate) || true_predicate_p (&new_predicate))
824     {
825       if (*p)
826         pool_free (edge_predicate_pool, *p);
827       *p = NULL;
828     }
829   else
830     {
831       if (!*p)
832         *p = (struct predicate *) pool_alloc (edge_predicate_pool);
833       **p = new_predicate;
834     }
835 }
836
837
838 /* KNOWN_VALS is partial mapping of parameters of NODE to constant values.
839    KNOWN_AGGS is a vector of aggreggate jump functions for each parameter.
840    Return clause of possible truths. When INLINE_P is true, assume that we are
841    inlining.
842
843    ERROR_MARK means compile time invariant.  */
844
845 static clause_t
846 evaluate_conditions_for_known_args (struct cgraph_node *node,
847                                     bool inline_p,
848                                     vec<tree> known_vals,
849                                     vec<ipa_agg_jump_function_p>
850                                     known_aggs)
851 {
852   clause_t clause = inline_p ? 0 : 1 << predicate_not_inlined_condition;
853   struct inline_summary *info = inline_summaries->get (node);
854   int i;
855   struct condition *c;
856
857   for (i = 0; vec_safe_iterate (info->conds, i, &c); i++)
858     {
859       tree val;
860       tree res;
861
862       /* We allow call stmt to have fewer arguments than the callee function
863          (especially for K&R style programs).  So bound check here (we assume
864          known_aggs vector, if non-NULL, has the same length as
865          known_vals).  */
866       gcc_checking_assert (!known_aggs.exists ()
867                            || (known_vals.length () == known_aggs.length ()));
868       if (c->operand_num >= (int) known_vals.length ())
869         {
870           clause |= 1 << (i + predicate_first_dynamic_condition);
871           continue;
872         }
873
874       if (c->agg_contents)
875         {
876           struct ipa_agg_jump_function *agg;
877
878           if (c->code == CHANGED
879               && !c->by_ref
880               && (known_vals[c->operand_num] == error_mark_node))
881             continue;
882
883           if (known_aggs.exists ())
884             {
885               agg = known_aggs[c->operand_num];
886               val = ipa_find_agg_cst_for_param (agg, c->offset, c->by_ref);
887             }
888           else
889             val = NULL_TREE;
890         }
891       else
892         {
893           val = known_vals[c->operand_num];
894           if (val == error_mark_node && c->code != CHANGED)
895             val = NULL_TREE;
896         }
897
898       if (!val)
899         {
900           clause |= 1 << (i + predicate_first_dynamic_condition);
901           continue;
902         }
903       if (c->code == IS_NOT_CONSTANT || c->code == CHANGED)
904         continue;
905
906       if (operand_equal_p (TYPE_SIZE (TREE_TYPE (c->val)),
907                            TYPE_SIZE (TREE_TYPE (val)), 0))
908         {
909           val = fold_unary (VIEW_CONVERT_EXPR, TREE_TYPE (c->val), val);
910
911           res = val
912             ? fold_binary_to_constant (c->code, boolean_type_node, val, c->val)
913             : NULL;
914
915           if (res && integer_zerop (res))
916             continue;
917         }
918       clause |= 1 << (i + predicate_first_dynamic_condition);
919     }
920   return clause;
921 }
922
923
924 /* Work out what conditions might be true at invocation of E.  */
925
926 static void
927 evaluate_properties_for_edge (struct cgraph_edge *e, bool inline_p,
928                               clause_t *clause_ptr,
929                               vec<tree> *known_vals_ptr,
930                               vec<ipa_polymorphic_call_context>
931                               *known_contexts_ptr,
932                               vec<ipa_agg_jump_function_p> *known_aggs_ptr)
933 {
934   struct cgraph_node *callee = e->callee->ultimate_alias_target ();
935   struct inline_summary *info = inline_summaries->get (callee);
936   vec<tree> known_vals = vNULL;
937   vec<ipa_agg_jump_function_p> known_aggs = vNULL;
938
939   if (clause_ptr)
940     *clause_ptr = inline_p ? 0 : 1 << predicate_not_inlined_condition;
941   if (known_vals_ptr)
942     known_vals_ptr->create (0);
943   if (known_contexts_ptr)
944     known_contexts_ptr->create (0);
945
946   if (ipa_node_params_sum
947       && !e->call_stmt_cannot_inline_p
948       && ((clause_ptr && info->conds) || known_vals_ptr || known_contexts_ptr))
949     {
950       struct ipa_node_params *parms_info;
951       struct ipa_edge_args *args = IPA_EDGE_REF (e);
952       struct inline_edge_summary *es = inline_edge_summary (e);
953       int i, count = ipa_get_cs_argument_count (args);
954
955       if (e->caller->global.inlined_to)
956         parms_info = IPA_NODE_REF (e->caller->global.inlined_to);
957       else
958         parms_info = IPA_NODE_REF (e->caller);
959
960       if (count && (info->conds || known_vals_ptr))
961         known_vals.safe_grow_cleared (count);
962       if (count && (info->conds || known_aggs_ptr))
963         known_aggs.safe_grow_cleared (count);
964       if (count && known_contexts_ptr)
965         known_contexts_ptr->safe_grow_cleared (count);
966
967       for (i = 0; i < count; i++)
968         {
969           struct ipa_jump_func *jf = ipa_get_ith_jump_func (args, i);
970           tree cst = ipa_value_from_jfunc (parms_info, jf);
971
972           if (!cst && e->call_stmt
973               && i < (int)gimple_call_num_args (e->call_stmt))
974             {
975               cst = gimple_call_arg (e->call_stmt, i);
976               if (!is_gimple_min_invariant (cst))
977                 cst = NULL;
978             }
979           if (cst)
980             {
981               gcc_checking_assert (TREE_CODE (cst) != TREE_BINFO);
982               if (known_vals.exists ())
983                 known_vals[i] = cst;
984             }
985           else if (inline_p && !es->param[i].change_prob)
986             known_vals[i] = error_mark_node;
987
988           if (known_contexts_ptr)
989             (*known_contexts_ptr)[i] = ipa_context_from_jfunc (parms_info, e,
990                                                                i, jf);
991           /* TODO: When IPA-CP starts propagating and merging aggregate jump
992              functions, use its knowledge of the caller too, just like the
993              scalar case above.  */
994           known_aggs[i] = &jf->agg;
995         }
996     }
997   else if (e->call_stmt && !e->call_stmt_cannot_inline_p
998            && ((clause_ptr && info->conds) || known_vals_ptr))
999     {
1000       int i, count = (int)gimple_call_num_args (e->call_stmt);
1001
1002       if (count && (info->conds || known_vals_ptr))
1003         known_vals.safe_grow_cleared (count);
1004       for (i = 0; i < count; i++)
1005         {
1006           tree cst = gimple_call_arg (e->call_stmt, i);
1007           if (!is_gimple_min_invariant (cst))
1008             cst = NULL;
1009           if (cst)
1010             known_vals[i] = cst;
1011         }
1012     }
1013
1014   if (clause_ptr)
1015     *clause_ptr = evaluate_conditions_for_known_args (callee, inline_p,
1016                                                       known_vals, known_aggs);
1017
1018   if (known_vals_ptr)
1019     *known_vals_ptr = known_vals;
1020   else
1021     known_vals.release ();
1022
1023   if (known_aggs_ptr)
1024     *known_aggs_ptr = known_aggs;
1025   else
1026     known_aggs.release ();
1027 }
1028
1029
1030 /* Allocate the inline summary vector or resize it to cover all cgraph nodes. */
1031
1032 static void
1033 inline_summary_alloc (void)
1034 {
1035   if (!edge_removal_hook_holder)
1036     edge_removal_hook_holder =
1037       symtab->add_edge_removal_hook (&inline_edge_removal_hook, NULL);
1038   if (!edge_duplication_hook_holder)
1039     edge_duplication_hook_holder =
1040       symtab->add_edge_duplication_hook (&inline_edge_duplication_hook, NULL);
1041
1042   if (!inline_summaries)
1043     inline_summaries = (inline_summary_t*) inline_summary_t::create_ggc (symtab);
1044
1045   if (inline_edge_summary_vec.length () <= (unsigned) symtab->edges_max_uid)
1046     inline_edge_summary_vec.safe_grow_cleared (symtab->edges_max_uid + 1);
1047   if (!edge_predicate_pool)
1048     edge_predicate_pool = create_alloc_pool ("edge predicates",
1049                                              sizeof (struct predicate), 10);
1050 }
1051
1052 /* We are called multiple time for given function; clear
1053    data from previous run so they are not cumulated.  */
1054
1055 static void
1056 reset_inline_edge_summary (struct cgraph_edge *e)
1057 {
1058   if (e->uid < (int) inline_edge_summary_vec.length ())
1059     {
1060       struct inline_edge_summary *es = inline_edge_summary (e);
1061
1062       es->call_stmt_size = es->call_stmt_time = 0;
1063       if (es->predicate)
1064         pool_free (edge_predicate_pool, es->predicate);
1065       es->predicate = NULL;
1066       es->param.release ();
1067     }
1068 }
1069
1070 /* We are called multiple time for given function; clear
1071    data from previous run so they are not cumulated.  */
1072
1073 static void
1074 reset_inline_summary (struct cgraph_node *node,
1075                       inline_summary *info)
1076 {
1077   struct cgraph_edge *e;
1078
1079   info->self_size = info->self_time = 0;
1080   info->estimated_stack_size = 0;
1081   info->estimated_self_stack_size = 0;
1082   info->stack_frame_offset = 0;
1083   info->size = 0;
1084   info->time = 0;
1085   info->growth = 0;
1086   info->scc_no = 0;
1087   if (info->loop_iterations)
1088     {
1089       pool_free (edge_predicate_pool, info->loop_iterations);
1090       info->loop_iterations = NULL;
1091     }
1092   if (info->loop_stride)
1093     {
1094       pool_free (edge_predicate_pool, info->loop_stride);
1095       info->loop_stride = NULL;
1096     }
1097   if (info->array_index)
1098     {
1099       pool_free (edge_predicate_pool, info->array_index);
1100       info->array_index = NULL;
1101     }
1102   vec_free (info->conds);
1103   vec_free (info->entry);
1104   for (e = node->callees; e; e = e->next_callee)
1105     reset_inline_edge_summary (e);
1106   for (e = node->indirect_calls; e; e = e->next_callee)
1107     reset_inline_edge_summary (e);
1108 }
1109
1110 /* Hook that is called by cgraph.c when a node is removed.  */
1111
1112 void
1113 inline_summary_t::remove (cgraph_node *node, inline_summary *info)
1114 {
1115   reset_inline_summary (node, info);
1116 }
1117
1118 /* Remap predicate P of former function to be predicate of duplicated function.
1119    POSSIBLE_TRUTHS is clause of possible truths in the duplicated node,
1120    INFO is inline summary of the duplicated node.  */
1121
1122 static struct predicate
1123 remap_predicate_after_duplication (struct predicate *p,
1124                                    clause_t possible_truths,
1125                                    struct inline_summary *info)
1126 {
1127   struct predicate new_predicate = true_predicate ();
1128   int j;
1129   for (j = 0; p->clause[j]; j++)
1130     if (!(possible_truths & p->clause[j]))
1131       {
1132         new_predicate = false_predicate ();
1133         break;
1134       }
1135     else
1136       add_clause (info->conds, &new_predicate,
1137                   possible_truths & p->clause[j]);
1138   return new_predicate;
1139 }
1140
1141 /* Same as remap_predicate_after_duplication but handle hint predicate *P.
1142    Additionally care about allocating new memory slot for updated predicate
1143    and set it to NULL when it becomes true or false (and thus uninteresting).
1144  */
1145
1146 static void
1147 remap_hint_predicate_after_duplication (struct predicate **p,
1148                                         clause_t possible_truths,
1149                                         struct inline_summary *info)
1150 {
1151   struct predicate new_predicate;
1152
1153   if (!*p)
1154     return;
1155
1156   new_predicate = remap_predicate_after_duplication (*p,
1157                                                      possible_truths, info);
1158   /* We do not want to free previous predicate; it is used by node origin.  */
1159   *p = NULL;
1160   set_hint_predicate (p, new_predicate);
1161 }
1162
1163
1164 /* Hook that is called by cgraph.c when a node is duplicated.  */
1165 void
1166 inline_summary_t::duplicate (cgraph_node *src,
1167                              cgraph_node *dst,
1168                              inline_summary *,
1169                              inline_summary *info)
1170 {
1171   inline_summary_alloc ();
1172   memcpy (info, inline_summaries->get (src), sizeof (inline_summary));
1173   /* TODO: as an optimization, we may avoid copying conditions
1174      that are known to be false or true.  */
1175   info->conds = vec_safe_copy (info->conds);
1176
1177   /* When there are any replacements in the function body, see if we can figure
1178      out that something was optimized out.  */
1179   if (ipa_node_params_sum && dst->clone.tree_map)
1180     {
1181       vec<size_time_entry, va_gc> *entry = info->entry;
1182       /* Use SRC parm info since it may not be copied yet.  */
1183       struct ipa_node_params *parms_info = IPA_NODE_REF (src);
1184       vec<tree> known_vals = vNULL;
1185       int count = ipa_get_param_count (parms_info);
1186       int i, j;
1187       clause_t possible_truths;
1188       struct predicate true_pred = true_predicate ();
1189       size_time_entry *e;
1190       int optimized_out_size = 0;
1191       bool inlined_to_p = false;
1192       struct cgraph_edge *edge, *next;
1193
1194       info->entry = 0;
1195       known_vals.safe_grow_cleared (count);
1196       for (i = 0; i < count; i++)
1197         {
1198           struct ipa_replace_map *r;
1199
1200           for (j = 0; vec_safe_iterate (dst->clone.tree_map, j, &r); j++)
1201             {
1202               if (((!r->old_tree && r->parm_num == i)
1203                    || (r->old_tree && r->old_tree == ipa_get_param (parms_info, i)))
1204                    && r->replace_p && !r->ref_p)
1205                 {
1206                   known_vals[i] = r->new_tree;
1207                   break;
1208                 }
1209             }
1210         }
1211       possible_truths = evaluate_conditions_for_known_args (dst, false,
1212                                                             known_vals,
1213                                                             vNULL);
1214       known_vals.release ();
1215
1216       account_size_time (info, 0, 0, &true_pred);
1217
1218       /* Remap size_time vectors.
1219          Simplify the predicate by prunning out alternatives that are known
1220          to be false.
1221          TODO: as on optimization, we can also eliminate conditions known
1222          to be true.  */
1223       for (i = 0; vec_safe_iterate (entry, i, &e); i++)
1224         {
1225           struct predicate new_predicate;
1226           new_predicate = remap_predicate_after_duplication (&e->predicate,
1227                                                              possible_truths,
1228                                                              info);
1229           if (false_predicate_p (&new_predicate))
1230             optimized_out_size += e->size;
1231           else
1232             account_size_time (info, e->size, e->time, &new_predicate);
1233         }
1234
1235       /* Remap edge predicates with the same simplification as above.
1236          Also copy constantness arrays.   */
1237       for (edge = dst->callees; edge; edge = next)
1238         {
1239           struct predicate new_predicate;
1240           struct inline_edge_summary *es = inline_edge_summary (edge);
1241           next = edge->next_callee;
1242
1243           if (!edge->inline_failed)
1244             inlined_to_p = true;
1245           if (!es->predicate)
1246             continue;
1247           new_predicate = remap_predicate_after_duplication (es->predicate,
1248                                                              possible_truths,
1249                                                              info);
1250           if (false_predicate_p (&new_predicate)
1251               && !false_predicate_p (es->predicate))
1252             optimized_out_size += es->call_stmt_size * INLINE_SIZE_SCALE;
1253           edge_set_predicate (edge, &new_predicate);
1254         }
1255
1256       /* Remap indirect edge predicates with the same simplificaiton as above. 
1257          Also copy constantness arrays.   */
1258       for (edge = dst->indirect_calls; edge; edge = next)
1259         {
1260           struct predicate new_predicate;
1261           struct inline_edge_summary *es = inline_edge_summary (edge);
1262           next = edge->next_callee;
1263
1264           gcc_checking_assert (edge->inline_failed);
1265           if (!es->predicate)
1266             continue;
1267           new_predicate = remap_predicate_after_duplication (es->predicate,
1268                                                              possible_truths,
1269                                                              info);
1270           if (false_predicate_p (&new_predicate)
1271               && !false_predicate_p (es->predicate))
1272             optimized_out_size += es->call_stmt_size * INLINE_SIZE_SCALE;
1273           edge_set_predicate (edge, &new_predicate);
1274         }
1275       remap_hint_predicate_after_duplication (&info->loop_iterations,
1276                                               possible_truths, info);
1277       remap_hint_predicate_after_duplication (&info->loop_stride,
1278                                               possible_truths, info);
1279       remap_hint_predicate_after_duplication (&info->array_index,
1280                                               possible_truths, info);
1281
1282       /* If inliner or someone after inliner will ever start producing
1283          non-trivial clones, we will get trouble with lack of information
1284          about updating self sizes, because size vectors already contains
1285          sizes of the calees.  */
1286       gcc_assert (!inlined_to_p || !optimized_out_size);
1287     }
1288   else
1289     {
1290       info->entry = vec_safe_copy (info->entry);
1291       if (info->loop_iterations)
1292         {
1293           predicate p = *info->loop_iterations;
1294           info->loop_iterations = NULL;
1295           set_hint_predicate (&info->loop_iterations, p);
1296         }
1297       if (info->loop_stride)
1298         {
1299           predicate p = *info->loop_stride;
1300           info->loop_stride = NULL;
1301           set_hint_predicate (&info->loop_stride, p);
1302         }
1303       if (info->array_index)
1304         {
1305           predicate p = *info->array_index;
1306           info->array_index = NULL;
1307           set_hint_predicate (&info->array_index, p);
1308         }
1309     }
1310   if (!dst->global.inlined_to)
1311     inline_update_overall_summary (dst);
1312 }
1313
1314
1315 /* Hook that is called by cgraph.c when a node is duplicated.  */
1316
1317 static void
1318 inline_edge_duplication_hook (struct cgraph_edge *src,
1319                               struct cgraph_edge *dst,
1320                               ATTRIBUTE_UNUSED void *data)
1321 {
1322   struct inline_edge_summary *info;
1323   struct inline_edge_summary *srcinfo;
1324   inline_summary_alloc ();
1325   info = inline_edge_summary (dst);
1326   srcinfo = inline_edge_summary (src);
1327   memcpy (info, srcinfo, sizeof (struct inline_edge_summary));
1328   info->predicate = NULL;
1329   edge_set_predicate (dst, srcinfo->predicate);
1330   info->param = srcinfo->param.copy ();
1331   if (!dst->indirect_unknown_callee && src->indirect_unknown_callee)
1332     {
1333       info->call_stmt_size -= (eni_size_weights.indirect_call_cost
1334                                - eni_size_weights.call_cost);
1335       info->call_stmt_time -= (eni_time_weights.indirect_call_cost
1336                                - eni_time_weights.call_cost);
1337     }
1338 }
1339
1340
1341 /* Keep edge cache consistent across edge removal.  */
1342
1343 static void
1344 inline_edge_removal_hook (struct cgraph_edge *edge,
1345                           void *data ATTRIBUTE_UNUSED)
1346 {
1347   if (edge_growth_cache.exists ())
1348     reset_edge_growth_cache (edge);
1349   reset_inline_edge_summary (edge);
1350 }
1351
1352
1353 /* Initialize growth caches.  */
1354
1355 void
1356 initialize_growth_caches (void)
1357 {
1358   if (symtab->edges_max_uid)
1359     edge_growth_cache.safe_grow_cleared (symtab->edges_max_uid);
1360 }
1361
1362
1363 /* Free growth caches.  */
1364
1365 void
1366 free_growth_caches (void)
1367 {
1368   edge_growth_cache.release ();
1369 }
1370
1371
1372 /* Dump edge summaries associated to NODE and recursively to all clones.
1373    Indent by INDENT.  */
1374
1375 static void
1376 dump_inline_edge_summary (FILE *f, int indent, struct cgraph_node *node,
1377                           struct inline_summary *info)
1378 {
1379   struct cgraph_edge *edge;
1380   for (edge = node->callees; edge; edge = edge->next_callee)
1381     {
1382       struct inline_edge_summary *es = inline_edge_summary (edge);
1383       struct cgraph_node *callee = edge->callee->ultimate_alias_target ();
1384       int i;
1385
1386       fprintf (f,
1387                "%*s%s/%i %s\n%*s  loop depth:%2i freq:%4i size:%2i"
1388                " time: %2i callee size:%2i stack:%2i",
1389                indent, "", callee->name (), callee->order,
1390                !edge->inline_failed
1391                ? "inlined" : cgraph_inline_failed_string (edge-> inline_failed),
1392                indent, "", es->loop_depth, edge->frequency,
1393                es->call_stmt_size, es->call_stmt_time,
1394                (int) inline_summaries->get (callee)->size / INLINE_SIZE_SCALE,
1395                (int) inline_summaries->get (callee)->estimated_stack_size);
1396
1397       if (es->predicate)
1398         {
1399           fprintf (f, " predicate: ");
1400           dump_predicate (f, info->conds, es->predicate);
1401         }
1402       else
1403         fprintf (f, "\n");
1404       if (es->param.exists ())
1405         for (i = 0; i < (int) es->param.length (); i++)
1406           {
1407             int prob = es->param[i].change_prob;
1408
1409             if (!prob)
1410               fprintf (f, "%*s op%i is compile time invariant\n",
1411                        indent + 2, "", i);
1412             else if (prob != REG_BR_PROB_BASE)
1413               fprintf (f, "%*s op%i change %f%% of time\n", indent + 2, "", i,
1414                        prob * 100.0 / REG_BR_PROB_BASE);
1415           }
1416       if (!edge->inline_failed)
1417         {
1418           fprintf (f, "%*sStack frame offset %i, callee self size %i,"
1419                    " callee size %i\n",
1420                    indent + 2, "",
1421                    (int) inline_summaries->get (callee)->stack_frame_offset,
1422                    (int) inline_summaries->get (callee)->estimated_self_stack_size,
1423                    (int) inline_summaries->get (callee)->estimated_stack_size);
1424           dump_inline_edge_summary (f, indent + 2, callee, info);
1425         }
1426     }
1427   for (edge = node->indirect_calls; edge; edge = edge->next_callee)
1428     {
1429       struct inline_edge_summary *es = inline_edge_summary (edge);
1430       fprintf (f, "%*sindirect call loop depth:%2i freq:%4i size:%2i"
1431                " time: %2i",
1432                indent, "",
1433                es->loop_depth,
1434                edge->frequency, es->call_stmt_size, es->call_stmt_time);
1435       if (es->predicate)
1436         {
1437           fprintf (f, "predicate: ");
1438           dump_predicate (f, info->conds, es->predicate);
1439         }
1440       else
1441         fprintf (f, "\n");
1442     }
1443 }
1444
1445
1446 void
1447 dump_inline_summary (FILE *f, struct cgraph_node *node)
1448 {
1449   if (node->definition)
1450     {
1451       struct inline_summary *s = inline_summaries->get (node);
1452       size_time_entry *e;
1453       int i;
1454       fprintf (f, "Inline summary for %s/%i", node->name (),
1455                node->order);
1456       if (DECL_DISREGARD_INLINE_LIMITS (node->decl))
1457         fprintf (f, " always_inline");
1458       if (s->inlinable)
1459         fprintf (f, " inlinable");
1460       if (s->contains_cilk_spawn)
1461         fprintf (f, " contains_cilk_spawn");
1462       fprintf (f, "\n  self time:       %i\n", s->self_time);
1463       fprintf (f, "  global time:     %i\n", s->time);
1464       fprintf (f, "  self size:       %i\n", s->self_size);
1465       fprintf (f, "  global size:     %i\n", s->size);
1466       fprintf (f, "  min size:       %i\n", s->min_size);
1467       fprintf (f, "  self stack:      %i\n",
1468                (int) s->estimated_self_stack_size);
1469       fprintf (f, "  global stack:    %i\n", (int) s->estimated_stack_size);
1470       if (s->growth)
1471         fprintf (f, "  estimated growth:%i\n", (int) s->growth);
1472       if (s->scc_no)
1473         fprintf (f, "  In SCC:          %i\n", (int) s->scc_no);
1474       for (i = 0; vec_safe_iterate (s->entry, i, &e); i++)
1475         {
1476           fprintf (f, "    size:%f, time:%f, predicate:",
1477                    (double) e->size / INLINE_SIZE_SCALE,
1478                    (double) e->time / INLINE_TIME_SCALE);
1479           dump_predicate (f, s->conds, &e->predicate);
1480         }
1481       if (s->loop_iterations)
1482         {
1483           fprintf (f, "  loop iterations:");
1484           dump_predicate (f, s->conds, s->loop_iterations);
1485         }
1486       if (s->loop_stride)
1487         {
1488           fprintf (f, "  loop stride:");
1489           dump_predicate (f, s->conds, s->loop_stride);
1490         }
1491       if (s->array_index)
1492         {
1493           fprintf (f, "  array index:");
1494           dump_predicate (f, s->conds, s->array_index);
1495         }
1496       fprintf (f, "  calls:\n");
1497       dump_inline_edge_summary (f, 4, node, s);
1498       fprintf (f, "\n");
1499     }
1500 }
1501
1502 DEBUG_FUNCTION void
1503 debug_inline_summary (struct cgraph_node *node)
1504 {
1505   dump_inline_summary (stderr, node);
1506 }
1507
1508 void
1509 dump_inline_summaries (FILE *f)
1510 {
1511   struct cgraph_node *node;
1512
1513   FOR_EACH_DEFINED_FUNCTION (node)
1514     if (!node->global.inlined_to)
1515       dump_inline_summary (f, node);
1516 }
1517
1518 /* Give initial reasons why inlining would fail on EDGE.  This gets either
1519    nullified or usually overwritten by more precise reasons later.  */
1520
1521 void
1522 initialize_inline_failed (struct cgraph_edge *e)
1523 {
1524   struct cgraph_node *callee = e->callee;
1525
1526   if (e->indirect_unknown_callee)
1527     e->inline_failed = CIF_INDIRECT_UNKNOWN_CALL;
1528   else if (!callee->definition)
1529     e->inline_failed = CIF_BODY_NOT_AVAILABLE;
1530   else if (callee->local.redefined_extern_inline)
1531     e->inline_failed = CIF_REDEFINED_EXTERN_INLINE;
1532   else if (e->call_stmt_cannot_inline_p)
1533     e->inline_failed = CIF_MISMATCHED_ARGUMENTS;
1534   else if (cfun && fn_contains_cilk_spawn_p (cfun))
1535     /* We can't inline if the function is spawing a function.  */
1536     e->inline_failed = CIF_FUNCTION_NOT_INLINABLE;
1537   else
1538     e->inline_failed = CIF_FUNCTION_NOT_CONSIDERED;
1539 }
1540
1541 /* Callback of walk_aliased_vdefs.  Flags that it has been invoked to the
1542    boolean variable pointed to by DATA.  */
1543
1544 static bool
1545 mark_modified (ao_ref *ao ATTRIBUTE_UNUSED, tree vdef ATTRIBUTE_UNUSED,
1546                void *data)
1547 {
1548   bool *b = (bool *) data;
1549   *b = true;
1550   return true;
1551 }
1552
1553 /* If OP refers to value of function parameter, return the corresponding
1554    parameter.  */
1555
1556 static tree
1557 unmodified_parm_1 (gimple stmt, tree op)
1558 {
1559   /* SSA_NAME referring to parm default def?  */
1560   if (TREE_CODE (op) == SSA_NAME
1561       && SSA_NAME_IS_DEFAULT_DEF (op)
1562       && TREE_CODE (SSA_NAME_VAR (op)) == PARM_DECL)
1563     return SSA_NAME_VAR (op);
1564   /* Non-SSA parm reference?  */
1565   if (TREE_CODE (op) == PARM_DECL)
1566     {
1567       bool modified = false;
1568
1569       ao_ref refd;
1570       ao_ref_init (&refd, op);
1571       walk_aliased_vdefs (&refd, gimple_vuse (stmt), mark_modified, &modified,
1572                           NULL);
1573       if (!modified)
1574         return op;
1575     }
1576   return NULL_TREE;
1577 }
1578
1579 /* If OP refers to value of function parameter, return the corresponding
1580    parameter.  Also traverse chains of SSA register assignments.  */
1581
1582 static tree
1583 unmodified_parm (gimple stmt, tree op)
1584 {
1585   tree res = unmodified_parm_1 (stmt, op);
1586   if (res)
1587     return res;
1588
1589   if (TREE_CODE (op) == SSA_NAME
1590       && !SSA_NAME_IS_DEFAULT_DEF (op)
1591       && gimple_assign_single_p (SSA_NAME_DEF_STMT (op)))
1592     return unmodified_parm (SSA_NAME_DEF_STMT (op),
1593                             gimple_assign_rhs1 (SSA_NAME_DEF_STMT (op)));
1594   return NULL_TREE;
1595 }
1596
1597 /* If OP refers to a value of a function parameter or value loaded from an
1598    aggregate passed to a parameter (either by value or reference), return TRUE
1599    and store the number of the parameter to *INDEX_P and information whether
1600    and how it has been loaded from an aggregate into *AGGPOS.  INFO describes
1601    the function parameters, STMT is the statement in which OP is used or
1602    loaded.  */
1603
1604 static bool
1605 unmodified_parm_or_parm_agg_item (struct ipa_node_params *info,
1606                                   gimple stmt, tree op, int *index_p,
1607                                   struct agg_position_info *aggpos)
1608 {
1609   tree res = unmodified_parm_1 (stmt, op);
1610
1611   gcc_checking_assert (aggpos);
1612   if (res)
1613     {
1614       *index_p = ipa_get_param_decl_index (info, res);
1615       if (*index_p < 0)
1616         return false;
1617       aggpos->agg_contents = false;
1618       aggpos->by_ref = false;
1619       return true;
1620     }
1621
1622   if (TREE_CODE (op) == SSA_NAME)
1623     {
1624       if (SSA_NAME_IS_DEFAULT_DEF (op)
1625           || !gimple_assign_single_p (SSA_NAME_DEF_STMT (op)))
1626         return false;
1627       stmt = SSA_NAME_DEF_STMT (op);
1628       op = gimple_assign_rhs1 (stmt);
1629       if (!REFERENCE_CLASS_P (op))
1630         return unmodified_parm_or_parm_agg_item (info, stmt, op, index_p,
1631                                                  aggpos);
1632     }
1633
1634   aggpos->agg_contents = true;
1635   return ipa_load_from_parm_agg (info, stmt, op, index_p, &aggpos->offset,
1636                                  &aggpos->by_ref);
1637 }
1638
1639 /* See if statement might disappear after inlining.
1640    0 - means not eliminated
1641    1 - half of statements goes away
1642    2 - for sure it is eliminated.
1643    We are not terribly sophisticated, basically looking for simple abstraction
1644    penalty wrappers.  */
1645
1646 static int
1647 eliminated_by_inlining_prob (gimple stmt)
1648 {
1649   enum gimple_code code = gimple_code (stmt);
1650   enum tree_code rhs_code;
1651
1652   if (!optimize)
1653     return 0;
1654
1655   switch (code)
1656     {
1657     case GIMPLE_RETURN:
1658       return 2;
1659     case GIMPLE_ASSIGN:
1660       if (gimple_num_ops (stmt) != 2)
1661         return 0;
1662
1663       rhs_code = gimple_assign_rhs_code (stmt);
1664
1665       /* Casts of parameters, loads from parameters passed by reference
1666          and stores to return value or parameters are often free after
1667          inlining dua to SRA and further combining.
1668          Assume that half of statements goes away.  */
1669       if (CONVERT_EXPR_CODE_P (rhs_code)
1670           || rhs_code == VIEW_CONVERT_EXPR
1671           || rhs_code == ADDR_EXPR
1672           || gimple_assign_rhs_class (stmt) == GIMPLE_SINGLE_RHS)
1673         {
1674           tree rhs = gimple_assign_rhs1 (stmt);
1675           tree lhs = gimple_assign_lhs (stmt);
1676           tree inner_rhs = get_base_address (rhs);
1677           tree inner_lhs = get_base_address (lhs);
1678           bool rhs_free = false;
1679           bool lhs_free = false;
1680
1681           if (!inner_rhs)
1682             inner_rhs = rhs;
1683           if (!inner_lhs)
1684             inner_lhs = lhs;
1685
1686           /* Reads of parameter are expected to be free.  */
1687           if (unmodified_parm (stmt, inner_rhs))
1688             rhs_free = true;
1689           /* Match expressions of form &this->field. Those will most likely
1690              combine with something upstream after inlining.  */
1691           else if (TREE_CODE (inner_rhs) == ADDR_EXPR)
1692             {
1693               tree op = get_base_address (TREE_OPERAND (inner_rhs, 0));
1694               if (TREE_CODE (op) == PARM_DECL)
1695                 rhs_free = true;
1696               else if (TREE_CODE (op) == MEM_REF
1697                        && unmodified_parm (stmt, TREE_OPERAND (op, 0)))
1698                 rhs_free = true;
1699             }
1700
1701           /* When parameter is not SSA register because its address is taken
1702              and it is just copied into one, the statement will be completely
1703              free after inlining (we will copy propagate backward).   */
1704           if (rhs_free && is_gimple_reg (lhs))
1705             return 2;
1706
1707           /* Reads of parameters passed by reference
1708              expected to be free (i.e. optimized out after inlining).  */
1709           if (TREE_CODE (inner_rhs) == MEM_REF
1710               && unmodified_parm (stmt, TREE_OPERAND (inner_rhs, 0)))
1711             rhs_free = true;
1712
1713           /* Copying parameter passed by reference into gimple register is
1714              probably also going to copy propagate, but we can't be quite
1715              sure.  */
1716           if (rhs_free && is_gimple_reg (lhs))
1717             lhs_free = true;
1718
1719           /* Writes to parameters, parameters passed by value and return value
1720              (either dirrectly or passed via invisible reference) are free.  
1721
1722              TODO: We ought to handle testcase like
1723              struct a {int a,b;};
1724              struct a
1725              retrurnsturct (void)
1726              {
1727              struct a a ={1,2};
1728              return a;
1729              }
1730
1731              This translate into:
1732
1733              retrurnsturct ()
1734              {
1735              int a$b;
1736              int a$a;
1737              struct a a;
1738              struct a D.2739;
1739
1740              <bb 2>:
1741              D.2739.a = 1;
1742              D.2739.b = 2;
1743              return D.2739;
1744
1745              }
1746              For that we either need to copy ipa-split logic detecting writes
1747              to return value.  */
1748           if (TREE_CODE (inner_lhs) == PARM_DECL
1749               || TREE_CODE (inner_lhs) == RESULT_DECL
1750               || (TREE_CODE (inner_lhs) == MEM_REF
1751                   && (unmodified_parm (stmt, TREE_OPERAND (inner_lhs, 0))
1752                       || (TREE_CODE (TREE_OPERAND (inner_lhs, 0)) == SSA_NAME
1753                           && SSA_NAME_VAR (TREE_OPERAND (inner_lhs, 0))
1754                           && TREE_CODE (SSA_NAME_VAR (TREE_OPERAND
1755                                                       (inner_lhs,
1756                                                        0))) == RESULT_DECL))))
1757             lhs_free = true;
1758           if (lhs_free
1759               && (is_gimple_reg (rhs) || is_gimple_min_invariant (rhs)))
1760             rhs_free = true;
1761           if (lhs_free && rhs_free)
1762             return 1;
1763         }
1764       return 0;
1765     default:
1766       return 0;
1767     }
1768 }
1769
1770
1771 /* If BB ends by a conditional we can turn into predicates, attach corresponding
1772    predicates to the CFG edges.   */
1773
1774 static void
1775 set_cond_stmt_execution_predicate (struct ipa_node_params *info,
1776                                    struct inline_summary *summary,
1777                                    basic_block bb)
1778 {
1779   gimple last;
1780   tree op;
1781   int index;
1782   struct agg_position_info aggpos;
1783   enum tree_code code, inverted_code;
1784   edge e;
1785   edge_iterator ei;
1786   gimple set_stmt;
1787   tree op2;
1788
1789   last = last_stmt (bb);
1790   if (!last || gimple_code (last) != GIMPLE_COND)
1791     return;
1792   if (!is_gimple_ip_invariant (gimple_cond_rhs (last)))
1793     return;
1794   op = gimple_cond_lhs (last);
1795   /* TODO: handle conditionals like
1796      var = op0 < 4;
1797      if (var != 0).  */
1798   if (unmodified_parm_or_parm_agg_item (info, last, op, &index, &aggpos))
1799     {
1800       code = gimple_cond_code (last);
1801       inverted_code = invert_tree_comparison (code, HONOR_NANS (op));
1802
1803       FOR_EACH_EDGE (e, ei, bb->succs)
1804         {
1805           enum tree_code this_code = (e->flags & EDGE_TRUE_VALUE
1806                                       ? code : inverted_code);
1807           /* invert_tree_comparison will return ERROR_MARK on FP
1808              comparsions that are not EQ/NE instead of returning proper
1809              unordered one.  Be sure it is not confused with NON_CONSTANT.  */
1810           if (this_code != ERROR_MARK)
1811             {
1812               struct predicate p = add_condition (summary, index, &aggpos,
1813                                                   this_code,
1814                                                   gimple_cond_rhs (last));
1815               e->aux = pool_alloc (edge_predicate_pool);
1816               *(struct predicate *) e->aux = p;
1817             }
1818         }
1819     }
1820
1821   if (TREE_CODE (op) != SSA_NAME)
1822     return;
1823   /* Special case
1824      if (builtin_constant_p (op))
1825      constant_code
1826      else
1827      nonconstant_code.
1828      Here we can predicate nonconstant_code.  We can't
1829      really handle constant_code since we have no predicate
1830      for this and also the constant code is not known to be
1831      optimized away when inliner doen't see operand is constant.
1832      Other optimizers might think otherwise.  */
1833   if (gimple_cond_code (last) != NE_EXPR
1834       || !integer_zerop (gimple_cond_rhs (last)))
1835     return;
1836   set_stmt = SSA_NAME_DEF_STMT (op);
1837   if (!gimple_call_builtin_p (set_stmt, BUILT_IN_CONSTANT_P)
1838       || gimple_call_num_args (set_stmt) != 1)
1839     return;
1840   op2 = gimple_call_arg (set_stmt, 0);
1841   if (!unmodified_parm_or_parm_agg_item
1842       (info, set_stmt, op2, &index, &aggpos))
1843     return;
1844   FOR_EACH_EDGE (e, ei, bb->succs) if (e->flags & EDGE_FALSE_VALUE)
1845     {
1846       struct predicate p = add_condition (summary, index, &aggpos,
1847                                           IS_NOT_CONSTANT, NULL_TREE);
1848       e->aux = pool_alloc (edge_predicate_pool);
1849       *(struct predicate *) e->aux = p;
1850     }
1851 }
1852
1853
1854 /* If BB ends by a switch we can turn into predicates, attach corresponding
1855    predicates to the CFG edges.   */
1856
1857 static void
1858 set_switch_stmt_execution_predicate (struct ipa_node_params *info,
1859                                      struct inline_summary *summary,
1860                                      basic_block bb)
1861 {
1862   gimple lastg;
1863   tree op;
1864   int index;
1865   struct agg_position_info aggpos;
1866   edge e;
1867   edge_iterator ei;
1868   size_t n;
1869   size_t case_idx;
1870
1871   lastg = last_stmt (bb);
1872   if (!lastg || gimple_code (lastg) != GIMPLE_SWITCH)
1873     return;
1874   gswitch *last = as_a <gswitch *> (lastg);
1875   op = gimple_switch_index (last);
1876   if (!unmodified_parm_or_parm_agg_item (info, last, op, &index, &aggpos))
1877     return;
1878
1879   FOR_EACH_EDGE (e, ei, bb->succs)
1880     {
1881       e->aux = pool_alloc (edge_predicate_pool);
1882       *(struct predicate *) e->aux = false_predicate ();
1883     }
1884   n = gimple_switch_num_labels (last);
1885   for (case_idx = 0; case_idx < n; ++case_idx)
1886     {
1887       tree cl = gimple_switch_label (last, case_idx);
1888       tree min, max;
1889       struct predicate p;
1890
1891       e = find_edge (bb, label_to_block (CASE_LABEL (cl)));
1892       min = CASE_LOW (cl);
1893       max = CASE_HIGH (cl);
1894
1895       /* For default we might want to construct predicate that none
1896          of cases is met, but it is bit hard to do not having negations
1897          of conditionals handy.  */
1898       if (!min && !max)
1899         p = true_predicate ();
1900       else if (!max)
1901         p = add_condition (summary, index, &aggpos, EQ_EXPR, min);
1902       else
1903         {
1904           struct predicate p1, p2;
1905           p1 = add_condition (summary, index, &aggpos, GE_EXPR, min);
1906           p2 = add_condition (summary, index, &aggpos, LE_EXPR, max);
1907           p = and_predicates (summary->conds, &p1, &p2);
1908         }
1909       *(struct predicate *) e->aux
1910         = or_predicates (summary->conds, &p, (struct predicate *) e->aux);
1911     }
1912 }
1913
1914
1915 /* For each BB in NODE attach to its AUX pointer predicate under
1916    which it is executable.  */
1917
1918 static void
1919 compute_bb_predicates (struct cgraph_node *node,
1920                        struct ipa_node_params *parms_info,
1921                        struct inline_summary *summary)
1922 {
1923   struct function *my_function = DECL_STRUCT_FUNCTION (node->decl);
1924   bool done = false;
1925   basic_block bb;
1926
1927   FOR_EACH_BB_FN (bb, my_function)
1928     {
1929       set_cond_stmt_execution_predicate (parms_info, summary, bb);
1930       set_switch_stmt_execution_predicate (parms_info, summary, bb);
1931     }
1932
1933   /* Entry block is always executable.  */
1934   ENTRY_BLOCK_PTR_FOR_FN (my_function)->aux
1935     = pool_alloc (edge_predicate_pool);
1936   *(struct predicate *) ENTRY_BLOCK_PTR_FOR_FN (my_function)->aux
1937     = true_predicate ();
1938
1939   /* A simple dataflow propagation of predicates forward in the CFG.
1940      TODO: work in reverse postorder.  */
1941   while (!done)
1942     {
1943       done = true;
1944       FOR_EACH_BB_FN (bb, my_function)
1945         {
1946           struct predicate p = false_predicate ();
1947           edge e;
1948           edge_iterator ei;
1949           FOR_EACH_EDGE (e, ei, bb->preds)
1950             {
1951               if (e->src->aux)
1952                 {
1953                   struct predicate this_bb_predicate
1954                     = *(struct predicate *) e->src->aux;
1955                   if (e->aux)
1956                     this_bb_predicate
1957                       = and_predicates (summary->conds, &this_bb_predicate,
1958                                         (struct predicate *) e->aux);
1959                   p = or_predicates (summary->conds, &p, &this_bb_predicate);
1960                   if (true_predicate_p (&p))
1961                     break;
1962                 }
1963             }
1964           if (false_predicate_p (&p))
1965             gcc_assert (!bb->aux);
1966           else
1967             {
1968               if (!bb->aux)
1969                 {
1970                   done = false;
1971                   bb->aux = pool_alloc (edge_predicate_pool);
1972                   *((struct predicate *) bb->aux) = p;
1973                 }
1974               else if (!predicates_equal_p (&p, (struct predicate *) bb->aux))
1975                 {
1976                   /* This OR operation is needed to ensure monotonous data flow
1977                      in the case we hit the limit on number of clauses and the
1978                      and/or operations above give approximate answers.  */
1979                   p = or_predicates (summary->conds, &p, (struct predicate *)bb->aux);
1980                   if (!predicates_equal_p (&p, (struct predicate *) bb->aux))
1981                     {
1982                       done = false;
1983                       *((struct predicate *) bb->aux) = p;
1984                     }
1985                 }
1986             }
1987         }
1988     }
1989 }
1990
1991
1992 /* We keep info about constantness of SSA names.  */
1993
1994 typedef struct predicate predicate_t;
1995 /* Return predicate specifying when the STMT might have result that is not
1996    a compile time constant.  */
1997
1998 static struct predicate
1999 will_be_nonconstant_expr_predicate (struct ipa_node_params *info,
2000                                     struct inline_summary *summary,
2001                                     tree expr,
2002                                     vec<predicate_t> nonconstant_names)
2003 {
2004   tree parm;
2005   int index;
2006
2007   while (UNARY_CLASS_P (expr))
2008     expr = TREE_OPERAND (expr, 0);
2009
2010   parm = unmodified_parm (NULL, expr);
2011   if (parm && (index = ipa_get_param_decl_index (info, parm)) >= 0)
2012     return add_condition (summary, index, NULL, CHANGED, NULL_TREE);
2013   if (is_gimple_min_invariant (expr))
2014     return false_predicate ();
2015   if (TREE_CODE (expr) == SSA_NAME)
2016     return nonconstant_names[SSA_NAME_VERSION (expr)];
2017   if (BINARY_CLASS_P (expr) || COMPARISON_CLASS_P (expr))
2018     {
2019       struct predicate p1 = will_be_nonconstant_expr_predicate
2020         (info, summary, TREE_OPERAND (expr, 0),
2021          nonconstant_names);
2022       struct predicate p2;
2023       if (true_predicate_p (&p1))
2024         return p1;
2025       p2 = will_be_nonconstant_expr_predicate (info, summary,
2026                                                TREE_OPERAND (expr, 1),
2027                                                nonconstant_names);
2028       return or_predicates (summary->conds, &p1, &p2);
2029     }
2030   else if (TREE_CODE (expr) == COND_EXPR)
2031     {
2032       struct predicate p1 = will_be_nonconstant_expr_predicate
2033         (info, summary, TREE_OPERAND (expr, 0),
2034          nonconstant_names);
2035       struct predicate p2;
2036       if (true_predicate_p (&p1))
2037         return p1;
2038       p2 = will_be_nonconstant_expr_predicate (info, summary,
2039                                                TREE_OPERAND (expr, 1),
2040                                                nonconstant_names);
2041       if (true_predicate_p (&p2))
2042         return p2;
2043       p1 = or_predicates (summary->conds, &p1, &p2);
2044       p2 = will_be_nonconstant_expr_predicate (info, summary,
2045                                                TREE_OPERAND (expr, 2),
2046                                                nonconstant_names);
2047       return or_predicates (summary->conds, &p1, &p2);
2048     }
2049   else
2050     {
2051       debug_tree (expr);
2052       gcc_unreachable ();
2053     }
2054   return false_predicate ();
2055 }
2056
2057
2058 /* Return predicate specifying when the STMT might have result that is not
2059    a compile time constant.  */
2060
2061 static struct predicate
2062 will_be_nonconstant_predicate (struct ipa_node_params *info,
2063                                struct inline_summary *summary,
2064                                gimple stmt,
2065                                vec<predicate_t> nonconstant_names)
2066 {
2067   struct predicate p = true_predicate ();
2068   ssa_op_iter iter;
2069   tree use;
2070   struct predicate op_non_const;
2071   bool is_load;
2072   int base_index;
2073   struct agg_position_info aggpos;
2074
2075   /* What statments might be optimized away
2076      when their arguments are constant.  */
2077   if (gimple_code (stmt) != GIMPLE_ASSIGN
2078       && gimple_code (stmt) != GIMPLE_COND
2079       && gimple_code (stmt) != GIMPLE_SWITCH
2080       && (gimple_code (stmt) != GIMPLE_CALL
2081           || !(gimple_call_flags (stmt) & ECF_CONST)))
2082     return p;
2083
2084   /* Stores will stay anyway.  */
2085   if (gimple_store_p (stmt))
2086     return p;
2087
2088   is_load = gimple_assign_load_p (stmt);
2089
2090   /* Loads can be optimized when the value is known.  */
2091   if (is_load)
2092     {
2093       tree op;
2094       gcc_assert (gimple_assign_single_p (stmt));
2095       op = gimple_assign_rhs1 (stmt);
2096       if (!unmodified_parm_or_parm_agg_item (info, stmt, op, &base_index,
2097                                              &aggpos))
2098         return p;
2099     }
2100   else
2101     base_index = -1;
2102
2103   /* See if we understand all operands before we start
2104      adding conditionals.  */
2105   FOR_EACH_SSA_TREE_OPERAND (use, stmt, iter, SSA_OP_USE)
2106     {
2107       tree parm = unmodified_parm (stmt, use);
2108       /* For arguments we can build a condition.  */
2109       if (parm && ipa_get_param_decl_index (info, parm) >= 0)
2110         continue;
2111       if (TREE_CODE (use) != SSA_NAME)
2112         return p;
2113       /* If we know when operand is constant,
2114          we still can say something useful.  */
2115       if (!true_predicate_p (&nonconstant_names[SSA_NAME_VERSION (use)]))
2116         continue;
2117       return p;
2118     }
2119
2120   if (is_load)
2121     op_non_const =
2122       add_condition (summary, base_index, &aggpos, CHANGED, NULL);
2123   else
2124     op_non_const = false_predicate ();
2125   FOR_EACH_SSA_TREE_OPERAND (use, stmt, iter, SSA_OP_USE)
2126     {
2127       tree parm = unmodified_parm (stmt, use);
2128       int index;
2129
2130       if (parm && (index = ipa_get_param_decl_index (info, parm)) >= 0)
2131         {
2132           if (index != base_index)
2133             p = add_condition (summary, index, NULL, CHANGED, NULL_TREE);
2134           else
2135             continue;
2136         }
2137       else
2138         p = nonconstant_names[SSA_NAME_VERSION (use)];
2139       op_non_const = or_predicates (summary->conds, &p, &op_non_const);
2140     }
2141   if ((gimple_code (stmt) == GIMPLE_ASSIGN || gimple_code (stmt) == GIMPLE_CALL)
2142       && gimple_op (stmt, 0)
2143       && TREE_CODE (gimple_op (stmt, 0)) == SSA_NAME)
2144     nonconstant_names[SSA_NAME_VERSION (gimple_op (stmt, 0))]
2145       = op_non_const;
2146   return op_non_const;
2147 }
2148
2149 struct record_modified_bb_info
2150 {
2151   bitmap bb_set;
2152   gimple stmt;
2153 };
2154
2155 /* Callback of walk_aliased_vdefs.  Records basic blocks where the value may be
2156    set except for info->stmt.  */
2157
2158 static bool
2159 record_modified (ao_ref *ao ATTRIBUTE_UNUSED, tree vdef, void *data)
2160 {
2161   struct record_modified_bb_info *info =
2162     (struct record_modified_bb_info *) data;
2163   if (SSA_NAME_DEF_STMT (vdef) == info->stmt)
2164     return false;
2165   bitmap_set_bit (info->bb_set,
2166                   SSA_NAME_IS_DEFAULT_DEF (vdef)
2167                   ? ENTRY_BLOCK_PTR_FOR_FN (cfun)->index
2168                   : gimple_bb (SSA_NAME_DEF_STMT (vdef))->index);
2169   return false;
2170 }
2171
2172 /* Return probability (based on REG_BR_PROB_BASE) that I-th parameter of STMT
2173    will change since last invocation of STMT. 
2174
2175    Value 0 is reserved for compile time invariants.
2176    For common parameters it is REG_BR_PROB_BASE.  For loop invariants it
2177    ought to be REG_BR_PROB_BASE / estimated_iters.  */
2178
2179 static int
2180 param_change_prob (gimple stmt, int i)
2181 {
2182   tree op = gimple_call_arg (stmt, i);
2183   basic_block bb = gimple_bb (stmt);
2184   tree base;
2185
2186   /* Global invariants neve change.  */
2187   if (is_gimple_min_invariant (op))
2188     return 0;
2189   /* We would have to do non-trivial analysis to really work out what
2190      is the probability of value to change (i.e. when init statement
2191      is in a sibling loop of the call). 
2192
2193      We do an conservative estimate: when call is executed N times more often
2194      than the statement defining value, we take the frequency 1/N.  */
2195   if (TREE_CODE (op) == SSA_NAME)
2196     {
2197       int init_freq;
2198
2199       if (!bb->frequency)
2200         return REG_BR_PROB_BASE;
2201
2202       if (SSA_NAME_IS_DEFAULT_DEF (op))
2203         init_freq = ENTRY_BLOCK_PTR_FOR_FN (cfun)->frequency;
2204       else
2205         init_freq = gimple_bb (SSA_NAME_DEF_STMT (op))->frequency;
2206
2207       if (!init_freq)
2208         init_freq = 1;
2209       if (init_freq < bb->frequency)
2210         return MAX (GCOV_COMPUTE_SCALE (init_freq, bb->frequency), 1);
2211       else
2212         return REG_BR_PROB_BASE;
2213     }
2214
2215   base = get_base_address (op);
2216   if (base)
2217     {
2218       ao_ref refd;
2219       int max;
2220       struct record_modified_bb_info info;
2221       bitmap_iterator bi;
2222       unsigned index;
2223       tree init = ctor_for_folding (base);
2224
2225       if (init != error_mark_node)
2226         return 0;
2227       if (!bb->frequency)
2228         return REG_BR_PROB_BASE;
2229       ao_ref_init (&refd, op);
2230       info.stmt = stmt;
2231       info.bb_set = BITMAP_ALLOC (NULL);
2232       walk_aliased_vdefs (&refd, gimple_vuse (stmt), record_modified, &info,
2233                           NULL);
2234       if (bitmap_bit_p (info.bb_set, bb->index))
2235         {
2236           BITMAP_FREE (info.bb_set);
2237           return REG_BR_PROB_BASE;
2238         }
2239
2240       /* Assume that every memory is initialized at entry.
2241          TODO: Can we easilly determine if value is always defined
2242          and thus we may skip entry block?  */
2243       if (ENTRY_BLOCK_PTR_FOR_FN (cfun)->frequency)
2244         max = ENTRY_BLOCK_PTR_FOR_FN (cfun)->frequency;
2245       else
2246         max = 1;
2247
2248       EXECUTE_IF_SET_IN_BITMAP (info.bb_set, 0, index, bi)
2249         max = MIN (max, BASIC_BLOCK_FOR_FN (cfun, index)->frequency);
2250
2251       BITMAP_FREE (info.bb_set);
2252       if (max < bb->frequency)
2253         return MAX (GCOV_COMPUTE_SCALE (max, bb->frequency), 1);
2254       else
2255         return REG_BR_PROB_BASE;
2256     }
2257   return REG_BR_PROB_BASE;
2258 }
2259
2260 /* Find whether a basic block BB is the final block of a (half) diamond CFG
2261    sub-graph and if the predicate the condition depends on is known.  If so,
2262    return true and store the pointer the predicate in *P.  */
2263
2264 static bool
2265 phi_result_unknown_predicate (struct ipa_node_params *info,
2266                               inline_summary *summary, basic_block bb,
2267                               struct predicate *p,
2268                               vec<predicate_t> nonconstant_names)
2269 {
2270   edge e;
2271   edge_iterator ei;
2272   basic_block first_bb = NULL;
2273   gimple stmt;
2274
2275   if (single_pred_p (bb))
2276     {
2277       *p = false_predicate ();
2278       return true;
2279     }
2280
2281   FOR_EACH_EDGE (e, ei, bb->preds)
2282     {
2283       if (single_succ_p (e->src))
2284         {
2285           if (!single_pred_p (e->src))
2286             return false;
2287           if (!first_bb)
2288             first_bb = single_pred (e->src);
2289           else if (single_pred (e->src) != first_bb)
2290             return false;
2291         }
2292       else
2293         {
2294           if (!first_bb)
2295             first_bb = e->src;
2296           else if (e->src != first_bb)
2297             return false;
2298         }
2299     }
2300
2301   if (!first_bb)
2302     return false;
2303
2304   stmt = last_stmt (first_bb);
2305   if (!stmt
2306       || gimple_code (stmt) != GIMPLE_COND
2307       || !is_gimple_ip_invariant (gimple_cond_rhs (stmt)))
2308     return false;
2309
2310   *p = will_be_nonconstant_expr_predicate (info, summary,
2311                                            gimple_cond_lhs (stmt),
2312                                            nonconstant_names);
2313   if (true_predicate_p (p))
2314     return false;
2315   else
2316     return true;
2317 }
2318
2319 /* Given a PHI statement in a function described by inline properties SUMMARY
2320    and *P being the predicate describing whether the selected PHI argument is
2321    known, store a predicate for the result of the PHI statement into
2322    NONCONSTANT_NAMES, if possible.  */
2323
2324 static void
2325 predicate_for_phi_result (struct inline_summary *summary, gphi *phi,
2326                           struct predicate *p,
2327                           vec<predicate_t> nonconstant_names)
2328 {
2329   unsigned i;
2330
2331   for (i = 0; i < gimple_phi_num_args (phi); i++)
2332     {
2333       tree arg = gimple_phi_arg (phi, i)->def;
2334       if (!is_gimple_min_invariant (arg))
2335         {
2336           gcc_assert (TREE_CODE (arg) == SSA_NAME);
2337           *p = or_predicates (summary->conds, p,
2338                               &nonconstant_names[SSA_NAME_VERSION (arg)]);
2339           if (true_predicate_p (p))
2340             return;
2341         }
2342     }
2343
2344   if (dump_file && (dump_flags & TDF_DETAILS))
2345     {
2346       fprintf (dump_file, "\t\tphi predicate: ");
2347       dump_predicate (dump_file, summary->conds, p);
2348     }
2349   nonconstant_names[SSA_NAME_VERSION (gimple_phi_result (phi))] = *p;
2350 }
2351
2352 /* Return predicate specifying when array index in access OP becomes non-constant.  */
2353
2354 static struct predicate
2355 array_index_predicate (inline_summary *info,
2356                        vec< predicate_t> nonconstant_names, tree op)
2357 {
2358   struct predicate p = false_predicate ();
2359   while (handled_component_p (op))
2360     {
2361       if (TREE_CODE (op) == ARRAY_REF || TREE_CODE (op) == ARRAY_RANGE_REF)
2362         {
2363           if (TREE_CODE (TREE_OPERAND (op, 1)) == SSA_NAME)
2364             p = or_predicates (info->conds, &p,
2365                                &nonconstant_names[SSA_NAME_VERSION
2366                                                   (TREE_OPERAND (op, 1))]);
2367         }
2368       op = TREE_OPERAND (op, 0);
2369     }
2370   return p;
2371 }
2372
2373 /* For a typical usage of __builtin_expect (a<b, 1), we
2374    may introduce an extra relation stmt:
2375    With the builtin, we have
2376      t1 = a <= b;
2377      t2 = (long int) t1;
2378      t3 = __builtin_expect (t2, 1);
2379      if (t3 != 0)
2380        goto ...
2381    Without the builtin, we have
2382      if (a<=b)
2383        goto...
2384    This affects the size/time estimation and may have
2385    an impact on the earlier inlining.
2386    Here find this pattern and fix it up later.  */
2387
2388 static gimple
2389 find_foldable_builtin_expect (basic_block bb)
2390 {
2391   gimple_stmt_iterator bsi;
2392
2393   for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
2394     {
2395       gimple stmt = gsi_stmt (bsi);
2396       if (gimple_call_builtin_p (stmt, BUILT_IN_EXPECT)
2397           || (is_gimple_call (stmt)
2398               && gimple_call_internal_p (stmt)
2399               && gimple_call_internal_fn (stmt) == IFN_BUILTIN_EXPECT))
2400         {
2401           tree var = gimple_call_lhs (stmt);
2402           tree arg = gimple_call_arg (stmt, 0);
2403           use_operand_p use_p;
2404           gimple use_stmt;
2405           bool match = false;
2406           bool done = false;
2407
2408           if (!var || !arg)
2409             continue;
2410           gcc_assert (TREE_CODE (var) == SSA_NAME);
2411
2412           while (TREE_CODE (arg) == SSA_NAME)
2413             {
2414               gimple stmt_tmp = SSA_NAME_DEF_STMT (arg);
2415               if (!is_gimple_assign (stmt_tmp))
2416                 break;
2417               switch (gimple_assign_rhs_code (stmt_tmp))
2418                 {
2419                   case LT_EXPR:
2420                   case LE_EXPR:
2421                   case GT_EXPR:
2422                   case GE_EXPR:
2423                   case EQ_EXPR:
2424                   case NE_EXPR:
2425                     match = true;
2426                     done = true;
2427                     break;
2428                   CASE_CONVERT:
2429                     break;
2430                   default:
2431                     done = true;
2432                     break;
2433                 }
2434               if (done)
2435                 break;
2436               arg = gimple_assign_rhs1 (stmt_tmp);
2437             }
2438
2439           if (match && single_imm_use (var, &use_p, &use_stmt)
2440               && gimple_code (use_stmt) == GIMPLE_COND)
2441             return use_stmt;
2442         }
2443     }
2444   return NULL;
2445 }
2446
2447 /* Return true when the basic blocks contains only clobbers followed by RESX.
2448    Such BBs are kept around to make removal of dead stores possible with
2449    presence of EH and will be optimized out by optimize_clobbers later in the
2450    game. 
2451
2452    NEED_EH is used to recurse in case the clobber has non-EH predecestors
2453    that can be clobber only, too.. When it is false, the RESX is not necessary
2454    on the end of basic block.  */
2455
2456 static bool
2457 clobber_only_eh_bb_p (basic_block bb, bool need_eh = true)
2458 {
2459   gimple_stmt_iterator gsi = gsi_last_bb (bb);
2460   edge_iterator ei;
2461   edge e;
2462
2463   if (need_eh)
2464     {
2465       if (gsi_end_p (gsi))
2466         return false;
2467       if (gimple_code (gsi_stmt (gsi)) != GIMPLE_RESX)
2468         return false;
2469       gsi_prev (&gsi);
2470     }
2471   else if (!single_succ_p (bb))
2472     return false;
2473
2474   for (; !gsi_end_p (gsi); gsi_prev (&gsi))
2475     {
2476       gimple stmt = gsi_stmt (gsi);
2477       if (is_gimple_debug (stmt))
2478         continue;
2479       if (gimple_clobber_p (stmt))
2480         continue;
2481       if (gimple_code (stmt) == GIMPLE_LABEL)
2482         break;
2483       return false;
2484     }
2485
2486   /* See if all predecestors are either throws or clobber only BBs.  */
2487   FOR_EACH_EDGE (e, ei, bb->preds)
2488     if (!(e->flags & EDGE_EH)
2489         && !clobber_only_eh_bb_p (e->src, false))
2490       return false;
2491
2492   return true;
2493 }
2494
2495 /* Compute function body size parameters for NODE.
2496    When EARLY is true, we compute only simple summaries without
2497    non-trivial predicates to drive the early inliner.  */
2498
2499 static void
2500 estimate_function_body_sizes (struct cgraph_node *node, bool early)
2501 {
2502   gcov_type time = 0;
2503   /* Estimate static overhead for function prologue/epilogue and alignment. */
2504   int size = 2;
2505   /* Benefits are scaled by probability of elimination that is in range
2506      <0,2>.  */
2507   basic_block bb;
2508   struct function *my_function = DECL_STRUCT_FUNCTION (node->decl);
2509   int freq;
2510   struct inline_summary *info = inline_summaries->get (node);
2511   struct predicate bb_predicate;
2512   struct ipa_node_params *parms_info = NULL;
2513   vec<predicate_t> nonconstant_names = vNULL;
2514   int nblocks, n;
2515   int *order;
2516   predicate array_index = true_predicate ();
2517   gimple fix_builtin_expect_stmt;
2518
2519   info->conds = NULL;
2520   info->entry = NULL;
2521
2522   /* When optimizing and analyzing for IPA inliner, initialize loop optimizer
2523      so we can produce proper inline hints.
2524
2525      When optimizing and analyzing for early inliner, initialize node params
2526      so we can produce correct BB predicates.  */
2527      
2528   if (opt_for_fn (node->decl, optimize))
2529     {
2530       calculate_dominance_info (CDI_DOMINATORS);
2531       if (!early)
2532         loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
2533       else
2534         {
2535           ipa_check_create_node_params ();
2536           ipa_initialize_node_params (node);
2537         }
2538
2539       if (ipa_node_params_sum)
2540         {
2541           parms_info = IPA_NODE_REF (node);
2542           nonconstant_names.safe_grow_cleared
2543             (SSANAMES (my_function)->length ());
2544         }
2545     }
2546
2547   if (dump_file)
2548     fprintf (dump_file, "\nAnalyzing function body size: %s\n",
2549              node->name ());
2550
2551   /* When we run into maximal number of entries, we assign everything to the
2552      constant truth case.  Be sure to have it in list. */
2553   bb_predicate = true_predicate ();
2554   account_size_time (info, 0, 0, &bb_predicate);
2555
2556   bb_predicate = not_inlined_predicate ();
2557   account_size_time (info, 2 * INLINE_SIZE_SCALE, 0, &bb_predicate);
2558
2559   gcc_assert (my_function && my_function->cfg);
2560   if (parms_info)
2561     compute_bb_predicates (node, parms_info, info);
2562   gcc_assert (cfun == my_function);
2563   order = XNEWVEC (int, n_basic_blocks_for_fn (cfun));
2564   nblocks = pre_and_rev_post_order_compute (NULL, order, false);
2565   for (n = 0; n < nblocks; n++)
2566     {
2567       bb = BASIC_BLOCK_FOR_FN (cfun, order[n]);
2568       freq = compute_call_stmt_bb_frequency (node->decl, bb);
2569       if (clobber_only_eh_bb_p (bb))
2570         {
2571           if (dump_file && (dump_flags & TDF_DETAILS))
2572             fprintf (dump_file, "\n Ignoring BB %i;"
2573                      " it will be optimized away by cleanup_clobbers\n",
2574                      bb->index);
2575           continue;
2576         }
2577
2578       /* TODO: Obviously predicates can be propagated down across CFG.  */
2579       if (parms_info)
2580         {
2581           if (bb->aux)
2582             bb_predicate = *(struct predicate *) bb->aux;
2583           else
2584             bb_predicate = false_predicate ();
2585         }
2586       else
2587         bb_predicate = true_predicate ();
2588
2589       if (dump_file && (dump_flags & TDF_DETAILS))
2590         {
2591           fprintf (dump_file, "\n BB %i predicate:", bb->index);
2592           dump_predicate (dump_file, info->conds, &bb_predicate);
2593         }
2594
2595       if (parms_info && nonconstant_names.exists ())
2596         {
2597           struct predicate phi_predicate;
2598           bool first_phi = true;
2599
2600           for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi);
2601                gsi_next (&bsi))
2602             {
2603               if (first_phi
2604                   && !phi_result_unknown_predicate (parms_info, info, bb,
2605                                                     &phi_predicate,
2606                                                     nonconstant_names))
2607                 break;
2608               first_phi = false;
2609               if (dump_file && (dump_flags & TDF_DETAILS))
2610                 {
2611                   fprintf (dump_file, "  ");
2612                   print_gimple_stmt (dump_file, gsi_stmt (bsi), 0, 0);
2613                 }
2614               predicate_for_phi_result (info, bsi.phi (), &phi_predicate,
2615                                         nonconstant_names);
2616             }
2617         }
2618
2619       fix_builtin_expect_stmt = find_foldable_builtin_expect (bb);
2620
2621       for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi);
2622            gsi_next (&bsi))
2623         {
2624           gimple stmt = gsi_stmt (bsi);
2625           int this_size = estimate_num_insns (stmt, &eni_size_weights);
2626           int this_time = estimate_num_insns (stmt, &eni_time_weights);
2627           int prob;
2628           struct predicate will_be_nonconstant;
2629
2630           /* This relation stmt should be folded after we remove
2631              buildin_expect call. Adjust the cost here.  */
2632           if (stmt == fix_builtin_expect_stmt)
2633             {
2634               this_size--;
2635               this_time--;
2636             }
2637
2638           if (dump_file && (dump_flags & TDF_DETAILS))
2639             {
2640               fprintf (dump_file, "  ");
2641               print_gimple_stmt (dump_file, stmt, 0, 0);
2642               fprintf (dump_file, "\t\tfreq:%3.2f size:%3i time:%3i\n",
2643                        ((double) freq) / CGRAPH_FREQ_BASE, this_size,
2644                        this_time);
2645             }
2646
2647           if (gimple_assign_load_p (stmt) && nonconstant_names.exists ())
2648             {
2649               struct predicate this_array_index;
2650               this_array_index =
2651                 array_index_predicate (info, nonconstant_names,
2652                                        gimple_assign_rhs1 (stmt));
2653               if (!false_predicate_p (&this_array_index))
2654                 array_index =
2655                   and_predicates (info->conds, &array_index,
2656                                   &this_array_index);
2657             }
2658           if (gimple_store_p (stmt) && nonconstant_names.exists ())
2659             {
2660               struct predicate this_array_index;
2661               this_array_index =
2662                 array_index_predicate (info, nonconstant_names,
2663                                        gimple_get_lhs (stmt));
2664               if (!false_predicate_p (&this_array_index))
2665                 array_index =
2666                   and_predicates (info->conds, &array_index,
2667                                   &this_array_index);
2668             }
2669
2670
2671           if (is_gimple_call (stmt)
2672               && !gimple_call_internal_p (stmt))
2673             {
2674               struct cgraph_edge *edge = node->get_edge (stmt);
2675               struct inline_edge_summary *es = inline_edge_summary (edge);
2676
2677               /* Special case: results of BUILT_IN_CONSTANT_P will be always
2678                  resolved as constant.  We however don't want to optimize
2679                  out the cgraph edges.  */
2680               if (nonconstant_names.exists ()
2681                   && gimple_call_builtin_p (stmt, BUILT_IN_CONSTANT_P)
2682                   && gimple_call_lhs (stmt)
2683                   && TREE_CODE (gimple_call_lhs (stmt)) == SSA_NAME)
2684                 {
2685                   struct predicate false_p = false_predicate ();
2686                   nonconstant_names[SSA_NAME_VERSION (gimple_call_lhs (stmt))]
2687                     = false_p;
2688                 }
2689               if (ipa_node_params_sum)
2690                 {
2691                   int count = gimple_call_num_args (stmt);
2692                   int i;
2693
2694                   if (count)
2695                     es->param.safe_grow_cleared (count);
2696                   for (i = 0; i < count; i++)
2697                     {
2698                       int prob = param_change_prob (stmt, i);
2699                       gcc_assert (prob >= 0 && prob <= REG_BR_PROB_BASE);
2700                       es->param[i].change_prob = prob;
2701                     }
2702                 }
2703
2704               es->call_stmt_size = this_size;
2705               es->call_stmt_time = this_time;
2706               es->loop_depth = bb_loop_depth (bb);
2707               edge_set_predicate (edge, &bb_predicate);
2708             }
2709
2710           /* TODO: When conditional jump or swithc is known to be constant, but
2711              we did not translate it into the predicates, we really can account
2712              just maximum of the possible paths.  */
2713           if (parms_info)
2714             will_be_nonconstant
2715               = will_be_nonconstant_predicate (parms_info, info,
2716                                                stmt, nonconstant_names);
2717           if (this_time || this_size)
2718             {
2719               struct predicate p;
2720
2721               this_time *= freq;
2722
2723               prob = eliminated_by_inlining_prob (stmt);
2724               if (prob == 1 && dump_file && (dump_flags & TDF_DETAILS))
2725                 fprintf (dump_file,
2726                          "\t\t50%% will be eliminated by inlining\n");
2727               if (prob == 2 && dump_file && (dump_flags & TDF_DETAILS))
2728                 fprintf (dump_file, "\t\tWill be eliminated by inlining\n");
2729
2730               if (parms_info)
2731                 p = and_predicates (info->conds, &bb_predicate,
2732                                     &will_be_nonconstant);
2733               else
2734                 p = true_predicate ();
2735
2736               if (!false_predicate_p (&p)
2737                   || (is_gimple_call (stmt)
2738                       && !false_predicate_p (&bb_predicate)))
2739                 {
2740                   time += this_time;
2741                   size += this_size;
2742                   if (time > MAX_TIME * INLINE_TIME_SCALE)
2743                     time = MAX_TIME * INLINE_TIME_SCALE;
2744                 }
2745
2746               /* We account everything but the calls.  Calls have their own
2747                  size/time info attached to cgraph edges.  This is necessary
2748                  in order to make the cost disappear after inlining.  */
2749               if (!is_gimple_call (stmt))
2750                 {
2751                   if (prob)
2752                     {
2753                       struct predicate ip = not_inlined_predicate ();
2754                       ip = and_predicates (info->conds, &ip, &p);
2755                       account_size_time (info, this_size * prob,
2756                                          this_time * prob, &ip);
2757                     }
2758                   if (prob != 2)
2759                     account_size_time (info, this_size * (2 - prob),
2760                                        this_time * (2 - prob), &p);
2761                 }
2762
2763               gcc_assert (time >= 0);
2764               gcc_assert (size >= 0);
2765             }
2766         }
2767     }
2768   set_hint_predicate (&inline_summaries->get (node)->array_index, array_index);
2769   time = (time + CGRAPH_FREQ_BASE / 2) / CGRAPH_FREQ_BASE;
2770   if (time > MAX_TIME)
2771     time = MAX_TIME;
2772   free (order);
2773
2774   if (nonconstant_names.exists () && !early)
2775     {
2776       struct loop *loop;
2777       predicate loop_iterations = true_predicate ();
2778       predicate loop_stride = true_predicate ();
2779
2780       if (dump_file && (dump_flags & TDF_DETAILS))
2781         flow_loops_dump (dump_file, NULL, 0);
2782       scev_initialize ();
2783       FOR_EACH_LOOP (loop, 0)
2784         {
2785           vec<edge> exits;
2786           edge ex;
2787           unsigned int j, i;
2788           struct tree_niter_desc niter_desc;
2789           basic_block *body = get_loop_body (loop);
2790           bb_predicate = *(struct predicate *) loop->header->aux;
2791
2792           exits = get_loop_exit_edges (loop);
2793           FOR_EACH_VEC_ELT (exits, j, ex)
2794             if (number_of_iterations_exit (loop, ex, &niter_desc, false)
2795                 && !is_gimple_min_invariant (niter_desc.niter))
2796             {
2797               predicate will_be_nonconstant
2798                 = will_be_nonconstant_expr_predicate (parms_info, info,
2799                                                       niter_desc.niter,
2800                                                       nonconstant_names);
2801               if (!true_predicate_p (&will_be_nonconstant))
2802                 will_be_nonconstant = and_predicates (info->conds,
2803                                                       &bb_predicate,
2804                                                       &will_be_nonconstant);
2805               if (!true_predicate_p (&will_be_nonconstant)
2806                   && !false_predicate_p (&will_be_nonconstant))
2807                 /* This is slightly inprecise.  We may want to represent each
2808                    loop with independent predicate.  */
2809                 loop_iterations =
2810                   and_predicates (info->conds, &loop_iterations,
2811                                   &will_be_nonconstant);
2812             }
2813           exits.release ();
2814
2815           for (i = 0; i < loop->num_nodes; i++)
2816             {
2817               gimple_stmt_iterator gsi;
2818               bb_predicate = *(struct predicate *) body[i]->aux;
2819               for (gsi = gsi_start_bb (body[i]); !gsi_end_p (gsi);
2820                    gsi_next (&gsi))
2821                 {
2822                   gimple stmt = gsi_stmt (gsi);
2823                   affine_iv iv;
2824                   ssa_op_iter iter;
2825                   tree use;
2826
2827                   FOR_EACH_SSA_TREE_OPERAND (use, stmt, iter, SSA_OP_USE)
2828                   {
2829                     predicate will_be_nonconstant;
2830
2831                     if (!simple_iv
2832                         (loop, loop_containing_stmt (stmt), use, &iv, true)
2833                         || is_gimple_min_invariant (iv.step))
2834                       continue;
2835                     will_be_nonconstant
2836                       = will_be_nonconstant_expr_predicate (parms_info, info,
2837                                                             iv.step,
2838                                                             nonconstant_names);
2839                     if (!true_predicate_p (&will_be_nonconstant))
2840                       will_be_nonconstant
2841                          = and_predicates (info->conds,
2842                                            &bb_predicate,
2843                                            &will_be_nonconstant);
2844                     if (!true_predicate_p (&will_be_nonconstant)
2845                         && !false_predicate_p (&will_be_nonconstant))
2846                       /* This is slightly inprecise.  We may want to represent
2847                          each loop with independent predicate.  */
2848                       loop_stride =
2849                         and_predicates (info->conds, &loop_stride,
2850                                         &will_be_nonconstant);
2851                   }
2852                 }
2853             }
2854           free (body);
2855         }
2856       set_hint_predicate (&inline_summaries->get (node)->loop_iterations,
2857                           loop_iterations);
2858       set_hint_predicate (&inline_summaries->get (node)->loop_stride, loop_stride);
2859       scev_finalize ();
2860     }
2861   FOR_ALL_BB_FN (bb, my_function)
2862     {
2863       edge e;
2864       edge_iterator ei;
2865
2866       if (bb->aux)
2867         pool_free (edge_predicate_pool, bb->aux);
2868       bb->aux = NULL;
2869       FOR_EACH_EDGE (e, ei, bb->succs)
2870         {
2871           if (e->aux)
2872             pool_free (edge_predicate_pool, e->aux);
2873           e->aux = NULL;
2874         }
2875     }
2876   inline_summaries->get (node)->self_time = time;
2877   inline_summaries->get (node)->self_size = size;
2878   nonconstant_names.release ();
2879   if (opt_for_fn (node->decl, optimize))
2880     {
2881       if (!early)
2882         loop_optimizer_finalize ();
2883       else if (!ipa_edge_args_vector)
2884         ipa_free_all_node_params ();
2885       free_dominance_info (CDI_DOMINATORS);
2886     }
2887   if (dump_file)
2888     {
2889       fprintf (dump_file, "\n");
2890       dump_inline_summary (dump_file, node);
2891     }
2892 }
2893
2894
2895 /* Compute parameters of functions used by inliner.
2896    EARLY is true when we compute parameters for the early inliner  */
2897
2898 void
2899 compute_inline_parameters (struct cgraph_node *node, bool early)
2900 {
2901   HOST_WIDE_INT self_stack_size;
2902   struct cgraph_edge *e;
2903   struct inline_summary *info;
2904
2905   gcc_assert (!node->global.inlined_to);
2906
2907   inline_summary_alloc ();
2908
2909   info = inline_summaries->get (node);
2910   reset_inline_summary (node, info);
2911
2912   /* FIXME: Thunks are inlinable, but tree-inline don't know how to do that.
2913      Once this happen, we will need to more curefully predict call
2914      statement size.  */
2915   if (node->thunk.thunk_p)
2916     {
2917       struct inline_edge_summary *es = inline_edge_summary (node->callees);
2918       struct predicate t = true_predicate ();
2919
2920       info->inlinable = 0;
2921       node->callees->call_stmt_cannot_inline_p = true;
2922       node->local.can_change_signature = false;
2923       es->call_stmt_time = 1;
2924       es->call_stmt_size = 1;
2925       account_size_time (info, 0, 0, &t);
2926       return;
2927     }
2928
2929   /* Even is_gimple_min_invariant rely on current_function_decl.  */
2930   push_cfun (DECL_STRUCT_FUNCTION (node->decl));
2931
2932   /* Estimate the stack size for the function if we're optimizing.  */
2933   self_stack_size = optimize ? estimated_stack_frame_size (node) : 0;
2934   info->estimated_self_stack_size = self_stack_size;
2935   info->estimated_stack_size = self_stack_size;
2936   info->stack_frame_offset = 0;
2937
2938   /* Can this function be inlined at all?  */
2939   if (!opt_for_fn (node->decl, optimize)
2940       && !lookup_attribute ("always_inline",
2941                             DECL_ATTRIBUTES (node->decl)))
2942     info->inlinable = false;
2943   else
2944     info->inlinable = tree_inlinable_function_p (node->decl);
2945
2946   info->contains_cilk_spawn = fn_contains_cilk_spawn_p (cfun);
2947
2948   /* Type attributes can use parameter indices to describe them.  */
2949   if (TYPE_ATTRIBUTES (TREE_TYPE (node->decl)))
2950     node->local.can_change_signature = false;
2951   else
2952     {
2953       /* Otherwise, inlinable functions always can change signature.  */
2954       if (info->inlinable)
2955         node->local.can_change_signature = true;
2956       else
2957         {
2958           /* Functions calling builtin_apply can not change signature.  */
2959           for (e = node->callees; e; e = e->next_callee)
2960             {
2961               tree cdecl = e->callee->decl;
2962               if (DECL_BUILT_IN (cdecl)
2963                   && DECL_BUILT_IN_CLASS (cdecl) == BUILT_IN_NORMAL
2964                   && (DECL_FUNCTION_CODE (cdecl) == BUILT_IN_APPLY_ARGS
2965                       || DECL_FUNCTION_CODE (cdecl) == BUILT_IN_VA_START))
2966                 break;
2967             }
2968           node->local.can_change_signature = !e;
2969         }
2970     }
2971   estimate_function_body_sizes (node, early);
2972
2973   for (e = node->callees; e; e = e->next_callee)
2974     if (e->callee->comdat_local_p ())
2975       break;
2976   node->calls_comdat_local = (e != NULL);
2977
2978   /* Inlining characteristics are maintained by the cgraph_mark_inline.  */
2979   info->time = info->self_time;
2980   info->size = info->self_size;
2981   info->stack_frame_offset = 0;
2982   info->estimated_stack_size = info->estimated_self_stack_size;
2983 #ifdef ENABLE_CHECKING
2984   inline_update_overall_summary (node);
2985   gcc_assert (info->time == info->self_time && info->size == info->self_size);
2986 #endif
2987
2988   pop_cfun ();
2989 }
2990
2991
2992 /* Compute parameters of functions used by inliner using
2993    current_function_decl.  */
2994
2995 static unsigned int
2996 compute_inline_parameters_for_current (void)
2997 {
2998   compute_inline_parameters (cgraph_node::get (current_function_decl), true);
2999   return 0;
3000 }
3001
3002 namespace {
3003
3004 const pass_data pass_data_inline_parameters =
3005 {
3006   GIMPLE_PASS, /* type */
3007   "inline_param", /* name */
3008   OPTGROUP_INLINE, /* optinfo_flags */
3009   TV_INLINE_PARAMETERS, /* tv_id */
3010   0, /* properties_required */
3011   0, /* properties_provided */
3012   0, /* properties_destroyed */
3013   0, /* todo_flags_start */
3014   0, /* todo_flags_finish */
3015 };
3016
3017 class pass_inline_parameters : public gimple_opt_pass
3018 {
3019 public:
3020   pass_inline_parameters (gcc::context *ctxt)
3021     : gimple_opt_pass (pass_data_inline_parameters, ctxt)
3022   {}
3023
3024   /* opt_pass methods: */
3025   opt_pass * clone () { return new pass_inline_parameters (m_ctxt); }
3026   virtual unsigned int execute (function *)
3027     {
3028       return compute_inline_parameters_for_current ();
3029     }
3030
3031 }; // class pass_inline_parameters
3032
3033 } // anon namespace
3034
3035 gimple_opt_pass *
3036 make_pass_inline_parameters (gcc::context *ctxt)
3037 {
3038   return new pass_inline_parameters (ctxt);
3039 }
3040
3041
3042 /* Estimate benefit devirtualizing indirect edge IE, provided KNOWN_VALS,
3043    KNOWN_CONTEXTS and KNOWN_AGGS.  */
3044
3045 static bool
3046 estimate_edge_devirt_benefit (struct cgraph_edge *ie,
3047                               int *size, int *time,
3048                               vec<tree> known_vals,
3049                               vec<ipa_polymorphic_call_context> known_contexts,
3050                               vec<ipa_agg_jump_function_p> known_aggs)
3051 {
3052   tree target;
3053   struct cgraph_node *callee;
3054   struct inline_summary *isummary;
3055   enum availability avail;
3056   bool speculative;
3057
3058   if (!known_vals.exists () && !known_contexts.exists ())
3059     return false;
3060   if (!opt_for_fn (ie->caller->decl, flag_indirect_inlining))
3061     return false;
3062
3063   target = ipa_get_indirect_edge_target (ie, known_vals, known_contexts,
3064                                          known_aggs, &speculative);
3065   if (!target || speculative)
3066     return false;
3067
3068   /* Account for difference in cost between indirect and direct calls.  */
3069   *size -= (eni_size_weights.indirect_call_cost - eni_size_weights.call_cost);
3070   *time -= (eni_time_weights.indirect_call_cost - eni_time_weights.call_cost);
3071   gcc_checking_assert (*time >= 0);
3072   gcc_checking_assert (*size >= 0);
3073
3074   callee = cgraph_node::get (target);
3075   if (!callee || !callee->definition)
3076     return false;
3077   callee = callee->function_symbol (&avail);
3078   if (avail < AVAIL_AVAILABLE)
3079     return false;
3080   isummary = inline_summaries->get (callee);
3081   return isummary->inlinable;
3082 }
3083
3084 /* Increase SIZE, MIN_SIZE (if non-NULL) and TIME for size and time needed to
3085    handle edge E with probability PROB.
3086    Set HINTS if edge may be devirtualized.
3087    KNOWN_VALS, KNOWN_AGGS and KNOWN_CONTEXTS describe context of the call
3088    site.  */
3089
3090 static inline void
3091 estimate_edge_size_and_time (struct cgraph_edge *e, int *size, int *min_size,
3092                              int *time,
3093                              int prob,
3094                              vec<tree> known_vals,
3095                              vec<ipa_polymorphic_call_context> known_contexts,
3096                              vec<ipa_agg_jump_function_p> known_aggs,
3097                              inline_hints *hints)
3098 {
3099   struct inline_edge_summary *es = inline_edge_summary (e);
3100   int call_size = es->call_stmt_size;
3101   int call_time = es->call_stmt_time;
3102   int cur_size;
3103   if (!e->callee
3104       && estimate_edge_devirt_benefit (e, &call_size, &call_time,
3105                                        known_vals, known_contexts, known_aggs)
3106       && hints && e->maybe_hot_p ())
3107     *hints |= INLINE_HINT_indirect_call;
3108   cur_size = call_size * INLINE_SIZE_SCALE;
3109   *size += cur_size;
3110   if (min_size)
3111     *min_size += cur_size;
3112   *time += apply_probability ((gcov_type) call_time, prob)
3113     * e->frequency * (INLINE_TIME_SCALE / CGRAPH_FREQ_BASE);
3114   if (*time > MAX_TIME * INLINE_TIME_SCALE)
3115     *time = MAX_TIME * INLINE_TIME_SCALE;
3116 }
3117
3118
3119
3120 /* Increase SIZE, MIN_SIZE and TIME for size and time needed to handle all
3121    calls in NODE.  POSSIBLE_TRUTHS, KNOWN_VALS, KNOWN_AGGS and KNOWN_CONTEXTS
3122    describe context of the call site.  */
3123
3124 static void
3125 estimate_calls_size_and_time (struct cgraph_node *node, int *size,
3126                               int *min_size, int *time,
3127                               inline_hints *hints,
3128                               clause_t possible_truths,
3129                               vec<tree> known_vals,
3130                               vec<ipa_polymorphic_call_context> known_contexts,
3131                               vec<ipa_agg_jump_function_p> known_aggs)
3132 {
3133   struct cgraph_edge *e;
3134   for (e = node->callees; e; e = e->next_callee)
3135     {
3136       struct inline_edge_summary *es = inline_edge_summary (e);
3137
3138       /* Do not care about zero sized builtins.  */
3139       if (e->inline_failed && !es->call_stmt_size)
3140         {
3141           gcc_checking_assert (!es->call_stmt_time);
3142           continue;
3143         }
3144       if (!es->predicate
3145           || evaluate_predicate (es->predicate, possible_truths))
3146         {
3147           if (e->inline_failed)
3148             {
3149               /* Predicates of calls shall not use NOT_CHANGED codes,
3150                  sowe do not need to compute probabilities.  */
3151               estimate_edge_size_and_time (e, size,
3152                                            es->predicate ? NULL : min_size,
3153                                            time, REG_BR_PROB_BASE,
3154                                            known_vals, known_contexts,
3155                                            known_aggs, hints);
3156             }
3157           else
3158             estimate_calls_size_and_time (e->callee, size, min_size, time,
3159                                           hints,
3160                                           possible_truths,
3161                                           known_vals, known_contexts,
3162                                           known_aggs);
3163         }
3164     }
3165   for (e = node->indirect_calls; e; e = e->next_callee)
3166     {
3167       struct inline_edge_summary *es = inline_edge_summary (e);
3168       if (!es->predicate
3169           || evaluate_predicate (es->predicate, possible_truths))
3170         estimate_edge_size_and_time (e, size,
3171                                      es->predicate ? NULL : min_size,
3172                                      time, REG_BR_PROB_BASE,
3173                                      known_vals, known_contexts, known_aggs,
3174                                      hints);
3175     }
3176 }
3177
3178
3179 /* Estimate size and time needed to execute NODE assuming
3180    POSSIBLE_TRUTHS clause, and KNOWN_VALS, KNOWN_AGGS and KNOWN_CONTEXTS
3181    information about NODE's arguments.  If non-NULL use also probability
3182    information present in INLINE_PARAM_SUMMARY vector.
3183    Additionally detemine hints determined by the context.  Finally compute
3184    minimal size needed for the call that is independent on the call context and
3185    can be used for fast estimates.  Return the values in RET_SIZE,
3186    RET_MIN_SIZE, RET_TIME and RET_HINTS.  */
3187
3188 static void
3189 estimate_node_size_and_time (struct cgraph_node *node,
3190                              clause_t possible_truths,
3191                              vec<tree> known_vals,
3192                              vec<ipa_polymorphic_call_context> known_contexts,
3193                              vec<ipa_agg_jump_function_p> known_aggs,
3194                              int *ret_size, int *ret_min_size, int *ret_time,
3195                              inline_hints *ret_hints,
3196                              vec<inline_param_summary>
3197                              inline_param_summary)
3198 {
3199   struct inline_summary *info = inline_summaries->get (node);
3200   size_time_entry *e;
3201   int size = 0;
3202   int time = 0;
3203   int min_size = 0;
3204   inline_hints hints = 0;
3205   int i;
3206
3207   if (dump_file && (dump_flags & TDF_DETAILS))
3208     {
3209       bool found = false;
3210       fprintf (dump_file, "   Estimating body: %s/%i\n"
3211                "   Known to be false: ", node->name (),
3212                node->order);
3213
3214       for (i = predicate_not_inlined_condition;
3215            i < (predicate_first_dynamic_condition
3216                 + (int) vec_safe_length (info->conds)); i++)
3217         if (!(possible_truths & (1 << i)))
3218           {
3219             if (found)
3220               fprintf (dump_file, ", ");
3221             found = true;
3222             dump_condition (dump_file, info->conds, i);
3223           }
3224     }
3225
3226   for (i = 0; vec_safe_iterate (info->entry, i, &e); i++)
3227     if (evaluate_predicate (&e->predicate, possible_truths))
3228       {
3229         size += e->size;
3230         gcc_checking_assert (e->time >= 0);
3231         gcc_checking_assert (time >= 0);
3232         if (!inline_param_summary.exists ())
3233           time += e->time;
3234         else
3235           {
3236             int prob = predicate_probability (info->conds,
3237                                               &e->predicate,
3238                                               possible_truths,
3239                                               inline_param_summary);
3240             gcc_checking_assert (prob >= 0);
3241             gcc_checking_assert (prob <= REG_BR_PROB_BASE);
3242             time += apply_probability ((gcov_type) e->time, prob);
3243           }
3244         if (time > MAX_TIME * INLINE_TIME_SCALE)
3245           time = MAX_TIME * INLINE_TIME_SCALE;
3246         gcc_checking_assert (time >= 0);
3247
3248       }
3249   gcc_checking_assert (true_predicate_p (&(*info->entry)[0].predicate));
3250   min_size = (*info->entry)[0].size;
3251   gcc_checking_assert (size >= 0);
3252   gcc_checking_assert (time >= 0);
3253
3254   if (info->loop_iterations
3255       && !evaluate_predicate (info->loop_iterations, possible_truths))
3256     hints |= INLINE_HINT_loop_iterations;
3257   if (info->loop_stride
3258       && !evaluate_predicate (info->loop_stride, possible_truths))
3259     hints |= INLINE_HINT_loop_stride;
3260   if (info->array_index
3261       && !evaluate_predicate (info->array_index, possible_truths))
3262     hints |= INLINE_HINT_array_index;
3263   if (info->scc_no)
3264     hints |= INLINE_HINT_in_scc;
3265   if (DECL_DECLARED_INLINE_P (node->decl))
3266     hints |= INLINE_HINT_declared_inline;
3267
3268   estimate_calls_size_and_time (node, &size, &min_size, &time, &hints, possible_truths,
3269                                 known_vals, known_contexts, known_aggs);
3270   gcc_checking_assert (size >= 0);
3271   gcc_checking_assert (time >= 0);
3272   time = RDIV (time, INLINE_TIME_SCALE);
3273   size = RDIV (size, INLINE_SIZE_SCALE);
3274   min_size = RDIV (min_size, INLINE_SIZE_SCALE);
3275
3276   if (dump_file && (dump_flags & TDF_DETAILS))
3277     fprintf (dump_file, "\n   size:%i time:%i\n", (int) size, (int) time);
3278   if (ret_time)
3279     *ret_time = time;
3280   if (ret_size)
3281     *ret_size = size;
3282   if (ret_min_size)
3283     *ret_min_size = min_size;
3284   if (ret_hints)
3285     *ret_hints = hints;
3286   return;
3287 }
3288
3289
3290 /* Estimate size and time needed to execute callee of EDGE assuming that
3291    parameters known to be constant at caller of EDGE are propagated.
3292    KNOWN_VALS and KNOWN_CONTEXTS are vectors of assumed known constant values
3293    and types for parameters.  */
3294
3295 void
3296 estimate_ipcp_clone_size_and_time (struct cgraph_node *node,
3297                                    vec<tree> known_vals,
3298                                    vec<ipa_polymorphic_call_context>
3299                                    known_contexts,
3300                                    vec<ipa_agg_jump_function_p> known_aggs,
3301                                    int *ret_size, int *ret_time,
3302                                    inline_hints *hints)
3303 {
3304   clause_t clause;
3305
3306   clause = evaluate_conditions_for_known_args (node, false, known_vals,
3307                                                known_aggs);
3308   estimate_node_size_and_time (node, clause, known_vals, known_contexts,
3309                                known_aggs, ret_size, NULL, ret_time, hints, vNULL);
3310 }
3311
3312 /* Translate all conditions from callee representation into caller
3313    representation and symbolically evaluate predicate P into new predicate.
3314
3315    INFO is inline_summary of function we are adding predicate into, CALLEE_INFO
3316    is summary of function predicate P is from. OPERAND_MAP is array giving
3317    callee formal IDs the caller formal IDs. POSSSIBLE_TRUTHS is clausule of all
3318    callee conditions that may be true in caller context.  TOPLEV_PREDICATE is
3319    predicate under which callee is executed.  OFFSET_MAP is an array of of
3320    offsets that need to be added to conditions, negative offset means that
3321    conditions relying on values passed by reference have to be discarded
3322    because they might not be preserved (and should be considered offset zero
3323    for other purposes).  */
3324
3325 static struct predicate
3326 remap_predicate (struct inline_summary *info,
3327                  struct inline_summary *callee_info,
3328                  struct predicate *p,
3329                  vec<int> operand_map,
3330                  vec<int> offset_map,
3331                  clause_t possible_truths, struct predicate *toplev_predicate)
3332 {
3333   int i;
3334   struct predicate out = true_predicate ();
3335
3336   /* True predicate is easy.  */
3337   if (true_predicate_p (p))
3338     return *toplev_predicate;
3339   for (i = 0; p->clause[i]; i++)
3340     {
3341       clause_t clause = p->clause[i];
3342       int cond;
3343       struct predicate clause_predicate = false_predicate ();
3344
3345       gcc_assert (i < MAX_CLAUSES);
3346
3347       for (cond = 0; cond < NUM_CONDITIONS; cond++)
3348         /* Do we have condition we can't disprove?   */
3349         if (clause & possible_truths & (1 << cond))
3350           {
3351             struct predicate cond_predicate;
3352             /* Work out if the condition can translate to predicate in the
3353                inlined function.  */
3354             if (cond >= predicate_first_dynamic_condition)
3355               {
3356                 struct condition *c;
3357
3358                 c = &(*callee_info->conds)[cond
3359                                            -
3360                                            predicate_first_dynamic_condition];
3361                 /* See if we can remap condition operand to caller's operand.
3362                    Otherwise give up.  */
3363                 if (!operand_map.exists ()
3364                     || (int) operand_map.length () <= c->operand_num
3365                     || operand_map[c->operand_num] == -1
3366                     /* TODO: For non-aggregate conditions, adding an offset is
3367                        basically an arithmetic jump function processing which
3368                        we should support in future.  */
3369                     || ((!c->agg_contents || !c->by_ref)
3370                         && offset_map[c->operand_num] > 0)
3371                     || (c->agg_contents && c->by_ref
3372                         && offset_map[c->operand_num] < 0))
3373                   cond_predicate = true_predicate ();
3374                 else
3375                   {
3376                     struct agg_position_info ap;
3377                     HOST_WIDE_INT offset_delta = offset_map[c->operand_num];
3378                     if (offset_delta < 0)
3379                       {
3380                         gcc_checking_assert (!c->agg_contents || !c->by_ref);
3381                         offset_delta = 0;
3382                       }
3383                     gcc_assert (!c->agg_contents
3384                                 || c->by_ref || offset_delta == 0);
3385                     ap.offset = c->offset + offset_delta;
3386                     ap.agg_contents = c->agg_contents;
3387                     ap.by_ref = c->by_ref;
3388                     cond_predicate = add_condition (info,
3389                                                     operand_map[c->operand_num],
3390                                                     &ap, c->code, c->val);
3391                   }
3392               }
3393             /* Fixed conditions remains same, construct single
3394                condition predicate.  */
3395             else
3396               {
3397                 cond_predicate.clause[0] = 1 << cond;
3398                 cond_predicate.clause[1] = 0;
3399               }
3400             clause_predicate = or_predicates (info->conds, &clause_predicate,
3401                                               &cond_predicate);
3402           }
3403       out = and_predicates (info->conds, &out, &clause_predicate);
3404     }
3405   return and_predicates (info->conds, &out, toplev_predicate);
3406 }
3407
3408
3409 /* Update summary information of inline clones after inlining.
3410    Compute peak stack usage.  */
3411
3412 static void
3413 inline_update_callee_summaries (struct cgraph_node *node, int depth)
3414 {
3415   struct cgraph_edge *e;
3416   struct inline_summary *callee_info = inline_summaries->get (node);
3417   struct inline_summary *caller_info = inline_summaries->get (node->callers->caller);
3418   HOST_WIDE_INT peak;
3419
3420   callee_info->stack_frame_offset
3421     = caller_info->stack_frame_offset
3422     + caller_info->estimated_self_stack_size;
3423   peak = callee_info->stack_frame_offset
3424     + callee_info->estimated_self_stack_size;
3425   if (inline_summaries->get (node->global.inlined_to)->estimated_stack_size < peak)
3426       inline_summaries->get (node->global.inlined_to)->estimated_stack_size = peak;
3427   ipa_propagate_frequency (node);
3428   for (e = node->callees; e; e = e->next_callee)
3429     {
3430       if (!e->inline_failed)
3431         inline_update_callee_summaries (e->callee, depth);
3432       inline_edge_summary (e)->loop_depth += depth;
3433     }
3434   for (e = node->indirect_calls; e; e = e->next_callee)
3435     inline_edge_summary (e)->loop_depth += depth;
3436 }
3437
3438 /* Update change_prob of EDGE after INLINED_EDGE has been inlined.
3439    When functoin A is inlined in B and A calls C with parameter that
3440    changes with probability PROB1 and C is known to be passthroug
3441    of argument if B that change with probability PROB2, the probability
3442    of change is now PROB1*PROB2.  */
3443
3444 static void
3445 remap_edge_change_prob (struct cgraph_edge *inlined_edge,
3446                         struct cgraph_edge *edge)
3447 {
3448   if (ipa_node_params_sum)
3449     {
3450       int i;
3451       struct ipa_edge_args *args = IPA_EDGE_REF (edge);
3452       struct inline_edge_summary *es = inline_edge_summary (edge);
3453       struct inline_edge_summary *inlined_es
3454         = inline_edge_summary (inlined_edge);
3455
3456       for (i = 0; i < ipa_get_cs_argument_count (args); i++)
3457         {
3458           struct ipa_jump_func *jfunc = ipa_get_ith_jump_func (args, i);
3459           if (jfunc->type == IPA_JF_PASS_THROUGH
3460               && (ipa_get_jf_pass_through_formal_id (jfunc)
3461                   < (int) inlined_es->param.length ()))
3462             {
3463               int jf_formal_id = ipa_get_jf_pass_through_formal_id (jfunc);
3464               int prob1 = es->param[i].change_prob;
3465               int prob2 = inlined_es->param[jf_formal_id].change_prob;
3466               int prob = combine_probabilities (prob1, prob2);
3467
3468               if (prob1 && prob2 && !prob)
3469                 prob = 1;
3470
3471               es->param[i].change_prob = prob;
3472             }
3473         }
3474     }
3475 }
3476
3477 /* Update edge summaries of NODE after INLINED_EDGE has been inlined.
3478
3479    Remap predicates of callees of NODE.  Rest of arguments match
3480    remap_predicate.
3481
3482    Also update change probabilities.  */
3483
3484 static void
3485 remap_edge_summaries (struct cgraph_edge *inlined_edge,
3486                       struct cgraph_node *node,
3487                       struct inline_summary *info,
3488                       struct inline_summary *callee_info,
3489                       vec<int> operand_map,
3490                       vec<int> offset_map,
3491                       clause_t possible_truths,
3492                       struct predicate *toplev_predicate)
3493 {
3494   struct cgraph_edge *e, *next;
3495   for (e = node->callees; e; e = next)
3496     {
3497       struct inline_edge_summary *es = inline_edge_summary (e);
3498       struct predicate p;
3499       next = e->next_callee;
3500
3501       if (e->inline_failed)
3502         {
3503           remap_edge_change_prob (inlined_edge, e);
3504
3505           if (es->predicate)
3506             {
3507               p = remap_predicate (info, callee_info,
3508                                    es->predicate, operand_map, offset_map,
3509                                    possible_truths, toplev_predicate);
3510               edge_set_predicate (e, &p);
3511             }
3512           else
3513             edge_set_predicate (e, toplev_predicate);
3514         }
3515       else
3516         remap_edge_summaries (inlined_edge, e->callee, info, callee_info,
3517                               operand_map, offset_map, possible_truths,
3518                               toplev_predicate);
3519     }
3520   for (e = node->indirect_calls; e; e = next)
3521     {
3522       struct inline_edge_summary *es = inline_edge_summary (e);
3523       struct predicate p;
3524       next = e->next_callee;
3525
3526       remap_edge_change_prob (inlined_edge, e);
3527       if (es->predicate)
3528         {
3529           p = remap_predicate (info, callee_info,
3530                                es->predicate, operand_map, offset_map,
3531                                possible_truths, toplev_predicate);
3532           edge_set_predicate (e, &p);
3533         }
3534       else
3535         edge_set_predicate (e, toplev_predicate);
3536     }
3537 }
3538
3539 /* Same as remap_predicate, but set result into hint *HINT.  */
3540
3541 static void
3542 remap_hint_predicate (struct inline_summary *info,
3543                       struct inline_summary *callee_info,
3544                       struct predicate **hint,
3545                       vec<int> operand_map,
3546                       vec<int> offset_map,
3547                       clause_t possible_truths,
3548                       struct predicate *toplev_predicate)
3549 {
3550   predicate p;
3551
3552   if (!*hint)
3553     return;
3554   p = remap_predicate (info, callee_info,
3555                        *hint,
3556                        operand_map, offset_map,
3557                        possible_truths, toplev_predicate);
3558   if (!false_predicate_p (&p) && !true_predicate_p (&p))
3559     {
3560       if (!*hint)
3561         set_hint_predicate (hint, p);
3562       else
3563         **hint = and_predicates (info->conds, *hint, &p);
3564     }
3565 }
3566
3567 /* We inlined EDGE.  Update summary of the function we inlined into.  */
3568
3569 void
3570 inline_merge_summary (struct cgraph_edge *edge)
3571 {
3572   struct inline_summary *callee_info = inline_summaries->get (edge->callee);
3573   struct cgraph_node *to = (edge->caller->global.inlined_to
3574                             ? edge->caller->global.inlined_to : edge->caller);
3575   struct inline_summary *info = inline_summaries->get (to);
3576   clause_t clause = 0;          /* not_inline is known to be false.  */
3577   size_time_entry *e;
3578   vec<int> operand_map = vNULL;
3579   vec<int> offset_map = vNULL;
3580   int i;
3581   struct predicate toplev_predicate;
3582   struct predicate true_p = true_predicate ();
3583   struct inline_edge_summary *es = inline_edge_summary (edge);
3584
3585   if (es->predicate)
3586     toplev_predicate = *es->predicate;
3587   else
3588     toplev_predicate = true_predicate ();
3589
3590   if (callee_info->conds)
3591     evaluate_properties_for_edge (edge, true, &clause, NULL, NULL, NULL);
3592   if (ipa_node_params_sum && callee_info->conds)
3593     {
3594       struct ipa_edge_args *args = IPA_EDGE_REF (edge);
3595       int count = ipa_get_cs_argument_count (args);
3596       int i;
3597
3598       if (count)
3599         {
3600           operand_map.safe_grow_cleared (count);
3601           offset_map.safe_grow_cleared (count);
3602         }
3603       for (i = 0; i < count; i++)
3604         {
3605           struct ipa_jump_func *jfunc = ipa_get_ith_jump_func (args, i);
3606           int map = -1;
3607
3608           /* TODO: handle non-NOPs when merging.  */
3609           if (jfunc->type == IPA_JF_PASS_THROUGH)
3610             {
3611               if (ipa_get_jf_pass_through_operation (jfunc) == NOP_EXPR)
3612                 map = ipa_get_jf_pass_through_formal_id (jfunc);
3613               if (!ipa_get_jf_pass_through_agg_preserved (jfunc))
3614                 offset_map[i] = -1;
3615             }
3616           else if (jfunc->type == IPA_JF_ANCESTOR)
3617             {
3618               HOST_WIDE_INT offset = ipa_get_jf_ancestor_offset (jfunc);
3619               if (offset >= 0 && offset < INT_MAX)
3620                 {
3621                   map = ipa_get_jf_ancestor_formal_id (jfunc);
3622                   if (!ipa_get_jf_ancestor_agg_preserved (jfunc))
3623                     offset = -1;
3624                   offset_map[i] = offset;
3625                 }
3626             }
3627           operand_map[i] = map;
3628           gcc_assert (map < ipa_get_param_count (IPA_NODE_REF (to)));
3629         }
3630     }
3631   for (i = 0; vec_safe_iterate (callee_info->entry, i, &e); i++)
3632     {
3633       struct predicate p = remap_predicate (info, callee_info,
3634                                             &e->predicate, operand_map,
3635                                             offset_map, clause,
3636                                             &toplev_predicate);
3637       if (!false_predicate_p (&p))
3638         {
3639           gcov_type add_time = ((gcov_type) e->time * edge->frequency
3640                                 + CGRAPH_FREQ_BASE / 2) / CGRAPH_FREQ_BASE;
3641           int prob = predicate_probability (callee_info->conds,
3642                                             &e->predicate,
3643                                             clause, es->param);
3644           add_time = apply_probability ((gcov_type) add_time, prob);
3645           if (add_time > MAX_TIME * INLINE_TIME_SCALE)
3646             add_time = MAX_TIME * INLINE_TIME_SCALE;
3647           if (prob != REG_BR_PROB_BASE
3648               && dump_file && (dump_flags & TDF_DETAILS))
3649             {
3650               fprintf (dump_file, "\t\tScaling time by probability:%f\n",
3651                        (double) prob / REG_BR_PROB_BASE);
3652             }
3653           account_size_time (info, e->size, add_time, &p);
3654         }
3655     }
3656   remap_edge_summaries (edge, edge->callee, info, callee_info, operand_map,
3657                         offset_map, clause, &toplev_predicate);
3658   remap_hint_predicate (info, callee_info,
3659                         &callee_info->loop_iterations,
3660                         operand_map, offset_map, clause, &toplev_predicate);
3661   remap_hint_predicate (info, callee_info,
3662                         &callee_info->loop_stride,
3663                         operand_map, offset_map, clause, &toplev_predicate);
3664   remap_hint_predicate (info, callee_info,
3665                         &callee_info->array_index,
3666                         operand_map, offset_map, clause, &toplev_predicate);
3667
3668   inline_update_callee_summaries (edge->callee,
3669                                   inline_edge_summary (edge)->loop_depth);
3670
3671   /* We do not maintain predicates of inlined edges, free it.  */
3672   edge_set_predicate (edge, &true_p);
3673   /* Similarly remove param summaries.  */
3674   es->param.release ();
3675   operand_map.release ();
3676   offset_map.release ();
3677 }
3678
3679 /* For performance reasons inline_merge_summary is not updating overall size
3680    and time.  Recompute it.  */
3681
3682 void
3683 inline_update_overall_summary (struct cgraph_node *node)
3684 {
3685   struct inline_summary *info = inline_summaries->get (node);
3686   size_time_entry *e;
3687   int i;
3688
3689   info->size = 0;
3690   info->time = 0;
3691   for (i = 0; vec_safe_iterate (info->entry, i, &e); i++)
3692     {
3693       info->size += e->size, info->time += e->time;
3694       if (info->time > MAX_TIME * INLINE_TIME_SCALE)
3695         info->time = MAX_TIME * INLINE_TIME_SCALE;
3696     }
3697   estimate_calls_size_and_time (node, &info->size, &info->min_size,
3698                                 &info->time, NULL,
3699                                 ~(clause_t) (1 << predicate_false_condition),
3700                                 vNULL, vNULL, vNULL);
3701   info->time = (info->time + INLINE_TIME_SCALE / 2) / INLINE_TIME_SCALE;
3702   info->size = (info->size + INLINE_SIZE_SCALE / 2) / INLINE_SIZE_SCALE;
3703 }
3704
3705 /* Return hints derrived from EDGE.   */
3706 int
3707 simple_edge_hints (struct cgraph_edge *edge)
3708 {
3709   int hints = 0;
3710   struct cgraph_node *to = (edge->caller->global.inlined_to
3711                             ? edge->caller->global.inlined_to : edge->caller);
3712   struct cgraph_node *callee = edge->callee->ultimate_alias_target ();
3713   if (inline_summaries->get (to)->scc_no
3714       && inline_summaries->get (to)->scc_no
3715          == inline_summaries->get (callee)->scc_no
3716       && !edge->recursive_p ())
3717     hints |= INLINE_HINT_same_scc;
3718
3719   if (callee->lto_file_data && edge->caller->lto_file_data
3720       && edge->caller->lto_file_data != callee->lto_file_data
3721       && !callee->merged)
3722     hints |= INLINE_HINT_cross_module;
3723
3724   return hints;
3725 }
3726
3727 /* Estimate the time cost for the caller when inlining EDGE.
3728    Only to be called via estimate_edge_time, that handles the
3729    caching mechanism.
3730
3731    When caching, also update the cache entry.  Compute both time and
3732    size, since we always need both metrics eventually.  */
3733
3734 int
3735 do_estimate_edge_time (struct cgraph_edge *edge)
3736 {
3737   int time;
3738   int size;
3739   inline_hints hints;
3740   struct cgraph_node *callee;
3741   clause_t clause;
3742   vec<tree> known_vals;
3743   vec<ipa_polymorphic_call_context> known_contexts;
3744   vec<ipa_agg_jump_function_p> known_aggs;
3745   struct inline_edge_summary *es = inline_edge_summary (edge);
3746   int min_size;
3747
3748   callee = edge->callee->ultimate_alias_target ();
3749
3750   gcc_checking_assert (edge->inline_failed);
3751   evaluate_properties_for_edge (edge, true,
3752                                 &clause, &known_vals, &known_contexts,
3753                                 &known_aggs);
3754   estimate_node_size_and_time (callee, clause, known_vals, known_contexts,
3755                                known_aggs, &size, &min_size, &time, &hints, es->param);
3756
3757   /* When we have profile feedback, we can quite safely identify hot
3758      edges and for those we disable size limits.  Don't do that when
3759      probability that caller will call the callee is low however, since it
3760      may hurt optimization of the caller's hot path.  */
3761   if (edge->count && edge->maybe_hot_p ()
3762       && (edge->count * 2
3763           > (edge->caller->global.inlined_to
3764              ? edge->caller->global.inlined_to->count : edge->caller->count)))
3765     hints |= INLINE_HINT_known_hot;
3766
3767   known_vals.release ();
3768   known_contexts.release ();
3769   known_aggs.release ();
3770   gcc_checking_assert (size >= 0);
3771   gcc_checking_assert (time >= 0);
3772
3773   /* When caching, update the cache entry.  */
3774   if (edge_growth_cache.exists ())
3775     {
3776       inline_summaries->get (edge->callee)->min_size = min_size;
3777       if ((int) edge_growth_cache.length () <= edge->uid)
3778         edge_growth_cache.safe_grow_cleared (symtab->edges_max_uid);
3779       edge_growth_cache[edge->uid].time = time + (time >= 0);
3780
3781       edge_growth_cache[edge->uid].size = size + (size >= 0);
3782       hints |= simple_edge_hints (edge);
3783       edge_growth_cache[edge->uid].hints = hints + 1;
3784     }
3785   return time;
3786 }
3787
3788
3789 /* Return estimated callee growth after inlining EDGE.
3790    Only to be called via estimate_edge_size.  */
3791
3792 int
3793 do_estimate_edge_size (struct cgraph_edge *edge)
3794 {
3795   int size;
3796   struct cgraph_node *callee;
3797   clause_t clause;
3798   vec<tree> known_vals;
3799   vec<ipa_polymorphic_call_context> known_contexts;
3800   vec<ipa_agg_jump_function_p> known_aggs;
3801
3802   /* When we do caching, use do_estimate_edge_time to populate the entry.  */
3803
3804   if (edge_growth_cache.exists ())
3805     {
3806       do_estimate_edge_time (edge);
3807       size = edge_growth_cache[edge->uid].size;
3808       gcc_checking_assert (size);
3809       return size - (size > 0);
3810     }
3811
3812   callee = edge->callee->ultimate_alias_target ();
3813
3814   /* Early inliner runs without caching, go ahead and do the dirty work.  */
3815   gcc_checking_assert (edge->inline_failed);
3816   evaluate_properties_for_edge (edge, true,
3817                                 &clause, &known_vals, &known_contexts,
3818                                 &known_aggs);
3819   estimate_node_size_and_time (callee, clause, known_vals, known_contexts,
3820                                known_aggs, &size, NULL, NULL, NULL, vNULL);
3821   known_vals.release ();
3822   known_contexts.release ();
3823   known_aggs.release ();
3824   return size;
3825 }
3826
3827
3828 /* Estimate the growth of the caller when inlining EDGE.
3829    Only to be called via estimate_edge_size.  */
3830
3831 inline_hints
3832 do_estimate_edge_hints (struct cgraph_edge *edge)
3833 {
3834   inline_hints hints;
3835   struct cgraph_node *callee;
3836   clause_t clause;
3837   vec<tree> known_vals;
3838   vec<ipa_polymorphic_call_context> known_contexts;
3839   vec<ipa_agg_jump_function_p> known_aggs;
3840
3841   /* When we do caching, use do_estimate_edge_time to populate the entry.  */
3842
3843   if (edge_growth_cache.exists ())
3844     {
3845       do_estimate_edge_time (edge);
3846       hints = edge_growth_cache[edge->uid].hints;
3847       gcc_checking_assert (hints);
3848       return hints - 1;
3849     }
3850
3851   callee = edge->callee->ultimate_alias_target ();
3852
3853   /* Early inliner runs without caching, go ahead and do the dirty work.  */
3854   gcc_checking_assert (edge->inline_failed);
3855   evaluate_properties_for_edge (edge, true,
3856                                 &clause, &known_vals, &known_contexts,
3857                                 &known_aggs);
3858   estimate_node_size_and_time (callee, clause, known_vals, known_contexts,
3859                                known_aggs, NULL, NULL, NULL, &hints, vNULL);
3860   known_vals.release ();
3861   known_contexts.release ();
3862   known_aggs.release ();
3863   hints |= simple_edge_hints (edge);
3864   return hints;
3865 }
3866
3867
3868 /* Estimate self time of the function NODE after inlining EDGE.  */
3869
3870 int
3871 estimate_time_after_inlining (struct cgraph_node *node,
3872                               struct cgraph_edge *edge)
3873 {
3874   struct inline_edge_summary *es = inline_edge_summary (edge);
3875   if (!es->predicate || !false_predicate_p (es->predicate))
3876     {
3877       gcov_type time =
3878         inline_summaries->get (node)->time + estimate_edge_time (edge);
3879       if (time < 0)
3880         time = 0;
3881       if (time > MAX_TIME)
3882         time = MAX_TIME;
3883       return time;
3884     }
3885   return inline_summaries->get (node)->time;
3886 }
3887
3888
3889 /* Estimate the size of NODE after inlining EDGE which should be an
3890    edge to either NODE or a call inlined into NODE.  */
3891
3892 int
3893 estimate_size_after_inlining (struct cgraph_node *node,
3894                               struct cgraph_edge *edge)
3895 {
3896   struct inline_edge_summary *es = inline_edge_summary (edge);
3897   if (!es->predicate || !false_predicate_p (es->predicate))
3898     {
3899       int size = inline_summaries->get (node)->size + estimate_edge_growth (edge);
3900       gcc_assert (size >= 0);
3901       return size;
3902     }
3903   return inline_summaries->get (node)->size;
3904 }
3905
3906
3907 struct growth_data
3908 {
3909   struct cgraph_node *node;
3910   bool self_recursive;
3911   bool uninlinable;
3912   int growth;
3913 };
3914
3915
3916 /* Worker for do_estimate_growth.  Collect growth for all callers.  */
3917
3918 static bool
3919 do_estimate_growth_1 (struct cgraph_node *node, void *data)
3920 {
3921   struct cgraph_edge *e;
3922   struct growth_data *d = (struct growth_data *) data;
3923
3924   for (e = node->callers; e; e = e->next_caller)
3925     {
3926       gcc_checking_assert (e->inline_failed);
3927
3928       if (cgraph_inline_failed_type (e->inline_failed) == CIF_FINAL_ERROR)
3929         {
3930           d->uninlinable = true;
3931           continue;
3932         }
3933
3934       if (e->recursive_p ())
3935         {
3936           d->self_recursive = true;
3937           continue;
3938         }
3939       d->growth += estimate_edge_growth (e);
3940     }
3941   return false;
3942 }
3943
3944
3945 /* Estimate the growth caused by inlining NODE into all callees.  */
3946
3947 int
3948 estimate_growth (struct cgraph_node *node)
3949 {
3950   struct growth_data d = { node, false, false, 0 };
3951   struct inline_summary *info = inline_summaries->get (node);
3952
3953   node->call_for_symbol_and_aliases (do_estimate_growth_1, &d, true);
3954
3955   /* For self recursive functions the growth estimation really should be
3956      infinity.  We don't want to return very large values because the growth
3957      plays various roles in badness computation fractions.  Be sure to not
3958      return zero or negative growths. */
3959   if (d.self_recursive)
3960     d.growth = d.growth < info->size ? info->size : d.growth;
3961   else if (DECL_EXTERNAL (node->decl) || d.uninlinable)
3962     ;
3963   else
3964     {
3965       if (node->will_be_removed_from_program_if_no_direct_calls_p ())
3966         d.growth -= info->size;
3967       /* COMDAT functions are very often not shared across multiple units
3968          since they come from various template instantiations.
3969          Take this into account.  */
3970       else if (DECL_COMDAT (node->decl)
3971                && node->can_remove_if_no_direct_calls_p ())
3972         d.growth -= (info->size
3973                      * (100 - PARAM_VALUE (PARAM_COMDAT_SHARING_PROBABILITY))
3974                      + 50) / 100;
3975     }
3976
3977   return d.growth;
3978 }
3979
3980 /* Verify if there are fewer than MAX_CALLERS.  */
3981
3982 static bool
3983 check_callers (cgraph_node *node, int *max_callers)
3984 {
3985   ipa_ref *ref;
3986
3987   if (!node->can_remove_if_no_direct_calls_and_refs_p ())
3988     return true;
3989
3990   for (cgraph_edge *e = node->callers; e; e = e->next_caller)
3991     {
3992       (*max_callers)--;
3993       if (!*max_callers
3994           || cgraph_inline_failed_type (e->inline_failed) == CIF_FINAL_ERROR)
3995         return true;
3996     }
3997
3998   FOR_EACH_ALIAS (node, ref)
3999     if (check_callers (dyn_cast <cgraph_node *> (ref->referring), max_callers))
4000       return true;
4001
4002   return false;
4003 }
4004
4005
4006 /* Make cheap estimation if growth of NODE is likely positive knowing
4007    EDGE_GROWTH of one particular edge. 
4008    We assume that most of other edges will have similar growth
4009    and skip computation if there are too many callers.  */
4010
4011 bool
4012 growth_likely_positive (struct cgraph_node *node,
4013                         int edge_growth)
4014 {
4015   int max_callers;
4016   struct cgraph_edge *e;
4017   gcc_checking_assert (edge_growth > 0);
4018
4019   /* First quickly check if NODE is removable at all.  */
4020   if (DECL_EXTERNAL (node->decl))
4021     return true;
4022   if (!node->can_remove_if_no_direct_calls_and_refs_p ()
4023       || node->address_taken)
4024     return true;
4025
4026   max_callers = inline_summaries->get (node)->size * 4 / edge_growth + 2;
4027
4028   for (e = node->callers; e; e = e->next_caller)
4029     {
4030       max_callers--;
4031       if (!max_callers
4032           || cgraph_inline_failed_type (e->inline_failed) == CIF_FINAL_ERROR)
4033         return true;
4034     }
4035
4036   ipa_ref *ref;
4037   FOR_EACH_ALIAS (node, ref)
4038     if (check_callers (dyn_cast <cgraph_node *> (ref->referring), &max_callers))
4039       return true;
4040
4041   /* Unlike for functions called once, we play unsafe with
4042      COMDATs.  We can allow that since we know functions
4043      in consideration are small (and thus risk is small) and
4044      moreover grow estimates already accounts that COMDAT
4045      functions may or may not disappear when eliminated from
4046      current unit. With good probability making aggressive
4047      choice in all units is going to make overall program
4048      smaller.  */
4049   if (DECL_COMDAT (node->decl))
4050     {
4051       if (!node->can_remove_if_no_direct_calls_p ())
4052         return true;
4053     }
4054   else if (!node->will_be_removed_from_program_if_no_direct_calls_p ())
4055     return true;
4056
4057   return estimate_growth (node) > 0;
4058 }
4059
4060
4061 /* This function performs intraprocedural analysis in NODE that is required to
4062    inline indirect calls.  */
4063
4064 static void
4065 inline_indirect_intraprocedural_analysis (struct cgraph_node *node)
4066 {
4067   ipa_analyze_node (node);
4068   if (dump_file && (dump_flags & TDF_DETAILS))
4069     {
4070       ipa_print_node_params (dump_file, node);
4071       ipa_print_node_jump_functions (dump_file, node);
4072     }
4073 }
4074
4075
4076 /* Note function body size.  */
4077
4078 void
4079 inline_analyze_function (struct cgraph_node *node)
4080 {
4081   push_cfun (DECL_STRUCT_FUNCTION (node->decl));
4082
4083   if (dump_file)
4084     fprintf (dump_file, "\nAnalyzing function: %s/%u\n",
4085              node->name (), node->order);
4086   if (opt_for_fn (node->decl, optimize) && !node->thunk.thunk_p)
4087     inline_indirect_intraprocedural_analysis (node);
4088   compute_inline_parameters (node, false);
4089   if (!optimize)
4090     {
4091       struct cgraph_edge *e;
4092       for (e = node->callees; e; e = e->next_callee)
4093         {
4094           if (e->inline_failed == CIF_FUNCTION_NOT_CONSIDERED)
4095             e->inline_failed = CIF_FUNCTION_NOT_OPTIMIZED;
4096           e->call_stmt_cannot_inline_p = true;
4097         }
4098       for (e = node->indirect_calls; e; e = e->next_callee)
4099         {
4100           if (e->inline_failed == CIF_FUNCTION_NOT_CONSIDERED)
4101             e->inline_failed = CIF_FUNCTION_NOT_OPTIMIZED;
4102           e->call_stmt_cannot_inline_p = true;
4103         }
4104     }
4105
4106   pop_cfun ();
4107 }
4108
4109
4110 /* Called when new function is inserted to callgraph late.  */
4111
4112 void
4113 inline_summary_t::insert (struct cgraph_node *node, inline_summary *)
4114 {
4115   inline_analyze_function (node);
4116 }
4117
4118 /* Note function body size.  */
4119
4120 void
4121 inline_generate_summary (void)
4122 {
4123   struct cgraph_node *node;
4124
4125   /* When not optimizing, do not bother to analyze.  Inlining is still done
4126      because edge redirection needs to happen there.  */
4127   if (!optimize && !flag_generate_lto && !flag_generate_offload && !flag_wpa)
4128     return;
4129
4130   if (!inline_summaries)
4131     inline_summaries = (inline_summary_t*) inline_summary_t::create_ggc (symtab);
4132
4133   inline_summaries->enable_insertion_hook ();
4134
4135   ipa_register_cgraph_hooks ();
4136   inline_free_summary ();
4137
4138   FOR_EACH_DEFINED_FUNCTION (node)
4139     if (!node->alias)
4140       inline_analyze_function (node);
4141 }
4142
4143
4144 /* Read predicate from IB.  */
4145
4146 static struct predicate
4147 read_predicate (struct lto_input_block *ib)
4148 {
4149   struct predicate out;
4150   clause_t clause;
4151   int k = 0;
4152
4153   do
4154     {
4155       gcc_assert (k <= MAX_CLAUSES);
4156       clause = out.clause[k++] = streamer_read_uhwi (ib);
4157     }
4158   while (clause);
4159
4160   /* Zero-initialize the remaining clauses in OUT.  */
4161   while (k <= MAX_CLAUSES)
4162     out.clause[k++] = 0;
4163
4164   return out;
4165 }
4166
4167
4168 /* Write inline summary for edge E to OB.  */
4169
4170 static void
4171 read_inline_edge_summary (struct lto_input_block *ib, struct cgraph_edge *e)
4172 {
4173   struct inline_edge_summary *es = inline_edge_summary (e);
4174   struct predicate p;
4175   int length, i;
4176
4177   es->call_stmt_size = streamer_read_uhwi (ib);
4178   es->call_stmt_time = streamer_read_uhwi (ib);
4179   es->loop_depth = streamer_read_uhwi (ib);
4180   p = read_predicate (ib);
4181   edge_set_predicate (e, &p);
4182   length = streamer_read_uhwi (ib);
4183   if (length)
4184     {
4185       es->param.safe_grow_cleared (length);
4186       for (i = 0; i < length; i++)
4187         es->param[i].change_prob = streamer_read_uhwi (ib);
4188     }
4189 }
4190
4191
4192 /* Stream in inline summaries from the section.  */
4193
4194 static void
4195 inline_read_section (struct lto_file_decl_data *file_data, const char *data,
4196                      size_t len)
4197 {
4198   const struct lto_function_header *header =
4199     (const struct lto_function_header *) data;
4200   const int cfg_offset = sizeof (struct lto_function_header);
4201   const int main_offset = cfg_offset + header->cfg_size;
4202   const int string_offset = main_offset + header->main_size;
4203   struct data_in *data_in;
4204   unsigned int i, count2, j;
4205   unsigned int f_count;
4206
4207   lto_input_block ib ((const char *) data + main_offset, header->main_size,
4208                       file_data->mode_table);
4209
4210   data_in =
4211     lto_data_in_create (file_data, (const char *) data + string_offset,
4212                         header->string_size, vNULL);
4213   f_count = streamer_read_uhwi (&ib);
4214   for (i = 0; i < f_count; i++)
4215     {
4216       unsigned int index;
4217       struct cgraph_node *node;
4218       struct inline_summary *info;
4219       lto_symtab_encoder_t encoder;
4220       struct bitpack_d bp;
4221       struct cgraph_edge *e;
4222       predicate p;
4223
4224       index = streamer_read_uhwi (&ib);
4225       encoder = file_data->symtab_node_encoder;
4226       node = dyn_cast<cgraph_node *> (lto_symtab_encoder_deref (encoder,
4227                                                                 index));
4228       info = inline_summaries->get (node);
4229
4230       info->estimated_stack_size
4231         = info->estimated_self_stack_size = streamer_read_uhwi (&ib);
4232       info->size = info->self_size = streamer_read_uhwi (&ib);
4233       info->time = info->self_time = streamer_read_uhwi (&ib);
4234
4235       bp = streamer_read_bitpack (&ib);
4236       info->inlinable = bp_unpack_value (&bp, 1);
4237       info->contains_cilk_spawn = bp_unpack_value (&bp, 1);
4238
4239       count2 = streamer_read_uhwi (&ib);
4240       gcc_assert (!info->conds);
4241       for (j = 0; j < count2; j++)
4242         {
4243           struct condition c;
4244           c.operand_num = streamer_read_uhwi (&ib);
4245           c.code = (enum tree_code) streamer_read_uhwi (&ib);
4246           c.val = stream_read_tree (&ib, data_in);
4247           bp = streamer_read_bitpack (&ib);
4248           c.agg_contents = bp_unpack_value (&bp, 1);
4249           c.by_ref = bp_unpack_value (&bp, 1);
4250           if (c.agg_contents)
4251             c.offset = streamer_read_uhwi (&ib);
4252           vec_safe_push (info->conds, c);
4253         }
4254       count2 = streamer_read_uhwi (&ib);
4255       gcc_assert (!info->entry);
4256       for (j = 0; j < count2; j++)
4257         {
4258           struct size_time_entry e;
4259
4260           e.size = streamer_read_uhwi (&ib);
4261           e.time = streamer_read_uhwi (&ib);
4262           e.predicate = read_predicate (&ib);
4263
4264           vec_safe_push (info->entry, e);
4265         }
4266
4267       p = read_predicate (&ib);
4268       set_hint_predicate (&info->loop_iterations, p);
4269       p = read_predicate (&ib);
4270       set_hint_predicate (&info->loop_stride, p);
4271       p = read_predicate (&ib);
4272       set_hint_predicate (&info->array_index, p);
4273       for (e = node->callees; e; e = e->next_callee)
4274         read_inline_edge_summary (&ib, e);
4275       for (e = node->indirect_calls; e; e = e->next_callee)
4276         read_inline_edge_summary (&ib, e);
4277     }
4278
4279   lto_free_section_data (file_data, LTO_section_inline_summary, NULL, data,
4280                          len);
4281   lto_data_in_delete (data_in);
4282 }
4283
4284
4285 /* Read inline summary.  Jump functions are shared among ipa-cp
4286    and inliner, so when ipa-cp is active, we don't need to write them
4287    twice.  */
4288
4289 void
4290 inline_read_summary (void)
4291 {
4292   struct lto_file_decl_data **file_data_vec = lto_get_file_decl_data ();
4293   struct lto_file_decl_data *file_data;
4294   unsigned int j = 0;
4295
4296   inline_summary_alloc ();
4297
4298   while ((file_data = file_data_vec[j++]))
4299     {
4300       size_t len;
4301       const char *data = lto_get_section_data (file_data,
4302                                                LTO_section_inline_summary,
4303                                                NULL, &len);
4304       if (data)
4305         inline_read_section (file_data, data, len);
4306       else
4307         /* Fatal error here.  We do not want to support compiling ltrans units
4308            with different version of compiler or different flags than the WPA
4309            unit, so this should never happen.  */
4310         fatal_error (input_location,
4311                      "ipa inline summary is missing in input file");
4312     }
4313   if (optimize)
4314     {
4315       ipa_register_cgraph_hooks ();
4316       if (!flag_ipa_cp)
4317         ipa_prop_read_jump_functions ();
4318     }
4319
4320   gcc_assert (inline_summaries);
4321   inline_summaries->enable_insertion_hook ();
4322 }
4323
4324
4325 /* Write predicate P to OB.  */
4326
4327 static void
4328 write_predicate (struct output_block *ob, struct predicate *p)
4329 {
4330   int j;
4331   if (p)
4332     for (j = 0; p->clause[j]; j++)
4333       {
4334         gcc_assert (j < MAX_CLAUSES);
4335         streamer_write_uhwi (ob, p->clause[j]);
4336       }
4337   streamer_write_uhwi (ob, 0);
4338 }
4339
4340
4341 /* Write inline summary for edge E to OB.  */
4342
4343 static void
4344 write_inline_edge_summary (struct output_block *ob, struct cgraph_edge *e)
4345 {
4346   struct inline_edge_summary *es = inline_edge_summary (e);
4347   int i;
4348
4349   streamer_write_uhwi (ob, es->call_stmt_size);
4350   streamer_write_uhwi (ob, es->call_stmt_time);
4351   streamer_write_uhwi (ob, es->loop_depth);
4352   write_predicate (ob, es->predicate);
4353   streamer_write_uhwi (ob, es->param.length ());
4354   for (i = 0; i < (int) es->param.length (); i++)
4355     streamer_write_uhwi (ob, es->param[i].change_prob);
4356 }
4357
4358
4359 /* Write inline summary for node in SET.
4360    Jump functions are shared among ipa-cp and inliner, so when ipa-cp is
4361    active, we don't need to write them twice.  */
4362
4363 void
4364 inline_write_summary (void)
4365 {
4366   struct cgraph_node *node;
4367   struct output_block *ob = create_output_block (LTO_section_inline_summary);
4368   lto_symtab_encoder_t encoder = ob->decl_state->symtab_node_encoder;
4369   unsigned int count = 0;
4370   int i;
4371
4372   for (i = 0; i < lto_symtab_encoder_size (encoder); i++)
4373     {
4374       symtab_node *snode = lto_symtab_encoder_deref (encoder, i);
4375       cgraph_node *cnode = dyn_cast <cgraph_node *> (snode);
4376       if (cnode && cnode->definition && !cnode->alias)
4377         count++;
4378     }
4379   streamer_write_uhwi (ob, count);
4380
4381   for (i = 0; i < lto_symtab_encoder_size (encoder); i++)
4382     {
4383       symtab_node *snode = lto_symtab_encoder_deref (encoder, i);
4384       cgraph_node *cnode = dyn_cast <cgraph_node *> (snode);
4385       if (cnode && (node = cnode)->definition && !node->alias)
4386         {
4387           struct inline_summary *info = inline_summaries->get (node);
4388           struct bitpack_d bp;
4389           struct cgraph_edge *edge;
4390           int i;
4391           size_time_entry *e;
4392           struct condition *c;
4393
4394           streamer_write_uhwi (ob,
4395                                lto_symtab_encoder_encode (encoder,
4396                                                           
4397                                                           node));
4398           streamer_write_hwi (ob, info->estimated_self_stack_size);
4399           streamer_write_hwi (ob, info->self_size);
4400           streamer_write_hwi (ob, info->self_time);
4401           bp = bitpack_create (ob->main_stream);
4402           bp_pack_value (&bp, info->inlinable, 1);
4403           bp_pack_value (&bp, info->contains_cilk_spawn, 1);
4404           streamer_write_bitpack (&bp);
4405           streamer_write_uhwi (ob, vec_safe_length (info->conds));
4406           for (i = 0; vec_safe_iterate (info->conds, i, &c); i++)
4407             {
4408               streamer_write_uhwi (ob, c->operand_num);
4409               streamer_write_uhwi (ob, c->code);
4410               stream_write_tree (ob, c->val, true);
4411               bp = bitpack_create (ob->main_stream);
4412               bp_pack_value (&bp, c->agg_contents, 1);
4413               bp_pack_value (&bp, c->by_ref, 1);
4414               streamer_write_bitpack (&bp);
4415               if (c->agg_contents)
4416                 streamer_write_uhwi (ob, c->offset);
4417             }
4418           streamer_write_uhwi (ob, vec_safe_length (info->entry));
4419           for (i = 0; vec_safe_iterate (info->entry, i, &e); i++)
4420             {
4421               streamer_write_uhwi (ob, e->size);
4422               streamer_write_uhwi (ob, e->time);
4423               write_predicate (ob, &e->predicate);
4424             }
4425           write_predicate (ob, info->loop_iterations);
4426           write_predicate (ob, info->loop_stride);
4427           write_predicate (ob, info->array_index);
4428           for (edge = node->callees; edge; edge = edge->next_callee)
4429             write_inline_edge_summary (ob, edge);
4430           for (edge = node->indirect_calls; edge; edge = edge->next_callee)
4431             write_inline_edge_summary (ob, edge);
4432         }
4433     }
4434   streamer_write_char_stream (ob->main_stream, 0);
4435   produce_asm (ob, NULL);
4436   destroy_output_block (ob);
4437
4438   if (optimize && !flag_ipa_cp)
4439     ipa_prop_write_jump_functions ();
4440 }
4441
4442
4443 /* Release inline summary.  */
4444
4445 void
4446 inline_free_summary (void)
4447 {
4448   struct cgraph_node *node;
4449   if (edge_removal_hook_holder)
4450     symtab->remove_edge_removal_hook (edge_removal_hook_holder);
4451   edge_removal_hook_holder = NULL;
4452   if (edge_duplication_hook_holder)
4453     symtab->remove_edge_duplication_hook (edge_duplication_hook_holder);
4454   edge_duplication_hook_holder = NULL;
4455   if (!inline_edge_summary_vec.exists ())
4456     return;
4457   FOR_EACH_DEFINED_FUNCTION (node)
4458     if (!node->alias)
4459       reset_inline_summary (node, inline_summaries->get (node));
4460   inline_summaries->release ();
4461   inline_summaries = NULL;
4462   inline_edge_summary_vec.release ();
4463   if (edge_predicate_pool)
4464     free_alloc_pool (edge_predicate_pool);
4465   edge_predicate_pool = 0;
4466 }