Debian Codegraph @

gcc/ipa-cp.cc

raw
1 /* Interprocedural constant propagation
2 Copyright (C) 2005-2025 Free Software Foundation, Inc.
3
4 Contributed by Razya Ladelsky <[email protected]> and Martin Jambor
5 <[email protected]>
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
22
23 /* Interprocedural constant propagation (IPA-CP).
24
25 The goal of this transformation is to
26
27 1) discover functions which are always invoked with some arguments with the
28 same known constant values and modify the functions so that the
29 subsequent optimizations can take advantage of the knowledge, and
30
31 2) partial specialization - create specialized versions of functions
32 transformed in this way if some parameters are known constants only in
33 certain contexts but the estimated tradeoff between speedup and cost size
34 is deemed good.
35
36 The algorithm also propagates types and attempts to perform type based
37 devirtualization. Types are propagated much like constants.
38
39 The algorithm basically consists of three stages. In the first, functions
40 are analyzed one at a time and jump functions are constructed for all known
41 call-sites. In the second phase, the pass propagates information from the
42 jump functions across the call to reveal what values are available at what
43 call sites, performs estimations of effects of known values on functions and
44 their callees, and finally decides what specialized extra versions should be
45 created. In the third, the special versions materialize and appropriate
46 calls are redirected.
47
48 The algorithm used is to a certain extent based on "Interprocedural Constant
49 Propagation", by David Callahan, Keith D Cooper, Ken Kennedy, Linda Torczon,
50 Comp86, pg 152-161 and "A Methodology for Procedure Cloning" by Keith D
51 Cooper, Mary W. Hall, and Ken Kennedy.
52
53
54 First stage - intraprocedural analysis
55 =======================================
56
57 This phase computes jump_function and modification flags.
58
59 A jump function for a call-site represents the values passed as an actual
60 arguments of a given call-site. In principle, there are three types of
61 values:
62
63 Pass through - the caller's formal parameter is passed as an actual
64 argument, plus an operation on it can be performed.
65 Constant - a constant is passed as an actual argument.
66 Unknown - neither of the above.
67
68 All jump function types are described in detail in ipa-prop.h, together with
69 the data structures that represent them and methods of accessing them.
70
71 ipcp_generate_summary() is the main function of the first stage.
72
73 Second stage - interprocedural analysis
74 ========================================
75
76 This stage is itself divided into two phases. In the first, we propagate
77 known values over the call graph, in the second, we make cloning decisions.
78 It uses a different algorithm than the original Callahan's paper.
79
80 First, we traverse the functions topologically from callers to callees and,
81 for each strongly connected component (SCC), we propagate constants
82 according to previously computed jump functions. We also record what known
83 values depend on other known values and estimate local effects. Finally, we
84 propagate cumulative information about these effects from dependent values
85 to those on which they depend.
86
87 Second, we again traverse the call graph in the same topological order and
88 make clones for functions which we know are called with the same values in
89 all contexts and decide about extra specialized clones of functions just for
90 some contexts - these decisions are based on both local estimates and
91 cumulative estimates propagated from callees.
92
93 ipcp_propagate_stage() and ipcp_decision_stage() together constitute the
94 third stage.
95
96 Third phase - materialization of clones, call statement updates.
97 ============================================
98
99 This stage is currently performed by call graph code (mainly in cgraphunit.cc
100 and tree-inline.cc) according to instructions inserted to the call graph by
101 the second stage. */
102
103 #define INCLUDE_ALGORITHM
104 #include "config.h"
105 #include "system.h"
106 #include "coretypes.h"
107 #include "backend.h"
108 #include "tree.h"
109 #include "gimple-expr.h"
110 #include "gimple.h"
111 #include "predict.h"
112 #include "sreal.h"
113 #include "alloc-pool.h"
114 #include "tree-pass.h"
115 #include "cgraph.h"
116 #include "diagnostic.h"
117 #include "fold-const.h"
118 #include "gimple-iterator.h"
119 #include "gimple-fold.h"
120 #include "symbol-summary.h"
121 #include "tree-vrp.h"
122 #include "ipa-cp.h"
123 #include "ipa-prop.h"
124 #include "tree-pretty-print.h"
125 #include "tree-inline.h"
126 #include "ipa-fnsummary.h"
127 #include "ipa-utils.h"
128 #include "tree-ssa-ccp.h"
129 #include "stringpool.h"
130 #include "attribs.h"
131 #include "dbgcnt.h"
132 #include "symtab-clones.h"
133 #include "gimple-range.h"
134
135
136 /* Allocation pools for values and their sources in ipa-cp. */
137
138 object_allocator<ipcp_value<tree> > ipcp_cst_values_pool
139 ("IPA-CP constant values");
140
141 object_allocator<ipcp_value<ipa_polymorphic_call_context> >
142 ipcp_poly_ctx_values_pool ("IPA-CP polymorphic contexts");
143
144 object_allocator<ipcp_value_source<tree> > ipcp_sources_pool
145 ("IPA-CP value sources");
146
147 object_allocator<ipcp_agg_lattice> ipcp_agg_lattice_pool
148 ("IPA_CP aggregate lattices");
149
150 /* Base count to use in heuristics when using profile feedback. */
151
152 static profile_count base_count;
153
154 /* Original overall size of the program. */
155
156 static long overall_size, orig_overall_size;
157
158 /* Node name to unique clone suffix number map. */
159 static hash_map<const char *, unsigned> *clone_num_suffixes;
160
161 /* Return the param lattices structure corresponding to the Ith formal
162 parameter of the function described by INFO. */
163 static inline class ipcp_param_lattices *
164 ipa_get_parm_lattices (class ipa_node_params *info, int i)
165 {
166 gcc_assert (i >= 0 && i < ipa_get_param_count (info));
167 gcc_checking_assert (!info->ipcp_orig_node);
168 return &(info->lattices[i]);
169 }
170
171 /* Return the lattice corresponding to the scalar value of the Ith formal
172 parameter of the function described by INFO. */
173 static inline ipcp_lattice<tree> *
174 ipa_get_scalar_lat (class ipa_node_params *info, int i)
175 {
176 class ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
177 return &plats->itself;
178 }
179
180 /* Return the lattice corresponding to the scalar value of the Ith formal
181 parameter of the function described by INFO. */
182 static inline ipcp_lattice<ipa_polymorphic_call_context> *
183 ipa_get_poly_ctx_lat (class ipa_node_params *info, int i)
184 {
185 class ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
186 return &plats->ctxlat;
187 }
188
189 /* Return whether LAT is a lattice with a single constant and without an
190 undefined value. */
191
192 template <typename valtype>
193 inline bool
194 ipcp_lattice<valtype>::is_single_const ()
195 {
196 if (bottom || contains_variable || values_count != 1)
197 return false;
198 else
199 return true;
200 }
201
202 /* Return true iff X and Y should be considered equal values by IPA-CP. */
203
204 bool
205 values_equal_for_ipcp_p (tree x, tree y)
206 {
207 gcc_checking_assert (x != NULL_TREE && y != NULL_TREE);
208
209 if (x == y)
210 return true;
211
212 if (TREE_CODE (x) == ADDR_EXPR
213 && TREE_CODE (y) == ADDR_EXPR
214 && (TREE_CODE (TREE_OPERAND (x, 0)) == CONST_DECL
215 || (TREE_CODE (TREE_OPERAND (x, 0)) == VAR_DECL
216 && DECL_IN_CONSTANT_POOL (TREE_OPERAND (x, 0))))
217 && (TREE_CODE (TREE_OPERAND (y, 0)) == CONST_DECL
218 || (TREE_CODE (TREE_OPERAND (y, 0)) == VAR_DECL
219 && DECL_IN_CONSTANT_POOL (TREE_OPERAND (y, 0)))))
220 return TREE_OPERAND (x, 0) == TREE_OPERAND (y, 0)
221 || operand_equal_p (DECL_INITIAL (TREE_OPERAND (x, 0)),
222 DECL_INITIAL (TREE_OPERAND (y, 0)), 0);
223 else
224 return operand_equal_p (x, y, 0);
225 }
226
227 /* Print V which is extracted from a value in a lattice to F. This overloaded
228 function is used to print tree constants. */
229
230 static void
231 print_ipcp_constant_value (FILE * f, tree v)
232 {
233 ipa_print_constant_value (f, v);
234 }
235
236 /* Print V which is extracted from a value in a lattice to F. This overloaded
237 function is used to print constant polymorphic call contexts. */
238
239 static void
240 print_ipcp_constant_value (FILE * f, ipa_polymorphic_call_context v)
241 {
242 v.dump(f, false);
243 }
244
245 /* Print a lattice LAT to F. */
246
247 template <typename valtype>
248 void
249 ipcp_lattice<valtype>::print (FILE * f, bool dump_sources, bool dump_benefits)
250 {
251 ipcp_value<valtype> *val;
252 bool prev = false;
253
254 if (bottom)
255 {
256 fprintf (f, "BOTTOM\n");
257 return;
258 }
259
260 if (!values_count && !contains_variable)
261 {
262 fprintf (f, "TOP\n");
263 return;
264 }
265
266 if (contains_variable)
267 {
268 fprintf (f, "VARIABLE");
269 prev = true;
270 if (dump_benefits)
271 fprintf (f, "\n");
272 }
273
274 for (val = values; val; val = val->next)
275 {
276 if (dump_benefits && prev)
277 fprintf (f, " ");
278 else if (!dump_benefits && prev)
279 fprintf (f, ", ");
280 else
281 prev = true;
282
283 print_ipcp_constant_value (f, val->value);
284
285 if (dump_sources)
286 {
287 ipcp_value_source<valtype> *s;
288
289 if (val->self_recursion_generated_p ())
290 fprintf (f, " [self_gen(%i), from:",
291 val->self_recursion_generated_level);
292 else
293 fprintf (f, " [scc: %i, from:", val->scc_no);
294 for (s = val->sources; s; s = s->next)
295 fprintf (f, " %i(%f)", s->cs->caller->get_uid (),
296 s->cs->sreal_frequency ().to_double ());
297 fprintf (f, "]");
298 }
299
300 if (dump_benefits)
301 fprintf (f, " [loc_time: %g, loc_size: %i, "
302 "prop_time: %g, prop_size: %i]\n",
303 val->local_time_benefit.to_double (), val->local_size_cost,
304 val->prop_time_benefit.to_double (), val->prop_size_cost);
305 }
306 if (!dump_benefits)
307 fprintf (f, "\n");
308 }
309
310 /* Print VALUE to F in a form which in usual cases does not take thousands of
311 characters. */
312
313 static void
314 ipcp_print_widest_int (FILE *f, const widest_int &value)
315 {
316 if (value == -1)
317 fprintf (f, "-1");
318 else if (wi::arshift (value, 128) == -1)
319 {
320 char buf[35], *p = buf + 2;
321 widest_int v = wi::zext (value, 128);
322 size_t len;
323 print_hex (v, buf);
324 len = strlen (p);
325 if (len == 32)
326 {
327 fprintf (f, "0xf..f");
328 while (*p == 'f')
329 ++p;
330 }
331 else
332 fprintf (f, "0xf..f%0*d", (int) (32 - len), 0);
333 fputs (p, f);
334 }
335 else
336 print_hex (value, f);
337 }
338
339 void
340 ipcp_bits_lattice::print (FILE *f)
341 {
342 if (top_p ())
343 fprintf (f, " Bits unknown (TOP)\n");
344 else if (bottom_p ())
345 fprintf (f, " Bits unusable (BOTTOM)\n");
346 else
347 {
348 fprintf (f, " Bits: value = ");
349 ipcp_print_widest_int (f, get_value ());
350 fprintf (f, ", mask = ");
351 ipcp_print_widest_int (f, get_mask ());
352 fprintf (f, "\n");
353 }
354 }
355
356 /* Print value range lattice to F. */
357
358 void
359 ipcp_vr_lattice::print (FILE * f)
360 {
361 m_vr.dump (f);
362 }
363
364 /* Print all ipcp_lattices of all functions to F. */
365
366 static void
367 print_all_lattices (FILE * f, bool dump_sources, bool dump_benefits)
368 {
369 struct cgraph_node *node;
370 int i, count;
371
372 fprintf (f, "\nLattices:\n");
373 FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
374 {
375 class ipa_node_params *info;
376
377 info = ipa_node_params_sum->get (node);
378 /* Skip unoptimized functions and constprop clones since we don't make
379 lattices for them. */
380 if (!info || info->ipcp_orig_node)
381 continue;
382 fprintf (f, " Node: %s:\n", node->dump_name ());
383 count = ipa_get_param_count (info);
384 for (i = 0; i < count; i++)
385 {
386 struct ipcp_agg_lattice *aglat;
387 class ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
388 fprintf (f, " param [%d]: ", i);
389 plats->itself.print (f, dump_sources, dump_benefits);
390 fprintf (f, " ctxs: ");
391 plats->ctxlat.print (f, dump_sources, dump_benefits);
392 plats->bits_lattice.print (f);
393 fprintf (f, " ");
394 plats->m_value_range.print (f);
395 fprintf (f, "\n");
396 if (plats->virt_call)
397 fprintf (f, " virt_call flag set\n");
398
399 if (plats->aggs_bottom)
400 {
401 fprintf (f, " AGGS BOTTOM\n");
402 continue;
403 }
404 if (plats->aggs_contain_variable)
405 fprintf (f, " AGGS VARIABLE\n");
406 for (aglat = plats->aggs; aglat; aglat = aglat->next)
407 {
408 fprintf (f, " %soffset " HOST_WIDE_INT_PRINT_DEC ": ",
409 plats->aggs_by_ref ? "ref " : "", aglat->offset);
410 aglat->print (f, dump_sources, dump_benefits);
411 }
412 }
413 }
414 }
415
416 /* Determine whether it is at all technically possible to create clones of NODE
417 and store this information in the ipa_node_params structure associated
418 with NODE. */
419
420 static void
421 determine_versionability (struct cgraph_node *node,
422 class ipa_node_params *info)
423 {
424 const char *reason = NULL;
425
426 /* There are a number of generic reasons functions cannot be versioned. We
427 also cannot remove parameters if there are type attributes such as fnspec
428 present. */
429 if (node->alias || node->thunk)
430 reason = "alias or thunk";
431 else if (!node->versionable)
432 reason = "not a tree_versionable_function";
433 else if (node->get_availability () <= AVAIL_INTERPOSABLE)
434 reason = "insufficient body availability";
435 else if (!opt_for_fn (node->decl, optimize)
436 || !opt_for_fn (node->decl, flag_ipa_cp))
437 reason = "non-optimized function";
438 else if (lookup_attribute ("omp declare simd", DECL_ATTRIBUTES (node->decl)))
439 {
440 /* Ideally we should clone the SIMD clones themselves and create
441 vector copies of them, so IPA-cp and SIMD clones can happily
442 coexist, but that may not be worth the effort. */
443 reason = "function has SIMD clones";
444 }
445 else if (lookup_attribute ("target_clones", DECL_ATTRIBUTES (node->decl)))
446 {
447 /* Ideally we should clone the target clones themselves and create
448 copies of them, so IPA-cp and target clones can happily
449 coexist, but that may not be worth the effort. */
450 reason = "function target_clones attribute";
451 }
452 /* Don't clone decls local to a comdat group; it breaks and for C++
453 decloned constructors, inlining is always better anyway. */
454 else if (node->comdat_local_p ())
455 reason = "comdat-local function";
456 else if (node->calls_comdat_local)
457 {
458 /* TODO: call is versionable if we make sure that all
459 callers are inside of a comdat group. */
460 reason = "calls comdat-local function";
461 }
462
463 /* Functions calling BUILT_IN_VA_ARG_PACK and BUILT_IN_VA_ARG_PACK_LEN
464 work only when inlined. Cloning them may still lead to better code
465 because ipa-cp will not give up on cloning further. If the function is
466 external this however leads to wrong code because we may end up producing
467 offline copy of the function. */
468 if (DECL_EXTERNAL (node->decl))
469 for (cgraph_edge *edge = node->callees; !reason && edge;
470 edge = edge->next_callee)
471 if (fndecl_built_in_p (edge->callee->decl, BUILT_IN_NORMAL))
472 {
473 if (DECL_FUNCTION_CODE (edge->callee->decl) == BUILT_IN_VA_ARG_PACK)
474 reason = "external function which calls va_arg_pack";
475 if (DECL_FUNCTION_CODE (edge->callee->decl)
476 == BUILT_IN_VA_ARG_PACK_LEN)
477 reason = "external function which calls va_arg_pack_len";
478 }
479
480 if (reason && dump_file && !node->alias && !node->thunk)
481 fprintf (dump_file, "Function %s is not versionable, reason: %s.\n",
482 node->dump_name (), reason);
483
484 info->versionable = (reason == NULL);
485 }
486
487 /* Return true if it is at all technically possible to create clones of a
488 NODE. */
489
490 static bool
491 ipcp_versionable_function_p (struct cgraph_node *node)
492 {
493 ipa_node_params *info = ipa_node_params_sum->get (node);
494 return info && info->versionable;
495 }
496
497 /* Structure holding accumulated information about callers of a node. */
498
499 struct caller_statistics
500 {
501 /* If requested (see below), self-recursive call counts are summed into this
502 field. */
503 profile_count rec_count_sum;
504 /* The sum of all ipa counts of all the other (non-recursive) calls. */
505 profile_count count_sum;
506 /* Sum of all frequencies for all calls. */
507 sreal freq_sum;
508 /* Number of calls and hot calls respectively. */
509 int n_calls, n_hot_calls;
510 /* If itself is set up, also count the number of non-self-recursive
511 calls. */
512 int n_nonrec_calls;
513 /* If non-NULL, this is the node itself and calls from it should have their
514 counts included in rec_count_sum and not count_sum. */
515 cgraph_node *itself;
516 };
517
518 /* Initialize fields of STAT to zeroes and optionally set it up so that edges
519 from IGNORED_CALLER are not counted. */
520
521 static inline void
522 init_caller_stats (caller_statistics *stats, cgraph_node *itself = NULL)
523 {
524 stats->rec_count_sum = profile_count::zero ();
525 stats->count_sum = profile_count::zero ();
526 stats->n_calls = 0;
527 stats->n_hot_calls = 0;
528 stats->n_nonrec_calls = 0;
529 stats->freq_sum = 0;
530 stats->itself = itself;
531 }
532
533 /* Worker callback of cgraph_for_node_and_aliases accumulating statistics of
534 non-thunk incoming edges to NODE. */
535
536 static bool
537 gather_caller_stats (struct cgraph_node *node, void *data)
538 {
539 struct caller_statistics *stats = (struct caller_statistics *) data;
540 struct cgraph_edge *cs;
541
542 for (cs = node->callers; cs; cs = cs->next_caller)
543 if (!cs->caller->thunk)
544 {
545 ipa_node_params *info = ipa_node_params_sum->get (cs->caller);
546 if (info && info->node_dead)
547 continue;
548
549 if (cs->count.ipa ().initialized_p ())
550 {
551 if (stats->itself && stats->itself == cs->caller)
552 stats->rec_count_sum += cs->count.ipa ();
553 else
554 stats->count_sum += cs->count.ipa ();
555 }
556 stats->freq_sum += cs->sreal_frequency ();
557 stats->n_calls++;
558 if (stats->itself && stats->itself != cs->caller)
559 stats->n_nonrec_calls++;
560
561 if (cs->maybe_hot_p ())
562 stats->n_hot_calls ++;
563 }
564 return false;
565
566 }
567
568 /* Return true if this NODE is viable candidate for cloning. */
569
570 static bool
571 ipcp_cloning_candidate_p (struct cgraph_node *node)
572 {
573 struct caller_statistics stats;
574
575 gcc_checking_assert (node->has_gimple_body_p ());
576
577 if (!opt_for_fn (node->decl, flag_ipa_cp_clone))
578 {
579 if (dump_file)
580 fprintf (dump_file, "Not considering %s for cloning; "
581 "-fipa-cp-clone disabled.\n",
582 node->dump_name ());
583 return false;
584 }
585
586 if (node->optimize_for_size_p ())
587 {
588 if (dump_file)
589 fprintf (dump_file, "Not considering %s for cloning; "
590 "optimizing it for size.\n",
591 node->dump_name ());
592 return false;
593 }
594
595 init_caller_stats (&stats);
596 node->call_for_symbol_thunks_and_aliases (gather_caller_stats, &stats, false);
597
598 if (ipa_size_summaries->get (node)->self_size < stats.n_calls)
599 {
600 if (dump_file)
601 fprintf (dump_file, "Considering %s for cloning; code might shrink.\n",
602 node->dump_name ());
603 return true;
604 }
605
606 /* When profile is available and function is hot, propagate into it even if
607 calls seems cold; constant propagation can improve function's speed
608 significantly. */
609 if (stats.count_sum > profile_count::zero ()
610 && node->count.ipa ().initialized_p ())
611 {
612 if (stats.count_sum > node->count.ipa ().apply_scale (90, 100))
613 {
614 if (dump_file)
615 fprintf (dump_file, "Considering %s for cloning; "
616 "usually called directly.\n",
617 node->dump_name ());
618 return true;
619 }
620 }
621 if (!stats.n_hot_calls)
622 {
623 if (dump_file)
624 fprintf (dump_file, "Not considering %s for cloning; no hot calls.\n",
625 node->dump_name ());
626 return false;
627 }
628 if (dump_file)
629 fprintf (dump_file, "Considering %s for cloning.\n",
630 node->dump_name ());
631 return true;
632 }
633
634 template <typename valtype>
635 class value_topo_info
636 {
637 public:
638 /* Head of the linked list of topologically sorted values. */
639 ipcp_value<valtype> *values_topo;
640 /* Stack for creating SCCs, represented by a linked list too. */
641 ipcp_value<valtype> *stack;
642 /* Counter driving the algorithm in add_val_to_toposort. */
643 int dfs_counter;
644
645 value_topo_info () : values_topo (NULL), stack (NULL), dfs_counter (0)
646 {}
647 void add_val (ipcp_value<valtype> *cur_val);
648 void propagate_effects ();
649 };
650
651 /* Arrays representing a topological ordering of call graph nodes and a stack
652 of nodes used during constant propagation and also data required to perform
653 topological sort of values and propagation of benefits in the determined
654 order. */
655
656 class ipa_topo_info
657 {
658 public:
659 /* Array with obtained topological order of cgraph nodes. */
660 struct cgraph_node **order;
661 /* Stack of cgraph nodes used during propagation within SCC until all values
662 in the SCC stabilize. */
663 struct cgraph_node **stack;
664 int nnodes, stack_top;
665
666 value_topo_info<tree> constants;
667 value_topo_info<ipa_polymorphic_call_context> contexts;
668
669 ipa_topo_info () : order(NULL), stack(NULL), nnodes(0), stack_top(0),
670 constants ()
671 {}
672 };
673
674 /* Skip edges from and to nodes without ipa_cp enabled.
675 Ignore not available symbols. */
676
677 static bool
678 ignore_edge_p (cgraph_edge *e)
679 {
680 enum availability avail;
681 cgraph_node *ultimate_target
682 = e->callee->function_or_virtual_thunk_symbol (&avail, e->caller);
683
684 return (avail <= AVAIL_INTERPOSABLE
685 || !opt_for_fn (ultimate_target->decl, optimize)
686 || !opt_for_fn (ultimate_target->decl, flag_ipa_cp));
687 }
688
689 /* Allocate the arrays in TOPO and topologically sort the nodes into order. */
690
691 static void
692 build_toporder_info (class ipa_topo_info *topo)
693 {
694 topo->order = XCNEWVEC (struct cgraph_node *, symtab->cgraph_count);
695 topo->stack = XCNEWVEC (struct cgraph_node *, symtab->cgraph_count);
696
697 gcc_checking_assert (topo->stack_top == 0);
698 topo->nnodes = ipa_reduced_postorder (topo->order, true,
699 ignore_edge_p);
700 }
701
702 /* Free information about strongly connected components and the arrays in
703 TOPO. */
704
705 static void
706 free_toporder_info (class ipa_topo_info *topo)
707 {
708 ipa_free_postorder_info ();
709 free (topo->order);
710 free (topo->stack);
711 }
712
713 /* Add NODE to the stack in TOPO, unless it is already there. */
714
715 static inline void
716 push_node_to_stack (class ipa_topo_info *topo, struct cgraph_node *node)
717 {
718 ipa_node_params *info = ipa_node_params_sum->get (node);
719 if (info->node_enqueued)
720 return;
721 info->node_enqueued = 1;
722 topo->stack[topo->stack_top++] = node;
723 }
724
725 /* Pop a node from the stack in TOPO and return it or return NULL if the stack
726 is empty. */
727
728 static struct cgraph_node *
729 pop_node_from_stack (class ipa_topo_info *topo)
730 {
731 if (topo->stack_top)
732 {
733 struct cgraph_node *node;
734 topo->stack_top--;
735 node = topo->stack[topo->stack_top];
736 ipa_node_params_sum->get (node)->node_enqueued = 0;
737 return node;
738 }
739 else
740 return NULL;
741 }
742
743 /* Set lattice LAT to bottom and return true if it previously was not set as
744 such. */
745
746 template <typename valtype>
747 inline bool
748 ipcp_lattice<valtype>::set_to_bottom ()
749 {
750 bool ret = !bottom;
751 bottom = true;
752 return ret;
753 }
754
755 /* Mark lattice as containing an unknown value and return true if it previously
756 was not marked as such. */
757
758 template <typename valtype>
759 inline bool
760 ipcp_lattice<valtype>::set_contains_variable ()
761 {
762 bool ret = !contains_variable;
763 contains_variable = true;
764 return ret;
765 }
766
767 /* Set all aggregate lattices in PLATS to bottom and return true if they were
768 not previously set as such. */
769
770 static inline bool
771 set_agg_lats_to_bottom (class ipcp_param_lattices *plats)
772 {
773 bool ret = !plats->aggs_bottom;
774 plats->aggs_bottom = true;
775 return ret;
776 }
777
778 /* Mark all aggregate lattices in PLATS as containing an unknown value and
779 return true if they were not previously marked as such. */
780
781 static inline bool
782 set_agg_lats_contain_variable (class ipcp_param_lattices *plats)
783 {
784 bool ret = !plats->aggs_contain_variable;
785 plats->aggs_contain_variable = true;
786 return ret;
787 }
788
789 bool
790 ipcp_vr_lattice::meet_with (const ipcp_vr_lattice &other)
791 {
792 return meet_with_1 (other.m_vr);
793 }
794
795 /* Meet the current value of the lattice with the range described by
796 P_VR. */
797
798 bool
799 ipcp_vr_lattice::meet_with (const vrange &p_vr)
800 {
801 return meet_with_1 (p_vr);
802 }
803
804 /* Meet the current value of the lattice with the range described by
805 OTHER_VR. Return TRUE if anything changed. */
806
807 bool
808 ipcp_vr_lattice::meet_with_1 (const vrange &other_vr)
809 {
810 if (bottom_p ())
811 return false;
812
813 if (other_vr.varying_p ())
814 return set_to_bottom ();
815
816 bool res;
817 if (flag_checking)
818 {
819 value_range save (m_vr);
820 res = m_vr.union_ (other_vr);
821 gcc_assert (res == (m_vr != save));
822 }
823 else
824 res = m_vr.union_ (other_vr);
825 return res;
826 }
827
828 /* Return true if value range information in the lattice is yet unknown. */
829
830 bool
831 ipcp_vr_lattice::top_p () const
832 {
833 return m_vr.undefined_p ();
834 }
835
836 /* Return true if value range information in the lattice is known to be
837 unusable. */
838
839 bool
840 ipcp_vr_lattice::bottom_p () const
841 {
842 return m_vr.varying_p ();
843 }
844
845 /* Set value range information in the lattice to bottom. Return true if it
846 previously was in a different state. */
847
848 bool
849 ipcp_vr_lattice::set_to_bottom ()
850 {
851 if (m_vr.varying_p ())
852 return false;
853
854 /* Setting an unsupported type here forces the temporary to default
855 to unsupported_range, which can handle VARYING/DEFINED ranges,
856 but nothing else (union, intersect, etc). This allows us to set
857 bottoms on any ranges, and is safe as all users of the lattice
858 check for bottom first. */
859 m_vr.set_type (void_type_node);
860 m_vr.set_varying (void_type_node);
861
862 return true;
863 }
864
865 /* Set lattice value to bottom, if it already isn't the case. */
866
867 bool
868 ipcp_bits_lattice::set_to_bottom ()
869 {
870 if (bottom_p ())
871 return false;
872 m_lattice_val = IPA_BITS_VARYING;
873 m_value = 0;
874 m_mask = -1;
875 return true;
876 }
877
878 /* Set to constant if it isn't already. Only meant to be called
879 when switching state from TOP. */
880
881 bool
882 ipcp_bits_lattice::set_to_constant (widest_int value, widest_int mask)
883 {
884 gcc_assert (top_p ());
885 m_lattice_val = IPA_BITS_CONSTANT;
886 m_value = wi::bit_and (wi::bit_not (mask), value);
887 m_mask = mask;
888 return true;
889 }
890
891 /* Return true if any of the known bits are non-zero. */
892
893 bool
894 ipcp_bits_lattice::known_nonzero_p () const
895 {
896 if (!constant_p ())
897 return false;
898 return wi::ne_p (wi::bit_and (wi::bit_not (m_mask), m_value), 0);
899 }
900
901 /* Convert operand to value, mask form. */
902
903 void
904 ipcp_bits_lattice::get_value_and_mask (tree operand, widest_int *valuep, widest_int *maskp)
905 {
906 wide_int get_nonzero_bits (const_tree);
907
908 if (TREE_CODE (operand) == INTEGER_CST)
909 {
910 *valuep = wi::to_widest (operand);
911 *maskp = 0;
912 }
913 else
914 {
915 *valuep = 0;
916 *maskp = -1;
917 }
918 }
919
920 /* Meet operation, similar to ccp_lattice_meet, we xor values
921 if this->value, value have different values at same bit positions, we want
922 to drop that bit to varying. Return true if mask is changed.
923 This function assumes that the lattice value is in CONSTANT state. If
924 DROP_ALL_ONES, mask out any known bits with value one afterwards. */
925
926 bool
927 ipcp_bits_lattice::meet_with_1 (widest_int value, widest_int mask,
928 unsigned precision, bool drop_all_ones)
929 {
930 gcc_assert (constant_p ());
931
932 widest_int old_mask = m_mask;
933 m_mask = (m_mask | mask) | (m_value ^ value);
934 if (drop_all_ones)
935 m_mask |= m_value;
936
937 widest_int cap_mask = wi::shifted_mask <widest_int> (0, precision, true);
938 m_mask |= cap_mask;
939 if (wi::sext (m_mask, precision) == -1)
940 return set_to_bottom ();
941
942 m_value &= ~m_mask;
943 return m_mask != old_mask;
944 }
945
946 /* Meet the bits lattice with operand
947 described by <value, mask, sgn, precision. */
948
949 bool
950 ipcp_bits_lattice::meet_with (widest_int value, widest_int mask,
951 unsigned precision)
952 {
953 if (bottom_p ())
954 return false;
955
956 if (top_p ())
957 {
958 if (wi::sext (mask, precision) == -1)
959 return set_to_bottom ();
960 return set_to_constant (value, mask);
961 }
962
963 return meet_with_1 (value, mask, precision, false);
964 }
965
966 /* Meet bits lattice with the result of bit_value_binop (other, operand)
967 if code is binary operation or bit_value_unop (other) if code is unary op.
968 In the case when code is nop_expr, no adjustment is required. If
969 DROP_ALL_ONES, mask out any known bits with value one afterwards. */
970
971 bool
972 ipcp_bits_lattice::meet_with (ipcp_bits_lattice& other, unsigned precision,
973 signop sgn, enum tree_code code, tree operand,
974 bool drop_all_ones)
975 {
976 if (other.bottom_p ())
977 return set_to_bottom ();
978
979 if (bottom_p () || other.top_p ())
980 return false;
981
982 widest_int adjusted_value, adjusted_mask;
983
984 if (TREE_CODE_CLASS (code) == tcc_binary)
985 {
986 tree type = TREE_TYPE (operand);
987 widest_int o_value, o_mask;
988 get_value_and_mask (operand, &o_value, &o_mask);
989
990 bit_value_binop (code, sgn, precision, &adjusted_value, &adjusted_mask,
991 sgn, precision, other.get_value (), other.get_mask (),
992 TYPE_SIGN (type), TYPE_PRECISION (type), o_value, o_mask);
993
994 if (wi::sext (adjusted_mask, precision) == -1)
995 return set_to_bottom ();
996 }
997
998 else if (TREE_CODE_CLASS (code) == tcc_unary)
999 {
1000 bit_value_unop (code, sgn, precision, &adjusted_value,
1001 &adjusted_mask, sgn, precision, other.get_value (),
1002 other.get_mask ());
1003
1004 if (wi::sext (adjusted_mask, precision) == -1)
1005 return set_to_bottom ();
1006 }
1007
1008 else
1009 return set_to_bottom ();
1010
1011 if (top_p ())
1012 {
1013 if (drop_all_ones)
1014 {
1015 adjusted_mask |= adjusted_value;
1016 adjusted_value &= ~adjusted_mask;
1017 }
1018 widest_int cap_mask = wi::shifted_mask <widest_int> (0, precision, true);
1019 adjusted_mask |= cap_mask;
1020 if (wi::sext (adjusted_mask, precision) == -1)
1021 return set_to_bottom ();
1022 return set_to_constant (adjusted_value, adjusted_mask);
1023 }
1024 else
1025 return meet_with_1 (adjusted_value, adjusted_mask, precision,
1026 drop_all_ones);
1027 }
1028
1029 /* Dump the contents of the list to FILE. */
1030
1031 void
1032 ipa_argagg_value_list::dump (FILE *f)
1033 {
1034 bool comma = false;
1035 for (const ipa_argagg_value &av : m_elts)
1036 {
1037 fprintf (f, "%s %i[%u]=", comma ? "," : "",
1038 av.index, av.unit_offset);
1039 print_generic_expr (f, av.value);
1040 if (av.by_ref)
1041 fprintf (f, "(by_ref)");
1042 if (av.killed)
1043 fprintf (f, "(killed)");
1044 comma = true;
1045 }
1046 fprintf (f, "\n");
1047 }
1048
1049 /* Dump the contents of the list to stderr. */
1050
1051 void
1052 ipa_argagg_value_list::debug ()
1053 {
1054 dump (stderr);
1055 }
1056
1057 /* Return the item describing a constant stored for INDEX at UNIT_OFFSET or
1058 NULL if there is no such constant. */
1059
1060 const ipa_argagg_value *
1061 ipa_argagg_value_list::get_elt (int index, unsigned unit_offset) const
1062 {
1063 ipa_argagg_value key;
1064 key.index = index;
1065 key.unit_offset = unit_offset;
1066 const ipa_argagg_value *res
1067 = std::lower_bound (m_elts.begin (), m_elts.end (), key,
1068 [] (const ipa_argagg_value &elt,
1069 const ipa_argagg_value &val)
1070 {
1071 if (elt.index < val.index)
1072 return true;
1073 if (elt.index > val.index)
1074 return false;
1075 if (elt.unit_offset < val.unit_offset)
1076 return true;
1077 return false;
1078 });
1079
1080 if (res == m_elts.end ()
1081 || res->index != index
1082 || res->unit_offset != unit_offset)
1083 res = nullptr;
1084
1085 /* TODO: perhaps remove the check (that the underlying array is indeed
1086 sorted) if it turns out it can be too slow? */
1087 if (!flag_checking)
1088 return res;
1089
1090 const ipa_argagg_value *slow_res = NULL;
1091 int prev_index = -1;
1092 unsigned prev_unit_offset = 0;
1093 for (const ipa_argagg_value &av : m_elts)
1094 {
1095 gcc_assert (prev_index < 0
1096 || prev_index < av.index
1097 || prev_unit_offset < av.unit_offset);
1098 prev_index = av.index;
1099 prev_unit_offset = av.unit_offset;
1100 if (av.index == index
1101 && av.unit_offset == unit_offset)
1102 slow_res = &av;
1103 }
1104 gcc_assert (res == slow_res);
1105
1106 return res;
1107 }
1108
1109 /* Return the first item describing a constant stored for parameter with INDEX,
1110 regardless of offset or reference, or NULL if there is no such constant. */
1111
1112 const ipa_argagg_value *
1113 ipa_argagg_value_list::get_elt_for_index (int index) const
1114 {
1115 const ipa_argagg_value *res
1116 = std::lower_bound (m_elts.begin (), m_elts.end (), index,
1117 [] (const ipa_argagg_value &elt, unsigned idx)
1118 {
1119 return elt.index < idx;
1120 });
1121 if (res == m_elts.end ()
1122 || res->index != index)
1123 res = nullptr;
1124 return res;
1125 }
1126
1127 /* Return the aggregate constant stored for INDEX at UNIT_OFFSET, not
1128 performing any check of whether value is passed by reference, or NULL_TREE
1129 if there is no such constant. */
1130
1131 tree
1132 ipa_argagg_value_list::get_value (int index, unsigned unit_offset) const
1133 {
1134 const ipa_argagg_value *av = get_elt (index, unit_offset);
1135 return av ? av->value : NULL_TREE;
1136 }
1137
1138 /* Return the aggregate constant stored for INDEX at UNIT_OFFSET, if it is
1139 passed by reference or not according to BY_REF, or NULL_TREE if there is
1140 no such constant. */
1141
1142 tree
1143 ipa_argagg_value_list::get_value (int index, unsigned unit_offset,
1144 bool by_ref) const
1145 {
1146 const ipa_argagg_value *av = get_elt (index, unit_offset);
1147 if (av && av->by_ref == by_ref)
1148 return av->value;
1149 return NULL_TREE;
1150 }
1151
1152 /* Return true if all elements present in OTHER are also present in this
1153 list. */
1154
1155 bool
1156 ipa_argagg_value_list::superset_of_p (const ipa_argagg_value_list &other) const
1157 {
1158 unsigned j = 0;
1159 for (unsigned i = 0; i < other.m_elts.size (); i++)
1160 {
1161 unsigned other_index = other.m_elts[i].index;
1162 unsigned other_offset = other.m_elts[i].unit_offset;
1163
1164 while (j < m_elts.size ()
1165 && (m_elts[j].index < other_index
1166 || (m_elts[j].index == other_index
1167 && m_elts[j].unit_offset < other_offset)))
1168 j++;
1169
1170 if (j >= m_elts.size ()
1171 || m_elts[j].index != other_index
1172 || m_elts[j].unit_offset != other_offset
1173 || m_elts[j].by_ref != other.m_elts[i].by_ref
1174 || !m_elts[j].value
1175 || !values_equal_for_ipcp_p (m_elts[j].value, other.m_elts[i].value))
1176 return false;
1177 }
1178 return true;
1179 }
1180
1181 /* Push all items in this list that describe parameter SRC_INDEX into RES as
1182 ones describing DST_INDEX while subtracting UNIT_DELTA from their unit
1183 offsets but skip those which would end up with a negative offset. */
1184
1185 void
1186 ipa_argagg_value_list::push_adjusted_values (unsigned src_index,
1187 unsigned dest_index,
1188 unsigned unit_delta,
1189 vec<ipa_argagg_value> *res) const
1190 {
1191 const ipa_argagg_value *av = get_elt_for_index (src_index);
1192 if (!av)
1193 return;
1194 unsigned prev_unit_offset = 0;
1195 bool first = true;
1196 for (; av < m_elts.end (); ++av)
1197 {
1198 if (av->index > src_index)
1199 return;
1200 if (av->index == src_index
1201 && (av->unit_offset >= unit_delta)
1202 && av->value)
1203 {
1204 ipa_argagg_value new_av;
1205 gcc_checking_assert (av->value);
1206 new_av.value = av->value;
1207 new_av.unit_offset = av->unit_offset - unit_delta;
1208 new_av.index = dest_index;
1209 new_av.by_ref = av->by_ref;
1210 gcc_assert (!av->killed);
1211 new_av.killed = false;
1212
1213 /* Quick check that the offsets we push are indeed increasing. */
1214 gcc_assert (first
1215 || new_av.unit_offset > prev_unit_offset);
1216 prev_unit_offset = new_av.unit_offset;
1217 first = false;
1218
1219 res->safe_push (new_av);
1220 }
1221 }
1222 }
1223
1224 /* Push to RES information about single lattices describing aggregate values in
1225 PLATS as those describing parameter DEST_INDEX and the original offset minus
1226 UNIT_DELTA. Return true if any item has been pushed to RES. */
1227
1228 static bool
1229 push_agg_values_from_plats (ipcp_param_lattices *plats, int dest_index,
1230 unsigned unit_delta,
1231 vec<ipa_argagg_value> *res)
1232 {
1233 if (plats->aggs_contain_variable)
1234 return false;
1235
1236 bool pushed_sth = false;
1237 bool first = true;
1238 unsigned prev_unit_offset = 0;
1239 for (struct ipcp_agg_lattice *aglat = plats->aggs; aglat; aglat = aglat->next)
1240 if (aglat->is_single_const ()
1241 && (aglat->offset / BITS_PER_UNIT - unit_delta) >= 0)
1242 {
1243 ipa_argagg_value iav;
1244 iav.value = aglat->values->value;
1245 iav.unit_offset = aglat->offset / BITS_PER_UNIT - unit_delta;
1246 iav.index = dest_index;
1247 iav.by_ref = plats->aggs_by_ref;
1248 iav.killed = false;
1249
1250 gcc_assert (first
1251 || iav.unit_offset > prev_unit_offset);
1252 prev_unit_offset = iav.unit_offset;
1253 first = false;
1254
1255 pushed_sth = true;
1256 res->safe_push (iav);
1257 }
1258 return pushed_sth;
1259 }
1260
1261 /* Turn all values in LIST that are not present in OTHER into NULL_TREEs.
1262 Return the number of remaining valid entries. */
1263
1264 static unsigned
1265 intersect_argaggs_with (vec<ipa_argagg_value> &elts,
1266 const vec<ipa_argagg_value> &other)
1267 {
1268 unsigned valid_entries = 0;
1269 unsigned j = 0;
1270 for (unsigned i = 0; i < elts.length (); i++)
1271 {
1272 if (!elts[i].value)
1273 continue;
1274
1275 unsigned this_index = elts[i].index;
1276 unsigned this_offset = elts[i].unit_offset;
1277
1278 while (j < other.length ()
1279 && (other[j].index < this_index
1280 || (other[j].index == this_index
1281 && other[j].unit_offset < this_offset)))
1282 j++;
1283
1284 if (j >= other.length ())
1285 {
1286 elts[i].value = NULL_TREE;
1287 continue;
1288 }
1289
1290 if (other[j].index == this_index
1291 && other[j].unit_offset == this_offset
1292 && other[j].by_ref == elts[i].by_ref
1293 && other[j].value
1294 && values_equal_for_ipcp_p (other[j].value, elts[i].value))
1295 valid_entries++;
1296 else
1297 elts[i].value = NULL_TREE;
1298 }
1299 return valid_entries;
1300 }
1301
1302 /* Mark bot aggregate and scalar lattices as containing an unknown variable,
1303 return true is any of them has not been marked as such so far. */
1304
1305 static inline bool
1306 set_all_contains_variable (class ipcp_param_lattices *plats)
1307 {
1308 bool ret;
1309 ret = plats->itself.set_contains_variable ();
1310 ret |= plats->ctxlat.set_contains_variable ();
1311 ret |= set_agg_lats_contain_variable (plats);
1312 ret |= plats->bits_lattice.set_to_bottom ();
1313 ret |= plats->m_value_range.set_to_bottom ();
1314 return ret;
1315 }
1316
1317 /* Worker of call_for_symbol_thunks_and_aliases, increment the integer DATA
1318 points to by the number of callers to NODE. */
1319
1320 static bool
1321 count_callers (cgraph_node *node, void *data)
1322 {
1323 int *caller_count = (int *) data;
1324
1325 for (cgraph_edge *cs = node->callers; cs; cs = cs->next_caller)
1326 /* Local thunks can be handled transparently, but if the thunk cannot
1327 be optimized out, count it as a real use. */
1328 if (!cs->caller->thunk || !cs->caller->local)
1329 ++*caller_count;
1330 return false;
1331 }
1332
1333 /* Worker of call_for_symbol_thunks_and_aliases, it is supposed to be called on
1334 the one caller of some other node. Set the caller's corresponding flag. */
1335
1336 static bool
1337 set_single_call_flag (cgraph_node *node, void *)
1338 {
1339 cgraph_edge *cs = node->callers;
1340 /* Local thunks can be handled transparently, skip them. */
1341 while (cs && cs->caller->thunk && cs->caller->local)
1342 cs = cs->next_caller;
1343 if (cs)
1344 if (ipa_node_params* info = ipa_node_params_sum->get (cs->caller))
1345 {
1346 info->node_calling_single_call = true;
1347 return true;
1348 }
1349 return false;
1350 }
1351
1352 /* Initialize ipcp_lattices. */
1353
1354 static void
1355 initialize_node_lattices (struct cgraph_node *node)
1356 {
1357 ipa_node_params *info = ipa_node_params_sum->get (node);
1358 struct cgraph_edge *ie;
1359 bool disable = false, variable = false;
1360 int i;
1361
1362 gcc_checking_assert (node->has_gimple_body_p ());
1363
1364 if (!ipa_get_param_count (info))
1365 disable = true;
1366 else if (node->local)
1367 {
1368 int caller_count = 0;
1369 node->call_for_symbol_thunks_and_aliases (count_callers, &caller_count,
1370 true);
1371 if (caller_count == 1)
1372 node->call_for_symbol_thunks_and_aliases (set_single_call_flag,
1373 NULL, true);
1374 else if (caller_count == 0)
1375 {
1376 gcc_checking_assert (!opt_for_fn (node->decl, flag_toplevel_reorder));
1377 variable = true;
1378 }
1379 }
1380 else
1381 {
1382 /* When cloning is allowed, we can assume that externally visible
1383 functions are not called. We will compensate this by cloning
1384 later. */
1385 if (ipcp_versionable_function_p (node)
1386 && ipcp_cloning_candidate_p (node))
1387 variable = true;
1388 else
1389 disable = true;
1390 }
1391
1392 if (dump_file && (dump_flags & TDF_DETAILS)
1393 && !node->alias && !node->thunk)
1394 {
1395 fprintf (dump_file, "Initializing lattices of %s\n",
1396 node->dump_name ());
1397 if (disable || variable)
1398 fprintf (dump_file, " Marking all lattices as %s\n",
1399 disable ? "BOTTOM" : "VARIABLE");
1400 }
1401
1402 auto_vec<bool, 16> surviving_params;
1403 bool pre_modified = false;
1404
1405 clone_info *cinfo = clone_info::get (node);
1406
1407 if (!disable && cinfo && cinfo->param_adjustments)
1408 {
1409 /* At the moment all IPA optimizations should use the number of
1410 parameters of the prevailing decl as the m_always_copy_start.
1411 Handling any other value would complicate the code below, so for the
1412 time bing let's only assert it is so. */
1413 gcc_assert ((cinfo->param_adjustments->m_always_copy_start
1414 == ipa_get_param_count (info))
1415 || cinfo->param_adjustments->m_always_copy_start < 0);
1416
1417 pre_modified = true;
1418 cinfo->param_adjustments->get_surviving_params (&surviving_params);
1419
1420 if (dump_file && (dump_flags & TDF_DETAILS)
1421 && !node->alias && !node->thunk)
1422 {
1423 bool first = true;
1424 for (int j = 0; j < ipa_get_param_count (info); j++)
1425 {
1426 if (j < (int) surviving_params.length ()
1427 && surviving_params[j])
1428 continue;
1429 if (first)
1430 {
1431 fprintf (dump_file,
1432 " The following parameters are dead on arrival:");
1433 first = false;
1434 }
1435 fprintf (dump_file, " %u", j);
1436 }
1437 if (!first)
1438 fprintf (dump_file, "\n");
1439 }
1440 }
1441
1442 for (i = 0; i < ipa_get_param_count (info); i++)
1443 {
1444 ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
1445 tree type = ipa_get_type (info, i);
1446 if (disable
1447 || !ipa_get_type (info, i)
1448 || (pre_modified && (surviving_params.length () <= (unsigned) i
1449 || !surviving_params[i])))
1450 {
1451 plats->itself.set_to_bottom ();
1452 plats->ctxlat.set_to_bottom ();
1453 set_agg_lats_to_bottom (plats);
1454 plats->bits_lattice.set_to_bottom ();
1455 plats->m_value_range.init (type);
1456 plats->m_value_range.set_to_bottom ();
1457 }
1458 else
1459 {
1460 plats->m_value_range.init (type);
1461 if (variable)
1462 set_all_contains_variable (plats);
1463 }
1464 }
1465
1466 for (ie = node->indirect_calls; ie; ie = ie->next_callee)
1467 if (ie->indirect_info->polymorphic
1468 && ie->indirect_info->param_index >= 0)
1469 {
1470 gcc_checking_assert (ie->indirect_info->param_index >= 0);
1471 ipa_get_parm_lattices (info,
1472 ie->indirect_info->param_index)->virt_call = 1;
1473 }
1474 }
1475
1476 /* Return VALUE if it is NULL_TREE or if it can be directly safely IPA-CP
1477 propagated to a parameter of type PARAM_TYPE, or return a fold-converted
1478 VALUE to PARAM_TYPE if that is possible. Return NULL_TREE otherwise. */
1479
1480 tree
1481 ipacp_value_safe_for_type (tree param_type, tree value)
1482 {
1483 if (!value)
1484 return NULL_TREE;
1485 tree val_type = TREE_TYPE (value);
1486 if (param_type == val_type
1487 || useless_type_conversion_p (param_type, val_type))
1488 return value;
1489 if (fold_convertible_p (param_type, value))
1490 return fold_convert (param_type, value);
1491 else
1492 return NULL_TREE;
1493 }
1494
1495 /* Return the result of a (possibly arithmetic) operation determined by OPCODE
1496 on the constant value INPUT. OPERAND is 2nd operand for binary operation
1497 and is required for binary operations. RES_TYPE, required when opcode is
1498 not NOP_EXPR, is the type in which any operation is to be performed. Return
1499 NULL_TREE if that cannot be determined or be considered an interprocedural
1500 invariant. */
1501
1502 static tree
1503 ipa_get_jf_arith_result (enum tree_code opcode, tree input, tree operand,
1504 tree res_type)
1505 {
1506 tree res;
1507
1508 if (opcode == NOP_EXPR)
1509 return input;
1510 if (!is_gimple_ip_invariant (input))
1511 return NULL_TREE;
1512
1513 if (opcode == ASSERT_EXPR)
1514 {
1515 if (values_equal_for_ipcp_p (input, operand))
1516 return input;
1517 else
1518 return NULL_TREE;
1519 }
1520
1521 if (TREE_CODE_CLASS (opcode) == tcc_unary)
1522 res = fold_unary (opcode, res_type, input);
1523 else
1524 res = fold_binary (opcode, res_type, input, operand);
1525
1526 if (res && !is_gimple_ip_invariant (res))
1527 return NULL_TREE;
1528
1529 return res;
1530 }
1531
1532 /* Return the result of an ancestor jump function JFUNC on the constant value
1533 INPUT. Return NULL_TREE if that cannot be determined. */
1534
1535 static tree
1536 ipa_get_jf_ancestor_result (struct ipa_jump_func *jfunc, tree input)
1537 {
1538 gcc_checking_assert (TREE_CODE (input) != TREE_BINFO);
1539 if (TREE_CODE (input) == ADDR_EXPR)
1540 {
1541 gcc_checking_assert (is_gimple_ip_invariant_address (input));
1542 poly_int64 off = ipa_get_jf_ancestor_offset (jfunc);
1543 if (known_eq (off, 0))
1544 return input;
1545 poly_int64 byte_offset = exact_div (off, BITS_PER_UNIT);
1546 return build1 (ADDR_EXPR, TREE_TYPE (input),
1547 fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (input)), input,
1548 build_int_cst (ptr_type_node, byte_offset)));
1549 }
1550 else if (ipa_get_jf_ancestor_keep_null (jfunc)
1551 && zerop (input))
1552 return input;
1553 else
1554 return NULL_TREE;
1555 }
1556
1557 /* Determine whether JFUNC evaluates to a single known constant value and if
1558 so, return it. Otherwise return NULL. INFO describes the caller node or
1559 the one it is inlined to, so that pass-through jump functions can be
1560 evaluated. PARM_TYPE is the type of the parameter to which the result is
1561 passed. */
1562
1563 tree
1564 ipa_value_from_jfunc (class ipa_node_params *info, struct ipa_jump_func *jfunc,
1565 tree parm_type)
1566 {
1567 if (jfunc->type == IPA_JF_CONST)
1568 return ipa_get_jf_constant (jfunc);
1569 else if (jfunc->type == IPA_JF_PASS_THROUGH
1570 || jfunc->type == IPA_JF_ANCESTOR)
1571 {
1572 tree input;
1573 int idx;
1574
1575 if (jfunc->type == IPA_JF_PASS_THROUGH)
1576 idx = ipa_get_jf_pass_through_formal_id (jfunc);
1577 else
1578 idx = ipa_get_jf_ancestor_formal_id (jfunc);
1579
1580 if (info->ipcp_orig_node)
1581 input = info->known_csts[idx];
1582 else
1583 {
1584 ipcp_lattice<tree> *lat;
1585
1586 if (info->lattices.is_empty ()
1587 || idx >= ipa_get_param_count (info))
1588 return NULL_TREE;
1589 lat = ipa_get_scalar_lat (info, idx);
1590 if (!lat->is_single_const ())
1591 return NULL_TREE;
1592 input = lat->values->value;
1593 }
1594
1595 if (!input)
1596 return NULL_TREE;
1597
1598 if (jfunc->type == IPA_JF_PASS_THROUGH)
1599 {
1600 if (!parm_type)
1601 return NULL_TREE;
1602 enum tree_code opcode = ipa_get_jf_pass_through_operation (jfunc);
1603 tree op2 = ipa_get_jf_pass_through_operand (jfunc);
1604 tree op_type
1605 = (opcode == NOP_EXPR) ? NULL_TREE
1606 : ipa_get_jf_pass_through_op_type (jfunc);
1607 tree cstval = ipa_get_jf_arith_result (opcode, input, op2, op_type);
1608 return ipacp_value_safe_for_type (parm_type, cstval);
1609 }
1610 else
1611 return ipa_get_jf_ancestor_result (jfunc, input);
1612 }
1613 else
1614 return NULL_TREE;
1615 }
1616
1617 /* Determine whether JFUNC evaluates to single known polymorphic context, given
1618 that INFO describes the caller node or the one it is inlined to, CS is the
1619 call graph edge corresponding to JFUNC and CSIDX index of the described
1620 parameter. */
1621
1622 ipa_polymorphic_call_context
1623 ipa_context_from_jfunc (ipa_node_params *info, cgraph_edge *cs, int csidx,
1624 ipa_jump_func *jfunc)
1625 {
1626 ipa_edge_args *args = ipa_edge_args_sum->get (cs);
1627 ipa_polymorphic_call_context ctx;
1628 ipa_polymorphic_call_context *edge_ctx
1629 = cs ? ipa_get_ith_polymorhic_call_context (args, csidx) : NULL;
1630
1631 if (edge_ctx && !edge_ctx->useless_p ())
1632 ctx = *edge_ctx;
1633
1634 if (jfunc->type == IPA_JF_PASS_THROUGH
1635 || jfunc->type == IPA_JF_ANCESTOR)
1636 {
1637 ipa_polymorphic_call_context srcctx;
1638 int srcidx;
1639 bool type_preserved = true;
1640 if (jfunc->type == IPA_JF_PASS_THROUGH)
1641 {
1642 if (ipa_get_jf_pass_through_operation (jfunc) != NOP_EXPR)
1643 return ctx;
1644 type_preserved = ipa_get_jf_pass_through_type_preserved (jfunc);
1645 srcidx = ipa_get_jf_pass_through_formal_id (jfunc);
1646 }
1647 else
1648 {
1649 type_preserved = ipa_get_jf_ancestor_type_preserved (jfunc);
1650 srcidx = ipa_get_jf_ancestor_formal_id (jfunc);
1651 }
1652 if (info->ipcp_orig_node)
1653 {
1654 if (info->known_contexts.exists ())
1655 srcctx = info->known_contexts[srcidx];
1656 }
1657 else
1658 {
1659 if (info->lattices.is_empty ()
1660 || srcidx >= ipa_get_param_count (info))
1661 return ctx;
1662 ipcp_lattice<ipa_polymorphic_call_context> *lat;
1663 lat = ipa_get_poly_ctx_lat (info, srcidx);
1664 if (!lat->is_single_const ())
1665 return ctx;
1666 srcctx = lat->values->value;
1667 }
1668 if (srcctx.useless_p ())
1669 return ctx;
1670 if (jfunc->type == IPA_JF_ANCESTOR)
1671 srcctx.offset_by (ipa_get_jf_ancestor_offset (jfunc));
1672 if (!type_preserved)
1673 srcctx.possible_dynamic_type_change (cs->in_polymorphic_cdtor);
1674 srcctx.combine_with (ctx);
1675 return srcctx;
1676 }
1677
1678 return ctx;
1679 }
1680
1681 /* Emulate effects of unary OPERATION and/or conversion from SRC_TYPE to
1682 DST_TYPE on value range in SRC_VR and store it to DST_VR. Return true if
1683 the result is a range that is not VARYING nor UNDEFINED. */
1684
1685 bool
1686 ipa_vr_operation_and_type_effects (vrange &dst_vr,
1687 const vrange &src_vr,
1688 enum tree_code operation,
1689 tree dst_type, tree src_type)
1690 {
1691 if (!ipa_vr_supported_type_p (dst_type)
1692 || !ipa_vr_supported_type_p (src_type))
1693 return false;
1694
1695 range_op_handler handler (operation);
1696 if (!handler)
1697 return false;
1698
1699 value_range varying (dst_type);
1700 varying.set_varying (dst_type);
1701
1702 return (handler.operand_check_p (dst_type, src_type, dst_type)
1703 && handler.fold_range (dst_vr, dst_type, src_vr, varying)
1704 && !dst_vr.varying_p ()
1705 && !dst_vr.undefined_p ());
1706 }
1707
1708 /* Same as above, but the SRC_VR argument is an IPA_VR which must
1709 first be extracted onto a vrange. */
1710
1711 bool
1712 ipa_vr_operation_and_type_effects (vrange &dst_vr,
1713 const ipa_vr &src_vr,
1714 enum tree_code operation,
1715 tree dst_type, tree src_type)
1716 {
1717 value_range tmp;
1718 src_vr.get_vrange (tmp);
1719 return ipa_vr_operation_and_type_effects (dst_vr, tmp, operation,
1720 dst_type, src_type);
1721 }
1722
1723 /* Given a PASS_THROUGH jump function JFUNC that takes as its source SRC_VR of
1724 SRC_TYPE and the result needs to be DST_TYPE, if any value range information
1725 can be deduced at all, intersect VR with it. CONTEXT_NODE is the call graph
1726 node representing the function for which optimization flags should be
1727 evaluated. */
1728
1729 static void
1730 ipa_vr_intersect_with_arith_jfunc (vrange &vr,
1731 ipa_jump_func *jfunc,
1732 cgraph_node *context_node,
1733 const value_range &src_vr,
1734 tree src_type,
1735 tree dst_type)
1736 {
1737 if (src_vr.undefined_p () || src_vr.varying_p ())
1738 return;
1739
1740 enum tree_code operation = ipa_get_jf_pass_through_operation (jfunc);
1741 if (TREE_CODE_CLASS (operation) == tcc_unary)
1742 {
1743 value_range op_res;
1744 const value_range *inter_vr;
1745 if (operation != NOP_EXPR)
1746 {
1747 tree operation_type = ipa_get_jf_pass_through_op_type (jfunc);
1748 op_res.set_varying (operation_type);
1749 if (!ipa_vr_operation_and_type_effects (op_res, src_vr, operation,
1750 operation_type, src_type))
1751 return;
1752 if (src_type == dst_type)
1753 {
1754 vr.intersect (op_res);
1755 return;
1756 }
1757 inter_vr = &op_res;
1758 src_type = operation_type;
1759 }
1760 else
1761 inter_vr = &src_vr;
1762
1763 value_range tmp_res (dst_type);
1764 if (ipa_vr_operation_and_type_effects (tmp_res, *inter_vr, NOP_EXPR,
1765 dst_type, src_type))
1766 vr.intersect (tmp_res);
1767 return;
1768 }
1769
1770 tree operand = ipa_get_jf_pass_through_operand (jfunc);
1771 range_op_handler handler (operation);
1772 if (!handler)
1773 return;
1774 value_range op_vr (TREE_TYPE (operand));
1775 ipa_get_range_from_ip_invariant (op_vr, operand, context_node);
1776
1777 tree operation_type = ipa_get_jf_pass_through_op_type (jfunc);
1778 value_range op_res (operation_type);
1779 if (!ipa_vr_supported_type_p (operation_type)
1780 || !handler.operand_check_p (operation_type, src_type, op_vr.type ())
1781 || !handler.fold_range (op_res, operation_type, src_vr, op_vr))
1782 return;
1783
1784 value_range tmp_res (dst_type);
1785 if (ipa_vr_operation_and_type_effects (tmp_res, op_res, NOP_EXPR, dst_type,
1786 operation_type))
1787 vr.intersect (tmp_res);
1788 }
1789
1790 /* Determine range of JFUNC given that INFO describes the caller node or
1791 the one it is inlined to, CS is the call graph edge corresponding to JFUNC
1792 and PARM_TYPE of the parameter. */
1793
1794 void
1795 ipa_value_range_from_jfunc (vrange &vr,
1796 ipa_node_params *info, cgraph_edge *cs,
1797 ipa_jump_func *jfunc, tree parm_type)
1798 {
1799 vr.set_varying (parm_type);
1800
1801 if (jfunc->m_vr && jfunc->m_vr->known_p ())
1802 ipa_vr_operation_and_type_effects (vr,
1803 *jfunc->m_vr,
1804 NOP_EXPR, parm_type,
1805 jfunc->m_vr->type ());
1806 if (vr.singleton_p ())
1807 return;
1808
1809 if (jfunc->type == IPA_JF_PASS_THROUGH)
1810 {
1811 ipcp_transformation *sum
1812 = ipcp_get_transformation_summary (cs->caller->inlined_to
1813 ? cs->caller->inlined_to
1814 : cs->caller);
1815 if (!sum || !sum->m_vr)
1816 return;
1817
1818 int idx = ipa_get_jf_pass_through_formal_id (jfunc);
1819
1820 if (!(*sum->m_vr)[idx].known_p ())
1821 return;
1822 tree src_type = ipa_get_type (info, idx);
1823 value_range srcvr;
1824 (*sum->m_vr)[idx].get_vrange (srcvr);
1825
1826 ipa_vr_intersect_with_arith_jfunc (vr, jfunc, cs->caller, srcvr, src_type,
1827 parm_type);
1828 }
1829 }
1830
1831 /* Determine whether ITEM, jump function for an aggregate part, evaluates to a
1832 single known constant value and if so, return it. Otherwise return NULL.
1833 NODE and INFO describes the caller node or the one it is inlined to, and
1834 its related info. */
1835
1836 tree
1837 ipa_agg_value_from_jfunc (ipa_node_params *info, cgraph_node *node,
1838 const ipa_agg_jf_item *item)
1839 {
1840 tree value = NULL_TREE;
1841 int src_idx;
1842
1843 if (item->offset < 0
1844 || item->jftype == IPA_JF_UNKNOWN
1845 || item->offset >= (HOST_WIDE_INT) UINT_MAX * BITS_PER_UNIT)
1846 return NULL_TREE;
1847
1848 if (item->jftype == IPA_JF_CONST)
1849 return item->value.constant;
1850
1851 gcc_checking_assert (item->jftype == IPA_JF_PASS_THROUGH
1852 || item->jftype == IPA_JF_LOAD_AGG);
1853
1854 src_idx = item->value.pass_through.formal_id;
1855
1856 if (info->ipcp_orig_node)
1857 {
1858 if (item->jftype == IPA_JF_PASS_THROUGH)
1859 value = info->known_csts[src_idx];
1860 else if (ipcp_transformation *ts = ipcp_get_transformation_summary (node))
1861 {
1862 ipa_argagg_value_list avl (ts);
1863 value = avl.get_value (src_idx,
1864 item->value.load_agg.offset / BITS_PER_UNIT,
1865 item->value.load_agg.by_ref);
1866 }
1867 }
1868 else if (!info->lattices.is_empty ())
1869 {
1870 class ipcp_param_lattices *src_plats
1871 = ipa_get_parm_lattices (info, src_idx);
1872
1873 if (item->jftype == IPA_JF_PASS_THROUGH)
1874 {
1875 struct ipcp_lattice<tree> *lat = &src_plats->itself;
1876
1877 if (!lat->is_single_const ())
1878 return NULL_TREE;
1879
1880 value = lat->values->value;
1881 }
1882 else if (src_plats->aggs
1883 && !src_plats->aggs_bottom
1884 && !src_plats->aggs_contain_variable
1885 && src_plats->aggs_by_ref == item->value.load_agg.by_ref)
1886 {
1887 struct ipcp_agg_lattice *aglat;
1888
1889 for (aglat = src_plats->aggs; aglat; aglat = aglat->next)
1890 {
1891 if (aglat->offset > item->value.load_agg.offset)
1892 break;
1893
1894 if (aglat->offset == item->value.load_agg.offset)
1895 {
1896 if (aglat->is_single_const ())
1897 value = aglat->values->value;
1898 break;
1899 }
1900 }
1901 }
1902 }
1903
1904 if (!value)
1905 return NULL_TREE;
1906
1907 if (item->jftype == IPA_JF_LOAD_AGG)
1908 {
1909 tree load_type = item->value.load_agg.type;
1910 tree value_type = TREE_TYPE (value);
1911
1912 /* Ensure value type is compatible with load type. */
1913 if (!useless_type_conversion_p (load_type, value_type))
1914 return NULL_TREE;
1915 }
1916
1917 tree cstval = ipa_get_jf_arith_result (item->value.pass_through.operation,
1918 value,
1919 item->value.pass_through.operand,
1920 item->value.pass_through.op_type);
1921 return ipacp_value_safe_for_type (item->type, cstval);
1922 }
1923
1924 /* Process all items in AGG_JFUNC relative to caller (or the node the original
1925 caller is inlined to) NODE which described by INFO and push the results to
1926 RES as describing values passed in parameter DST_INDEX. */
1927
1928 void
1929 ipa_push_agg_values_from_jfunc (ipa_node_params *info, cgraph_node *node,
1930 ipa_agg_jump_function *agg_jfunc,
1931 unsigned dst_index,
1932 vec<ipa_argagg_value> *res)
1933 {
1934 unsigned prev_unit_offset = 0;
1935 bool first = true;
1936
1937 for (const ipa_agg_jf_item &item : agg_jfunc->items)
1938 {
1939 tree value = ipa_agg_value_from_jfunc (info, node, &item);
1940 if (!value)
1941 continue;
1942
1943 ipa_argagg_value iav;
1944 iav.value = value;
1945 iav.unit_offset = item.offset / BITS_PER_UNIT;
1946 iav.index = dst_index;
1947 iav.by_ref = agg_jfunc->by_ref;
1948 iav.killed = 0;
1949
1950 gcc_assert (first
1951 || iav.unit_offset > prev_unit_offset);
1952 prev_unit_offset = iav.unit_offset;
1953 first = false;
1954
1955 res->safe_push (iav);
1956 }
1957 }
1958
1959 /* If checking is enabled, verify that no lattice is in the TOP state, i.e. not
1960 bottom, not containing a variable component and without any known value at
1961 the same time. */
1962
1963 DEBUG_FUNCTION void
1964 ipcp_verify_propagated_values (void)
1965 {
1966 struct cgraph_node *node;
1967
1968 FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
1969 {
1970 ipa_node_params *info = ipa_node_params_sum->get (node);
1971 if (!opt_for_fn (node->decl, flag_ipa_cp)
1972 || !opt_for_fn (node->decl, optimize))
1973 continue;
1974 int i, count = ipa_get_param_count (info);
1975
1976 for (i = 0; i < count; i++)
1977 {
1978 ipcp_lattice<tree> *lat = ipa_get_scalar_lat (info, i);
1979
1980 if (!lat->bottom
1981 && !lat->contains_variable
1982 && lat->values_count == 0)
1983 {
1984 if (dump_file)
1985 {
1986 symtab->dump (dump_file);
1987 fprintf (dump_file, "\nIPA lattices after constant "
1988 "propagation, before gcc_unreachable:\n");
1989 print_all_lattices (dump_file, true, false);
1990 }
1991
1992 gcc_unreachable ();
1993 }
1994 }
1995 }
1996 }
1997
1998 /* Return true iff X and Y should be considered equal contexts by IPA-CP. */
1999
2000 static bool
2001 values_equal_for_ipcp_p (ipa_polymorphic_call_context x,
2002 ipa_polymorphic_call_context y)
2003 {
2004 return x.equal_to (y);
2005 }
2006
2007
2008 /* Add a new value source to the value represented by THIS, marking that a
2009 value comes from edge CS and (if the underlying jump function is a
2010 pass-through or an ancestor one) from a caller value SRC_VAL of a caller
2011 parameter described by SRC_INDEX. OFFSET is negative if the source was the
2012 scalar value of the parameter itself or the offset within an aggregate. */
2013
2014 template <typename valtype>
2015 void
2016 ipcp_value<valtype>::add_source (cgraph_edge *cs, ipcp_value *src_val,
2017 int src_idx, HOST_WIDE_INT offset)
2018 {
2019 ipcp_value_source<valtype> *src;
2020
2021 src = new (ipcp_sources_pool.allocate ()) ipcp_value_source<valtype>;
2022 src->offset = offset;
2023 src->cs = cs;
2024 src->val = src_val;
2025 src->index = src_idx;
2026
2027 src->next = sources;
2028 sources = src;
2029 }
2030
2031 /* Allocate a new ipcp_value holding a tree constant, initialize its value to
2032 SOURCE and clear all other fields. */
2033
2034 static ipcp_value<tree> *
2035 allocate_and_init_ipcp_value (tree cst, unsigned same_lat_gen_level)
2036 {
2037 ipcp_value<tree> *val;
2038
2039 val = new (ipcp_cst_values_pool.allocate ()) ipcp_value<tree>();
2040 val->value = cst;
2041 val->self_recursion_generated_level = same_lat_gen_level;
2042 return val;
2043 }
2044
2045 /* Allocate a new ipcp_value holding a polymorphic context, initialize its
2046 value to SOURCE and clear all other fields. */
2047
2048 static ipcp_value<ipa_polymorphic_call_context> *
2049 allocate_and_init_ipcp_value (ipa_polymorphic_call_context ctx,
2050 unsigned same_lat_gen_level)
2051 {
2052 ipcp_value<ipa_polymorphic_call_context> *val;
2053
2054 val = new (ipcp_poly_ctx_values_pool.allocate ())
2055 ipcp_value<ipa_polymorphic_call_context>();
2056 val->value = ctx;
2057 val->self_recursion_generated_level = same_lat_gen_level;
2058 return val;
2059 }
2060
2061 /* Try to add NEWVAL to LAT, potentially creating a new ipcp_value for it. CS,
2062 SRC_VAL SRC_INDEX and OFFSET are meant for add_source and have the same
2063 meaning. OFFSET -1 means the source is scalar and not a part of an
2064 aggregate. If non-NULL, VAL_P records address of existing or newly added
2065 ipcp_value.
2066
2067 If the value is generated for a self-recursive call as a result of an
2068 arithmetic pass-through jump-function acting on a value in the same lattice,
2069 SAME_LAT_GEN_LEVEL must be the length of such chain, otherwise it must be
2070 zero. If it is non-zero, PARAM_IPA_CP_VALUE_LIST_SIZE limit is ignored. */
2071
2072 template <typename valtype>
2073 bool
2074 ipcp_lattice<valtype>::add_value (valtype newval, cgraph_edge *cs,
2075 ipcp_value<valtype> *src_val,
2076 int src_idx, HOST_WIDE_INT offset,
2077 ipcp_value<valtype> **val_p,
2078 unsigned same_lat_gen_level)
2079 {
2080 ipcp_value<valtype> *val, *last_val = NULL;
2081
2082 if (val_p)
2083 *val_p = NULL;
2084
2085 if (bottom)
2086 return false;
2087
2088 for (val = values; val; last_val = val, val = val->next)
2089 if (values_equal_for_ipcp_p (val->value, newval))
2090 {
2091 if (val_p)
2092 *val_p = val;
2093
2094 if (val->self_recursion_generated_level < same_lat_gen_level)
2095 val->self_recursion_generated_level = same_lat_gen_level;
2096
2097 if (ipa_edge_within_scc (cs))
2098 {
2099 ipcp_value_source<valtype> *s;
2100 for (s = val->sources; s; s = s->next)
2101 if (s->cs == cs && s->val == src_val)
2102 break;
2103 if (s)
2104 return false;
2105 }
2106
2107 val->add_source (cs, src_val, src_idx, offset);
2108 return false;
2109 }
2110
2111 if (!same_lat_gen_level && values_count >= opt_for_fn (cs->callee->decl,
2112 param_ipa_cp_value_list_size))
2113 {
2114 /* We can only free sources, not the values themselves, because sources
2115 of other values in this SCC might point to them. */
2116 for (val = values; val; val = val->next)
2117 {
2118 while (val->sources)
2119 {
2120 ipcp_value_source<valtype> *src = val->sources;
2121 val->sources = src->next;
2122 ipcp_sources_pool.remove ((ipcp_value_source<tree>*)src);
2123 }
2124 }
2125 values = NULL;
2126 return set_to_bottom ();
2127 }
2128
2129 values_count++;
2130 val = allocate_and_init_ipcp_value (newval, same_lat_gen_level);
2131 val->add_source (cs, src_val, src_idx, offset);
2132 val->next = NULL;
2133
2134 /* Add the new value to end of value list, which can reduce iterations
2135 of propagation stage for recursive function. */
2136 if (last_val)
2137 last_val->next = val;
2138 else
2139 values = val;
2140
2141 if (val_p)
2142 *val_p = val;
2143
2144 return true;
2145 }
2146
2147 /* A helper function that returns result of operation specified by OPCODE on
2148 the value of SRC_VAL. If non-NULL, OPND1_TYPE is expected type for the
2149 value of SRC_VAL. If the operation is binary, OPND2 is a constant value
2150 acting as its second operand. OP_TYPE is the type in which the operation is
2151 performed. */
2152
2153 static tree
2154 get_val_across_arith_op (enum tree_code opcode,
2155 tree opnd1_type,
2156 tree opnd2,
2157 ipcp_value<tree> *src_val,
2158 tree op_type)
2159 {
2160 tree opnd1 = src_val->value;
2161
2162 /* Skip source values that is incompatible with specified type. */
2163 if (opnd1_type
2164 && !useless_type_conversion_p (opnd1_type, TREE_TYPE (opnd1)))
2165 return NULL_TREE;
2166
2167 return ipa_get_jf_arith_result (opcode, opnd1, opnd2, op_type);
2168 }
2169
2170 /* Propagate values through an arithmetic transformation described by a jump
2171 function associated with edge CS, taking values from SRC_LAT and putting
2172 them into DEST_LAT. OPND1_TYPE, if non-NULL, is the expected type for the
2173 values in SRC_LAT. OPND2 is a constant value if transformation is a binary
2174 operation. SRC_OFFSET specifies offset in an aggregate if SRC_LAT describes
2175 lattice of a part of an aggregate, otherwise it should be -1. SRC_IDX is
2176 the index of the source parameter. OP_TYPE is the type in which the
2177 operation is performed and can be NULL when OPCODE is NOP_EXPR. RES_TYPE is
2178 the value type of result being propagated into. Return true if DEST_LAT
2179 changed. */
2180
2181 static bool
2182 propagate_vals_across_arith_jfunc (cgraph_edge *cs,
2183 enum tree_code opcode,
2184 tree opnd1_type,
2185 tree opnd2,
2186 ipcp_lattice<tree> *src_lat,
2187 ipcp_lattice<tree> *dest_lat,
2188 HOST_WIDE_INT src_offset,
2189 int src_idx,
2190 tree op_type,
2191 tree res_type)
2192 {
2193 ipcp_value<tree> *src_val;
2194 bool ret = false;
2195
2196 /* Due to circular dependencies, propagating within an SCC through arithmetic
2197 transformation would create infinite number of values. But for
2198 self-feeding recursive function, we could allow propagation in a limited
2199 count, and this can enable a simple kind of recursive function versioning.
2200 For other scenario, we would just make lattices bottom. */
2201 if (opcode != NOP_EXPR && ipa_edge_within_scc (cs))
2202 {
2203 int i;
2204
2205 int max_recursive_depth = opt_for_fn(cs->caller->decl,
2206 param_ipa_cp_max_recursive_depth);
2207 if (src_lat != dest_lat || max_recursive_depth < 1)
2208 return dest_lat->set_contains_variable ();
2209
2210 /* No benefit if recursive execution is in low probability. */
2211 if (cs->sreal_frequency () * 100
2212 <= ((sreal) 1) * opt_for_fn (cs->caller->decl,
2213 param_ipa_cp_min_recursive_probability))
2214 return dest_lat->set_contains_variable ();
2215
2216 auto_vec<ipcp_value<tree> *, 8> val_seeds;
2217
2218 for (src_val = src_lat->values; src_val; src_val = src_val->next)
2219 {
2220 /* Now we do not use self-recursively generated value as propagation
2221 source, this is absolutely conservative, but could avoid explosion
2222 of lattice's value space, especially when one recursive function
2223 calls another recursive. */
2224 if (src_val->self_recursion_generated_p ())
2225 {
2226 ipcp_value_source<tree> *s;
2227
2228 /* If the lattice has already been propagated for the call site,
2229 no need to do that again. */
2230 for (s = src_val->sources; s; s = s->next)
2231 if (s->cs == cs)
2232 return dest_lat->set_contains_variable ();
2233 }
2234 else
2235 val_seeds.safe_push (src_val);
2236 }
2237
2238 gcc_assert ((int) val_seeds.length () <= param_ipa_cp_value_list_size);
2239
2240 /* Recursively generate lattice values with a limited count. */
2241 FOR_EACH_VEC_ELT (val_seeds, i, src_val)
2242 {
2243 for (int j = 1; j < max_recursive_depth; j++)
2244 {
2245 tree cstval = get_val_across_arith_op (opcode, opnd1_type, opnd2,
2246 src_val, op_type);
2247 cstval = ipacp_value_safe_for_type (res_type, cstval);
2248 if (!cstval)
2249 break;
2250
2251 ret |= dest_lat->add_value (cstval, cs, src_val, src_idx,
2252 src_offset, &src_val, j);
2253 gcc_checking_assert (src_val);
2254 }
2255 }
2256 ret |= dest_lat->set_contains_variable ();
2257 }
2258 else
2259 for (src_val = src_lat->values; src_val; src_val = src_val->next)
2260 {
2261 /* Now we do not use self-recursively generated value as propagation
2262 source, otherwise it is easy to make value space of normal lattice
2263 overflow. */
2264 if (src_val->self_recursion_generated_p ())
2265 {
2266 ret |= dest_lat->set_contains_variable ();
2267 continue;
2268 }
2269
2270 tree cstval = get_val_across_arith_op (opcode, opnd1_type, opnd2,
2271 src_val, op_type);
2272 cstval = ipacp_value_safe_for_type (res_type, cstval);
2273 if (cstval)
2274 ret |= dest_lat->add_value (cstval, cs, src_val, src_idx,
2275 src_offset);
2276 else
2277 ret |= dest_lat->set_contains_variable ();
2278 }
2279
2280 return ret;
2281 }
2282
2283 /* Propagate values through a pass-through jump function JFUNC associated with
2284 edge CS, taking values from SRC_LAT and putting them into DEST_LAT. SRC_IDX
2285 is the index of the source parameter. PARM_TYPE is the type of the
2286 parameter to which the result is passed. */
2287
2288 static bool
2289 propagate_vals_across_pass_through (cgraph_edge *cs, ipa_jump_func *jfunc,
2290 ipcp_lattice<tree> *src_lat,
2291 ipcp_lattice<tree> *dest_lat, int src_idx,
2292 tree parm_type)
2293 {
2294 gcc_checking_assert (parm_type);
2295 enum tree_code opcode = ipa_get_jf_pass_through_operation (jfunc);
2296 tree op_type = (opcode == NOP_EXPR) ? NULL_TREE
2297 : ipa_get_jf_pass_through_op_type (jfunc);
2298 return propagate_vals_across_arith_jfunc (cs, opcode, NULL_TREE,
2299 ipa_get_jf_pass_through_operand (jfunc),
2300 src_lat, dest_lat, -1, src_idx, op_type,
2301 parm_type);
2302 }
2303
2304 /* Propagate values through an ancestor jump function JFUNC associated with
2305 edge CS, taking values from SRC_LAT and putting them into DEST_LAT. SRC_IDX
2306 is the index of the source parameter. */
2307
2308 static bool
2309 propagate_vals_across_ancestor (struct cgraph_edge *cs,
2310 struct ipa_jump_func *jfunc,
2311 ipcp_lattice<tree> *src_lat,
2312 ipcp_lattice<tree> *dest_lat, int src_idx,
2313 tree param_type)
2314 {
2315 ipcp_value<tree> *src_val;
2316 bool ret = false;
2317
2318 if (ipa_edge_within_scc (cs))
2319 return dest_lat->set_contains_variable ();
2320
2321 for (src_val = src_lat->values; src_val; src_val = src_val->next)
2322 {
2323 tree t = ipa_get_jf_ancestor_result (jfunc, src_val->value);
2324 t = ipacp_value_safe_for_type (param_type, t);
2325 if (t)
2326 ret |= dest_lat->add_value (t, cs, src_val, src_idx);
2327 else
2328 ret |= dest_lat->set_contains_variable ();
2329 }
2330
2331 return ret;
2332 }
2333
2334 /* Propagate scalar values across jump function JFUNC that is associated with
2335 edge CS and put the values into DEST_LAT. PARM_TYPE is the type of the
2336 parameter to which the result is passed. */
2337
2338 static bool
2339 propagate_scalar_across_jump_function (struct cgraph_edge *cs,
2340 struct ipa_jump_func *jfunc,
2341 ipcp_lattice<tree> *dest_lat,
2342 tree param_type)
2343 {
2344 if (dest_lat->bottom)
2345 return false;
2346
2347 if (jfunc->type == IPA_JF_CONST)
2348 {
2349 tree val = ipa_get_jf_constant (jfunc);
2350 val = ipacp_value_safe_for_type (param_type, val);
2351 if (val)
2352 return dest_lat->add_value (val, cs, NULL, 0);
2353 else
2354 return dest_lat->set_contains_variable ();
2355 }
2356 else if (jfunc->type == IPA_JF_PASS_THROUGH
2357 || jfunc->type == IPA_JF_ANCESTOR)
2358 {
2359 ipa_node_params *caller_info = ipa_node_params_sum->get (cs->caller);
2360 ipcp_lattice<tree> *src_lat;
2361 int src_idx;
2362 bool ret;
2363
2364 if (jfunc->type == IPA_JF_PASS_THROUGH)
2365 src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
2366 else
2367 src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
2368
2369 src_lat = ipa_get_scalar_lat (caller_info, src_idx);
2370 if (src_lat->bottom)
2371 return dest_lat->set_contains_variable ();
2372
2373 /* If we would need to clone the caller and cannot, do not propagate. */
2374 if (!ipcp_versionable_function_p (cs->caller)
2375 && (src_lat->contains_variable
2376 || (src_lat->values_count > 1)))
2377 return dest_lat->set_contains_variable ();
2378
2379 if (jfunc->type == IPA_JF_PASS_THROUGH)
2380 ret = propagate_vals_across_pass_through (cs, jfunc, src_lat,
2381 dest_lat, src_idx,
2382 param_type);
2383 else
2384 ret = propagate_vals_across_ancestor (cs, jfunc, src_lat, dest_lat,
2385 src_idx, param_type);
2386
2387 if (src_lat->contains_variable)
2388 ret |= dest_lat->set_contains_variable ();
2389
2390 return ret;
2391 }
2392
2393 /* TODO: We currently do not handle member method pointers in IPA-CP (we only
2394 use it for indirect inlining), we should propagate them too. */
2395 return dest_lat->set_contains_variable ();
2396 }
2397
2398 /* Propagate scalar values across jump function JFUNC that is associated with
2399 edge CS and describes argument IDX and put the values into DEST_LAT. */
2400
2401 static bool
2402 propagate_context_across_jump_function (cgraph_edge *cs,
2403 ipa_jump_func *jfunc, int idx,
2404 ipcp_lattice<ipa_polymorphic_call_context> *dest_lat)
2405 {
2406 if (dest_lat->bottom)
2407 return false;
2408 ipa_edge_args *args = ipa_edge_args_sum->get (cs);
2409 bool ret = false;
2410 bool added_sth = false;
2411 bool type_preserved = true;
2412
2413 ipa_polymorphic_call_context edge_ctx, *edge_ctx_ptr
2414 = ipa_get_ith_polymorhic_call_context (args, idx);
2415
2416 if (edge_ctx_ptr)
2417 edge_ctx = *edge_ctx_ptr;
2418
2419 if (jfunc->type == IPA_JF_PASS_THROUGH
2420 || jfunc->type == IPA_JF_ANCESTOR)
2421 {
2422 ipa_node_params *caller_info = ipa_node_params_sum->get (cs->caller);
2423 int src_idx;
2424 ipcp_lattice<ipa_polymorphic_call_context> *src_lat;
2425
2426 /* TODO: Once we figure out how to propagate speculations, it will
2427 probably be a good idea to switch to speculation if type_preserved is
2428 not set instead of punting. */
2429 if (jfunc->type == IPA_JF_PASS_THROUGH)
2430 {
2431 if (ipa_get_jf_pass_through_operation (jfunc) != NOP_EXPR)
2432 goto prop_fail;
2433 type_preserved = ipa_get_jf_pass_through_type_preserved (jfunc);
2434 src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
2435 }
2436 else
2437 {
2438 type_preserved = ipa_get_jf_ancestor_type_preserved (jfunc);
2439 src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
2440 }
2441
2442 src_lat = ipa_get_poly_ctx_lat (caller_info, src_idx);
2443 /* If we would need to clone the caller and cannot, do not propagate. */
2444 if (!ipcp_versionable_function_p (cs->caller)
2445 && (src_lat->contains_variable
2446 || (src_lat->values_count > 1)))
2447 goto prop_fail;
2448
2449 ipcp_value<ipa_polymorphic_call_context> *src_val;
2450 for (src_val = src_lat->values; src_val; src_val = src_val->next)
2451 {
2452 ipa_polymorphic_call_context cur = src_val->value;
2453
2454 if (!type_preserved)
2455 cur.possible_dynamic_type_change (cs->in_polymorphic_cdtor);
2456 if (jfunc->type == IPA_JF_ANCESTOR)
2457 cur.offset_by (ipa_get_jf_ancestor_offset (jfunc));
2458 /* TODO: In cases we know how the context is going to be used,
2459 we can improve the result by passing proper OTR_TYPE. */
2460 cur.combine_with (edge_ctx);
2461 if (!cur.useless_p ())
2462 {
2463 if (src_lat->contains_variable
2464 && !edge_ctx.equal_to (cur))
2465 ret |= dest_lat->set_contains_variable ();
2466 ret |= dest_lat->add_value (cur, cs, src_val, src_idx);
2467 added_sth = true;
2468 }
2469 }
2470 }
2471
2472 prop_fail:
2473 if (!added_sth)
2474 {
2475 if (!edge_ctx.useless_p ())
2476 ret |= dest_lat->add_value (edge_ctx, cs);
2477 else
2478 ret |= dest_lat->set_contains_variable ();
2479 }
2480
2481 return ret;
2482 }
2483
2484 /* Propagate bits across jfunc that is associated with
2485 edge cs and update dest_lattice accordingly. */
2486
2487 bool
2488 propagate_bits_across_jump_function (cgraph_edge *cs, int idx,
2489 ipa_jump_func *jfunc,
2490 ipcp_bits_lattice *dest_lattice)
2491 {
2492 if (dest_lattice->bottom_p ())
2493 return false;
2494
2495 enum availability availability;
2496 cgraph_node *callee = cs->callee->function_symbol (&availability);
2497 ipa_node_params *callee_info = ipa_node_params_sum->get (callee);
2498 tree parm_type = ipa_get_type (callee_info, idx);
2499
2500 /* For K&R C programs, ipa_get_type() could return NULL_TREE. Avoid the
2501 transform for these cases. Similarly, we can have bad type mismatches
2502 with LTO, avoid doing anything with those too. */
2503 if (!parm_type
2504 || (!INTEGRAL_TYPE_P (parm_type) && !POINTER_TYPE_P (parm_type)))
2505 {
2506 if (dump_file && (dump_flags & TDF_DETAILS))
2507 fprintf (dump_file, "Setting dest_lattice to bottom, because type of "
2508 "param %i of %s is NULL or unsuitable for bits propagation\n",
2509 idx, cs->callee->dump_name ());
2510
2511 return dest_lattice->set_to_bottom ();
2512 }
2513
2514 if (jfunc->type == IPA_JF_PASS_THROUGH
2515 || jfunc->type == IPA_JF_ANCESTOR)
2516 {
2517 ipa_node_params *caller_info = ipa_node_params_sum->get (cs->caller);
2518 tree operand = NULL_TREE;
2519 tree op_type = NULL_TREE;
2520 enum tree_code code;
2521 unsigned src_idx;
2522 bool keep_null = false;
2523
2524 if (jfunc->type == IPA_JF_PASS_THROUGH)
2525 {
2526 code = ipa_get_jf_pass_through_operation (jfunc);
2527 src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
2528 if (code != NOP_EXPR)
2529 {
2530 operand = ipa_get_jf_pass_through_operand (jfunc);
2531 op_type = ipa_get_jf_pass_through_op_type (jfunc);
2532 }
2533 }
2534 else
2535 {
2536 code = POINTER_PLUS_EXPR;
2537 src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
2538 unsigned HOST_WIDE_INT offset
2539 = ipa_get_jf_ancestor_offset (jfunc) / BITS_PER_UNIT;
2540 keep_null = (ipa_get_jf_ancestor_keep_null (jfunc) || !offset);
2541 operand = build_int_cstu (size_type_node, offset);
2542 }
2543
2544 class ipcp_param_lattices *src_lats
2545 = ipa_get_parm_lattices (caller_info, src_idx);
2546
2547 /* Try to propagate bits if src_lattice is bottom, but jfunc is known.
2548 for eg consider:
2549 int f(int x)
2550 {
2551 g (x & 0xff);
2552 }
2553 Assume lattice for x is bottom, however we can still propagate
2554 result of x & 0xff == 0xff, which gets computed during ccp1 pass
2555 and we store it in jump function during analysis stage. */
2556
2557 if (!src_lats->bits_lattice.bottom_p ())
2558 {
2559 if (!op_type)
2560 op_type = ipa_get_type (caller_info, src_idx);
2561
2562 unsigned precision = TYPE_PRECISION (op_type);
2563 signop sgn = TYPE_SIGN (op_type);
2564 bool drop_all_ones
2565 = keep_null && !src_lats->bits_lattice.known_nonzero_p ();
2566
2567 return dest_lattice->meet_with (src_lats->bits_lattice, precision,
2568 sgn, code, operand, drop_all_ones);
2569 }
2570 }
2571
2572 value_range vr (parm_type);
2573 if (jfunc->m_vr)
2574 {
2575 jfunc->m_vr->get_vrange (vr);
2576 if (!vr.undefined_p () && !vr.varying_p ())
2577 {
2578 irange_bitmask bm = vr.get_bitmask ();
2579 widest_int mask
2580 = widest_int::from (bm.mask (), TYPE_SIGN (parm_type));
2581 widest_int value
2582 = widest_int::from (bm.value (), TYPE_SIGN (parm_type));
2583 return dest_lattice->meet_with (value, mask,
2584 TYPE_PRECISION (parm_type));
2585 }
2586 }
2587 return dest_lattice->set_to_bottom ();
2588 }
2589
2590 /* Propagate value range across jump function JFUNC that is associated with
2591 edge CS with param of callee of PARAM_TYPE and update DEST_PLATS
2592 accordingly. */
2593
2594 static bool
2595 propagate_vr_across_jump_function (cgraph_edge *cs, ipa_jump_func *jfunc,
2596 class ipcp_param_lattices *dest_plats,
2597 tree param_type)
2598 {
2599 ipcp_vr_lattice *dest_lat = &dest_plats->m_value_range;
2600
2601 if (dest_lat->bottom_p ())
2602 return false;
2603
2604 if (!param_type
2605 || !ipa_vr_supported_type_p (param_type))
2606 return dest_lat->set_to_bottom ();
2607
2608 value_range vr (param_type);
2609 vr.set_varying (param_type);
2610 if (jfunc->m_vr)
2611 ipa_vr_operation_and_type_effects (vr, *jfunc->m_vr, NOP_EXPR,
2612 param_type,
2613 jfunc->m_vr->type ());
2614
2615 if (jfunc->type == IPA_JF_PASS_THROUGH)
2616 {
2617 ipa_node_params *caller_info = ipa_node_params_sum->get (cs->caller);
2618 int src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
2619 class ipcp_param_lattices *src_lats
2620 = ipa_get_parm_lattices (caller_info, src_idx);
2621 tree operand_type = ipa_get_type (caller_info, src_idx);
2622
2623 if (src_lats->m_value_range.bottom_p ())
2624 return dest_lat->set_to_bottom ();
2625
2626 if (ipa_get_jf_pass_through_operation (jfunc) == NOP_EXPR
2627 || !ipa_edge_within_scc (cs))
2628 ipa_vr_intersect_with_arith_jfunc (vr, jfunc, cs->caller,
2629 src_lats->m_value_range.m_vr,
2630 operand_type, param_type);
2631 }
2632
2633 if (!vr.undefined_p () && !vr.varying_p ())
2634 return dest_lat->meet_with (vr);
2635 else
2636 return dest_lat->set_to_bottom ();
2637 }
2638
2639 /* If DEST_PLATS already has aggregate items, check that aggs_by_ref matches
2640 NEW_AGGS_BY_REF and if not, mark all aggs as bottoms and return true (in all
2641 other cases, return false). If there are no aggregate items, set
2642 aggs_by_ref to NEW_AGGS_BY_REF. */
2643
2644 static bool
2645 set_check_aggs_by_ref (class ipcp_param_lattices *dest_plats,
2646 bool new_aggs_by_ref)
2647 {
2648 if (dest_plats->aggs)
2649 {
2650 if (dest_plats->aggs_by_ref != new_aggs_by_ref)
2651 {
2652 set_agg_lats_to_bottom (dest_plats);
2653 return true;
2654 }
2655 }
2656 else
2657 dest_plats->aggs_by_ref = new_aggs_by_ref;
2658 return false;
2659 }
2660
2661 /* Walk aggregate lattices in DEST_PLATS from ***AGLAT on, until ***aglat is an
2662 already existing lattice for the given OFFSET and SIZE, marking all skipped
2663 lattices as containing variable and checking for overlaps. If there is no
2664 already existing lattice for the OFFSET and VAL_SIZE, create one, initialize
2665 it with offset, size and contains_variable to PRE_EXISTING, and return true,
2666 unless there are too many already. If there are two many, return false. If
2667 there are overlaps turn whole DEST_PLATS to bottom and return false. If any
2668 skipped lattices were newly marked as containing variable, set *CHANGE to
2669 true. MAX_AGG_ITEMS is the maximum number of lattices. */
2670
2671 static bool
2672 merge_agg_lats_step (class ipcp_param_lattices *dest_plats,
2673 HOST_WIDE_INT offset, HOST_WIDE_INT val_size,
2674 struct ipcp_agg_lattice ***aglat,
2675 bool pre_existing, bool *change, int max_agg_items)
2676 {
2677 gcc_checking_assert (offset >= 0);
2678
2679 while (**aglat && (**aglat)->offset < offset)
2680 {
2681 if ((**aglat)->offset + (**aglat)->size > offset)
2682 {
2683 set_agg_lats_to_bottom (dest_plats);
2684 return false;
2685 }
2686 *change |= (**aglat)->set_contains_variable ();
2687 *aglat = &(**aglat)->next;
2688 }
2689
2690 if (**aglat && (**aglat)->offset == offset)
2691 {
2692 if ((**aglat)->size != val_size)
2693 {
2694 set_agg_lats_to_bottom (dest_plats);
2695 return false;
2696 }
2697 gcc_assert (!(**aglat)->next
2698 || (**aglat)->next->offset >= offset + val_size);
2699 return true;
2700 }
2701 else
2702 {
2703 struct ipcp_agg_lattice *new_al;
2704
2705 if (**aglat && (**aglat)->offset < offset + val_size)
2706 {
2707 set_agg_lats_to_bottom (dest_plats);
2708 return false;
2709 }
2710 if (dest_plats->aggs_count == max_agg_items)
2711 return false;
2712 dest_plats->aggs_count++;
2713 new_al = ipcp_agg_lattice_pool.allocate ();
2714
2715 new_al->offset = offset;
2716 new_al->size = val_size;
2717 new_al->contains_variable = pre_existing;
2718
2719 new_al->next = **aglat;
2720 **aglat = new_al;
2721 return true;
2722 }
2723 }
2724
2725 /* Set all AGLAT and all other aggregate lattices reachable by next pointers as
2726 containing an unknown value. */
2727
2728 static bool
2729 set_chain_of_aglats_contains_variable (struct ipcp_agg_lattice *aglat)
2730 {
2731 bool ret = false;
2732 while (aglat)
2733 {
2734 ret |= aglat->set_contains_variable ();
2735 aglat = aglat->next;
2736 }
2737 return ret;
2738 }
2739
2740 /* Merge existing aggregate lattices in SRC_PLATS to DEST_PLATS, subtracting
2741 DELTA_OFFSET. CS is the call graph edge and SRC_IDX the index of the source
2742 parameter used for lattice value sources. Return true if DEST_PLATS changed
2743 in any way. */
2744
2745 static bool
2746 merge_aggregate_lattices (struct cgraph_edge *cs,
2747 class ipcp_param_lattices *dest_plats,
2748 class ipcp_param_lattices *src_plats,
2749 int src_idx, HOST_WIDE_INT offset_delta)
2750 {
2751 bool pre_existing = dest_plats->aggs != NULL;
2752 struct ipcp_agg_lattice **dst_aglat;
2753 bool ret = false;
2754
2755 if (set_check_aggs_by_ref (dest_plats, src_plats->aggs_by_ref))
2756 return true;
2757 if (src_plats->aggs_bottom)
2758 return set_agg_lats_contain_variable (dest_plats);
2759 if (src_plats->aggs_contain_variable)
2760 ret |= set_agg_lats_contain_variable (dest_plats);
2761 dst_aglat = &dest_plats->aggs;
2762
2763 int max_agg_items = opt_for_fn (cs->callee->function_symbol ()->decl,
2764 param_ipa_max_agg_items);
2765 for (struct ipcp_agg_lattice *src_aglat = src_plats->aggs;
2766 src_aglat;
2767 src_aglat = src_aglat->next)
2768 {
2769 HOST_WIDE_INT new_offset = src_aglat->offset - offset_delta;
2770
2771 if (new_offset < 0)
2772 continue;
2773 if (merge_agg_lats_step (dest_plats, new_offset, src_aglat->size,
2774 &dst_aglat, pre_existing, &ret, max_agg_items))
2775 {
2776 struct ipcp_agg_lattice *new_al = *dst_aglat;
2777
2778 dst_aglat = &(*dst_aglat)->next;
2779 if (src_aglat->bottom)
2780 {
2781 ret |= new_al->set_contains_variable ();
2782 continue;
2783 }
2784 if (src_aglat->contains_variable)
2785 ret |= new_al->set_contains_variable ();
2786 for (ipcp_value<tree> *val = src_aglat->values;
2787 val;
2788 val = val->next)
2789 ret |= new_al->add_value (val->value, cs, val, src_idx,
2790 src_aglat->offset);
2791 }
2792 else if (dest_plats->aggs_bottom)
2793 return true;
2794 }
2795 ret |= set_chain_of_aglats_contains_variable (*dst_aglat);
2796 return ret;
2797 }
2798
2799 /* Determine whether there is anything to propagate FROM SRC_PLATS through a
2800 pass-through JFUNC and if so, whether it has conform and conforms to the
2801 rules about propagating values passed by reference. */
2802
2803 static bool
2804 agg_pass_through_permissible_p (class ipcp_param_lattices *src_plats,
2805 struct ipa_jump_func *jfunc)
2806 {
2807 return src_plats->aggs
2808 && (!src_plats->aggs_by_ref
2809 || ipa_get_jf_pass_through_agg_preserved (jfunc));
2810 }
2811
2812 /* Propagate values through ITEM, jump function for a part of an aggregate,
2813 into corresponding aggregate lattice AGLAT. CS is the call graph edge
2814 associated with the jump function. Return true if AGLAT changed in any
2815 way. */
2816
2817 static bool
2818 propagate_aggregate_lattice (struct cgraph_edge *cs,
2819 struct ipa_agg_jf_item *item,
2820 struct ipcp_agg_lattice *aglat)
2821 {
2822 class ipa_node_params *caller_info;
2823 class ipcp_param_lattices *src_plats;
2824 struct ipcp_lattice<tree> *src_lat;
2825 HOST_WIDE_INT src_offset;
2826 int src_idx;
2827 tree load_type;
2828 bool ret;
2829
2830 if (item->jftype == IPA_JF_CONST)
2831 {
2832 tree value = item->value.constant;
2833
2834 gcc_checking_assert (is_gimple_ip_invariant (value));
2835 return aglat->add_value (value, cs, NULL, 0);
2836 }
2837
2838 gcc_checking_assert (item->jftype == IPA_JF_PASS_THROUGH
2839 || item->jftype == IPA_JF_LOAD_AGG);
2840
2841 caller_info = ipa_node_params_sum->get (cs->caller);
2842 src_idx = item->value.pass_through.formal_id;
2843 src_plats = ipa_get_parm_lattices (caller_info, src_idx);
2844
2845 if (item->jftype == IPA_JF_PASS_THROUGH)
2846 {
2847 load_type = NULL_TREE;
2848 src_lat = &src_plats->itself;
2849 src_offset = -1;
2850 }
2851 else
2852 {
2853 HOST_WIDE_INT load_offset = item->value.load_agg.offset;
2854 struct ipcp_agg_lattice *src_aglat;
2855
2856 for (src_aglat = src_plats->aggs; src_aglat; src_aglat = src_aglat->next)
2857 if (src_aglat->offset >= load_offset)
2858 break;
2859
2860 load_type = item->value.load_agg.type;
2861 if (!src_aglat
2862 || src_aglat->offset > load_offset
2863 || src_aglat->size != tree_to_shwi (TYPE_SIZE (load_type))
2864 || src_plats->aggs_by_ref != item->value.load_agg.by_ref)
2865 return aglat->set_contains_variable ();
2866
2867 src_lat = src_aglat;
2868 src_offset = load_offset;
2869 }
2870
2871 if (src_lat->bottom
2872 || (!ipcp_versionable_function_p (cs->caller)
2873 && !src_lat->is_single_const ()))
2874 return aglat->set_contains_variable ();
2875
2876 ret = propagate_vals_across_arith_jfunc (cs,
2877 item->value.pass_through.operation,
2878 load_type,
2879 item->value.pass_through.operand,
2880 src_lat, aglat,
2881 src_offset,
2882 src_idx,
2883 item->value.pass_through.op_type,
2884 item->type);
2885
2886 if (src_lat->contains_variable)
2887 ret |= aglat->set_contains_variable ();
2888
2889 return ret;
2890 }
2891
2892 /* Propagate scalar values across jump function JFUNC that is associated with
2893 edge CS and put the values into DEST_LAT. */
2894
2895 static bool
2896 propagate_aggs_across_jump_function (struct cgraph_edge *cs,
2897 struct ipa_jump_func *jfunc,
2898 class ipcp_param_lattices *dest_plats)
2899 {
2900 bool ret = false;
2901
2902 if (dest_plats->aggs_bottom)
2903 return false;
2904
2905 if (jfunc->type == IPA_JF_PASS_THROUGH
2906 && ipa_get_jf_pass_through_operation (jfunc) == NOP_EXPR)
2907 {
2908 ipa_node_params *caller_info = ipa_node_params_sum->get (cs->caller);
2909 int src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
2910 class ipcp_param_lattices *src_plats;
2911
2912 src_plats = ipa_get_parm_lattices (caller_info, src_idx);
2913 if (agg_pass_through_permissible_p (src_plats, jfunc))
2914 {
2915 /* Currently we do not produce clobber aggregate jump
2916 functions, replace with merging when we do. */
2917 gcc_assert (!jfunc->agg.items);
2918 ret |= merge_aggregate_lattices (cs, dest_plats, src_plats,
2919 src_idx, 0);
2920 return ret;
2921 }
2922 }
2923 else if (jfunc->type == IPA_JF_ANCESTOR
2924 && ipa_get_jf_ancestor_agg_preserved (jfunc))
2925 {
2926 ipa_node_params *caller_info = ipa_node_params_sum->get (cs->caller);
2927 int src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
2928 class ipcp_param_lattices *src_plats;
2929
2930 src_plats = ipa_get_parm_lattices (caller_info, src_idx);
2931 if (src_plats->aggs && src_plats->aggs_by_ref)
2932 {
2933 /* Currently we do not produce clobber aggregate jump
2934 functions, replace with merging when we do. */
2935 gcc_assert (!jfunc->agg.items);
2936 ret |= merge_aggregate_lattices (cs, dest_plats, src_plats, src_idx,
2937 ipa_get_jf_ancestor_offset (jfunc));
2938 }
2939 else if (!src_plats->aggs_by_ref)
2940 ret |= set_agg_lats_to_bottom (dest_plats);
2941 else
2942 ret |= set_agg_lats_contain_variable (dest_plats);
2943 return ret;
2944 }
2945
2946 if (jfunc->agg.items)
2947 {
2948 bool pre_existing = dest_plats->aggs != NULL;
2949 struct ipcp_agg_lattice **aglat = &dest_plats->aggs;
2950 struct ipa_agg_jf_item *item;
2951 int i;
2952
2953 if (set_check_aggs_by_ref (dest_plats, jfunc->agg.by_ref))
2954 return true;
2955
2956 int max_agg_items = opt_for_fn (cs->callee->function_symbol ()->decl,
2957 param_ipa_max_agg_items);
2958 FOR_EACH_VEC_ELT (*jfunc->agg.items, i, item)
2959 {
2960 HOST_WIDE_INT val_size;
2961
2962 if (item->offset < 0 || item->jftype == IPA_JF_UNKNOWN)
2963 continue;
2964 val_size = tree_to_shwi (TYPE_SIZE (item->type));
2965
2966 if (merge_agg_lats_step (dest_plats, item->offset, val_size,
2967 &aglat, pre_existing, &ret, max_agg_items))
2968 {
2969 ret |= propagate_aggregate_lattice (cs, item, *aglat);
2970 aglat = &(*aglat)->next;
2971 }
2972 else if (dest_plats->aggs_bottom)
2973 return true;
2974 }
2975
2976 ret |= set_chain_of_aglats_contains_variable (*aglat);
2977 }
2978 else
2979 ret |= set_agg_lats_contain_variable (dest_plats);
2980
2981 return ret;
2982 }
2983
2984 /* Return true if on the way cfrom CS->caller to the final (non-alias and
2985 non-thunk) destination, the call passes through a thunk. */
2986
2987 static bool
2988 call_passes_through_thunk (cgraph_edge *cs)
2989 {
2990 cgraph_node *alias_or_thunk = cs->callee;
2991 while (alias_or_thunk->alias)
2992 alias_or_thunk = alias_or_thunk->get_alias_target ();
2993 return alias_or_thunk->thunk;
2994 }
2995
2996 /* Propagate constants from the caller to the callee of CS. INFO describes the
2997 caller. */
2998
2999 static bool
3000 propagate_constants_across_call (struct cgraph_edge *cs)
3001 {
3002 class ipa_node_params *callee_info;
3003 enum availability availability;
3004 cgraph_node *callee;
3005 class ipa_edge_args *args;
3006 bool ret = false;
3007 int i, args_count, parms_count;
3008
3009 callee = cs->callee->function_symbol (&availability);
3010 if (!callee->definition)
3011 return false;
3012 gcc_checking_assert (callee->has_gimple_body_p ());
3013 callee_info = ipa_node_params_sum->get (callee);
3014 if (!callee_info)
3015 return false;
3016
3017 args = ipa_edge_args_sum->get (cs);
3018 parms_count = ipa_get_param_count (callee_info);
3019 if (parms_count == 0)
3020 return false;
3021 if (!args
3022 || !opt_for_fn (cs->caller->decl, flag_ipa_cp)
3023 || !opt_for_fn (cs->caller->decl, optimize))
3024 {
3025 for (i = 0; i < parms_count; i++)
3026 ret |= set_all_contains_variable (ipa_get_parm_lattices (callee_info,
3027 i));
3028 return ret;
3029 }
3030 args_count = ipa_get_cs_argument_count (args);
3031
3032 /* If this call goes through a thunk we must not propagate to the first (0th)
3033 parameter. However, we might need to uncover a thunk from below a series
3034 of aliases first. */
3035 if (call_passes_through_thunk (cs))
3036 {
3037 ret |= set_all_contains_variable (ipa_get_parm_lattices (callee_info,
3038 0));
3039 i = 1;
3040 }
3041 else
3042 i = 0;
3043
3044 for (; (i < args_count) && (i < parms_count); i++)
3045 {
3046 struct ipa_jump_func *jump_func = ipa_get_ith_jump_func (args, i);
3047 class ipcp_param_lattices *dest_plats;
3048 tree param_type = ipa_get_type (callee_info, i);
3049
3050 dest_plats = ipa_get_parm_lattices (callee_info, i);
3051 if (availability == AVAIL_INTERPOSABLE)
3052 ret |= set_all_contains_variable (dest_plats);
3053 else
3054 {
3055 ret |= propagate_scalar_across_jump_function (cs, jump_func,
3056 &dest_plats->itself,
3057 param_type);
3058 ret |= propagate_context_across_jump_function (cs, jump_func, i,
3059 &dest_plats->ctxlat);
3060 ret
3061 |= propagate_bits_across_jump_function (cs, i, jump_func,
3062 &dest_plats->bits_lattice);
3063 ret |= propagate_aggs_across_jump_function (cs, jump_func,
3064 dest_plats);
3065 if (opt_for_fn (callee->decl, flag_ipa_vrp))
3066 ret |= propagate_vr_across_jump_function (cs, jump_func,
3067 dest_plats, param_type);
3068 else
3069 ret |= dest_plats->m_value_range.set_to_bottom ();
3070 }
3071 }
3072 for (; i < parms_count; i++)
3073 ret |= set_all_contains_variable (ipa_get_parm_lattices (callee_info, i));
3074
3075 return ret;
3076 }
3077
3078 /* If an indirect edge IE can be turned into a direct one based on KNOWN_VALS
3079 KNOWN_CONTEXTS, and known aggregates either in AVS or KNOWN_AGGS return
3080 the destination. The latter three can be NULL. If AGG_REPS is not NULL,
3081 KNOWN_AGGS is ignored. */
3082
3083 static tree
3084 ipa_get_indirect_edge_target_1 (struct cgraph_edge *ie,
3085 const vec<tree> &known_csts,
3086 const vec<ipa_polymorphic_call_context> &known_contexts,
3087 const ipa_argagg_value_list &avs,
3088 bool *speculative)
3089 {
3090 int param_index = ie->indirect_info->param_index;
3091 HOST_WIDE_INT anc_offset;
3092 tree t = NULL;
3093 tree target = NULL;
3094
3095 *speculative = false;
3096
3097 if (param_index == -1)
3098 return NULL_TREE;
3099
3100 if (!ie->indirect_info->polymorphic)
3101 {
3102 tree t = NULL;
3103
3104 if (ie->indirect_info->agg_contents)
3105 {
3106 t = NULL;
3107 if ((unsigned) param_index < known_csts.length ()
3108 && known_csts[param_index])
3109 t = ipa_find_agg_cst_from_init (known_csts[param_index],
3110 ie->indirect_info->offset,
3111 ie->indirect_info->by_ref);
3112
3113 if (!t && ie->indirect_info->guaranteed_unmodified)
3114 t = avs.get_value (param_index,
3115 ie->indirect_info->offset / BITS_PER_UNIT,
3116 ie->indirect_info->by_ref);
3117 }
3118 else if ((unsigned) param_index < known_csts.length ())
3119 t = known_csts[param_index];
3120
3121 if (t
3122 && TREE_CODE (t) == ADDR_EXPR
3123 && TREE_CODE (TREE_OPERAND (t, 0)) == FUNCTION_DECL)
3124 return TREE_OPERAND (t, 0);
3125 else
3126 return NULL_TREE;
3127 }
3128
3129 if (!opt_for_fn (ie->caller->decl, flag_devirtualize))
3130 return NULL_TREE;
3131
3132 gcc_assert (!ie->indirect_info->agg_contents);
3133 gcc_assert (!ie->indirect_info->by_ref);
3134 anc_offset = ie->indirect_info->offset;
3135
3136 t = NULL;
3137
3138 if ((unsigned) param_index < known_csts.length ()
3139 && known_csts[param_index])
3140 t = ipa_find_agg_cst_from_init (known_csts[param_index],
3141 ie->indirect_info->offset, true);
3142
3143 /* Try to work out value of virtual table pointer value in replacements. */
3144 /* or known aggregate values. */
3145 if (!t)
3146 t = avs.get_value (param_index,
3147 ie->indirect_info->offset / BITS_PER_UNIT,
3148 true);
3149
3150 /* If we found the virtual table pointer, lookup the target. */
3151 if (t)
3152 {
3153 tree vtable;
3154 unsigned HOST_WIDE_INT offset;
3155 if (vtable_pointer_value_to_vtable (t, &vtable, &offset))
3156 {
3157 bool can_refer;
3158 target = gimple_get_virt_method_for_vtable (ie->indirect_info->otr_token,
3159 vtable, offset, &can_refer);
3160 if (can_refer)
3161 {
3162 if (!target
3163 || fndecl_built_in_p (target, BUILT_IN_UNREACHABLE)
3164 || !possible_polymorphic_call_target_p
3165 (ie, cgraph_node::get (target)))
3166 {
3167 /* Do not speculate builtin_unreachable, it is stupid! */
3168 if (ie->indirect_info->vptr_changed)
3169 return NULL;
3170 target = ipa_impossible_devirt_target (ie, target);
3171 }
3172 *speculative = ie->indirect_info->vptr_changed;
3173 if (!*speculative)
3174 return target;
3175 }
3176 }
3177 }
3178
3179 /* Do we know the constant value of pointer? */
3180 if (!t && (unsigned) param_index < known_csts.length ())
3181 t = known_csts[param_index];
3182
3183 gcc_checking_assert (!t || TREE_CODE (t) != TREE_BINFO);
3184
3185 ipa_polymorphic_call_context context;
3186 if (known_contexts.length () > (unsigned int) param_index)
3187 {
3188 context = known_contexts[param_index];
3189 context.offset_by (anc_offset);
3190 if (ie->indirect_info->vptr_changed)
3191 context.possible_dynamic_type_change (ie->in_polymorphic_cdtor,
3192 ie->indirect_info->otr_type);
3193 if (t)
3194 {
3195 ipa_polymorphic_call_context ctx2 = ipa_polymorphic_call_context
3196 (t, ie->indirect_info->otr_type, anc_offset);
3197 if (!ctx2.useless_p ())
3198 context.combine_with (ctx2, ie->indirect_info->otr_type);
3199 }
3200 }
3201 else if (t)
3202 {
3203 context = ipa_polymorphic_call_context (t, ie->indirect_info->otr_type,
3204 anc_offset);
3205 if (ie->indirect_info->vptr_changed)
3206 context.possible_dynamic_type_change (ie->in_polymorphic_cdtor,
3207 ie->indirect_info->otr_type);
3208 }
3209 else
3210 return NULL_TREE;
3211
3212 vec <cgraph_node *>targets;
3213 bool final;
3214
3215 targets = possible_polymorphic_call_targets
3216 (ie->indirect_info->otr_type,
3217 ie->indirect_info->otr_token,
3218 context, &final);
3219 if (!final || targets.length () > 1)
3220 {
3221 struct cgraph_node *node;
3222 if (*speculative)
3223 return target;
3224 if (!opt_for_fn (ie->caller->decl, flag_devirtualize_speculatively)
3225 || ie->speculative || !ie->maybe_hot_p ())
3226 return NULL;
3227 node = try_speculative_devirtualization (ie->indirect_info->otr_type,
3228 ie->indirect_info->otr_token,
3229 context);
3230 if (node)
3231 {
3232 *speculative = true;
3233 target = node->decl;
3234 }
3235 else
3236 return NULL;
3237 }
3238 else
3239 {
3240 *speculative = false;
3241 if (targets.length () == 1)
3242 target = targets[0]->decl;
3243 else
3244 target = ipa_impossible_devirt_target (ie, NULL_TREE);
3245 }
3246
3247 if (target && !possible_polymorphic_call_target_p (ie,
3248 cgraph_node::get (target)))
3249 {
3250 if (*speculative)
3251 return NULL;
3252 target = ipa_impossible_devirt_target (ie, target);
3253 }
3254
3255 return target;
3256 }
3257
3258 /* If an indirect edge IE can be turned into a direct one based on data in
3259 AVALS, return the destination. Store into *SPECULATIVE a boolean determinig
3260 whether the discovered target is only speculative guess. */
3261
3262 tree
3263 ipa_get_indirect_edge_target (struct cgraph_edge *ie,
3264 ipa_call_arg_values *avals,
3265 bool *speculative)
3266 {
3267 ipa_argagg_value_list avl (avals);
3268 return ipa_get_indirect_edge_target_1 (ie, avals->m_known_vals,
3269 avals->m_known_contexts,
3270 avl, speculative);
3271 }
3272
3273 /* Calculate devirtualization time bonus for NODE, assuming we know information
3274 about arguments stored in AVALS. */
3275
3276 static int
3277 devirtualization_time_bonus (struct cgraph_node *node,
3278 ipa_auto_call_arg_values *avals)
3279 {
3280 struct cgraph_edge *ie;
3281 int res = 0;
3282
3283 for (ie = node->indirect_calls; ie; ie = ie->next_callee)
3284 {
3285 struct cgraph_node *callee;
3286 class ipa_fn_summary *isummary;
3287 enum availability avail;
3288 tree target;
3289 bool speculative;
3290
3291 ipa_argagg_value_list avl (avals);
3292 target = ipa_get_indirect_edge_target_1 (ie, avals->m_known_vals,
3293 avals->m_known_contexts,
3294 avl, &speculative);
3295 if (!target)
3296 continue;
3297
3298 /* Only bare minimum benefit for clearly un-inlineable targets. */
3299 res += 1;
3300 callee = cgraph_node::get (target);
3301 if (!callee || !callee->definition)
3302 continue;
3303 callee = callee->function_symbol (&avail);
3304 if (avail < AVAIL_AVAILABLE)
3305 continue;
3306 isummary = ipa_fn_summaries->get (callee);
3307 if (!isummary || !isummary->inlinable)
3308 continue;
3309
3310 int size = ipa_size_summaries->get (callee)->size;
3311 /* FIXME: The values below need re-considering and perhaps also
3312 integrating into the cost metrics, at lest in some very basic way. */
3313 int max_inline_insns_auto
3314 = opt_for_fn (callee->decl, param_max_inline_insns_auto);
3315 if (size <= max_inline_insns_auto / 4)
3316 res += 31 / ((int)speculative + 1);
3317 else if (size <= max_inline_insns_auto / 2)
3318 res += 15 / ((int)speculative + 1);
3319 else if (size <= max_inline_insns_auto
3320 || DECL_DECLARED_INLINE_P (callee->decl))
3321 res += 7 / ((int)speculative + 1);
3322 }
3323
3324 return res;
3325 }
3326
3327 /* Return time bonus incurred because of hints stored in ESTIMATES. */
3328
3329 static int
3330 hint_time_bonus (cgraph_node *node, const ipa_call_estimates &estimates)
3331 {
3332 int result = 0;
3333 ipa_hints hints = estimates.hints;
3334 if (hints & (INLINE_HINT_loop_iterations | INLINE_HINT_loop_stride))
3335 result += opt_for_fn (node->decl, param_ipa_cp_loop_hint_bonus);
3336
3337 sreal bonus_for_one = opt_for_fn (node->decl, param_ipa_cp_loop_hint_bonus);
3338
3339 if (hints & INLINE_HINT_loop_iterations)
3340 result += (estimates.loops_with_known_iterations * bonus_for_one).to_int ();
3341
3342 if (hints & INLINE_HINT_loop_stride)
3343 result += (estimates.loops_with_known_strides * bonus_for_one).to_int ();
3344
3345 return result;
3346 }
3347
3348 /* If there is a reason to penalize the function described by INFO in the
3349 cloning goodness evaluation, do so. */
3350
3351 static inline sreal
3352 incorporate_penalties (cgraph_node *node, ipa_node_params *info,
3353 sreal evaluation)
3354 {
3355 if (info->node_within_scc && !info->node_is_self_scc)
3356 evaluation = (evaluation
3357 * (100 - opt_for_fn (node->decl,
3358 param_ipa_cp_recursion_penalty))) / 100;
3359
3360 if (info->node_calling_single_call)
3361 evaluation = (evaluation
3362 * (100 - opt_for_fn (node->decl,
3363 param_ipa_cp_single_call_penalty)))
3364 / 100;
3365
3366 return evaluation;
3367 }
3368
3369 /* Return true if cloning NODE is a good idea, given the estimated TIME_BENEFIT
3370 and SIZE_COST and with the sum of frequencies of incoming edges to the
3371 potential new clone in FREQUENCIES. */
3372
3373 static bool
3374 good_cloning_opportunity_p (struct cgraph_node *node, sreal time_benefit,
3375 sreal freq_sum, profile_count count_sum,
3376 int size_cost)
3377 {
3378 if (time_benefit == 0
3379 || !opt_for_fn (node->decl, flag_ipa_cp_clone)
3380 || node->optimize_for_size_p ())
3381 return false;
3382
3383 gcc_assert (size_cost > 0);
3384
3385 ipa_node_params *info = ipa_node_params_sum->get (node);
3386 int eval_threshold = opt_for_fn (node->decl, param_ipa_cp_eval_threshold);
3387 if (count_sum.nonzero_p ())
3388 {
3389 gcc_assert (base_count.nonzero_p ());
3390 sreal factor = count_sum.probability_in (base_count).to_sreal ();
3391 sreal evaluation = (time_benefit * factor) / size_cost;
3392 evaluation = incorporate_penalties (node, info, evaluation);
3393 evaluation *= 1000;
3394
3395 if (dump_file && (dump_flags & TDF_DETAILS))
3396 {
3397 fprintf (dump_file, " good_cloning_opportunity_p (time: %g, "
3398 "size: %i, count_sum: ", time_benefit.to_double (),
3399 size_cost);
3400 count_sum.dump (dump_file);
3401 fprintf (dump_file, "%s%s) -> evaluation: %.2f, threshold: %i\n",
3402 info->node_within_scc
3403 ? (info->node_is_self_scc ? ", self_scc" : ", scc") : "",
3404 info->node_calling_single_call ? ", single_call" : "",
3405 evaluation.to_double (), eval_threshold);
3406 }
3407
3408 return evaluation.to_int () >= eval_threshold;
3409 }
3410 else
3411 {
3412 sreal evaluation = (time_benefit * freq_sum) / size_cost;
3413 evaluation = incorporate_penalties (node, info, evaluation);
3414 evaluation *= 1000;
3415
3416 if (dump_file && (dump_flags & TDF_DETAILS))
3417 fprintf (dump_file, " good_cloning_opportunity_p (time: %g, "
3418 "size: %i, freq_sum: %g%s%s) -> evaluation: %.2f, "
3419 "threshold: %i\n",
3420 time_benefit.to_double (), size_cost, freq_sum.to_double (),
3421 info->node_within_scc
3422 ? (info->node_is_self_scc ? ", self_scc" : ", scc") : "",
3423 info->node_calling_single_call ? ", single_call" : "",
3424 evaluation.to_double (), eval_threshold);
3425
3426 return evaluation.to_int () >= eval_threshold;
3427 }
3428 }
3429
3430 /* Grow vectors in AVALS and fill them with information about values of
3431 parameters that are known to be independent of the context. Only calculate
3432 m_known_aggs if CALCULATE_AGGS is true. INFO describes the function. If
3433 REMOVABLE_PARAMS_COST is non-NULL, the movement cost of all removable
3434 parameters will be stored in it.
3435
3436 TODO: Also grow context independent value range vectors. */
3437
3438 static bool
3439 gather_context_independent_values (class ipa_node_params *info,
3440 ipa_auto_call_arg_values *avals,
3441 bool calculate_aggs,
3442 int *removable_params_cost)
3443 {
3444 int i, count = ipa_get_param_count (info);
3445 bool ret = false;
3446
3447 avals->m_known_vals.safe_grow_cleared (count, true);
3448 avals->m_known_contexts.safe_grow_cleared (count, true);
3449
3450 if (removable_params_cost)
3451 *removable_params_cost = 0;
3452
3453 for (i = 0; i < count; i++)
3454 {
3455 class ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
3456 ipcp_lattice<tree> *lat = &plats->itself;
3457
3458 if (lat->is_single_const ())
3459 {
3460 ipcp_value<tree> *val = lat->values;
3461 gcc_checking_assert (TREE_CODE (val->value) != TREE_BINFO);
3462 avals->m_known_vals[i] = val->value;
3463 if (removable_params_cost)
3464 *removable_params_cost
3465 += estimate_move_cost (TREE_TYPE (val->value), false);
3466 ret = true;
3467 }
3468 else if (removable_params_cost
3469 && !ipa_is_param_used (info, i))
3470 *removable_params_cost
3471 += ipa_get_param_move_cost (info, i);
3472
3473 if (!ipa_is_param_used (info, i))
3474 continue;
3475
3476 ipcp_lattice<ipa_polymorphic_call_context> *ctxlat = &plats->ctxlat;
3477 /* Do not account known context as reason for cloning. We can see
3478 if it permits devirtualization. */
3479 if (ctxlat->is_single_const ())
3480 avals->m_known_contexts[i] = ctxlat->values->value;
3481
3482 if (calculate_aggs)
3483 ret |= push_agg_values_from_plats (plats, i, 0, &avals->m_known_aggs);
3484 }
3485
3486 return ret;
3487 }
3488
3489 /* Perform time and size measurement of NODE with the context given in AVALS,
3490 calculate the benefit compared to the node without specialization and store
3491 it into VAL. Take into account REMOVABLE_PARAMS_COST of all
3492 context-independent or unused removable parameters and EST_MOVE_COST, the
3493 estimated movement of the considered parameter. */
3494
3495 static void
3496 perform_estimation_of_a_value (cgraph_node *node,
3497 ipa_auto_call_arg_values *avals,
3498 int removable_params_cost, int est_move_cost,
3499 ipcp_value_base *val)
3500 {
3501 sreal time_benefit;
3502 ipa_call_estimates estimates;
3503
3504 estimate_ipcp_clone_size_and_time (node, avals, &estimates);
3505
3506 /* Extern inline functions have no cloning local time benefits because they
3507 will be inlined anyway. The only reason to clone them is if it enables
3508 optimization in any of the functions they call. */
3509 if (DECL_EXTERNAL (node->decl) && DECL_DECLARED_INLINE_P (node->decl))
3510 time_benefit = 0;
3511 else
3512 time_benefit = (estimates.nonspecialized_time - estimates.time)
3513 + (devirtualization_time_bonus (node, avals)
3514 + hint_time_bonus (node, estimates)
3515 + removable_params_cost + est_move_cost);
3516
3517 int size = estimates.size;
3518 gcc_checking_assert (size >=0);
3519 /* The inliner-heuristics based estimates may think that in certain
3520 contexts some functions do not have any size at all but we want
3521 all specializations to have at least a tiny cost, not least not to
3522 divide by zero. */
3523 if (size == 0)
3524 size = 1;
3525
3526 val->local_time_benefit = time_benefit;
3527 val->local_size_cost = size;
3528 }
3529
3530 /* Get the overall limit oof growth based on parameters extracted from growth.
3531 it does not really make sense to mix functions with different overall growth
3532 limits but it is possible and if it happens, we do not want to select one
3533 limit at random. */
3534
3535 static long
3536 get_max_overall_size (cgraph_node *node)
3537 {
3538 long max_new_size = orig_overall_size;
3539 long large_unit = opt_for_fn (node->decl, param_ipa_cp_large_unit_insns);
3540 if (max_new_size < large_unit)
3541 max_new_size = large_unit;
3542 int unit_growth = opt_for_fn (node->decl, param_ipa_cp_unit_growth);
3543 max_new_size += max_new_size * unit_growth / 100 + 1;
3544 return max_new_size;
3545 }
3546
3547 /* Return true if NODE should be cloned just for a parameter removal, possibly
3548 dumping a reason if not. */
3549
3550 static bool
3551 clone_for_param_removal_p (cgraph_node *node)
3552 {
3553 if (!node->can_change_signature)
3554 {
3555 if (dump_file && (dump_flags & TDF_DETAILS))
3556 fprintf (dump_file, " Not considering cloning to remove parameters, "
3557 "function cannot change signature.\n");
3558 return false;
3559 }
3560 if (node->can_be_local_p ())
3561 {
3562 if (dump_file && (dump_flags & TDF_DETAILS))
3563 fprintf (dump_file, " Not considering cloning to remove parameters, "
3564 "IPA-SRA can do it potentially better.\n");
3565 return false;
3566 }
3567 return true;
3568 }
3569
3570 /* Iterate over known values of parameters of NODE and estimate the local
3571 effects in terms of time and size they have. */
3572
3573 static void
3574 estimate_local_effects (struct cgraph_node *node)
3575 {
3576 ipa_node_params *info = ipa_node_params_sum->get (node);
3577 int count = ipa_get_param_count (info);
3578 bool always_const;
3579 int removable_params_cost;
3580
3581 if (!count || !ipcp_versionable_function_p (node))
3582 return;
3583
3584 if (dump_file && (dump_flags & TDF_DETAILS))
3585 fprintf (dump_file, "\nEstimating effects for %s.\n", node->dump_name ());
3586
3587 ipa_auto_call_arg_values avals;
3588 always_const = gather_context_independent_values (info, &avals, true,
3589 &removable_params_cost);
3590 int devirt_bonus = devirtualization_time_bonus (node, &avals);
3591 if (always_const || devirt_bonus
3592 || (removable_params_cost && clone_for_param_removal_p (node)))
3593 {
3594 struct caller_statistics stats;
3595 ipa_call_estimates estimates;
3596
3597 init_caller_stats (&stats);
3598 node->call_for_symbol_thunks_and_aliases (gather_caller_stats, &stats,
3599 false);
3600 estimate_ipcp_clone_size_and_time (node, &avals, &estimates);
3601 sreal time = estimates.nonspecialized_time - estimates.time;
3602 time += devirt_bonus;
3603 time += hint_time_bonus (node, estimates);
3604 time += removable_params_cost;
3605 int size = estimates.size - stats.n_calls * removable_params_cost;
3606
3607 if (dump_file)
3608 fprintf (dump_file, " - context independent values, size: %i, "
3609 "time_benefit: %f\n", size, (time).to_double ());
3610
3611 if (size <= 0 || node->local)
3612 {
3613 info->do_clone_for_all_contexts = true;
3614
3615 if (dump_file)
3616 fprintf (dump_file, " Decided to specialize for all "
3617 "known contexts, code not going to grow.\n");
3618 }
3619 else if (good_cloning_opportunity_p (node, time, stats.freq_sum,
3620 stats.count_sum, size))
3621 {
3622 if (size + overall_size <= get_max_overall_size (node))
3623 {
3624 info->do_clone_for_all_contexts = true;
3625 overall_size += size;
3626
3627 if (dump_file)
3628 fprintf (dump_file, " Decided to specialize for all "
3629 "known contexts, growth (to %li) deemed "
3630 "beneficial.\n", overall_size);
3631 }
3632 else if (dump_file && (dump_flags & TDF_DETAILS))
3633 fprintf (dump_file, " Not cloning for all contexts because "
3634 "maximum unit size would be reached with %li.\n",
3635 size + overall_size);
3636 }
3637 else if (dump_file && (dump_flags & TDF_DETAILS))
3638 fprintf (dump_file, " Not cloning for all contexts because "
3639 "!good_cloning_opportunity_p.\n");
3640
3641 }
3642
3643 for (int i = 0; i < count; i++)
3644 {
3645 class ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
3646 ipcp_lattice<tree> *lat = &plats->itself;
3647 ipcp_value<tree> *val;
3648
3649 if (lat->bottom
3650 || !lat->values
3651 || avals.m_known_vals[i])
3652 continue;
3653
3654 for (val = lat->values; val; val = val->next)
3655 {
3656 gcc_checking_assert (TREE_CODE (val->value) != TREE_BINFO);
3657 avals.m_known_vals[i] = val->value;
3658
3659 int emc = estimate_move_cost (TREE_TYPE (val->value), true);
3660 perform_estimation_of_a_value (node, &avals, removable_params_cost,
3661 emc, val);
3662
3663 if (dump_file && (dump_flags & TDF_DETAILS))
3664 {
3665 fprintf (dump_file, " - estimates for value ");
3666 print_ipcp_constant_value (dump_file, val->value);
3667 fprintf (dump_file, " for ");
3668 ipa_dump_param (dump_file, info, i);
3669 fprintf (dump_file, ": time_benefit: %g, size: %i\n",
3670 val->local_time_benefit.to_double (),
3671 val->local_size_cost);
3672 }
3673 }
3674 avals.m_known_vals[i] = NULL_TREE;
3675 }
3676
3677 for (int i = 0; i < count; i++)
3678 {
3679 class ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
3680
3681 if (!plats->virt_call)
3682 continue;
3683
3684 ipcp_lattice<ipa_polymorphic_call_context> *ctxlat = &plats->ctxlat;
3685 ipcp_value<ipa_polymorphic_call_context> *val;
3686
3687 if (ctxlat->bottom
3688 || !ctxlat->values
3689 || !avals.m_known_contexts[i].useless_p ())
3690 continue;
3691
3692 for (val = ctxlat->values; val; val = val->next)
3693 {
3694 avals.m_known_contexts[i] = val->value;
3695 perform_estimation_of_a_value (node, &avals, removable_params_cost,
3696 0, val);
3697
3698 if (dump_file && (dump_flags & TDF_DETAILS))
3699 {
3700 fprintf (dump_file, " - estimates for polymorphic context ");
3701 print_ipcp_constant_value (dump_file, val->value);
3702 fprintf (dump_file, " for ");
3703 ipa_dump_param (dump_file, info, i);
3704 fprintf (dump_file, ": time_benefit: %g, size: %i\n",
3705 val->local_time_benefit.to_double (),
3706 val->local_size_cost);
3707 }
3708 }
3709 avals.m_known_contexts[i] = ipa_polymorphic_call_context ();
3710 }
3711
3712 unsigned all_ctx_len = avals.m_known_aggs.length ();
3713 auto_vec<ipa_argagg_value, 32> all_ctx;
3714 all_ctx.reserve_exact (all_ctx_len);
3715 all_ctx.splice (avals.m_known_aggs);
3716 avals.m_known_aggs.safe_grow_cleared (all_ctx_len + 1);
3717
3718 unsigned j = 0;
3719 for (int index = 0; index < count; index++)
3720 {
3721 class ipcp_param_lattices *plats = ipa_get_parm_lattices (info, index);
3722
3723 if (plats->aggs_bottom || !plats->aggs)
3724 continue;
3725
3726 for (ipcp_agg_lattice *aglat = plats->aggs; aglat; aglat = aglat->next)
3727 {
3728 ipcp_value<tree> *val;
3729 if (aglat->bottom || !aglat->values
3730 /* If the following is true, the one value is already part of all
3731 context estimations. */
3732 || (!plats->aggs_contain_variable
3733 && aglat->is_single_const ()))
3734 continue;
3735
3736 unsigned unit_offset = aglat->offset / BITS_PER_UNIT;
3737 while (j < all_ctx_len
3738 && (all_ctx[j].index < index
3739 || (all_ctx[j].index == index
3740 && all_ctx[j].unit_offset < unit_offset)))
3741 {
3742 avals.m_known_aggs[j] = all_ctx[j];
3743 j++;
3744 }
3745
3746 for (unsigned k = j; k < all_ctx_len; k++)
3747 avals.m_known_aggs[k+1] = all_ctx[k];
3748
3749 for (val = aglat->values; val; val = val->next)
3750 {
3751 avals.m_known_aggs[j].value = val->value;
3752 avals.m_known_aggs[j].unit_offset = unit_offset;
3753 avals.m_known_aggs[j].index = index;
3754 avals.m_known_aggs[j].by_ref = plats->aggs_by_ref;
3755 avals.m_known_aggs[j].killed = false;
3756
3757 perform_estimation_of_a_value (node, &avals,
3758 removable_params_cost, 0, val);
3759
3760 if (dump_file && (dump_flags & TDF_DETAILS))
3761 {
3762 fprintf (dump_file, " - estimates for value ");
3763 print_ipcp_constant_value (dump_file, val->value);
3764 fprintf (dump_file, " for ");
3765 ipa_dump_param (dump_file, info, index);
3766 fprintf (dump_file, "[%soffset: " HOST_WIDE_INT_PRINT_DEC
3767 "]: time_benefit: %g, size: %i\n",
3768 plats->aggs_by_ref ? "ref " : "",
3769 aglat->offset,
3770 val->local_time_benefit.to_double (),
3771 val->local_size_cost);
3772 }
3773 }
3774 }
3775 }
3776 }
3777
3778
3779 /* Add value CUR_VAL and all yet-unsorted values it is dependent on to the
3780 topological sort of values. */
3781
3782 template <typename valtype>
3783 void
3784 value_topo_info<valtype>::add_val (ipcp_value<valtype> *cur_val)
3785 {
3786 ipcp_value_source<valtype> *src;
3787
3788 if (cur_val->dfs)
3789 return;
3790
3791 dfs_counter++;
3792 cur_val->dfs = dfs_counter;
3793 cur_val->low_link = dfs_counter;
3794
3795 cur_val->topo_next = stack;
3796 stack = cur_val;
3797 cur_val->on_stack = true;
3798
3799 for (src = cur_val->sources; src; src = src->next)
3800 if (src->val)
3801 {
3802 if (src->val->dfs == 0)
3803 {
3804 add_val (src->val);
3805 if (src->val->low_link < cur_val->low_link)
3806 cur_val->low_link = src->val->low_link;
3807 }
3808 else if (src->val->on_stack
3809 && src->val->dfs < cur_val->low_link)
3810 cur_val->low_link = src->val->dfs;
3811 }
3812
3813 if (cur_val->dfs == cur_val->low_link)
3814 {
3815 ipcp_value<valtype> *v, *scc_list = NULL;
3816
3817 do
3818 {
3819 v = stack;
3820 stack = v->topo_next;
3821 v->on_stack = false;
3822 v->scc_no = cur_val->dfs;
3823
3824 v->scc_next = scc_list;
3825 scc_list = v;
3826 }
3827 while (v != cur_val);
3828
3829 cur_val->topo_next = values_topo;
3830 values_topo = cur_val;
3831 }
3832 }
3833
3834 /* Add all values in lattices associated with NODE to the topological sort if
3835 they are not there yet. */
3836
3837 static void
3838 add_all_node_vals_to_toposort (cgraph_node *node, ipa_topo_info *topo)
3839 {
3840 ipa_node_params *info = ipa_node_params_sum->get (node);
3841 int i, count = ipa_get_param_count (info);
3842
3843 for (i = 0; i < count; i++)
3844 {
3845 class ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
3846 ipcp_lattice<tree> *lat = &plats->itself;
3847 struct ipcp_agg_lattice *aglat;
3848
3849 if (!lat->bottom)
3850 {
3851 ipcp_value<tree> *val;
3852 for (val = lat->values; val; val = val->next)
3853 topo->constants.add_val (val);
3854 }
3855
3856 if (!plats->aggs_bottom)
3857 for (aglat = plats->aggs; aglat; aglat = aglat->next)
3858 if (!aglat->bottom)
3859 {
3860 ipcp_value<tree> *val;
3861 for (val = aglat->values; val; val = val->next)
3862 topo->constants.add_val (val);
3863 }
3864
3865 ipcp_lattice<ipa_polymorphic_call_context> *ctxlat = &plats->ctxlat;
3866 if (!ctxlat->bottom)
3867 {
3868 ipcp_value<ipa_polymorphic_call_context> *ctxval;
3869 for (ctxval = ctxlat->values; ctxval; ctxval = ctxval->next)
3870 topo->contexts.add_val (ctxval);
3871 }
3872 }
3873 }
3874
3875 /* One pass of constants propagation along the call graph edges, from callers
3876 to callees (requires topological ordering in TOPO), iterate over strongly
3877 connected components. */
3878
3879 static void
3880 propagate_constants_topo (class ipa_topo_info *topo)
3881 {
3882 int i;
3883
3884 for (i = topo->nnodes - 1; i >= 0; i--)
3885 {
3886 unsigned j;
3887 struct cgraph_node *v, *node = topo->order[i];
3888 vec<cgraph_node *> cycle_nodes = ipa_get_nodes_in_cycle (node);
3889
3890 /* First, iteratively propagate within the strongly connected component
3891 until all lattices stabilize. */
3892 FOR_EACH_VEC_ELT (cycle_nodes, j, v)
3893 if (v->has_gimple_body_p ())
3894 {
3895 if (opt_for_fn (v->decl, flag_ipa_cp)
3896 && opt_for_fn (v->decl, optimize))
3897 push_node_to_stack (topo, v);
3898 /* When V is not optimized, we can not push it to stack, but
3899 still we need to set all its callees lattices to bottom. */
3900 else
3901 {
3902 for (cgraph_edge *cs = v->callees; cs; cs = cs->next_callee)
3903 propagate_constants_across_call (cs);
3904 }
3905 }
3906
3907 v = pop_node_from_stack (topo);
3908 while (v)
3909 {
3910 struct cgraph_edge *cs;
3911 class ipa_node_params *info = NULL;
3912 bool self_scc = true;
3913
3914 for (cs = v->callees; cs; cs = cs->next_callee)
3915 if (ipa_edge_within_scc (cs))
3916 {
3917 cgraph_node *callee = cs->callee->function_symbol ();
3918
3919 if (v != callee)
3920 self_scc = false;
3921
3922 if (!info)
3923 {
3924 info = ipa_node_params_sum->get (v);
3925 info->node_within_scc = true;
3926 }
3927
3928 if (propagate_constants_across_call (cs))
3929 push_node_to_stack (topo, callee);
3930 }
3931
3932 if (info)
3933 info->node_is_self_scc = self_scc;
3934
3935 v = pop_node_from_stack (topo);
3936 }
3937
3938 /* Afterwards, propagate along edges leading out of the SCC, calculates
3939 the local effects of the discovered constants and all valid values to
3940 their topological sort. */
3941 FOR_EACH_VEC_ELT (cycle_nodes, j, v)
3942 if (v->has_gimple_body_p ()
3943 && opt_for_fn (v->decl, flag_ipa_cp)
3944 && opt_for_fn (v->decl, optimize))
3945 {
3946 struct cgraph_edge *cs;
3947
3948 estimate_local_effects (v);
3949 add_all_node_vals_to_toposort (v, topo);
3950 for (cs = v->callees; cs; cs = cs->next_callee)
3951 if (!ipa_edge_within_scc (cs))
3952 propagate_constants_across_call (cs);
3953 }
3954 cycle_nodes.release ();
3955 }
3956 }
3957
3958 /* Propagate the estimated effects of individual values along the topological
3959 from the dependent values to those they depend on. */
3960
3961 template <typename valtype>
3962 void
3963 value_topo_info<valtype>::propagate_effects ()
3964 {
3965 ipcp_value<valtype> *base;
3966 hash_set<ipcp_value<valtype> *> processed_srcvals;
3967
3968 for (base = values_topo; base; base = base->topo_next)
3969 {
3970 ipcp_value_source<valtype> *src;
3971 ipcp_value<valtype> *val;
3972 sreal time = 0;
3973 HOST_WIDE_INT size = 0;
3974
3975 for (val = base; val; val = val->scc_next)
3976 {
3977 time = time + val->local_time_benefit + val->prop_time_benefit;
3978 size = size + val->local_size_cost + val->prop_size_cost;
3979 }
3980
3981 for (val = base; val; val = val->scc_next)
3982 {
3983 processed_srcvals.empty ();
3984 for (src = val->sources; src; src = src->next)
3985 if (src->val
3986 && src->cs->maybe_hot_p ())
3987 {
3988 if (!processed_srcvals.add (src->val))
3989 {
3990 HOST_WIDE_INT prop_size = size + src->val->prop_size_cost;
3991 if (prop_size < INT_MAX)
3992 src->val->prop_size_cost = prop_size;
3993 else
3994 continue;
3995 }
3996
3997 int special_factor = 1;
3998 if (val->same_scc (src->val))
3999 special_factor
4000 = opt_for_fn(src->cs->caller->decl,
4001 param_ipa_cp_recursive_freq_factor);
4002 else if (val->self_recursion_generated_p ()
4003 && (src->cs->callee->function_symbol ()
4004 == src->cs->caller))
4005 {
4006 int max_recur_gen_depth
4007 = opt_for_fn(src->cs->caller->decl,
4008 param_ipa_cp_max_recursive_depth);
4009 special_factor = max_recur_gen_depth
4010 - val->self_recursion_generated_level + 1;
4011 }
4012
4013 src->val->prop_time_benefit
4014 += time * special_factor * src->cs->sreal_frequency ();
4015 }
4016
4017 if (size < INT_MAX)
4018 {
4019 val->prop_time_benefit = time;
4020 val->prop_size_cost = size;
4021 }
4022 else
4023 {
4024 val->prop_time_benefit = 0;
4025 val->prop_size_cost = 0;
4026 }
4027 }
4028 }
4029 }
4030
4031 /* Callback for qsort to sort counts of all edges. */
4032
4033 static int
4034 compare_edge_profile_counts (const void *a, const void *b)
4035 {
4036 const profile_count *cnt1 = (const profile_count *) a;
4037 const profile_count *cnt2 = (const profile_count *) b;
4038
4039 if (*cnt1 < *cnt2)
4040 return 1;
4041 if (*cnt1 > *cnt2)
4042 return -1;
4043 return 0;
4044 }
4045
4046
4047 /* Propagate constants, polymorphic contexts and their effects from the
4048 summaries interprocedurally. */
4049
4050 static void
4051 ipcp_propagate_stage (class ipa_topo_info *topo)
4052 {
4053 struct cgraph_node *node;
4054
4055 if (dump_file)
4056 fprintf (dump_file, "\n Propagating constants:\n\n");
4057
4058 base_count = profile_count::uninitialized ();
4059
4060 bool compute_count_base = false;
4061 unsigned base_count_pos_percent = 0;
4062 FOR_EACH_DEFINED_FUNCTION (node)
4063 {
4064 if (node->has_gimple_body_p ()
4065 && opt_for_fn (node->decl, flag_ipa_cp)
4066 && opt_for_fn (node->decl, optimize))
4067 {
4068 ipa_node_params *info = ipa_node_params_sum->get (node);
4069 determine_versionability (node, info);
4070
4071 unsigned nlattices = ipa_get_param_count (info);
4072 info->lattices.safe_grow_cleared (nlattices, true);
4073 initialize_node_lattices (node);
4074 }
4075 ipa_size_summary *s = ipa_size_summaries->get (node);
4076 if (node->definition && !node->alias && s != NULL)
4077 overall_size += s->self_size;
4078 if (node->count.ipa ().initialized_p ())
4079 {
4080 compute_count_base = true;
4081 unsigned pos_percent = opt_for_fn (node->decl,
4082 param_ipa_cp_profile_count_base);
4083 base_count_pos_percent = MAX (base_count_pos_percent, pos_percent);
4084 }
4085 }
4086
4087 if (compute_count_base)
4088 {
4089 auto_vec<profile_count> all_edge_counts;
4090 all_edge_counts.reserve_exact (symtab->edges_count);
4091 FOR_EACH_DEFINED_FUNCTION (node)
4092 for (cgraph_edge *cs = node->callees; cs; cs = cs->next_callee)
4093 {
4094 profile_count count = cs->count.ipa ();
4095 if (!count.nonzero_p ())
4096 continue;
4097
4098 enum availability avail;
4099 cgraph_node *tgt
4100 = cs->callee->function_or_virtual_thunk_symbol (&avail);
4101 ipa_node_params *info = ipa_node_params_sum->get (tgt);
4102 if (info && info->versionable)
4103 all_edge_counts.quick_push (count);
4104 }
4105
4106 if (!all_edge_counts.is_empty ())
4107 {
4108 gcc_assert (base_count_pos_percent <= 100);
4109 all_edge_counts.qsort (compare_edge_profile_counts);
4110
4111 unsigned base_count_pos
4112 = ((all_edge_counts.length () * (base_count_pos_percent)) / 100);
4113 base_count = all_edge_counts[base_count_pos];
4114
4115 if (dump_file)
4116 {
4117 fprintf (dump_file, "\nSelected base_count from %u edges at "
4118 "position %u, arriving at: ", all_edge_counts.length (),
4119 base_count_pos);
4120 base_count.dump (dump_file);
4121 fprintf (dump_file, "\n");
4122 }
4123 }
4124 else if (dump_file)
4125 fprintf (dump_file, "\nNo candidates with non-zero call count found, "
4126 "continuing as if without profile feedback.\n");
4127 }
4128
4129 orig_overall_size = overall_size;
4130
4131 if (dump_file)
4132 fprintf (dump_file, "\noverall_size: %li\n", overall_size);
4133
4134 propagate_constants_topo (topo);
4135 if (flag_checking)
4136 ipcp_verify_propagated_values ();
4137 topo->constants.propagate_effects ();
4138 topo->contexts.propagate_effects ();
4139
4140 if (dump_file)
4141 {
4142 fprintf (dump_file, "\nIPA lattices after all propagation:\n");
4143 print_all_lattices (dump_file, (dump_flags & TDF_DETAILS), true);
4144 }
4145 }
4146
4147 /* Discover newly direct outgoing edges from NODE which is a new clone with
4148 known KNOWN_CSTS and make them direct. */
4149
4150 static void
4151 ipcp_discover_new_direct_edges (struct cgraph_node *node,
4152 vec<tree> known_csts,
4153 vec<ipa_polymorphic_call_context>
4154 known_contexts,
4155 vec<ipa_argagg_value, va_gc> *aggvals)
4156 {
4157 struct cgraph_edge *ie, *next_ie;
4158 bool found = false;
4159
4160 for (ie = node->indirect_calls; ie; ie = next_ie)
4161 {
4162 tree target;
4163 bool speculative;
4164
4165 next_ie = ie->next_callee;
4166 ipa_argagg_value_list avs (aggvals);
4167 target = ipa_get_indirect_edge_target_1 (ie, known_csts, known_contexts,
4168 avs, &speculative);
4169 if (target)
4170 {
4171 bool agg_contents = ie->indirect_info->agg_contents;
4172 bool polymorphic = ie->indirect_info->polymorphic;
4173 int param_index = ie->indirect_info->param_index;
4174 struct cgraph_edge *cs = ipa_make_edge_direct_to_target (ie, target,
4175 speculative);
4176 found = true;
4177
4178 if (cs && !agg_contents && !polymorphic)
4179 {
4180 ipa_node_params *info = ipa_node_params_sum->get (node);
4181 int c = ipa_get_controlled_uses (info, param_index);
4182 if (c != IPA_UNDESCRIBED_USE
4183 && !ipa_get_param_load_dereferenced (info, param_index))
4184 {
4185 struct ipa_ref *to_del;
4186
4187 c--;
4188 ipa_set_controlled_uses (info, param_index, c);
4189 if (dump_file && (dump_flags & TDF_DETAILS))
4190 fprintf (dump_file, " controlled uses count of param "
4191 "%i bumped down to %i\n", param_index, c);
4192 if (c == 0
4193 && (to_del = node->find_reference (cs->callee, NULL, 0,
4194 IPA_REF_ADDR)))
4195 {
4196 if (dump_file && (dump_flags & TDF_DETAILS))
4197 fprintf (dump_file, " and even removing its "
4198 "cloning-created reference\n");
4199 to_del->remove_reference ();
4200 }
4201 }
4202 }
4203 }
4204 }
4205 /* Turning calls to direct calls will improve overall summary. */
4206 if (found)
4207 ipa_update_overall_fn_summary (node);
4208 }
4209
4210 class edge_clone_summary;
4211 static call_summary <edge_clone_summary *> *edge_clone_summaries = NULL;
4212
4213 /* Edge clone summary. */
4214
4215 class edge_clone_summary
4216 {
4217 public:
4218 /* Default constructor. */
4219 edge_clone_summary (): prev_clone (NULL), next_clone (NULL) {}
4220
4221 /* Default destructor. */
4222 ~edge_clone_summary ()
4223 {
4224 if (prev_clone)
4225 edge_clone_summaries->get (prev_clone)->next_clone = next_clone;
4226 if (next_clone)
4227 edge_clone_summaries->get (next_clone)->prev_clone = prev_clone;
4228 }
4229
4230 cgraph_edge *prev_clone;
4231 cgraph_edge *next_clone;
4232 };
4233
4234 class edge_clone_summary_t:
4235 public call_summary <edge_clone_summary *>
4236 {
4237 public:
4238 edge_clone_summary_t (symbol_table *symtab):
4239 call_summary <edge_clone_summary *> (symtab)
4240 {
4241 m_initialize_when_cloning = true;
4242 }
4243
4244 void duplicate (cgraph_edge *src_edge, cgraph_edge *dst_edge,
4245 edge_clone_summary *src_data,
4246 edge_clone_summary *dst_data) final override;
4247 };
4248
4249 /* Edge duplication hook. */
4250
4251 void
4252 edge_clone_summary_t::duplicate (cgraph_edge *src_edge, cgraph_edge *dst_edge,
4253 edge_clone_summary *src_data,
4254 edge_clone_summary *dst_data)
4255 {
4256 if (src_data->next_clone)
4257 edge_clone_summaries->get (src_data->next_clone)->prev_clone = dst_edge;
4258 dst_data->prev_clone = src_edge;
4259 dst_data->next_clone = src_data->next_clone;
4260 src_data->next_clone = dst_edge;
4261 }
4262
4263 /* Return true is CS calls DEST or its clone for all contexts. When
4264 ALLOW_RECURSION_TO_CLONE is false, also return false for self-recursive
4265 edges from/to an all-context clone. */
4266
4267 static bool
4268 calls_same_node_or_its_all_contexts_clone_p (cgraph_edge *cs, cgraph_node *dest,
4269 bool allow_recursion_to_clone)
4270 {
4271 enum availability availability;
4272 cgraph_node *callee = cs->callee->function_symbol (&availability);
4273
4274 if (availability <= AVAIL_INTERPOSABLE)
4275 return false;
4276 if (callee == dest)
4277 return true;
4278 if (!allow_recursion_to_clone && cs->caller == callee)
4279 return false;
4280
4281 ipa_node_params *info = ipa_node_params_sum->get (callee);
4282 return info->is_all_contexts_clone && info->ipcp_orig_node == dest;
4283 }
4284
4285 /* Return true if edge CS does bring about the value described by SRC to
4286 DEST_VAL of node DEST or its clone for all contexts. */
4287
4288 static bool
4289 cgraph_edge_brings_value_p (cgraph_edge *cs, ipcp_value_source<tree> *src,
4290 cgraph_node *dest, ipcp_value<tree> *dest_val)
4291 {
4292 ipa_node_params *caller_info = ipa_node_params_sum->get (cs->caller);
4293
4294 if (!calls_same_node_or_its_all_contexts_clone_p (cs, dest, !src->val)
4295 || caller_info->node_dead)
4296 return false;
4297
4298 if (!src->val)
4299 return true;
4300
4301 if (caller_info->ipcp_orig_node)
4302 {
4303 tree t = NULL_TREE;
4304 if (src->offset == -1)
4305 t = caller_info->known_csts[src->index];
4306 else if (ipcp_transformation *ts
4307 = ipcp_get_transformation_summary (cs->caller))
4308 {
4309 ipa_argagg_value_list avl (ts);
4310 t = avl.get_value (src->index, src->offset / BITS_PER_UNIT);
4311 }
4312 return (t != NULL_TREE
4313 && values_equal_for_ipcp_p (src->val->value, t));
4314 }
4315 else
4316 {
4317 if (src->val == dest_val)
4318 return true;
4319
4320 struct ipcp_agg_lattice *aglat;
4321 class ipcp_param_lattices *plats = ipa_get_parm_lattices (caller_info,
4322 src->index);
4323 if (src->offset == -1)
4324 return (plats->itself.is_single_const ()
4325 && values_equal_for_ipcp_p (src->val->value,
4326 plats->itself.values->value));
4327 else
4328 {
4329 if (plats->aggs_bottom || plats->aggs_contain_variable)
4330 return false;
4331 for (aglat = plats->aggs; aglat; aglat = aglat->next)
4332 if (aglat->offset == src->offset)
4333 return (aglat->is_single_const ()
4334 && values_equal_for_ipcp_p (src->val->value,
4335 aglat->values->value));
4336 }
4337 return false;
4338 }
4339 }
4340
4341 /* Return true if edge CS does bring about the value described by SRC to
4342 DST_VAL of node DEST or its clone for all contexts. */
4343
4344 static bool
4345 cgraph_edge_brings_value_p (cgraph_edge *cs,
4346 ipcp_value_source<ipa_polymorphic_call_context> *src,
4347 cgraph_node *dest,
4348 ipcp_value<ipa_polymorphic_call_context> *)
4349 {
4350 ipa_node_params *caller_info = ipa_node_params_sum->get (cs->caller);
4351
4352 if (!calls_same_node_or_its_all_contexts_clone_p (cs, dest, true)
4353 || caller_info->node_dead)
4354 return false;
4355 if (!src->val)
4356 return true;
4357
4358 if (caller_info->ipcp_orig_node)
4359 return (caller_info->known_contexts.length () > (unsigned) src->index)
4360 && values_equal_for_ipcp_p (src->val->value,
4361 caller_info->known_contexts[src->index]);
4362
4363 class ipcp_param_lattices *plats = ipa_get_parm_lattices (caller_info,
4364 src->index);
4365 return plats->ctxlat.is_single_const ()
4366 && values_equal_for_ipcp_p (src->val->value,
4367 plats->ctxlat.values->value);
4368 }
4369
4370 /* Get the next clone in the linked list of clones of an edge. */
4371
4372 static inline struct cgraph_edge *
4373 get_next_cgraph_edge_clone (struct cgraph_edge *cs)
4374 {
4375 edge_clone_summary *s = edge_clone_summaries->get (cs);
4376 return s != NULL ? s->next_clone : NULL;
4377 }
4378
4379 /* Given VAL that is intended for DEST, iterate over all its sources and if any
4380 of them is viable and hot, return true. In that case, for those that still
4381 hold, add their edge frequency and their number and cumulative profile
4382 counts of self-ecursive and other edges into *FREQUENCY, *CALLER_COUNT,
4383 REC_COUNT_SUM and NONREC_COUNT_SUM respectively. */
4384
4385 template <typename valtype>
4386 static bool
4387 get_info_about_necessary_edges (ipcp_value<valtype> *val, cgraph_node *dest,
4388 sreal *freq_sum, int *caller_count,
4389 profile_count *rec_count_sum,
4390 profile_count *nonrec_count_sum)
4391 {
4392 ipcp_value_source<valtype> *src;
4393 sreal freq = 0;
4394 int count = 0;
4395 profile_count rec_cnt = profile_count::zero ();
4396 profile_count nonrec_cnt = profile_count::zero ();
4397 bool hot = false;
4398 bool non_self_recursive = false;
4399
4400 for (src = val->sources; src; src = src->next)
4401 {
4402 struct cgraph_edge *cs = src->cs;
4403 while (cs)
4404 {
4405 if (cgraph_edge_brings_value_p (cs, src, dest, val))
4406 {
4407 count++;
4408 freq += cs->sreal_frequency ();
4409 hot |= cs->maybe_hot_p ();
4410 if (cs->caller != dest)
4411 {
4412 non_self_recursive = true;
4413 if (cs->count.ipa ().initialized_p ())
4414 rec_cnt += cs->count.ipa ();
4415 }
4416 else if (cs->count.ipa ().initialized_p ())
4417 nonrec_cnt += cs->count.ipa ();
4418 }
4419 cs = get_next_cgraph_edge_clone (cs);
4420 }
4421 }
4422
4423 /* If the only edges bringing a value are self-recursive ones, do not bother
4424 evaluating it. */
4425 if (!non_self_recursive)
4426 return false;
4427
4428 *freq_sum = freq;
4429 *caller_count = count;
4430 *rec_count_sum = rec_cnt;
4431 *nonrec_count_sum = nonrec_cnt;
4432
4433 if (!hot && ipa_node_params_sum->get (dest)->node_within_scc)
4434 {
4435 struct cgraph_edge *cs;
4436
4437 /* Cold non-SCC source edge could trigger hot recursive execution of
4438 function. Consider the case as hot and rely on following cost model
4439 computation to further select right one. */
4440 for (cs = dest->callers; cs; cs = cs->next_caller)
4441 if (cs->caller == dest && cs->maybe_hot_p ())
4442 return true;
4443 }
4444
4445 return hot;
4446 }
4447
4448 /* Given a NODE, and a set of its CALLERS, try to adjust order of the callers
4449 to let a non-self-recursive caller be the first element. Thus, we can
4450 simplify intersecting operations on values that arrive from all of these
4451 callers, especially when there exists self-recursive call. Return true if
4452 this kind of adjustment is possible. */
4453
4454 static bool
4455 adjust_callers_for_value_intersection (vec<cgraph_edge *> &callers,
4456 cgraph_node *node)
4457 {
4458 for (unsigned i = 0; i < callers.length (); i++)
4459 {
4460 cgraph_edge *cs = callers[i];
4461
4462 if (cs->caller != node)
4463 {
4464 if (i > 0)
4465 {
4466 callers[i] = callers[0];
4467 callers[0] = cs;
4468 }
4469 return true;
4470 }
4471 }
4472 return false;
4473 }
4474
4475 /* Return a vector of incoming edges that do bring value VAL to node DEST. It
4476 is assumed their number is known and equal to CALLER_COUNT. */
4477
4478 template <typename valtype>
4479 static vec<cgraph_edge *>
4480 gather_edges_for_value (ipcp_value<valtype> *val, cgraph_node *dest,
4481 int caller_count)
4482 {
4483 ipcp_value_source<valtype> *src;
4484 vec<cgraph_edge *> ret;
4485
4486 ret.create (caller_count);
4487 for (src = val->sources; src; src = src->next)
4488 {
4489 struct cgraph_edge *cs = src->cs;
4490 while (cs)
4491 {
4492 if (cgraph_edge_brings_value_p (cs, src, dest, val))
4493 ret.quick_push (cs);
4494 cs = get_next_cgraph_edge_clone (cs);
4495 }
4496 }
4497
4498 if (caller_count > 1)
4499 adjust_callers_for_value_intersection (ret, dest);
4500
4501 return ret;
4502 }
4503
4504 /* Construct a replacement map for a know VALUE for a formal parameter PARAM.
4505 Return it or NULL if for some reason it cannot be created. FORCE_LOAD_REF
4506 should be set to true when the reference created for the constant should be
4507 a load one and not an address one because the corresponding parameter p is
4508 only used as *p. */
4509
4510 static struct ipa_replace_map *
4511 get_replacement_map (class ipa_node_params *info, tree value, int parm_num,
4512 bool force_load_ref)
4513 {
4514 struct ipa_replace_map *replace_map;
4515
4516 replace_map = ggc_alloc<ipa_replace_map> ();
4517 if (dump_file)
4518 {
4519 fprintf (dump_file, " replacing ");
4520 ipa_dump_param (dump_file, info, parm_num);
4521
4522 fprintf (dump_file, " with const ");
4523 print_generic_expr (dump_file, value);
4524
4525 if (force_load_ref)
4526 fprintf (dump_file, " - forcing load reference\n");
4527 else
4528 fprintf (dump_file, "\n");
4529 }
4530 replace_map->parm_num = parm_num;
4531 replace_map->new_tree = value;
4532 replace_map->force_load_ref = force_load_ref;
4533 return replace_map;
4534 }
4535
4536 /* Dump new profiling counts of NODE. SPEC is true when NODE is a specialzied
4537 one, otherwise it will be referred to as the original node. */
4538
4539 static void
4540 dump_profile_updates (cgraph_node *node, bool spec)
4541 {
4542 if (spec)
4543 fprintf (dump_file, " setting count of the specialized node %s to ",
4544 node->dump_name ());
4545 else
4546 fprintf (dump_file, " setting count of the original node %s to ",
4547 node->dump_name ());
4548
4549 node->count.dump (dump_file);
4550 fprintf (dump_file, "\n");
4551 for (cgraph_edge *cs = node->callees; cs; cs = cs->next_callee)
4552 {
4553 fprintf (dump_file, " edge to %s has count ",
4554 cs->callee->dump_name ());
4555 cs->count.dump (dump_file);
4556 fprintf (dump_file, "\n");
4557 }
4558 }
4559
4560 /* With partial train run we do not want to assume that original's count is
4561 zero whenever we redurect all executed edges to clone. Simply drop profile
4562 to local one in this case. In eany case, return the new value. ORIG_NODE
4563 is the original node and its count has not been updaed yet. */
4564
4565 profile_count
4566 lenient_count_portion_handling (profile_count remainder, cgraph_node *orig_node)
4567 {
4568 if (remainder.ipa_p () && !remainder.ipa ().nonzero_p ()
4569 && orig_node->count.ipa_p () && orig_node->count.ipa ().nonzero_p ()
4570 && opt_for_fn (orig_node->decl, flag_profile_partial_training))
4571 remainder = remainder.guessed_local ();
4572
4573 return remainder;
4574 }
4575
4576 /* Structure to sum counts coming from nodes other than the original node and
4577 its clones. */
4578
4579 struct gather_other_count_struct
4580 {
4581 cgraph_node *orig;
4582 profile_count other_count;
4583 };
4584
4585 /* Worker callback of call_for_symbol_thunks_and_aliases summing the number of
4586 counts that come from non-self-recursive calls.. */
4587
4588 static bool
4589 gather_count_of_non_rec_edges (cgraph_node *node, void *data)
4590 {
4591 gather_other_count_struct *desc = (gather_other_count_struct *) data;
4592 for (cgraph_edge *cs = node->callers; cs; cs = cs->next_caller)
4593 if (cs->caller != desc->orig && cs->caller->clone_of != desc->orig)
4594 desc->other_count += cs->count.ipa ();
4595 return false;
4596 }
4597
4598 /* Structure to help analyze if we need to boost counts of some clones of some
4599 non-recursive edges to match the new callee count. */
4600
4601 struct desc_incoming_count_struct
4602 {
4603 cgraph_node *orig;
4604 hash_set <cgraph_edge *> *processed_edges;
4605 profile_count count;
4606 unsigned unproc_orig_rec_edges;
4607 };
4608
4609 /* Go over edges calling NODE and its thunks and gather information about
4610 incoming counts so that we know if we need to make any adjustments. */
4611
4612 static void
4613 analyze_clone_icoming_counts (cgraph_node *node,
4614 desc_incoming_count_struct *desc)
4615 {
4616 for (cgraph_edge *cs = node->callers; cs; cs = cs->next_caller)
4617 if (cs->caller->thunk)
4618 {
4619 analyze_clone_icoming_counts (cs->caller, desc);
4620 continue;
4621 }
4622 else
4623 {
4624 if (cs->count.initialized_p ())
4625 desc->count += cs->count.ipa ();
4626 if (!desc->processed_edges->contains (cs)
4627 && cs->caller->clone_of == desc->orig)
4628 desc->unproc_orig_rec_edges++;
4629 }
4630 }
4631
4632 /* If caller edge counts of a clone created for a self-recursive arithmetic
4633 jump function must be adjusted because it is coming from a the "seed" clone
4634 for the first value and so has been excessively scaled back as if it was not
4635 a recursive call, adjust it so that the incoming counts of NODE match its
4636 count. NODE is the node or its thunk. */
4637
4638 static void
4639 adjust_clone_incoming_counts (cgraph_node *node,
4640 desc_incoming_count_struct *desc)
4641 {
4642 for (cgraph_edge *cs = node->callers; cs; cs = cs->next_caller)
4643 if (cs->caller->thunk)
4644 {
4645 adjust_clone_incoming_counts (cs->caller, desc);
4646 profile_count sum = profile_count::zero ();
4647 for (cgraph_edge *e = cs->caller->callers; e; e = e->next_caller)
4648 if (e->count.initialized_p ())
4649 sum += e->count.ipa ();
4650 cs->count = cs->count.combine_with_ipa_count (sum);
4651 }
4652 else if (!desc->processed_edges->contains (cs)
4653 && cs->caller->clone_of == desc->orig
4654 && cs->count.compatible_p (desc->count))
4655 {
4656 cs->count += desc->count;
4657 if (dump_file)
4658 {
4659 fprintf (dump_file, " Adjusted count of an incoming edge of "
4660 "a clone %s -> %s to ", cs->caller->dump_name (),
4661 cs->callee->dump_name ());
4662 cs->count.dump (dump_file);
4663 fprintf (dump_file, "\n");
4664 }
4665 }
4666 }
4667
4668 /* When ORIG_NODE has been cloned for values which have been generated fora
4669 self-recursive call as a result of an arithmetic pass-through
4670 jump-functions, adjust its count together with counts of all such clones in
4671 SELF_GEN_CLONES which also at this point contains ORIG_NODE itself.
4672
4673 The function sums the counts of the original node and all its clones that
4674 cannot be attributed to a specific clone because it comes from a
4675 non-recursive edge. This sum is then evenly divided between the clones and
4676 on top of that each one gets all the counts which can be attributed directly
4677 to it. */
4678
4679 static void
4680 update_counts_for_self_gen_clones (cgraph_node *orig_node,
4681 const vec<cgraph_node *> &self_gen_clones)
4682 {
4683 profile_count redist_sum = orig_node->count.ipa ();
4684 if (!(redist_sum > profile_count::zero ()))
4685 return;
4686
4687 if (dump_file)
4688 fprintf (dump_file, " Updating profile of self recursive clone "
4689 "series\n");
4690
4691 gather_other_count_struct gocs;
4692 gocs.orig = orig_node;
4693 gocs.other_count = profile_count::zero ();
4694
4695 auto_vec <profile_count, 8> other_edges_count;
4696 for (cgraph_node *n : self_gen_clones)
4697 {
4698 gocs.other_count = profile_count::zero ();
4699 n->call_for_symbol_thunks_and_aliases (gather_count_of_non_rec_edges,
4700 &gocs, false);
4701 other_edges_count.safe_push (gocs.other_count);
4702 redist_sum -= gocs.other_count;
4703 }
4704
4705 hash_set<cgraph_edge *> processed_edges;
4706 unsigned i = 0;
4707 for (cgraph_node *n : self_gen_clones)
4708 {
4709 profile_count orig_count = n->count;
4710 profile_count new_count
4711 = (redist_sum / self_gen_clones.length () + other_edges_count[i]);
4712 new_count = lenient_count_portion_handling (new_count, orig_node);
4713 n->count = new_count;
4714 profile_count::adjust_for_ipa_scaling (&new_count, &orig_count);
4715 for (cgraph_edge *cs = n->callees; cs; cs = cs->next_callee)
4716 {
4717 cs->count = cs->count.apply_scale (new_count, orig_count);
4718 processed_edges.add (cs);
4719 }
4720 for (cgraph_edge *cs = n->indirect_calls; cs; cs = cs->next_callee)
4721 cs->count = cs->count.apply_scale (new_count, orig_count);
4722
4723 i++;
4724 }
4725
4726 /* There are still going to be edges to ORIG_NODE that have one or more
4727 clones coming from another node clone in SELF_GEN_CLONES and which we
4728 scaled by the same amount, which means that the total incoming sum of
4729 counts to ORIG_NODE will be too high, scale such edges back. */
4730 for (cgraph_edge *cs = orig_node->callees; cs; cs = cs->next_callee)
4731 {
4732 if (cs->callee->ultimate_alias_target () == orig_node)
4733 {
4734 unsigned den = 0;
4735 for (cgraph_edge *e = cs; e; e = get_next_cgraph_edge_clone (e))
4736 if (e->callee->ultimate_alias_target () == orig_node
4737 && processed_edges.contains (e))
4738 den++;
4739 if (den > 0)
4740 for (cgraph_edge *e = cs; e; e = get_next_cgraph_edge_clone (e))
4741 if (e->callee->ultimate_alias_target () == orig_node
4742 && processed_edges.contains (e))
4743 e->count /= den;
4744 }
4745 }
4746
4747 /* Edges from the seeds of the valus generated for arithmetic jump-functions
4748 along self-recursive edges are likely to have fairly low count and so
4749 edges from them to nodes in the self_gen_clones do not correspond to the
4750 artificially distributed count of the nodes, the total sum of incoming
4751 edges to some clones might be too low. Detect this situation and correct
4752 it. */
4753 for (cgraph_node *n : self_gen_clones)
4754 {
4755 if (!(n->count.ipa () > profile_count::zero ()))
4756 continue;
4757
4758 desc_incoming_count_struct desc;
4759 desc.orig = orig_node;
4760 desc.processed_edges = &processed_edges;
4761 desc.count = profile_count::zero ();
4762 desc.unproc_orig_rec_edges = 0;
4763 analyze_clone_icoming_counts (n, &desc);
4764
4765 if (n->count.differs_from_p (desc.count))
4766 {
4767 if (n->count > desc.count
4768 && desc.unproc_orig_rec_edges > 0)
4769 {
4770 desc.count = n->count - desc.count;
4771 desc.count = desc.count /= desc.unproc_orig_rec_edges;
4772 adjust_clone_incoming_counts (n, &desc);
4773 }
4774 else if (dump_file)
4775 fprintf (dump_file,
4776 " Unable to fix up incoming counts for %s.\n",
4777 n->dump_name ());
4778 }
4779 }
4780
4781 if (dump_file)
4782 for (cgraph_node *n : self_gen_clones)
4783 dump_profile_updates (n, n != orig_node);
4784 return;
4785 }
4786
4787 /* After a specialized NEW_NODE version of ORIG_NODE has been created, update
4788 their profile information to reflect this. This function should not be used
4789 for clones generated for arithmetic pass-through jump functions on a
4790 self-recursive call graph edge, that situation is handled by
4791 update_counts_for_self_gen_clones. */
4792
4793 static void
4794 update_profiling_info (struct cgraph_node *orig_node,
4795 struct cgraph_node *new_node)
4796 {
4797 struct caller_statistics stats;
4798 profile_count new_sum;
4799 profile_count remainder, orig_node_count = orig_node->count.ipa ();
4800
4801 if (!(orig_node_count > profile_count::zero ()))
4802 return;
4803
4804 if (dump_file)
4805 {
4806 fprintf (dump_file, " Updating profile from original count: ");
4807 orig_node_count.dump (dump_file);
4808 fprintf (dump_file, "\n");
4809 }
4810
4811 init_caller_stats (&stats, new_node);
4812 new_node->call_for_symbol_thunks_and_aliases (gather_caller_stats, &stats,
4813 false);
4814 new_sum = stats.count_sum;
4815
4816 bool orig_edges_processed = false;
4817 if (new_sum > orig_node_count)
4818 {
4819 /* TODO: Profile has alreay gone astray, keep what we have but lower it
4820 to global0 category. */
4821 remainder = orig_node->count.global0 ();
4822
4823 for (cgraph_edge *cs = orig_node->callees; cs; cs = cs->next_callee)
4824 cs->count = cs->count.global0 ();
4825 for (cgraph_edge *cs = orig_node->indirect_calls;
4826 cs;
4827 cs = cs->next_callee)
4828 cs->count = cs->count.global0 ();
4829 orig_edges_processed = true;
4830 }
4831 else if (stats.rec_count_sum.nonzero_p ())
4832 {
4833 int new_nonrec_calls = stats.n_nonrec_calls;
4834 /* There are self-recursive edges which are likely to bring in the
4835 majority of calls but which we must divide in between the original and
4836 new node. */
4837 init_caller_stats (&stats, orig_node);
4838 orig_node->call_for_symbol_thunks_and_aliases (gather_caller_stats,
4839 &stats, false);
4840 int orig_nonrec_calls = stats.n_nonrec_calls;
4841 profile_count orig_nonrec_call_count = stats.count_sum;
4842
4843 if (orig_node->local)
4844 {
4845 if (!orig_nonrec_call_count.nonzero_p ())
4846 {
4847 if (dump_file)
4848 fprintf (dump_file, " The original is local and the only "
4849 "incoming edges from non-dead callers with nonzero "
4850 "counts are self-recursive, assuming it is cold.\n");
4851 /* The NEW_NODE count and counts of all its outgoing edges
4852 are still unmodified copies of ORIG_NODE's. Just clear
4853 the latter and bail out. */
4854 profile_count zero;
4855 if (opt_for_fn (orig_node->decl, flag_profile_partial_training))
4856 zero = profile_count::zero ().guessed_local ();
4857 else
4858 zero = profile_count::adjusted_zero ();
4859 orig_node->count = zero;
4860 for (cgraph_edge *cs = orig_node->callees;
4861 cs;
4862 cs = cs->next_callee)
4863 cs->count = zero;
4864 for (cgraph_edge *cs = orig_node->indirect_calls;
4865 cs;
4866 cs = cs->next_callee)
4867 cs->count = zero;
4868 return;
4869 }
4870 }
4871 else
4872 {
4873 /* Let's behave as if there was another caller that accounts for all
4874 the calls that were either indirect or from other compilation
4875 units. */
4876 orig_nonrec_calls++;
4877 profile_count pretend_caller_count
4878 = (orig_node_count - new_sum - orig_nonrec_call_count
4879 - stats.rec_count_sum);
4880 orig_nonrec_call_count += pretend_caller_count;
4881 }
4882
4883 /* Divide all "unexplained" counts roughly proportionally to sums of
4884 counts of non-recursive calls.
4885
4886 We put rather arbitrary limits on how many counts we claim because the
4887 number of non-self-recursive incoming count is only a rough guideline
4888 and there are cases (such as mcf) where using it blindly just takes
4889 too many. And if lattices are considered in the opposite order we
4890 could also take too few. */
4891 profile_count unexp = orig_node_count - new_sum - orig_nonrec_call_count;
4892
4893 int limit_den = 2 * (orig_nonrec_calls + new_nonrec_calls);
4894 profile_count new_part
4895 = MAX(MIN (unexp.apply_scale (new_sum,
4896 new_sum + orig_nonrec_call_count),
4897 unexp.apply_scale (limit_den - 1, limit_den)),
4898 unexp.apply_scale (new_nonrec_calls, limit_den));
4899 if (dump_file)
4900 {
4901 fprintf (dump_file, " Claiming ");
4902 new_part.dump (dump_file);
4903 fprintf (dump_file, " of unexplained ");
4904 unexp.dump (dump_file);
4905 fprintf (dump_file, " counts because of self-recursive "
4906 "calls\n");
4907 }
4908 new_sum += new_part;
4909 remainder = lenient_count_portion_handling (orig_node_count - new_sum,
4910 orig_node);
4911 }
4912 else
4913 remainder = lenient_count_portion_handling (orig_node_count - new_sum,
4914 orig_node);
4915
4916 new_sum = orig_node_count.combine_with_ipa_count (new_sum);
4917 new_node->count = new_sum;
4918 orig_node->count = remainder;
4919
4920 profile_count orig_new_node_count = orig_node_count;
4921 profile_count::adjust_for_ipa_scaling (&new_sum, &orig_new_node_count);
4922 for (cgraph_edge *cs = new_node->callees; cs; cs = cs->next_callee)
4923 cs->count = cs->count.apply_scale (new_sum, orig_new_node_count);
4924 for (cgraph_edge *cs = new_node->indirect_calls; cs; cs = cs->next_callee)
4925 cs->count = cs->count.apply_scale (new_sum, orig_new_node_count);
4926
4927 if (!orig_edges_processed)
4928 {
4929 profile_count::adjust_for_ipa_scaling (&remainder, &orig_node_count);
4930 for (cgraph_edge *cs = orig_node->callees; cs; cs = cs->next_callee)
4931 cs->count = cs->count.apply_scale (remainder, orig_node_count);
4932 for (cgraph_edge *cs = orig_node->indirect_calls;
4933 cs;
4934 cs = cs->next_callee)
4935 cs->count = cs->count.apply_scale (remainder, orig_node_count);
4936 }
4937
4938 if (dump_file)
4939 {
4940 dump_profile_updates (new_node, true);
4941 dump_profile_updates (orig_node, false);
4942 }
4943 }
4944
4945 /* Update the respective profile of specialized NEW_NODE and the original
4946 ORIG_NODE after additional edges with cumulative count sum REDIRECTED_SUM
4947 have been redirected to the specialized version. */
4948
4949 static void
4950 update_specialized_profile (struct cgraph_node *new_node,
4951 struct cgraph_node *orig_node,
4952 profile_count redirected_sum)
4953 {
4954 struct cgraph_edge *cs;
4955 profile_count new_node_count, orig_node_count = orig_node->count.ipa ();
4956
4957 if (dump_file)
4958 {
4959 fprintf (dump_file, " the sum of counts of redirected edges is ");
4960 redirected_sum.dump (dump_file);
4961 fprintf (dump_file, "\n old ipa count of the original node is ");
4962 orig_node_count.dump (dump_file);
4963 fprintf (dump_file, "\n");
4964 }
4965 if (!(orig_node_count > profile_count::zero ()))
4966 return;
4967
4968 new_node_count = new_node->count;
4969 new_node->count += redirected_sum;
4970 orig_node->count
4971 = lenient_count_portion_handling (orig_node->count - redirected_sum,
4972 orig_node);
4973
4974 for (cs = new_node->callees; cs; cs = cs->next_callee)
4975 cs->count += cs->count.apply_scale (redirected_sum, new_node_count);
4976
4977 for (cs = orig_node->callees; cs; cs = cs->next_callee)
4978 {
4979 profile_count dec = cs->count.apply_scale (redirected_sum,
4980 orig_node_count);
4981 cs->count -= dec;
4982 }
4983
4984 if (dump_file)
4985 {
4986 dump_profile_updates (new_node, true);
4987 dump_profile_updates (orig_node, false);
4988 }
4989 }
4990
4991 static void adjust_references_in_caller (cgraph_edge *cs,
4992 symtab_node *symbol, int index);
4993
4994 /* Simple structure to pass a symbol and index (with same meaning as parameters
4995 of adjust_references_in_caller) through a void* parameter of a
4996 call_for_symbol_thunks_and_aliases callback. */
4997 struct symbol_and_index_together
4998 {
4999 symtab_node *symbol;
5000 int index;
5001 };
5002
5003 /* Worker callback of call_for_symbol_thunks_and_aliases to recursively call
5004 adjust_references_in_caller on edges up in the call-graph, if necessary. */
5005 static bool
5006 adjust_refs_in_act_callers (struct cgraph_node *node, void *data)
5007 {
5008 symbol_and_index_together *pack = (symbol_and_index_together *) data;
5009 for (cgraph_edge *cs = node->callers; cs; cs = cs->next_caller)
5010 if (!cs->caller->thunk)
5011 adjust_references_in_caller (cs, pack->symbol, pack->index);
5012 return false;
5013 }
5014
5015 /* At INDEX of a function being called by CS there is an ADDR_EXPR of a
5016 variable which is only dereferenced and which is represented by SYMBOL. See
5017 if we can remove ADDR reference in callers assosiated witht the call. */
5018
5019 static void
5020 adjust_references_in_caller (cgraph_edge *cs, symtab_node *symbol, int index)
5021 {
5022 ipa_edge_args *args = ipa_edge_args_sum->get (cs);
5023 ipa_jump_func *jfunc = ipa_get_ith_jump_func (args, index);
5024 if (jfunc->type == IPA_JF_CONST)
5025 {
5026 ipa_ref *to_del = cs->caller->find_reference (symbol, cs->call_stmt,
5027 cs->lto_stmt_uid,
5028 IPA_REF_ADDR);
5029 if (!to_del)
5030 return;
5031 to_del->remove_reference ();
5032 ipa_zap_jf_refdesc (jfunc);
5033 if (dump_file)
5034 fprintf (dump_file, " Removed a reference from %s to %s.\n",
5035 cs->caller->dump_name (), symbol->dump_name ());
5036 return;
5037 }
5038
5039 if (jfunc->type != IPA_JF_PASS_THROUGH
5040 || ipa_get_jf_pass_through_operation (jfunc) != NOP_EXPR
5041 || ipa_get_jf_pass_through_refdesc_decremented (jfunc))
5042 return;
5043
5044 int fidx = ipa_get_jf_pass_through_formal_id (jfunc);
5045 cgraph_node *caller = cs->caller;
5046 ipa_node_params *caller_info = ipa_node_params_sum->get (caller);
5047 /* TODO: This consistency check may be too big and not really
5048 that useful. Consider removing it. */
5049 tree cst;
5050 if (caller_info->ipcp_orig_node)
5051 cst = caller_info->known_csts[fidx];
5052 else
5053 {
5054 ipcp_lattice<tree> *lat = ipa_get_scalar_lat (caller_info, fidx);
5055 gcc_assert (lat->is_single_const ());
5056 cst = lat->values->value;
5057 }
5058 gcc_assert (TREE_CODE (cst) == ADDR_EXPR
5059 && (symtab_node::get (get_base_address (TREE_OPERAND (cst, 0)))
5060 == symbol));
5061
5062 int cuses = ipa_get_controlled_uses (caller_info, fidx);
5063 if (cuses == IPA_UNDESCRIBED_USE)
5064 return;
5065 gcc_assert (cuses > 0);
5066 cuses--;
5067 ipa_set_controlled_uses (caller_info, fidx, cuses);
5068 ipa_set_jf_pass_through_refdesc_decremented (jfunc, true);
5069 if (dump_file && (dump_flags & TDF_DETAILS))
5070 fprintf (dump_file, " Controlled uses of parameter %i of %s dropped "
5071 "to %i.\n", fidx, caller->dump_name (), cuses);
5072 if (cuses)
5073 return;
5074
5075 if (caller_info->ipcp_orig_node)
5076 {
5077 /* Cloning machinery has created a reference here, we need to either
5078 remove it or change it to a read one. */
5079 ipa_ref *to_del = caller->find_reference (symbol, NULL, 0, IPA_REF_ADDR);
5080 if (to_del)
5081 {
5082 to_del->remove_reference ();
5083 if (dump_file)
5084 fprintf (dump_file, " Removed a reference from %s to %s.\n",
5085 cs->caller->dump_name (), symbol->dump_name ());
5086 if (ipa_get_param_load_dereferenced (caller_info, fidx))
5087 {
5088 caller->create_reference (symbol, IPA_REF_LOAD, NULL);
5089 if (dump_file)
5090 fprintf (dump_file,
5091 " ...and replaced it with LOAD one.\n");
5092 }
5093 }
5094 }
5095
5096 symbol_and_index_together pack;
5097 pack.symbol = symbol;
5098 pack.index = fidx;
5099 if (caller->can_change_signature)
5100 caller->call_for_symbol_thunks_and_aliases (adjust_refs_in_act_callers,
5101 &pack, true);
5102 }
5103
5104
5105 /* Return true if we would like to remove a parameter from NODE when cloning it
5106 with KNOWN_CSTS scalar constants. */
5107
5108 static bool
5109 want_remove_some_param_p (cgraph_node *node, vec<tree> known_csts)
5110 {
5111 auto_vec<bool, 16> surviving;
5112 bool filled_vec = false;
5113 ipa_node_params *info = ipa_node_params_sum->get (node);
5114 int i, count = ipa_get_param_count (info);
5115
5116 for (i = 0; i < count; i++)
5117 {
5118 if (!known_csts[i] && ipa_is_param_used (info, i))
5119 continue;
5120
5121 if (!filled_vec)
5122 {
5123 clone_info *info = clone_info::get (node);
5124 if (!info || !info->param_adjustments)
5125 return true;
5126 info->param_adjustments->get_surviving_params (&surviving);
5127 filled_vec = true;
5128 }
5129 if (surviving.length() < (unsigned) i && surviving[i])
5130 return true;
5131 }
5132 return false;
5133 }
5134
5135 /* Create a specialized version of NODE with known constants in KNOWN_CSTS,
5136 known contexts in KNOWN_CONTEXTS and known aggregate values in AGGVALS and
5137 redirect all edges in CALLERS to it. */
5138
5139 static struct cgraph_node *
5140 create_specialized_node (struct cgraph_node *node,
5141 vec<tree> known_csts,
5142 vec<ipa_polymorphic_call_context> known_contexts,
5143 vec<ipa_argagg_value, va_gc> *aggvals,
5144 vec<cgraph_edge *> &callers)
5145 {
5146 ipa_node_params *new_info, *info = ipa_node_params_sum->get (node);
5147 vec<ipa_replace_map *, va_gc> *replace_trees = NULL;
5148 vec<ipa_adjusted_param, va_gc> *new_params = NULL;
5149 struct cgraph_node *new_node;
5150 int i, count = ipa_get_param_count (info);
5151 clone_info *cinfo = clone_info::get (node);
5152 ipa_param_adjustments *old_adjustments = cinfo
5153 ? cinfo->param_adjustments : NULL;
5154 ipa_param_adjustments *new_adjustments;
5155 gcc_assert (!info->ipcp_orig_node);
5156 gcc_assert (node->can_change_signature
5157 || !old_adjustments);
5158
5159 if (old_adjustments)
5160 {
5161 /* At the moment all IPA optimizations should use the number of
5162 parameters of the prevailing decl as the m_always_copy_start.
5163 Handling any other value would complicate the code below, so for the
5164 time bing let's only assert it is so. */
5165 gcc_assert (old_adjustments->m_always_copy_start == count
5166 || old_adjustments->m_always_copy_start < 0);
5167 int old_adj_count = vec_safe_length (old_adjustments->m_adj_params);
5168 for (i = 0; i < old_adj_count; i++)
5169 {
5170 ipa_adjusted_param *old_adj = &(*old_adjustments->m_adj_params)[i];
5171 if (!node->can_change_signature
5172 || old_adj->op != IPA_PARAM_OP_COPY
5173 || (!known_csts[old_adj->base_index]
5174 && ipa_is_param_used (info, old_adj->base_index)))
5175 {
5176 ipa_adjusted_param new_adj = *old_adj;
5177
5178 new_adj.prev_clone_adjustment = true;
5179 new_adj.prev_clone_index = i;
5180 vec_safe_push (new_params, new_adj);
5181 }
5182 }
5183 bool skip_return = old_adjustments->m_skip_return;
5184 new_adjustments = (new (ggc_alloc <ipa_param_adjustments> ())
5185 ipa_param_adjustments (new_params, count,
5186 skip_return));
5187 }
5188 else if (node->can_change_signature
5189 && want_remove_some_param_p (node, known_csts))
5190 {
5191 ipa_adjusted_param adj;
5192 memset (&adj, 0, sizeof (adj));
5193 adj.op = IPA_PARAM_OP_COPY;
5194 for (i = 0; i < count; i++)
5195 if (!known_csts[i] && ipa_is_param_used (info, i))
5196 {
5197 adj.base_index = i;
5198 adj.prev_clone_index = i;
5199 vec_safe_push (new_params, adj);
5200 }
5201 new_adjustments = (new (ggc_alloc <ipa_param_adjustments> ())
5202 ipa_param_adjustments (new_params, count, false));
5203 }
5204 else
5205 new_adjustments = NULL;
5206
5207 auto_vec<cgraph_edge *, 2> self_recursive_calls;
5208 for (i = callers.length () - 1; i >= 0; i--)
5209 {
5210 cgraph_edge *cs = callers[i];
5211 if (cs->caller == node)
5212 {
5213 self_recursive_calls.safe_push (cs);
5214 callers.unordered_remove (i);
5215 }
5216 }
5217 replace_trees = cinfo ? vec_safe_copy (cinfo->tree_map) : NULL;
5218 for (i = 0; i < count; i++)
5219 {
5220 tree t = known_csts[i];
5221 if (!t)
5222 continue;
5223
5224 gcc_checking_assert (TREE_CODE (t) != TREE_BINFO);
5225
5226 bool load_ref = false;
5227 symtab_node *ref_symbol;
5228 if (TREE_CODE (t) == ADDR_EXPR)
5229 {
5230 tree base = get_base_address (TREE_OPERAND (t, 0));
5231 if (TREE_CODE (base) == VAR_DECL
5232 && ipa_get_controlled_uses (info, i) == 0
5233 && ipa_get_param_load_dereferenced (info, i)
5234 && (ref_symbol = symtab_node::get (base)))
5235 {
5236 load_ref = true;
5237 if (node->can_change_signature)
5238 for (cgraph_edge *caller : callers)
5239 adjust_references_in_caller (caller, ref_symbol, i);
5240 }
5241 }
5242
5243 ipa_replace_map *replace_map = get_replacement_map (info, t, i, load_ref);
5244 if (replace_map)
5245 vec_safe_push (replace_trees, replace_map);
5246 }
5247
5248 unsigned &suffix_counter = clone_num_suffixes->get_or_insert (
5249 IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (
5250 node->decl)));
5251 new_node = node->create_virtual_clone (callers, replace_trees,
5252 new_adjustments, "constprop",
5253 suffix_counter);
5254 suffix_counter++;
5255
5256 bool have_self_recursive_calls = !self_recursive_calls.is_empty ();
5257 for (unsigned j = 0; j < self_recursive_calls.length (); j++)
5258 {
5259 cgraph_edge *cs = get_next_cgraph_edge_clone (self_recursive_calls[j]);
5260 /* Cloned edges can disappear during cloning as speculation can be
5261 resolved, check that we have one and that it comes from the last
5262 cloning. */
5263 if (cs && cs->caller == new_node)
5264 cs->redirect_callee_duplicating_thunks (new_node);
5265 /* Any future code that would make more than one clone of an outgoing
5266 edge would confuse this mechanism, so let's check that does not
5267 happen. */
5268 gcc_checking_assert (!cs
5269 || !get_next_cgraph_edge_clone (cs)
5270 || get_next_cgraph_edge_clone (cs)->caller != new_node);
5271 }
5272 if (have_self_recursive_calls)
5273 new_node->expand_all_artificial_thunks ();
5274
5275 ipa_set_node_agg_value_chain (new_node, aggvals);
5276 for (const ipa_argagg_value &av : aggvals)
5277 new_node->maybe_create_reference (av.value, NULL);
5278
5279 if (dump_file && (dump_flags & TDF_DETAILS))
5280 {
5281 fprintf (dump_file, " the new node is %s.\n", new_node->dump_name ());
5282 if (known_contexts.exists ())
5283 {
5284 for (i = 0; i < count; i++)
5285 if (!known_contexts[i].useless_p ())
5286 {
5287 fprintf (dump_file, " known ctx %i is ", i);
5288 known_contexts[i].dump (dump_file);
5289 }
5290 }
5291 if (aggvals)
5292 {
5293 fprintf (dump_file, " Aggregate replacements:");
5294 ipa_argagg_value_list avs (aggvals);
5295 avs.dump (dump_file);
5296 }
5297 }
5298
5299 new_info = ipa_node_params_sum->get (new_node);
5300 new_info->ipcp_orig_node = node;
5301 new_node->ipcp_clone = true;
5302 new_info->known_csts = known_csts;
5303 new_info->known_contexts = known_contexts;
5304
5305 ipcp_discover_new_direct_edges (new_node, known_csts, known_contexts,
5306 aggvals);
5307
5308 return new_node;
5309 }
5310
5311 /* Return true if JFUNC, which describes a i-th parameter of call CS, is a
5312 pass-through function to itself when the cgraph_node involved is not an
5313 IPA-CP clone. When SIMPLE is true, further check if JFUNC is a simple
5314 no-operation pass-through. */
5315
5316 static bool
5317 self_recursive_pass_through_p (cgraph_edge *cs, ipa_jump_func *jfunc, int i,
5318 bool simple = true)
5319 {
5320 enum availability availability;
5321 if (jfunc->type == IPA_JF_PASS_THROUGH
5322 && cs->caller == cs->callee->function_symbol (&availability)
5323 && availability > AVAIL_INTERPOSABLE
5324 && (!simple || ipa_get_jf_pass_through_operation (jfunc) == NOP_EXPR)
5325 && ipa_get_jf_pass_through_formal_id (jfunc) == i
5326 && ipa_node_params_sum->get (cs->caller)
5327 && !ipa_node_params_sum->get (cs->caller)->ipcp_orig_node)
5328 return true;
5329 return false;
5330 }
5331
5332 /* Return true if JFUNC, which describes the i-th parameter of call CS, is an
5333 ancestor function with zero offset to itself when the cgraph_node involved
5334 is not an IPA-CP clone. */
5335
5336 static bool
5337 self_recursive_ancestor_p (cgraph_edge *cs, ipa_jump_func *jfunc, int i)
5338 {
5339 enum availability availability;
5340 if (jfunc->type == IPA_JF_ANCESTOR
5341 && cs->caller == cs->callee->function_symbol (&availability)
5342 && availability > AVAIL_INTERPOSABLE
5343 && ipa_get_jf_ancestor_offset (jfunc) == 0
5344 && ipa_get_jf_ancestor_formal_id (jfunc) == i
5345 && ipa_node_params_sum->get (cs->caller)
5346 && !ipa_node_params_sum->get (cs->caller)->ipcp_orig_node)
5347 return true;
5348 return false;
5349 }
5350
5351 /* Return true if JFUNC, which describes a part of an aggregate represented or
5352 pointed to by the i-th parameter of call CS, is a pass-through function to
5353 itself when the cgraph_node involved is not an IPA-CP clone.. When
5354 SIMPLE is true, further check if JFUNC is a simple no-operation
5355 pass-through. */
5356
5357 static bool
5358 self_recursive_agg_pass_through_p (const cgraph_edge *cs,
5359 const ipa_agg_jf_item *jfunc,
5360 int i, bool simple = true)
5361 {
5362 enum availability availability;
5363 if (cs->caller == cs->callee->function_symbol (&availability)
5364 && availability > AVAIL_INTERPOSABLE
5365 && jfunc->jftype == IPA_JF_LOAD_AGG
5366 && jfunc->offset == jfunc->value.load_agg.offset
5367 && (!simple || jfunc->value.pass_through.operation == NOP_EXPR)
5368 && jfunc->value.pass_through.formal_id == i
5369 && useless_type_conversion_p (jfunc->value.load_agg.type, jfunc->type)
5370 && ipa_node_params_sum->get (cs->caller)
5371 && !ipa_node_params_sum->get (cs->caller)->ipcp_orig_node)
5372 return true;
5373 return false;
5374 }
5375
5376 /* Given a NODE, and a subset of its CALLERS, try to populate blanks slots in
5377 KNOWN_CSTS with constants that are also known for all of the CALLERS. */
5378
5379 static void
5380 find_more_scalar_values_for_callers_subset (struct cgraph_node *node,
5381 vec<tree> &known_csts,
5382 const vec<cgraph_edge *> &callers)
5383 {
5384 ipa_node_params *info = ipa_node_params_sum->get (node);
5385 int i, count = ipa_get_param_count (info);
5386
5387 for (i = 0; i < count; i++)
5388 {
5389 struct cgraph_edge *cs;
5390 tree newval = NULL_TREE;
5391 int j;
5392 bool first = true;
5393 tree type = ipa_get_type (info, i);
5394
5395 if (ipa_get_scalar_lat (info, i)->bottom || known_csts[i])
5396 continue;
5397
5398 FOR_EACH_VEC_ELT (callers, j, cs)
5399 {
5400 struct ipa_jump_func *jump_func;
5401 tree t;
5402
5403 ipa_edge_args *args = ipa_edge_args_sum->get (cs);
5404 if (!args
5405 || i >= ipa_get_cs_argument_count (args)
5406 || (i == 0
5407 && call_passes_through_thunk (cs)))
5408 {
5409 newval = NULL_TREE;
5410 break;
5411 }
5412 jump_func = ipa_get_ith_jump_func (args, i);
5413
5414 /* Besides simple pass-through jump function, arithmetic jump
5415 function could also introduce argument-direct-pass-through for
5416 self-feeding recursive call. For example,
5417
5418 fn (int i)
5419 {
5420 fn (i & 1);
5421 }
5422
5423 Given that i is 0, recursive propagation via (i & 1) also gets
5424 0. */
5425 if (self_recursive_pass_through_p (cs, jump_func, i, false))
5426 {
5427 gcc_assert (newval);
5428 enum tree_code opcode
5429 = ipa_get_jf_pass_through_operation (jump_func);
5430 tree op_type = (opcode == NOP_EXPR) ? NULL_TREE
5431 : ipa_get_jf_pass_through_op_type (jump_func);
5432 t = ipa_get_jf_arith_result (opcode, newval,
5433 ipa_get_jf_pass_through_operand (jump_func),
5434 op_type);
5435 t = ipacp_value_safe_for_type (type, t);
5436 }
5437 else if (self_recursive_ancestor_p (cs, jump_func, i))
5438 continue;
5439 else
5440 t = ipa_value_from_jfunc (ipa_node_params_sum->get (cs->caller),
5441 jump_func, type);
5442 if (!t
5443 || (newval
5444 && !values_equal_for_ipcp_p (t, newval))
5445 || (!first && !newval))
5446 {
5447 newval = NULL_TREE;
5448 break;
5449 }
5450 else
5451 newval = t;
5452 first = false;
5453 }
5454
5455 if (newval)
5456 {
5457 if (dump_file && (dump_flags & TDF_DETAILS))
5458 {
5459 fprintf (dump_file, " adding an extra known scalar value ");
5460 print_ipcp_constant_value (dump_file, newval);
5461 fprintf (dump_file, " for ");
5462 ipa_dump_param (dump_file, info, i);
5463 fprintf (dump_file, "\n");
5464 }
5465
5466 known_csts[i] = newval;
5467 }
5468 }
5469 }
5470
5471 /* Given a NODE and a subset of its CALLERS, try to populate plank slots in
5472 KNOWN_CONTEXTS with polymorphic contexts that are also known for all of the
5473 CALLERS. */
5474
5475 static void
5476 find_more_contexts_for_caller_subset (cgraph_node *node,
5477 vec<ipa_polymorphic_call_context>
5478 *known_contexts,
5479 const vec<cgraph_edge *> &callers)
5480 {
5481 ipa_node_params *info = ipa_node_params_sum->get (node);
5482 int i, count = ipa_get_param_count (info);
5483
5484 for (i = 0; i < count; i++)
5485 {
5486 cgraph_edge *cs;
5487
5488 if (ipa_get_poly_ctx_lat (info, i)->bottom
5489 || (known_contexts->exists ()
5490 && !(*known_contexts)[i].useless_p ()))
5491 continue;
5492
5493 ipa_polymorphic_call_context newval;
5494 bool first = true;
5495 int j;
5496
5497 FOR_EACH_VEC_ELT (callers, j, cs)
5498 {
5499 ipa_edge_args *args = ipa_edge_args_sum->get (cs);
5500 if (!args
5501 || i >= ipa_get_cs_argument_count (args))
5502 return;
5503 ipa_jump_func *jfunc = ipa_get_ith_jump_func (args, i);
5504 ipa_polymorphic_call_context ctx;
5505 ctx = ipa_context_from_jfunc (ipa_node_params_sum->get (cs->caller),
5506 cs, i, jfunc);
5507 if (first)
5508 {
5509 newval = ctx;
5510 first = false;
5511 }
5512 else
5513 newval.meet_with (ctx);
5514 if (newval.useless_p ())
5515 break;
5516 }
5517
5518 if (!newval.useless_p ())
5519 {
5520 if (dump_file && (dump_flags & TDF_DETAILS))
5521 {
5522 fprintf (dump_file, " adding an extra known polymorphic "
5523 "context ");
5524 print_ipcp_constant_value (dump_file, newval);
5525 fprintf (dump_file, " for ");
5526 ipa_dump_param (dump_file, info, i);
5527 fprintf (dump_file, "\n");
5528 }
5529
5530 if (!known_contexts->exists ())
5531 known_contexts->safe_grow_cleared (ipa_get_param_count (info),
5532 true);
5533 (*known_contexts)[i] = newval;
5534 }
5535
5536 }
5537 }
5538
5539 /* Push all aggregate values coming along edge CS for parameter number INDEX to
5540 RES. If INTERIM is non-NULL, it contains the current interim state of
5541 collected aggregate values which can be used to compute values passed over
5542 self-recursive edges.
5543
5544 This basically one iteration of push_agg_values_from_edge over one
5545 parameter, which allows for simpler early returns. */
5546
5547 static void
5548 push_agg_values_for_index_from_edge (struct cgraph_edge *cs, int index,
5549 vec<ipa_argagg_value> *res,
5550 const ipa_argagg_value_list *interim)
5551 {
5552 bool agg_values_from_caller = false;
5553 bool agg_jf_preserved = false;
5554 unsigned unit_delta = UINT_MAX;
5555 int src_idx = -1;
5556 ipa_jump_func *jfunc = ipa_get_ith_jump_func (ipa_edge_args_sum->get (cs),
5557 index);
5558
5559 if (jfunc->type == IPA_JF_PASS_THROUGH
5560 && ipa_get_jf_pass_through_operation (jfunc) == NOP_EXPR)
5561 {
5562 agg_values_from_caller = true;
5563 agg_jf_preserved = ipa_get_jf_pass_through_agg_preserved (jfunc);
5564 src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
5565 unit_delta = 0;
5566 }
5567 else if (jfunc->type == IPA_JF_ANCESTOR
5568 && ipa_get_jf_ancestor_agg_preserved (jfunc))
5569 {
5570 agg_values_from_caller = true;
5571 agg_jf_preserved = true;
5572 src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
5573 unit_delta = ipa_get_jf_ancestor_offset (jfunc) / BITS_PER_UNIT;
5574 }
5575
5576 ipa_node_params *caller_info = ipa_node_params_sum->get (cs->caller);
5577 if (agg_values_from_caller)
5578 {
5579 if (caller_info->ipcp_orig_node)
5580 {
5581 struct cgraph_node *orig_node = caller_info->ipcp_orig_node;
5582 ipcp_transformation *ts
5583 = ipcp_get_transformation_summary (cs->caller);
5584 ipa_node_params *orig_info = ipa_node_params_sum->get (orig_node);
5585 ipcp_param_lattices *orig_plats
5586 = ipa_get_parm_lattices (orig_info, src_idx);
5587 if (ts
5588 && orig_plats->aggs
5589 && (agg_jf_preserved || !orig_plats->aggs_by_ref))
5590 {
5591 ipa_argagg_value_list src (ts);
5592 src.push_adjusted_values (src_idx, index, unit_delta, res);
5593 return;
5594 }
5595 }
5596 else
5597 {
5598 ipcp_param_lattices *src_plats
5599 = ipa_get_parm_lattices (caller_info, src_idx);
5600 if (src_plats->aggs
5601 && !src_plats->aggs_bottom
5602 && (agg_jf_preserved || !src_plats->aggs_by_ref))
5603 {
5604 if (interim && (self_recursive_pass_through_p (cs, jfunc, index)
5605 || self_recursive_ancestor_p (cs, jfunc, index)))
5606 {
5607 interim->push_adjusted_values (src_idx, index, unit_delta,
5608 res);
5609 return;
5610 }
5611 if (!src_plats->aggs_contain_variable)
5612 {
5613 push_agg_values_from_plats (src_plats, index, unit_delta,
5614 res);
5615 return;
5616 }
5617 }
5618 }
5619 }
5620
5621 if (!jfunc->agg.items)
5622 return;
5623 bool first = true;
5624 unsigned prev_unit_offset = 0;
5625 for (const ipa_agg_jf_item &agg_jf : *jfunc->agg.items)
5626 {
5627 tree value, srcvalue;
5628 /* Besides simple pass-through aggregate jump function, arithmetic
5629 aggregate jump function could also bring same aggregate value as
5630 parameter passed-in for self-feeding recursive call. For example,
5631
5632 fn (int *i)
5633 {
5634 int j = *i & 1;
5635 fn (&j);
5636 }
5637
5638 Given that *i is 0, recursive propagation via (*i & 1) also gets 0. */
5639 if (interim
5640 && self_recursive_agg_pass_through_p (cs, &agg_jf, index, false)
5641 && (srcvalue = interim->get_value(index,
5642 agg_jf.offset / BITS_PER_UNIT)))
5643 {
5644 value = ipa_get_jf_arith_result (agg_jf.value.pass_through.operation,
5645 srcvalue,
5646 agg_jf.value.pass_through.operand,
5647 agg_jf.value.pass_through.op_type);
5648 value = ipacp_value_safe_for_type (agg_jf.type, value);
5649 }
5650 else
5651 value = ipa_agg_value_from_jfunc (caller_info, cs->caller,
5652 &agg_jf);
5653 if (value)
5654 {
5655 struct ipa_argagg_value iav;
5656 iav.value = value;
5657 iav.unit_offset = agg_jf.offset / BITS_PER_UNIT;
5658 iav.index = index;
5659 iav.by_ref = jfunc->agg.by_ref;
5660 iav.killed = false;
5661
5662 gcc_assert (first
5663 || iav.unit_offset > prev_unit_offset);
5664 prev_unit_offset = iav.unit_offset;
5665 first = false;
5666
5667 res->safe_push (iav);
5668 }
5669 }
5670 return;
5671 }
5672
5673 /* Push all aggregate values coming along edge CS to RES. DEST_INFO is the
5674 description of ultimate callee of CS or the one it was cloned from (the
5675 summary where lattices are). If INTERIM is non-NULL, it contains the
5676 current interim state of collected aggregate values which can be used to
5677 compute values passed over self-recursive edges (if OPTIMIZE_SELF_RECURSION
5678 is true) and to skip values which clearly will not be part of intersection
5679 with INTERIM. */
5680
5681 static void
5682 push_agg_values_from_edge (struct cgraph_edge *cs,
5683 ipa_node_params *dest_info,
5684 vec<ipa_argagg_value> *res,
5685 const ipa_argagg_value_list *interim,
5686 bool optimize_self_recursion)
5687 {
5688 ipa_edge_args *args = ipa_edge_args_sum->get (cs);
5689 if (!args)
5690 return;
5691
5692 int count = MIN (ipa_get_param_count (dest_info),
5693 ipa_get_cs_argument_count (args));
5694
5695 unsigned interim_index = 0;
5696 for (int index = 0; index < count; index++)
5697 {
5698 if (interim)
5699 {
5700 while (interim_index < interim->m_elts.size ()
5701 && interim->m_elts[interim_index].value
5702 && interim->m_elts[interim_index].index < index)
5703 interim_index++;
5704 if (interim_index >= interim->m_elts.size ()
5705 || interim->m_elts[interim_index].index > index)
5706 continue;
5707 }
5708
5709 ipcp_param_lattices *plats = ipa_get_parm_lattices (dest_info, index);
5710 if (!ipa_is_param_used (dest_info, index)
5711 || plats->aggs_bottom)
5712 continue;
5713 push_agg_values_for_index_from_edge (cs, index, res,
5714 optimize_self_recursion ? interim
5715 : NULL);
5716 }
5717 }
5718
5719
5720 /* Look at edges in CALLERS and collect all known aggregate values that arrive
5721 from all of them. Return nullptr if there are none. */
5722
5723 static struct vec<ipa_argagg_value, va_gc> *
5724 find_aggregate_values_for_callers_subset (struct cgraph_node *node,
5725 const vec<cgraph_edge *> &callers)
5726 {
5727 ipa_node_params *dest_info = ipa_node_params_sum->get (node);
5728 if (dest_info->ipcp_orig_node)
5729 dest_info = ipa_node_params_sum->get (dest_info->ipcp_orig_node);
5730
5731 /* gather_edges_for_value puts a non-recursive call into the first element of
5732 callers if it can. */
5733 auto_vec<ipa_argagg_value, 32> interim;
5734 push_agg_values_from_edge (callers[0], dest_info, &interim, NULL, true);
5735
5736 unsigned valid_entries = interim.length ();
5737 if (!valid_entries)
5738 return nullptr;
5739
5740 unsigned caller_count = callers.length();
5741 for (unsigned i = 1; i < caller_count; i++)
5742 {
5743 auto_vec<ipa_argagg_value, 32> last;
5744 ipa_argagg_value_list avs (&interim);
5745 push_agg_values_from_edge (callers[i], dest_info, &last, &avs, true);
5746
5747 valid_entries = intersect_argaggs_with (interim, last);
5748 if (!valid_entries)
5749 return nullptr;
5750 }
5751
5752 vec<ipa_argagg_value, va_gc> *res = NULL;
5753 vec_safe_reserve_exact (res, valid_entries);
5754 for (const ipa_argagg_value &av : interim)
5755 if (av.value)
5756 res->quick_push(av);
5757 gcc_checking_assert (res->length () == valid_entries);
5758 return res;
5759 }
5760
5761 /* Determine whether CS also brings all scalar values that the NODE is
5762 specialized for. */
5763
5764 static bool
5765 cgraph_edge_brings_all_scalars_for_node (struct cgraph_edge *cs,
5766 struct cgraph_node *node)
5767 {
5768 ipa_node_params *dest_info = ipa_node_params_sum->get (node);
5769 int count = ipa_get_param_count (dest_info);
5770 class ipa_node_params *caller_info;
5771 class ipa_edge_args *args;
5772 int i;
5773
5774 caller_info = ipa_node_params_sum->get (cs->caller);
5775 args = ipa_edge_args_sum->get (cs);
5776 for (i = 0; i < count; i++)
5777 {
5778 struct ipa_jump_func *jump_func;
5779 tree val, t;
5780
5781 val = dest_info->known_csts[i];
5782 if (!val)
5783 continue;
5784
5785 if (i >= ipa_get_cs_argument_count (args))
5786 return false;
5787 jump_func = ipa_get_ith_jump_func (args, i);
5788 t = ipa_value_from_jfunc (caller_info, jump_func,
5789 ipa_get_type (dest_info, i));
5790 if (!t || !values_equal_for_ipcp_p (val, t))
5791 return false;
5792 }
5793 return true;
5794 }
5795
5796 /* Determine whether CS also brings all aggregate values that NODE is
5797 specialized for. */
5798
5799 static bool
5800 cgraph_edge_brings_all_agg_vals_for_node (struct cgraph_edge *cs,
5801 struct cgraph_node *node)
5802 {
5803 ipcp_transformation *ts = ipcp_get_transformation_summary (node);
5804 if (!ts || vec_safe_is_empty (ts->m_agg_values))
5805 return true;
5806
5807 const ipa_argagg_value_list existing (ts->m_agg_values);
5808 auto_vec<ipa_argagg_value, 32> edge_values;
5809 ipa_node_params *dest_info = ipa_node_params_sum->get (node);
5810 gcc_checking_assert (dest_info->ipcp_orig_node);
5811 dest_info = ipa_node_params_sum->get (dest_info->ipcp_orig_node);
5812 push_agg_values_from_edge (cs, dest_info, &edge_values, &existing, false);
5813 const ipa_argagg_value_list avl (&edge_values);
5814 return avl.superset_of_p (existing);
5815 }
5816
5817 /* Given an original NODE and a VAL for which we have already created a
5818 specialized clone, look whether there are incoming edges that still lead
5819 into the old node but now also bring the requested value and also conform to
5820 all other criteria such that they can be redirected the special node.
5821 This function can therefore redirect the final edge in a SCC. */
5822
5823 template <typename valtype>
5824 static void
5825 perhaps_add_new_callers (cgraph_node *node, ipcp_value<valtype> *val)
5826 {
5827 ipcp_value_source<valtype> *src;
5828 profile_count redirected_sum = profile_count::zero ();
5829
5830 for (src = val->sources; src; src = src->next)
5831 {
5832 struct cgraph_edge *cs = src->cs;
5833 while (cs)
5834 {
5835 if (cgraph_edge_brings_value_p (cs, src, node, val)
5836 && cgraph_edge_brings_all_scalars_for_node (cs, val->spec_node)
5837 && cgraph_edge_brings_all_agg_vals_for_node (cs, val->spec_node))
5838 {
5839 if (dump_file)
5840 fprintf (dump_file, " - adding an extra caller %s of %s\n",
5841 cs->caller->dump_name (),
5842 val->spec_node->dump_name ());
5843
5844 cs->redirect_callee_duplicating_thunks (val->spec_node);
5845 val->spec_node->expand_all_artificial_thunks ();
5846 if (cs->count.ipa ().initialized_p ())
5847 redirected_sum = redirected_sum + cs->count.ipa ();
5848 }
5849 cs = get_next_cgraph_edge_clone (cs);
5850 }
5851 }
5852
5853 if (redirected_sum.nonzero_p ())
5854 update_specialized_profile (val->spec_node, node, redirected_sum);
5855 }
5856
5857 /* Return true if KNOWN_CONTEXTS contain at least one useful context. */
5858
5859 static bool
5860 known_contexts_useful_p (vec<ipa_polymorphic_call_context> known_contexts)
5861 {
5862 ipa_polymorphic_call_context *ctx;
5863 int i;
5864
5865 FOR_EACH_VEC_ELT (known_contexts, i, ctx)
5866 if (!ctx->useless_p ())
5867 return true;
5868 return false;
5869 }
5870
5871 /* Return a copy of KNOWN_CSTS if it is not empty, otherwise return vNULL. */
5872
5873 static vec<ipa_polymorphic_call_context>
5874 copy_useful_known_contexts (const vec<ipa_polymorphic_call_context> &known_contexts)
5875 {
5876 if (known_contexts_useful_p (known_contexts))
5877 return known_contexts.copy ();
5878 else
5879 return vNULL;
5880 }
5881
5882 /* Copy known scalar values from AVALS into KNOWN_CSTS and modify the copy
5883 according to VAL and INDEX. If non-empty, replace KNOWN_CONTEXTS with its
5884 copy too. */
5885
5886 static void
5887 copy_known_vectors_add_val (ipa_auto_call_arg_values *avals,
5888 vec<tree> *known_csts,
5889 vec<ipa_polymorphic_call_context> *known_contexts,
5890 ipcp_value<tree> *val, int index)
5891 {
5892 *known_csts = avals->m_known_vals.copy ();
5893 *known_contexts = copy_useful_known_contexts (avals->m_known_contexts);
5894 (*known_csts)[index] = val->value;
5895 }
5896
5897 /* Copy known scalar values from AVALS into KNOWN_CSTS. Similarly, copy
5898 contexts to KNOWN_CONTEXTS and modify the copy according to VAL and
5899 INDEX. */
5900
5901 static void
5902 copy_known_vectors_add_val (ipa_auto_call_arg_values *avals,
5903 vec<tree> *known_csts,
5904 vec<ipa_polymorphic_call_context> *known_contexts,
5905 ipcp_value<ipa_polymorphic_call_context> *val,
5906 int index)
5907 {
5908 *known_csts = avals->m_known_vals.copy ();
5909 *known_contexts = avals->m_known_contexts.copy ();
5910 (*known_contexts)[index] = val->value;
5911 }
5912
5913 /* Return true if OFFSET indicates this was not an aggregate value or there is
5914 a replacement equivalent to VALUE, INDEX and OFFSET among those in the
5915 AGGVALS list. */
5916
5917 DEBUG_FUNCTION bool
5918 ipcp_val_agg_replacement_ok_p (vec<ipa_argagg_value, va_gc> *aggvals,
5919 int index, HOST_WIDE_INT offset, tree value)
5920 {
5921 if (offset == -1)
5922 return true;
5923
5924 const ipa_argagg_value_list avl (aggvals);
5925 tree v = avl.get_value (index, offset / BITS_PER_UNIT);
5926 return v && values_equal_for_ipcp_p (v, value);
5927 }
5928
5929 /* Return true if offset is minus one because source of a polymorphic context
5930 cannot be an aggregate value. */
5931
5932 DEBUG_FUNCTION bool
5933 ipcp_val_agg_replacement_ok_p (vec<ipa_argagg_value, va_gc> *,
5934 int , HOST_WIDE_INT offset,
5935 ipa_polymorphic_call_context)
5936 {
5937 return offset == -1;
5938 }
5939
5940 /* Decide whether to create a special version of NODE for value VAL of
5941 parameter at the given INDEX. If OFFSET is -1, the value is for the
5942 parameter itself, otherwise it is stored at the given OFFSET of the
5943 parameter. AVALS describes the other already known values. SELF_GEN_CLONES
5944 is a vector which contains clones created for self-recursive calls with an
5945 arithmetic pass-through jump function. */
5946
5947 template <typename valtype>
5948 static bool
5949 decide_about_value (struct cgraph_node *node, int index, HOST_WIDE_INT offset,
5950 ipcp_value<valtype> *val, ipa_auto_call_arg_values *avals,
5951 vec<cgraph_node *> *self_gen_clones)
5952 {
5953 int caller_count;
5954 sreal freq_sum;
5955 profile_count count_sum, rec_count_sum;
5956 vec<cgraph_edge *> callers;
5957
5958 if (val->spec_node)
5959 {
5960 perhaps_add_new_callers (node, val);
5961 return false;
5962 }
5963 else if (val->local_size_cost + overall_size > get_max_overall_size (node))
5964 {
5965 if (dump_file && (dump_flags & TDF_DETAILS))
5966 fprintf (dump_file, " Ignoring candidate value because "
5967 "maximum unit size would be reached with %li.\n",
5968 val->local_size_cost + overall_size);
5969 return false;
5970 }
5971 else if (!get_info_about_necessary_edges (val, node, &freq_sum, &caller_count,
5972 &rec_count_sum, &count_sum))
5973 return false;
5974
5975 if (!dbg_cnt (ipa_cp_values))
5976 return false;
5977
5978 if (val->self_recursion_generated_p ())
5979 {
5980 /* The edge counts in this case might not have been adjusted yet.
5981 Nevertleless, even if they were it would be only a guesswork which we
5982 can do now. The recursive part of the counts can be derived from the
5983 count of the original node anyway. */
5984 if (node->count.ipa ().nonzero_p ())
5985 {
5986 unsigned dem = self_gen_clones->length () + 1;
5987 rec_count_sum = node->count.ipa () / dem;
5988 }
5989 else
5990 rec_count_sum = profile_count::zero ();
5991 }
5992
5993 /* get_info_about_necessary_edges only sums up ipa counts. */
5994 count_sum += rec_count_sum;
5995
5996 if (dump_file && (dump_flags & TDF_DETAILS))
5997 {
5998 fprintf (dump_file, " - considering value ");
5999 print_ipcp_constant_value (dump_file, val->value);
6000 fprintf (dump_file, " for ");
6001 ipa_dump_param (dump_file, ipa_node_params_sum->get (node), index);
6002 if (offset != -1)
6003 fprintf (dump_file, ", offset: " HOST_WIDE_INT_PRINT_DEC, offset);
6004 fprintf (dump_file, " (caller_count: %i)\n", caller_count);
6005 }
6006
6007 if (!good_cloning_opportunity_p (node, val->local_time_benefit,
6008 freq_sum, count_sum,
6009 val->local_size_cost)
6010 && !good_cloning_opportunity_p (node, val->prop_time_benefit,
6011 freq_sum, count_sum, val->prop_size_cost))
6012 return false;
6013
6014 if (dump_file)
6015 fprintf (dump_file, " Creating a specialized node of %s.\n",
6016 node->dump_name ());
6017
6018 vec<tree> known_csts;
6019 vec<ipa_polymorphic_call_context> known_contexts;
6020
6021 callers = gather_edges_for_value (val, node, caller_count);
6022 if (offset == -1)
6023 copy_known_vectors_add_val (avals, &known_csts, &known_contexts, val, index);
6024 else
6025 {
6026 known_csts = avals->m_known_vals.copy ();
6027 known_contexts = copy_useful_known_contexts (avals->m_known_contexts);
6028 }
6029 find_more_scalar_values_for_callers_subset (node, known_csts, callers);
6030 find_more_contexts_for_caller_subset (node, &known_contexts, callers);
6031 vec<ipa_argagg_value, va_gc> *aggvals
6032 = find_aggregate_values_for_callers_subset (node, callers);
6033 gcc_checking_assert (ipcp_val_agg_replacement_ok_p (aggvals, index,
6034 offset, val->value));
6035 val->spec_node = create_specialized_node (node, known_csts, known_contexts,
6036 aggvals, callers);
6037
6038 if (val->self_recursion_generated_p ())
6039 self_gen_clones->safe_push (val->spec_node);
6040 else
6041 update_profiling_info (node, val->spec_node);
6042
6043 callers.release ();
6044 overall_size += val->local_size_cost;
6045 if (dump_file && (dump_flags & TDF_DETAILS))
6046 fprintf (dump_file, " overall size reached %li\n",
6047 overall_size);
6048
6049 /* TODO: If for some lattice there is only one other known value
6050 left, make a special node for it too. */
6051
6052 return true;
6053 }
6054
6055 /* Like irange::contains_p(), but convert VAL to the range of R if
6056 necessary. */
6057
6058 static inline bool
6059 ipa_range_contains_p (const vrange &r, tree val)
6060 {
6061 if (r.undefined_p ())
6062 return false;
6063
6064 tree type = r.type ();
6065 if (!wi::fits_to_tree_p (wi::to_wide (val), type))
6066 return false;
6067
6068 val = fold_convert (type, val);
6069 return r.contains_p (val);
6070 }
6071
6072 /* Decide whether and what specialized clones of NODE should be created. */
6073
6074 static bool
6075 decide_whether_version_node (struct cgraph_node *node)
6076 {
6077 ipa_node_params *info = ipa_node_params_sum->get (node);
6078 int i, count = ipa_get_param_count (info);
6079 bool ret = false;
6080
6081 if (count == 0)
6082 return false;
6083
6084 if (dump_file && (dump_flags & TDF_DETAILS))
6085 fprintf (dump_file, "\nEvaluating opportunities for %s.\n",
6086 node->dump_name ());
6087
6088 auto_vec <cgraph_node *, 9> self_gen_clones;
6089 ipa_auto_call_arg_values avals;
6090 gather_context_independent_values (info, &avals, false, NULL);
6091
6092 for (i = 0; i < count;i++)
6093 {
6094 if (!ipa_is_param_used (info, i))
6095 continue;
6096
6097 class ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
6098 ipcp_lattice<tree> *lat = &plats->itself;
6099 ipcp_lattice<ipa_polymorphic_call_context> *ctxlat = &plats->ctxlat;
6100
6101 if (!lat->bottom
6102 && !avals.m_known_vals[i])
6103 {
6104 ipcp_value<tree> *val;
6105 for (val = lat->values; val; val = val->next)
6106 {
6107 /* If some values generated for self-recursive calls with
6108 arithmetic jump functions fall outside of the known
6109 range for the parameter, we can skip them. */
6110 if (TREE_CODE (val->value) == INTEGER_CST
6111 && !plats->m_value_range.bottom_p ()
6112 && !ipa_range_contains_p (plats->m_value_range.m_vr,
6113 val->value))
6114 {
6115 /* This can happen also if a constant present in the source
6116 code falls outside of the range of parameter's type, so we
6117 cannot assert. */
6118 if (dump_file && (dump_flags & TDF_DETAILS))
6119 {
6120 fprintf (dump_file, " - skipping%s value ",
6121 val->self_recursion_generated_p ()
6122 ? " self_recursion_generated" : "");
6123 print_ipcp_constant_value (dump_file, val->value);
6124 fprintf (dump_file, " because it is outside known "
6125 "value range.\n");
6126 }
6127 continue;
6128 }
6129 ret |= decide_about_value (node, i, -1, val, &avals,
6130 &self_gen_clones);
6131 }
6132 }
6133
6134 if (!plats->aggs_bottom)
6135 {
6136 struct ipcp_agg_lattice *aglat;
6137 ipcp_value<tree> *val;
6138 for (aglat = plats->aggs; aglat; aglat = aglat->next)
6139 if (!aglat->bottom && aglat->values
6140 /* If the following is false, the one value has been considered
6141 for cloning for all contexts. */
6142 && (plats->aggs_contain_variable
6143 || !aglat->is_single_const ()))
6144 for (val = aglat->values; val; val = val->next)
6145 ret |= decide_about_value (node, i, aglat->offset, val, &avals,
6146 &self_gen_clones);
6147 }
6148
6149 if (!ctxlat->bottom
6150 && avals.m_known_contexts[i].useless_p ())
6151 {
6152 ipcp_value<ipa_polymorphic_call_context> *val;
6153 for (val = ctxlat->values; val; val = val->next)
6154 ret |= decide_about_value (node, i, -1, val, &avals,
6155 &self_gen_clones);
6156 }
6157 }
6158
6159 if (!self_gen_clones.is_empty ())
6160 {
6161 self_gen_clones.safe_push (node);
6162 update_counts_for_self_gen_clones (node, self_gen_clones);
6163 }
6164
6165 if (info->do_clone_for_all_contexts)
6166 {
6167 if (!dbg_cnt (ipa_cp_values))
6168 {
6169 info->do_clone_for_all_contexts = false;
6170 return ret;
6171 }
6172
6173 struct cgraph_node *clone;
6174 auto_vec<cgraph_edge *> callers = node->collect_callers ();
6175
6176 for (int i = callers.length () - 1; i >= 0; i--)
6177 {
6178 cgraph_edge *cs = callers[i];
6179 ipa_node_params *caller_info = ipa_node_params_sum->get (cs->caller);
6180
6181 if (caller_info && caller_info->node_dead)
6182 callers.unordered_remove (i);
6183 }
6184
6185 if (!adjust_callers_for_value_intersection (callers, node))
6186 {
6187 /* If node is not called by anyone, or all its caller edges are
6188 self-recursive, the node is not really in use, no need to do
6189 cloning. */
6190 info->do_clone_for_all_contexts = false;
6191 return ret;
6192 }
6193
6194 if (dump_file)
6195 fprintf (dump_file, " - Creating a specialized node of %s "
6196 "for all known contexts.\n", node->dump_name ());
6197
6198 vec<tree> known_csts = avals.m_known_vals.copy ();
6199 vec<ipa_polymorphic_call_context> known_contexts
6200 = copy_useful_known_contexts (avals.m_known_contexts);
6201 find_more_scalar_values_for_callers_subset (node, known_csts, callers);
6202 find_more_contexts_for_caller_subset (node, &known_contexts, callers);
6203 vec<ipa_argagg_value, va_gc> *aggvals
6204 = find_aggregate_values_for_callers_subset (node, callers);
6205
6206 if (!known_contexts_useful_p (known_contexts))
6207 {
6208 known_contexts.release ();
6209 known_contexts = vNULL;
6210 }
6211 clone = create_specialized_node (node, known_csts, known_contexts,
6212 aggvals, callers);
6213 info->do_clone_for_all_contexts = false;
6214 ipa_node_params_sum->get (clone)->is_all_contexts_clone = true;
6215 ret = true;
6216 }
6217
6218 return ret;
6219 }
6220
6221 /* Transitively mark all callees of NODE within the same SCC as not dead. */
6222
6223 static void
6224 spread_undeadness (struct cgraph_node *node)
6225 {
6226 struct cgraph_edge *cs;
6227
6228 for (cs = node->callees; cs; cs = cs->next_callee)
6229 if (ipa_edge_within_scc (cs))
6230 {
6231 struct cgraph_node *callee;
6232 class ipa_node_params *info;
6233
6234 callee = cs->callee->function_symbol (NULL);
6235 info = ipa_node_params_sum->get (callee);
6236
6237 if (info && info->node_dead)
6238 {
6239 info->node_dead = 0;
6240 spread_undeadness (callee);
6241 }
6242 }
6243 }
6244
6245 /* Return true if NODE has a caller from outside of its SCC that is not
6246 dead. Worker callback for cgraph_for_node_and_aliases. */
6247
6248 static bool
6249 has_undead_caller_from_outside_scc_p (struct cgraph_node *node,
6250 void *data ATTRIBUTE_UNUSED)
6251 {
6252 struct cgraph_edge *cs;
6253
6254 for (cs = node->callers; cs; cs = cs->next_caller)
6255 if (cs->caller->thunk
6256 && cs->caller->call_for_symbol_thunks_and_aliases
6257 (has_undead_caller_from_outside_scc_p, NULL, true))
6258 return true;
6259 else if (!ipa_edge_within_scc (cs))
6260 {
6261 ipa_node_params *caller_info = ipa_node_params_sum->get (cs->caller);
6262 if (!caller_info /* Unoptimized caller are like dead ones. */
6263 || !caller_info->node_dead)
6264 return true;
6265 }
6266 return false;
6267 }
6268
6269
6270 /* Identify nodes within the same SCC as NODE which are no longer needed
6271 because of new clones and will be removed as unreachable. */
6272
6273 static void
6274 identify_dead_nodes (struct cgraph_node *node)
6275 {
6276 struct cgraph_node *v;
6277 for (v = node; v; v = ((struct ipa_dfs_info *) v->aux)->next_cycle)
6278 if (v->local)
6279 {
6280 ipa_node_params *info = ipa_node_params_sum->get (v);
6281 if (info
6282 && !v->call_for_symbol_thunks_and_aliases
6283 (has_undead_caller_from_outside_scc_p, NULL, true))
6284 info->node_dead = 1;
6285 }
6286
6287 for (v = node; v; v = ((struct ipa_dfs_info *) v->aux)->next_cycle)
6288 {
6289 ipa_node_params *info = ipa_node_params_sum->get (v);
6290 if (info && !info->node_dead)
6291 spread_undeadness (v);
6292 }
6293
6294 if (dump_file && (dump_flags & TDF_DETAILS))
6295 {
6296 for (v = node; v; v = ((struct ipa_dfs_info *) v->aux)->next_cycle)
6297 if (ipa_node_params_sum->get (v)
6298 && ipa_node_params_sum->get (v)->node_dead)
6299 fprintf (dump_file, " Marking node as dead: %s.\n",
6300 v->dump_name ());
6301 }
6302 }
6303
6304 /* The decision stage. Iterate over the topological order of call graph nodes
6305 TOPO and make specialized clones if deemed beneficial. */
6306
6307 static void
6308 ipcp_decision_stage (class ipa_topo_info *topo)
6309 {
6310 int i;
6311
6312 if (dump_file)
6313 fprintf (dump_file, "\nIPA decision stage:\n\n");
6314
6315 for (i = topo->nnodes - 1; i >= 0; i--)
6316 {
6317 struct cgraph_node *node = topo->order[i];
6318 bool change = false, iterate = true;
6319
6320 while (iterate)
6321 {
6322 struct cgraph_node *v;
6323 iterate = false;
6324 for (v = node; v; v = ((struct ipa_dfs_info *) v->aux)->next_cycle)
6325 if (v->has_gimple_body_p ()
6326 && ipcp_versionable_function_p (v))
6327 iterate |= decide_whether_version_node (v);
6328
6329 change |= iterate;
6330 }
6331 if (change)
6332 identify_dead_nodes (node);
6333 }
6334 }
6335
6336 /* Look up all VR and bits information that we have discovered and copy it
6337 over to the transformation summary. */
6338
6339 static void
6340 ipcp_store_vr_results (void)
6341 {
6342 cgraph_node *node;
6343
6344 FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
6345 {
6346 ipa_node_params *info = ipa_node_params_sum->get (node);
6347 bool dumped_sth = false;
6348 bool found_useful_result = false;
6349 bool do_vr = true;
6350 bool do_bits = true;
6351
6352 if (!info || !opt_for_fn (node->decl, flag_ipa_vrp))
6353 {
6354 if (dump_file)
6355 fprintf (dump_file, "Not considering %s for VR discovery "
6356 "and propagate; -fipa-ipa-vrp: disabled.\n",
6357 node->dump_name ());
6358 do_vr = false;
6359 }
6360 if (!info || !opt_for_fn (node->decl, flag_ipa_bit_cp))
6361 {
6362 if (dump_file)
6363 fprintf (dump_file, "Not considering %s for ipa bitwise "
6364 "propagation ; -fipa-bit-cp: disabled.\n",
6365 node->dump_name ());
6366 do_bits = false;
6367 }
6368 if (!do_bits && !do_vr)
6369 continue;
6370
6371 if (info->ipcp_orig_node)
6372 info = ipa_node_params_sum->get (info->ipcp_orig_node);
6373 if (info->lattices.is_empty ())
6374 /* Newly expanded artificial thunks do not have lattices. */
6375 continue;
6376
6377 unsigned count = ipa_get_param_count (info);
6378 for (unsigned i = 0; i < count; i++)
6379 {
6380 ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
6381 if (do_vr
6382 && !plats->m_value_range.bottom_p ()
6383 && !plats->m_value_range.top_p ())
6384 {
6385 found_useful_result = true;
6386 break;
6387 }
6388 if (do_bits && plats->bits_lattice.constant_p ())
6389 {
6390 found_useful_result = true;
6391 break;
6392 }
6393 }
6394 if (!found_useful_result)
6395 continue;
6396
6397 ipcp_transformation_initialize ();
6398 ipcp_transformation *ts = ipcp_transformation_sum->get_create (node);
6399 vec_safe_reserve_exact (ts->m_vr, count);
6400
6401 for (unsigned i = 0; i < count; i++)
6402 {
6403 ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
6404 ipcp_bits_lattice *bits = NULL;
6405
6406 if (do_bits
6407 && plats->bits_lattice.constant_p ()
6408 && dbg_cnt (ipa_cp_bits))
6409 bits = &plats->bits_lattice;
6410
6411 if (do_vr
6412 && !plats->m_value_range.bottom_p ()
6413 && !plats->m_value_range.top_p ()
6414 && dbg_cnt (ipa_cp_vr))
6415 {
6416 if (bits)
6417 {
6418 value_range tmp = plats->m_value_range.m_vr;
6419 tree type = ipa_get_type (info, i);
6420 irange_bitmask bm (wide_int::from (bits->get_value (),
6421 TYPE_PRECISION (type),
6422 TYPE_SIGN (type)),
6423 wide_int::from (bits->get_mask (),
6424 TYPE_PRECISION (type),
6425 TYPE_SIGN (type)));
6426 tmp.update_bitmask (bm);
6427 // Reflecting the bitmask on the ranges can sometime
6428 // produce an UNDEFINED value if the the bitmask update
6429 // was previously deferred. See PR 120048.
6430 if (tmp.undefined_p ())
6431 tmp.set_varying (type);
6432 ipa_vr vr (tmp);
6433 ts->m_vr->quick_push (vr);
6434 }
6435 else
6436 {
6437 ipa_vr vr (plats->m_value_range.m_vr);
6438 ts->m_vr->quick_push (vr);
6439 }
6440 }
6441 else if (bits)
6442 {
6443 tree type = ipa_get_type (info, i);
6444 value_range tmp;
6445 tmp.set_varying (type);
6446 irange_bitmask bm (wide_int::from (bits->get_value (),
6447 TYPE_PRECISION (type),
6448 TYPE_SIGN (type)),
6449 wide_int::from (bits->get_mask (),
6450 TYPE_PRECISION (type),
6451 TYPE_SIGN (type)));
6452 tmp.update_bitmask (bm);
6453 // Reflecting the bitmask on the ranges can sometime
6454 // produce an UNDEFINED value if the the bitmask update
6455 // was previously deferred. See PR 120048.
6456 if (tmp.undefined_p ())
6457 tmp.set_varying (type);
6458 ipa_vr vr (tmp);
6459 ts->m_vr->quick_push (vr);
6460 }
6461 else
6462 {
6463 ipa_vr vr;
6464 ts->m_vr->quick_push (vr);
6465 }
6466
6467 if (!dump_file || !bits)
6468 continue;
6469
6470 if (!dumped_sth)
6471 {
6472 fprintf (dump_file, "Propagated bits info for function %s:\n",
6473 node->dump_name ());
6474 dumped_sth = true;
6475 }
6476 fprintf (dump_file, " param %i: value = ", i);
6477 ipcp_print_widest_int (dump_file, bits->get_value ());
6478 fprintf (dump_file, ", mask = ");
6479 ipcp_print_widest_int (dump_file, bits->get_mask ());
6480 fprintf (dump_file, "\n");
6481 }
6482 }
6483 }
6484
6485 /* The IPCP driver. */
6486
6487 static unsigned int
6488 ipcp_driver (void)
6489 {
6490 class ipa_topo_info topo;
6491
6492 if (edge_clone_summaries == NULL)
6493 edge_clone_summaries = new edge_clone_summary_t (symtab);
6494
6495 ipa_check_create_node_params ();
6496 ipa_check_create_edge_args ();
6497 clone_num_suffixes = new hash_map<const char *, unsigned>;
6498
6499 if (dump_file)
6500 {
6501 fprintf (dump_file, "\nIPA structures before propagation:\n");
6502 if (dump_flags & TDF_DETAILS)
6503 ipa_print_all_params (dump_file);
6504 ipa_print_all_jump_functions (dump_file);
6505 }
6506
6507 /* Topological sort. */
6508 build_toporder_info (&topo);
6509 /* Do the interprocedural propagation. */
6510 ipcp_propagate_stage (&topo);
6511 /* Decide what constant propagation and cloning should be performed. */
6512 ipcp_decision_stage (&topo);
6513 /* Store results of value range and bits propagation. */
6514 ipcp_store_vr_results ();
6515
6516 /* Free all IPCP structures. */
6517 delete clone_num_suffixes;
6518 free_toporder_info (&topo);
6519 delete edge_clone_summaries;
6520 edge_clone_summaries = NULL;
6521 ipa_free_all_structures_after_ipa_cp ();
6522 if (dump_file)
6523 fprintf (dump_file, "\nIPA constant propagation end\n");
6524 return 0;
6525 }
6526
6527 /* Initialization and computation of IPCP data structures. This is the initial
6528 intraprocedural analysis of functions, which gathers information to be
6529 propagated later on. */
6530
6531 static void
6532 ipcp_generate_summary (void)
6533 {
6534 struct cgraph_node *node;
6535
6536 if (dump_file)
6537 fprintf (dump_file, "\nIPA constant propagation start:\n");
6538 ipa_register_cgraph_hooks ();
6539
6540 FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
6541 ipa_analyze_node (node);
6542 }
6543
6544 namespace {
6545
6546 const pass_data pass_data_ipa_cp =
6547 {
6548 IPA_PASS, /* type */
6549 "cp", /* name */
6550 OPTGROUP_NONE, /* optinfo_flags */
6551 TV_IPA_CONSTANT_PROP, /* tv_id */
6552 0, /* properties_required */
6553 0, /* properties_provided */
6554 0, /* properties_destroyed */
6555 0, /* todo_flags_start */
6556 ( TODO_dump_symtab | TODO_remove_functions ), /* todo_flags_finish */
6557 };
6558
6559 class pass_ipa_cp : public ipa_opt_pass_d
6560 {
6561 public:
6562 pass_ipa_cp (gcc::context *ctxt)
6563 : ipa_opt_pass_d (pass_data_ipa_cp, ctxt,
6564 ipcp_generate_summary, /* generate_summary */
6565 NULL, /* write_summary */
6566 NULL, /* read_summary */
6567 ipcp_write_transformation_summaries, /*
6568 write_optimization_summary */
6569 ipcp_read_transformation_summaries, /*
6570 read_optimization_summary */
6571 NULL, /* stmt_fixup */
6572 0, /* function_transform_todo_flags_start */
6573 ipcp_transform_function, /* function_transform */
6574 NULL) /* variable_transform */
6575 {}
6576
6577 /* opt_pass methods: */
6578 bool gate (function *) final override
6579 {
6580 /* FIXME: We should remove the optimize check after we ensure we never run
6581 IPA passes when not optimizing. */
6582 return (flag_ipa_cp && optimize) || in_lto_p;
6583 }
6584
6585 unsigned int execute (function *) final override { return ipcp_driver (); }
6586
6587 }; // class pass_ipa_cp
6588
6589 } // anon namespace
6590
6591 ipa_opt_pass_d *
6592 make_pass_ipa_cp (gcc::context *ctxt)
6593 {
6594 return new pass_ipa_cp (ctxt);
6595 }
6596
6597 /* Reset all state within ipa-cp.cc so that we can rerun the compiler
6598 within the same process. For use by toplev::finalize. */
6599
6600 void
6601 ipa_cp_cc_finalize (void)
6602 {
6603 base_count = profile_count::uninitialized ();
6604 overall_size = 0;
6605 orig_overall_size = 0;
6606 ipcp_free_transformation_sum ();
6607 }
6608
6609 /* Given PARAM which must be a parameter of function FNDECL described by THIS,
6610 return its index in the DECL_ARGUMENTS chain, using a pre-computed
6611 DECL_UID-sorted vector if available (which is pre-computed only if there are
6612 many parameters). Can return -1 if param is static chain not represented
6613 among DECL_ARGUMENTS. */
6614
6615 int
6616 ipcp_transformation::get_param_index (const_tree fndecl, const_tree param) const
6617 {
6618 gcc_assert (TREE_CODE (param) == PARM_DECL);
6619 if (m_uid_to_idx)
6620 {
6621 unsigned puid = DECL_UID (param);
6622 const ipa_uid_to_idx_map_elt *res
6623 = std::lower_bound (m_uid_to_idx->begin(), m_uid_to_idx->end (), puid,
6624 [] (const ipa_uid_to_idx_map_elt &elt, unsigned uid)
6625 {
6626 return elt.uid < uid;
6627 });
6628 if (res == m_uid_to_idx->end ()
6629 || res->uid != puid)
6630 {
6631 gcc_assert (DECL_STATIC_CHAIN (fndecl));
6632 return -1;
6633 }
6634 return res->index;
6635 }
6636
6637 unsigned index = 0;
6638 for (tree p = DECL_ARGUMENTS (fndecl); p; p = DECL_CHAIN (p), index++)
6639 if (p == param)
6640 return (int) index;
6641
6642 gcc_assert (DECL_STATIC_CHAIN (fndecl));
6643 return -1;
6644 }
6645
6646 /* Helper function to qsort a vector of ipa_uid_to_idx_map_elt elements
6647 according to the uid. */
6648
6649 static int
6650 compare_uids (const void *a, const void *b)
6651 {
6652 const ipa_uid_to_idx_map_elt *e1 = (const ipa_uid_to_idx_map_elt *) a;
6653 const ipa_uid_to_idx_map_elt *e2 = (const ipa_uid_to_idx_map_elt *) b;
6654 if (e1->uid < e2->uid)
6655 return -1;
6656 if (e1->uid > e2->uid)
6657 return 1;
6658 gcc_unreachable ();
6659 }
6660
6661 /* Assuming THIS describes FNDECL and it has sufficiently many parameters to
6662 justify the overhead, create a DECL_UID-sorted vector to speed up mapping
6663 from parameters to their indices in DECL_ARGUMENTS chain. */
6664
6665 void
6666 ipcp_transformation::maybe_create_parm_idx_map (tree fndecl)
6667 {
6668 int c = count_formal_params (fndecl);
6669 if (c < 32)
6670 return;
6671
6672 m_uid_to_idx = NULL;
6673 vec_safe_reserve (m_uid_to_idx, c, true);
6674 unsigned index = 0;
6675 for (tree p = DECL_ARGUMENTS (fndecl); p; p = DECL_CHAIN (p), index++)
6676 {
6677 ipa_uid_to_idx_map_elt elt;
6678 elt.uid = DECL_UID (p);
6679 elt.index = index;
6680 m_uid_to_idx->quick_push (elt);
6681 }
6682 m_uid_to_idx->qsort (compare_uids);
6683 }