Debian Codegraph @

gcc/lto/lto-partition.cc

raw
1 /* LTO partitioning logic routines.
2 Copyright (C) 2009-2025 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
19
20 #include "config.h"
21 #define INCLUDE_VECTOR
22 #include "system.h"
23 #include "coretypes.h"
24 #include "target.h"
25 #include "function.h"
26 #include "basic-block.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "alloc-pool.h"
30 #include "stringpool.h"
31 #include "cgraph.h"
32 #include "lto-streamer.h"
33 #include "symbol-summary.h"
34 #include "tree-vrp.h"
35 #include "sreal.h"
36 #include "ipa-cp.h"
37 #include "ipa-prop.h"
38 #include "ipa-fnsummary.h"
39 #include "lto-partition.h"
40 #include "ipa-locality-cloning.h"
41
42 #include <limits>
43
44 vec<ltrans_partition> ltrans_partitions;
45
46 static void add_symbol_to_partition (ltrans_partition part, symtab_node *node);
47
48
49 /* Helper for qsort; compare partitions and return one with smaller order. */
50
51 static int
52 cmp_partitions_order (const void *a, const void *b)
53 {
54 const struct ltrans_partition_def *pa
55 = *(struct ltrans_partition_def *const *)a;
56 const struct ltrans_partition_def *pb
57 = *(struct ltrans_partition_def *const *)b;
58 int ordera = -1, orderb = -1;
59
60 if (lto_symtab_encoder_size (pa->encoder))
61 ordera = lto_symtab_encoder_deref (pa->encoder, 0)->order;
62 if (lto_symtab_encoder_size (pb->encoder))
63 orderb = lto_symtab_encoder_deref (pb->encoder, 0)->order;
64 return orderb - ordera;
65 }
66
67 /* Create new partition with name NAME.
68 Does not push into ltrans_partitions. */
69 static ltrans_partition
70 new_partition_no_push (const char *name)
71 {
72 ltrans_partition part = XCNEW (struct ltrans_partition_def);
73 part->encoder = lto_symtab_encoder_new (false);
74 part->name = name;
75 part->insns = 0;
76 part->symbols = 0;
77 return part;
78 }
79
80 /* Create new partition with name NAME. */
81
82 static ltrans_partition
83 new_partition (const char *name)
84 {
85 ltrans_partition part = new_partition_no_push (name);
86 ltrans_partitions.safe_push (part);
87 return part;
88 }
89
90 /* Free memory used by ltrans partition.
91 Encoder can be kept to be freed after streaming. */
92 static void
93 free_ltrans_partition (ltrans_partition part, bool delete_encoder)
94 {
95 if (part->initializers_visited)
96 delete part->initializers_visited;
97 if (delete_encoder)
98 lto_symtab_encoder_delete (part->encoder);
99 free (part);
100 }
101
102 /* Free memory used by ltrans datastructures. */
103
104 void
105 free_ltrans_partitions (void)
106 {
107 unsigned int idx;
108 ltrans_partition part;
109 for (idx = 0; ltrans_partitions.iterate (idx, &part); idx++)
110 free_ltrans_partition (part, false);
111 ltrans_partitions.release ();
112 }
113
114 /* Return true if symbol is already in some partition. */
115
116 static inline bool
117 symbol_partitioned_p (symtab_node *node)
118 {
119 return node->aux;
120 }
121
122 /* Add references into the partition. */
123 static void
124 add_references_to_partition (ltrans_partition part, symtab_node *node)
125 {
126 int i;
127 struct ipa_ref *ref = NULL;
128
129 /* Add all duplicated references to the partition. */
130 for (i = 0; node->iterate_reference (i, ref); i++)
131 if (ref->referred->get_partitioning_class () == SYMBOL_DUPLICATE)
132 add_symbol_to_partition (part, ref->referred);
133 /* References to a readonly variable may be constant foled into its value.
134 Recursively look into the initializers of the constant variable and add
135 references, too. */
136 else if (is_a <varpool_node *> (ref->referred)
137 && (dyn_cast <varpool_node *> (ref->referred)
138 ->ctor_useable_for_folding_p ())
139 && !lto_symtab_encoder_in_partition_p (part->encoder, ref->referred))
140 {
141 if (!part->initializers_visited)
142 part->initializers_visited = new hash_set<symtab_node *>;
143 if (!part->initializers_visited->add (ref->referred))
144 add_references_to_partition (part, ref->referred);
145 }
146 }
147
148 /* Helper function for add_symbol_to_partition doing the actual dirty work
149 of adding NODE to PART. */
150
151 static bool
152 add_symbol_to_partition_1 (ltrans_partition part, symtab_node *node)
153 {
154 enum symbol_partitioning_class c = node->get_partitioning_class ();
155 struct ipa_ref *ref;
156 symtab_node *node1;
157
158 /* If NODE is already there, we have nothing to do. */
159 if (lto_symtab_encoder_in_partition_p (part->encoder, node))
160 return true;
161
162 /* non-duplicated aliases or tunks of a duplicated symbol needs to be output
163 just once.
164
165 Be lax about comdats; they may or may not be duplicated and we may
166 end up in need to duplicate keyed comdat because it has unkeyed alias. */
167 if (c == SYMBOL_PARTITION && !DECL_COMDAT (node->decl)
168 && symbol_partitioned_p (node))
169 return false;
170
171 /* Be sure that we never try to duplicate partitioned symbol
172 or add external symbol. */
173 gcc_assert (c != SYMBOL_EXTERNAL
174 && (c == SYMBOL_DUPLICATE || !symbol_partitioned_p (node)));
175
176 part->symbols++;
177
178 lto_set_symtab_encoder_in_partition (part->encoder, node);
179
180 if (symbol_partitioned_p (node))
181 {
182 node->in_other_partition = 1;
183 if (dump_file)
184 fprintf (dump_file,
185 "Symbol node %s now used in multiple partitions\n",
186 node->dump_name ());
187 }
188 node->aux = (void *)((size_t)node->aux + 1);
189
190 if (cgraph_node *cnode = dyn_cast <cgraph_node *> (node))
191 {
192 struct cgraph_edge *e;
193 if (!node->alias && c == SYMBOL_PARTITION)
194 part->insns += ipa_size_summaries->get (cnode)->size;
195
196 /* Add all inline clones and callees that are duplicated. */
197 for (e = cnode->callees; e; e = e->next_callee)
198 if (!e->inline_failed)
199 add_symbol_to_partition_1 (part, e->callee);
200 else if (e->callee->get_partitioning_class () == SYMBOL_DUPLICATE)
201 add_symbol_to_partition (part, e->callee);
202
203 /* Add all thunks associated with the function. */
204 for (e = cnode->callers; e; e = e->next_caller)
205 if (e->caller->thunk && !e->caller->inlined_to)
206 add_symbol_to_partition_1 (part, e->caller);
207 }
208
209 add_references_to_partition (part, node);
210
211 /* Add all aliases associated with the symbol. */
212
213 FOR_EACH_ALIAS (node, ref)
214 if (!ref->referring->transparent_alias)
215 add_symbol_to_partition_1 (part, ref->referring);
216 else
217 {
218 struct ipa_ref *ref2;
219 /* We do not need to add transparent aliases if they are not used.
220 However we must add aliases of transparent aliases if they exist. */
221 FOR_EACH_ALIAS (ref->referring, ref2)
222 {
223 /* Nested transparent aliases are not permitted. */
224 gcc_checking_assert (!ref2->referring->transparent_alias);
225 add_symbol_to_partition_1 (part, ref2->referring);
226 }
227 }
228
229 /* Ensure that SAME_COMDAT_GROUP lists all allways added in a group. */
230 if (node->same_comdat_group)
231 for (node1 = node->same_comdat_group;
232 node1 != node; node1 = node1->same_comdat_group)
233 if (!node->alias)
234 {
235 bool added = add_symbol_to_partition_1 (part, node1);
236 gcc_assert (added);
237 }
238 return true;
239 }
240
241 /* If symbol NODE is really part of other symbol's definition (i.e. it is
242 internal label, thunk, alias or so), return the outer symbol.
243 When add_symbol_to_partition_1 is called on the outer symbol it must
244 eventually add NODE, too. */
245 static symtab_node *
246 contained_in_symbol (symtab_node *node)
247 {
248 /* There is no need to consider transparent aliases to be part of the
249 definition: they are only useful insite the partition they are output
250 and thus we will always see an explicit reference to it. */
251 if (node->transparent_alias)
252 return node;
253 if (cgraph_node *cnode = dyn_cast <cgraph_node *> (node))
254 {
255 cnode = cnode->function_symbol ();
256 if (cnode->inlined_to)
257 cnode = cnode->inlined_to;
258 return cnode;
259 }
260 else if (varpool_node *vnode = dyn_cast <varpool_node *> (node))
261 return vnode->ultimate_alias_target ();
262 return node;
263 }
264
265 /* Add symbol NODE to partition. When definition of NODE is part
266 of other symbol definition, add the other symbol, too. */
267
268 static void
269 add_symbol_to_partition (ltrans_partition part, symtab_node *node)
270 {
271 symtab_node *node1;
272
273 /* Verify that we do not try to duplicate something that cannot be. */
274 gcc_checking_assert (node->get_partitioning_class () == SYMBOL_DUPLICATE
275 || !symbol_partitioned_p (node));
276
277 while ((node1 = contained_in_symbol (node)) != node)
278 node = node1;
279
280 /* If we have duplicated symbol contained in something we cannot duplicate,
281 we are very badly screwed. The other way is possible, so we do not
282 assert this in add_symbol_to_partition_1.
283
284 Be lax about comdats; they may or may not be duplicated and we may
285 end up in need to duplicate keyed comdat because it has unkeyed alias. */
286
287 gcc_assert (node->get_partitioning_class () == SYMBOL_DUPLICATE
288 || DECL_COMDAT (node->decl)
289 || !symbol_partitioned_p (node));
290
291 add_symbol_to_partition_1 (part, node);
292 }
293
294 /* Undo all additions until number of cgraph nodes in PARITION is N_CGRAPH_NODES
295 and number of varpool nodes is N_VARPOOL_NODES. */
296
297 static void
298 undo_partition (ltrans_partition partition, unsigned int n_nodes)
299 {
300 while (lto_symtab_encoder_size (partition->encoder) > (int)n_nodes)
301 {
302 symtab_node *node = lto_symtab_encoder_deref (partition->encoder,
303 n_nodes);
304 partition->symbols--;
305 cgraph_node *cnode;
306
307 /* After UNDO we no longer know what was visited. */
308 if (partition->initializers_visited)
309 delete partition->initializers_visited;
310 partition->initializers_visited = NULL;
311
312 if (!node->alias && (cnode = dyn_cast <cgraph_node *> (node))
313 && node->get_partitioning_class () == SYMBOL_PARTITION)
314 partition->insns -= ipa_size_summaries->get (cnode)->size;
315 lto_symtab_encoder_delete_node (partition->encoder, node);
316 node->aux = (void *)((size_t)node->aux - 1);
317 }
318 }
319
320 /* Group cgrah nodes by input files. This is used mainly for testing
321 right now. */
322
323 void
324 lto_1_to_1_map (void)
325 {
326 symtab_node *node;
327 struct lto_file_decl_data *file_data;
328 hash_map<lto_file_decl_data *, ltrans_partition> pmap;
329 ltrans_partition partition;
330 int npartitions = 0;
331
332 FOR_EACH_SYMBOL (node)
333 {
334 if (node->get_partitioning_class () != SYMBOL_PARTITION
335 || symbol_partitioned_p (node))
336 continue;
337
338 file_data = node->lto_file_data;
339
340 if (file_data)
341 {
342 ltrans_partition *slot = &pmap.get_or_insert (file_data);
343 if (*slot)
344 partition = *slot;
345 else
346 {
347 partition = new_partition (file_data->file_name);
348 *slot = partition;
349 npartitions++;
350 }
351 }
352 else if (!file_data && ltrans_partitions.length ())
353 partition = ltrans_partitions[0];
354 else
355 {
356 partition = new_partition ("");
357 npartitions++;
358 }
359
360 add_symbol_to_partition (partition, node);
361 }
362
363 /* If the cgraph is empty, create one cgraph node set so that there is still
364 an output file for any variables that need to be exported in a DSO. */
365 if (!npartitions)
366 new_partition ("empty");
367
368 /* Order partitions by order of symbols because they are linked into binary
369 that way. */
370 ltrans_partitions.qsort (cmp_partitions_order);
371 }
372
373 /* Maximal partitioning. Put every new symbol into new partition if possible. */
374
375 void
376 lto_max_map (void)
377 {
378 symtab_node *node;
379 ltrans_partition partition;
380 int npartitions = 0;
381
382 FOR_EACH_SYMBOL (node)
383 {
384 if (node->get_partitioning_class () != SYMBOL_PARTITION
385 || symbol_partitioned_p (node))
386 continue;
387 partition = new_partition (node->asm_name ());
388 add_symbol_to_partition (partition, node);
389 npartitions++;
390 }
391 if (!npartitions)
392 new_partition ("empty");
393 }
394
395 /* Helper function for qsort; sort nodes by order. */
396 static int
397 node_cmp (const void *pa, const void *pb)
398 {
399 const symtab_node *a = *static_cast<const symtab_node * const *> (pa);
400 const symtab_node *b = *static_cast<const symtab_node * const *> (pb);
401 return b->order - a->order;
402 }
403
404 /* Add all symtab nodes from NEXT_NODE to PARTITION in order. */
405
406 static void
407 add_sorted_nodes (vec<symtab_node *> &next_nodes, ltrans_partition partition)
408 {
409 unsigned i;
410 symtab_node *node;
411
412 next_nodes.qsort (node_cmp);
413 FOR_EACH_VEC_ELT (next_nodes, i, node)
414 if (!symbol_partitioned_p (node))
415 add_symbol_to_partition (partition, node);
416 }
417
418 /* Return true if we should account reference from N1 to N2 in cost
419 of partition boundary. */
420
421 bool
422 account_reference_p (symtab_node *n1, symtab_node *n2)
423 {
424 if (cgraph_node *cnode = dyn_cast <cgraph_node *> (n1))
425 n1 = cnode;
426 /* Do not account references from aliases - they are never split across
427 partitions. */
428 if (n1->alias)
429 return false;
430 /* Do not account recursion - the code below will handle it incorrectly
431 otherwise. Do not account references to external symbols: they will
432 never become local. Finally do not account references to duplicated
433 symbols: they will be always local. */
434 if (n1 == n2
435 || !n2->definition
436 || n2->get_partitioning_class () != SYMBOL_PARTITION)
437 return false;
438 /* If referring node is external symbol do not account it to boundary
439 cost. Those are added into units only to enable possible constant
440 folding and devirtulization.
441
442 Here we do not know if it will ever be added to some partition
443 (this is decided by compute_ltrans_boundary) and second it is not
444 that likely that constant folding will actually use the reference. */
445 if (contained_in_symbol (n1)
446 ->get_partitioning_class () == SYMBOL_EXTERNAL)
447 return false;
448 return true;
449 }
450
451 /* Joins two partitions into one.
452 NULL partitions are equivalent to empty partition.
453 If both partition are non-null, symbols from FROM are added into INTO. */
454 static ltrans_partition
455 join_partitions (ltrans_partition into, ltrans_partition from)
456 {
457 if (!into)
458 return from;
459 if (!from)
460 return into;
461
462 lto_symtab_encoder_iterator lsei;
463 lto_symtab_encoder_t encoder = from->encoder;
464
465 /* If aux is non zero, it will not be added to the new partition. Since
466 adding symbols is recursive, it is safer to reduce aux of all symbols
467 before adding any symbols to other partition. */
468 for (lsei = lsei_start (encoder); !lsei_end_p (lsei); lsei_next (&lsei))
469 {
470 symtab_node *node = lsei_node (lsei);
471 node->aux = (void *)((size_t)node->aux - 1);
472 }
473
474 for (lsei = lsei_start (encoder); !lsei_end_p (lsei); lsei_next (&lsei))
475 {
476 symtab_node *node = lsei_node (lsei);
477
478 if (symbol_partitioned_p (node))
479 continue;
480
481 add_symbol_to_partition (into, node);
482 }
483
484 free_ltrans_partition (from, true);
485
486 return into;
487 }
488
489 /* Takes symbols from given partitions and splits them into N partitions where
490 each partitions contains one symbol and its requirements. */
491 static std::vector<ltrans_partition>
492 split_partition_into_nodes (ltrans_partition part)
493 {
494 std::vector<ltrans_partition> partitions;
495
496 lto_symtab_encoder_iterator lsei;
497 lto_symtab_encoder_t encoder = part->encoder;
498
499 for (lsei = lsei_start (encoder); !lsei_end_p (lsei); lsei_next (&lsei))
500 {
501 symtab_node *node = lsei_node (lsei);
502 node->aux = (void *)((size_t)node->aux - 1);
503 }
504
505 for (lsei = lsei_start (encoder); !lsei_end_p (lsei); lsei_next (&lsei))
506 {
507 symtab_node *node = lsei_node (lsei);
508
509 if (node->get_partitioning_class () != SYMBOL_PARTITION
510 || symbol_partitioned_p (node))
511 continue;
512
513 ltrans_partition new_part = new_partition_no_push (part->name);
514 add_symbol_to_partition (new_part, node);
515 partitions.push_back (new_part);
516 }
517
518 return partitions;
519 }
520
521 /* Returns whether partition contains symbols that cannot be reordered. */
522 static bool
523 is_partition_reorder (ltrans_partition part)
524 {
525 lto_symtab_encoder_iterator lsei;
526 lto_symtab_encoder_t encoder = part->encoder;
527
528 for (lsei = lsei_start (encoder); !lsei_end_p (lsei); lsei_next (&lsei))
529 {
530 symtab_node *node = lsei_node (lsei);
531 if (node->no_reorder)
532 return false;
533 }
534 return true;
535 }
536
537 /* Represents groups of symbols, that should be partitioned into n_partitions
538 partitions. */
539 class partition_set
540 {
541 public:
542 /* Metadata to easily pass copy to new partition_set. */
543 class metadata
544 {
545 public:
546 /* Partitions can be reordered. */
547 bool reorder;
548 /* Partitions can be split into individual symbols. */
549 bool splitable;
550
551 metadata (bool reorder, bool splitable):
552 reorder (reorder), splitable (splitable)
553 {}
554 };
555 metadata data;
556
557 /* Symbol groups. Use push (g) to insert symbols. */
558 std::vector<ltrans_partition> sym_groups;
559 /* Number of partitions these symbols should be partitioned into. */
560 size_t n_partitions;
561 /* Total number of instructions of all symbols. */
562 int64_t insns;
563
564 /* Constructor. Symbols and n_partitions can be added later. */
565 partition_set (metadata data, std::vector<ltrans_partition> sym_groups = {},
566 size_t n_partitions = 0)
567 : data (data), sym_groups (std::move (sym_groups)),
568 n_partitions (n_partitions), insns (0)
569 {
570 for (ltrans_partition g: this->sym_groups)
571 insns += g->insns;
572 }
573
574 /* Adds symbol group and updates total insns. */
575 void
576 push (ltrans_partition g)
577 {
578 sym_groups.push_back (g);
579 insns += g->insns;
580 }
581
582 /* Returns whether any symbols group is contained. */
583 bool
584 empty ()
585 {
586 return sym_groups.empty ();
587 }
588 };
589
590 /* Distributes total n_partitions among partition_sets.
591 Aims to be as fair as possible. */
592 static void
593 distribute_n_partitions (std::vector<partition_set>& ps, size_t n_partitions)
594 {
595 gcc_assert (ps.size ());
596 gcc_assert (ps.size () <= n_partitions);
597
598 int64_t total_size = 0;
599
600 for (partition_set& p: ps)
601 {
602 total_size += p.insns;
603 p.n_partitions = 0;
604 }
605
606 if (total_size <= 0)
607 total_size = 1;
608
609 size_t n_partitions_allocated = 0;
610
611 /* First we allocate largest amount of partitions so that target_sizes are
612 larger than target size of total (insns/total_size).
613 All partition_set must have n_partitions at least one. */
614 for (partition_set& p: ps)
615 {
616 p.n_partitions = n_partitions * p.insns / total_size;
617 if (p.n_partitions == 0 && p.sym_groups.size ())
618 p.n_partitions = 1;
619 if (!p.data.splitable)
620 p.n_partitions = std::min (p.n_partitions, p.sym_groups.size ());
621
622 n_partitions_allocated += p.n_partitions;
623 }
624
625 /* Rare special case, with a lot of initially 0 sized splits. */
626 while (n_partitions_allocated > n_partitions)
627 {
628 size_t idx = 0;
629 int64_t min = std::numeric_limits<int64_t>::max ();
630
631 for (size_t i = 0; i < ps.size (); ++i)
632 {
633 if (ps[i].n_partitions <= 1)
634 continue;
635
636 int64_t target_size = ps[i].insns / ps[i].n_partitions;
637 if (min > target_size)
638 {
639 min = target_size;
640 idx = i;
641 }
642 }
643
644 ps[idx].n_partitions--;
645 n_partitions_allocated--;
646 }
647
648 /* Typical case where with any increase of n_partitions target size will cross
649 total target size. We optimize for minimal:
650 (old_target_size - total_target_size)
651 - (total_target_size - new_target_size). */
652 while (n_partitions_allocated < n_partitions)
653 {
654 size_t idx = 0;
655 int64_t max = 0;
656
657 for (size_t i = 0; i < ps.size (); ++i)
658 {
659 if (ps[i].sym_groups.size () <= 1 && !ps[i].data.splitable)
660 continue;
661
662 int64_t target_size = ps[i].insns / ps[i].n_partitions;
663 int64_t new_target_size = ps[i].insns / (ps[i].n_partitions + 1);
664
665 int64_t positive_change = target_size + new_target_size;
666
667 if (max < positive_change)
668 {
669 max = positive_change;
670 idx = i;
671 }
672 }
673
674 ps[idx].n_partitions++;
675 n_partitions_allocated++;
676 }
677 }
678
679 /* Splits off symbol groups that are larger than target size.
680 n_partitions are then distributed between individual
681 split off symbol groups, and everything else as a whole.
682
683 Split off symbol groups with n_partitions > 1, are
684 then split into individual symbols.
685
686 Order is not conserved. This pass is ignored if reorder is not allowed. */
687 static std::vector<partition_set>
688 partition_over_target_split (partition_set& p)
689 {
690 gcc_assert (p.n_partitions >= 1);
691
692 std::vector<partition_set> all;
693 partition_set small (p.data);
694
695 int64_t target_size = p.insns / p.n_partitions;
696
697 for (ltrans_partition g: p.sym_groups)
698 {
699 if (g->insns > target_size
700 && (p.data.reorder || is_partition_reorder (g)))
701 all.push_back (partition_set (p.data, {g}));
702 else
703 small.push (g);
704 }
705
706 if (all.empty ())
707 return {};
708
709 if (small.sym_groups.size ())
710 {
711 /* Handles special case where n_partitions might be smaller than
712 all.size (). Which can happen as result of interger division or with
713 0 sized partition_sets. Then also prevents too small symbol group.
714 This should also be a special case; more common one,
715 but with no correctness problems. */
716 if (all.size () && (
717 small.insns < (int64_t) p.n_partitions
718 || small.insns < target_size * 0.6
719 || small.insns < param_min_partition_size))
720 {
721 size_t idx = 0;
722 int64_t min_insns = std::numeric_limits<int64_t>::max ();
723 for (size_t i = 0; i < all.size (); ++i)
724 {
725 if (all[i].insns < min_insns)
726 {
727 min_insns = all[i].insns;
728 idx = i;
729 }
730 }
731
732 gcc_assert (all[idx].sym_groups.size () == 1);
733
734 ltrans_partition& into = all[idx].sym_groups[0];
735 for (ltrans_partition g: small.sym_groups)
736 into = join_partitions (into, g);
737
738 all[idx].insns = into->insns;
739 }
740 else
741 {
742 gcc_assert (all.size () < p.n_partitions);
743 all.push_back (std::move (small));
744 }
745 }
746
747 distribute_n_partitions (all, p.n_partitions);
748
749 for (partition_set& p: all)
750 {
751 gcc_assert (p.sym_groups.size ());
752
753 /* Handles large symbol groups (large files) that will be
754 further divided. */
755 if (p.sym_groups.size () == 1 && p.n_partitions > 1)
756 {
757 p.sym_groups = split_partition_into_nodes (p.sym_groups[0]);
758 p.data.reorder = false;
759 p.data.splitable = false;
760 }
761 }
762
763 return all;
764 }
765
766 /* Splits partition_set into two partition_sets with
767 equal or off by one n_partitions.
768 Order is conserved. */
769 static std::vector<partition_set>
770 partition_binary_split (partition_set& p)
771 {
772 gcc_assert (p.n_partitions > 1);
773
774 if (p.sym_groups.size () < 2)
775 return {};
776
777 int64_t target_size = p.insns / p.n_partitions;
778
779
780 std::vector<partition_set> result (2, partition_set (p.data));
781 partition_set& first = result[0];
782 partition_set& second = result[1];
783
784 first.n_partitions = p.n_partitions/2;
785 second.n_partitions = p.n_partitions - first.n_partitions;
786
787 int64_t first_target_size = first.n_partitions * target_size;
788
789 int64_t insns = 0;
790 for (ltrans_partition g: p.sym_groups)
791 {
792 /* We want at least one symbol in first partition. */
793 if (first.empty ())
794 first.push (g);
795 else if (insns < first_target_size)
796 {
797 if (insns + g->insns < first_target_size)
798 first.push (g);
799 else
800 {
801 /* Target splitting point is in this symbol group. */
802 int64_t diff_first = first_target_size - insns;
803 int64_t diff_second = (insns + g->insns) - first_target_size;
804
805 if (diff_first * second.n_partitions
806 > diff_second * first.n_partitions)
807 first.push (g);
808 else
809 second.push (g);
810 }
811 }
812 else
813 second.push (g);
814
815 insns += g->insns;
816 }
817
818 return result;
819 }
820
821 /* Split partition_set into 'into' partition_sets with equal or off by one
822 number of symbol groups. Sizes of symbol groups are ignored for deciding
823 where to split. n_partitions is then distributed among new partition_sets
824 based on their sizes.
825 Order in conserved. */
826 static std::vector<partition_set>
827 partition_fixed_split (partition_set& p, size_t into)
828 {
829 gcc_assert (into < p.n_partitions);
830
831 std::vector<partition_set> result;
832
833 for (size_t i = 0; i < into; ++i)
834 {
835 size_t begin = i * p.sym_groups.size () / into;
836 size_t end = (i + 1) * p.sym_groups.size () / into;
837
838 auto it = p.sym_groups.begin ();
839 result.push_back (partition_set (p.data, {it + begin, it + end}));
840 }
841
842 distribute_n_partitions (result, p.n_partitions);
843
844 return result;
845 }
846
847
848 /* Base implementation to inherit from for all Partitioners. */
849 class partitioner_base {
850 public:
851 /* Partitions sym_groups into n_partitions partitions inserted into
852 ltrans_partitions. */
853 void
854 apply (std::vector<ltrans_partition>& sym_groups, int n_partitions)
855 {
856 partition_set p (partition_set::metadata (true, true),
857 std::move (sym_groups), n_partitions);
858 split (p, 0);
859 }
860
861 protected:
862 partitioner_base (int64_t min_partition_size, int64_t max_partition_size):
863 min_partition_size (min_partition_size),
864 max_partition_size (max_partition_size)
865 {
866 gcc_assert (min_partition_size != 0);
867 gcc_assert (max_partition_size != 0);
868 }
869 virtual ~partitioner_base ()
870 {}
871
872 /* Joins all symbol groups into one finalized partition. */
873 void
874 finalize (partition_set& p)
875 {
876 ltrans_partition joined = NULL;
877
878 for (ltrans_partition g: p.sym_groups)
879 joined = join_partitions (joined, g);
880
881 if (joined)
882 ltrans_partitions.safe_push (joined);
883 }
884
885 /* Splits all partition_sets. */
886 void
887 split_list (std::vector<partition_set>& ps, uintptr_t state)
888 {
889 for (partition_set& p: ps)
890 split (p, state);
891 }
892
893 /* Handles common cases:
894 too large or small n_partitions, or n_partitions = 1.
895 And then calls split_state. */
896 void
897 split (partition_set& p, uintptr_t state)
898 {
899 size_t min_partitions = p.insns / max_partition_size + 1;
900 size_t max_partitions = p.insns / min_partition_size;
901 if (!p.data.splitable)
902 max_partitions = std::min (max_partitions, p.sym_groups.size ());
903
904 p.n_partitions = std::max (p.n_partitions, min_partitions);
905 p.n_partitions = std::min (p.n_partitions, max_partitions);
906
907 if (p.n_partitions <= 1)
908 return finalize (p);
909
910 split_state (p, state);
911 }
912
913 /* State machine for specific partitioner implementation. */
914 virtual void
915 split_state (partition_set& p, uintptr_t state) = 0;
916
917 int64_t min_partition_size, max_partition_size;
918 };
919
920
921 /* Partitioner combining fixed, over_target, and binary partitionings. */
922 class partitioner_default: public partitioner_base
923 {
924 public:
925 partitioner_default (int64_t min_partition_size, int64_t max_partition_size):
926 partitioner_base (min_partition_size, max_partition_size)
927 {}
928
929 private:
930 virtual void
931 split_state (partition_set& p, uintptr_t state)
932 {
933 const uintptr_t FIXED = 0;
934 const uintptr_t OVER_TARGET = 1;
935 const uintptr_t BINARY = 2;
936
937 std::vector<partition_set> ps;
938
939 switch (state)
940 {
941 case FIXED:
942 if (p.n_partitions > 64 && p.sym_groups.size () >= 4)
943 {
944 ps = partition_fixed_split (p, 4);
945 split_list (ps, OVER_TARGET);
946 break;
947 }
948
949 /* FALLTHROUGH */
950 case OVER_TARGET:
951 ps = partition_over_target_split (p);
952 if (!ps.empty ())
953 {
954 split_list (ps, BINARY);
955 break;
956 }
957
958 /* FALLTHROUGH */
959 case BINARY:
960 ps = partition_binary_split (p);
961 if (!ps.empty ())
962 {
963 split_list (ps, OVER_TARGET);
964 break;
965 }
966
967 /* FALLTHROUGH */
968 default:
969 finalize (p);
970 }
971 }
972 };
973
974 /* Group cgraph nodes into equally-sized partitions.
975 It tries to keep symbols from single source file together to minimize
976 propagation of divergence.
977
978 It starts with symbols already grouped by source files. If reasonably
979 possible it only either combines several files into one final partition,
980 or, if a file is large, split the file into several final partitions.
981
982 Intermediate representation is partition_set which contains set of
983 groups of symbols (each group corresponding to original source file) and
984 number of final partitions this partition_set should split into.
985
986 First partition_fixed_split splits partition_set into constant number of
987 partition_sets with equal number of symbols groups. If for example there
988 are 39 source files, the resulting partition_sets will contain 10, 10,
989 10, and 9 source files. This splitting intentionally ignores estimated
990 instruction counts to minimize propagation of divergence.
991
992 Second partition_over_target_split separates too large files and splits
993 them into individual symbols to be combined back into several smaller
994 files in next step.
995
996 Third partition_binary_split splits partition_set into two halves until
997 it should be split into only one final partition, at which point the
998 remaining symbols are joined into one final partition.
999 */
1000
1001 void
1002 lto_cache_map (int n_lto_partitions, int max_partition_size)
1003 {
1004 lto_1_to_1_map ();
1005
1006 std::vector<ltrans_partition> partitions;
1007 for (unsigned i = 0; i < ltrans_partitions.length (); ++i)
1008 {
1009 ltrans_partition part = ltrans_partitions[i];
1010 partitions.push_back (part);
1011 }
1012 ltrans_partitions.truncate (0);
1013
1014 partitioner_default partitioner = partitioner_default
1015 (param_min_partition_size, max_partition_size);
1016
1017 partitioner.apply (partitions, n_lto_partitions);
1018 }
1019
1020 /* Group cgraph nodes into equally-sized partitions.
1021
1022 The partitioning algorithm is simple: nodes are taken in predefined order.
1023 The order corresponds to the order we want functions to have in the final
1024 output. In the future this will be given by function reordering pass, but
1025 at the moment we use the topological order, which is a good approximation.
1026
1027 The goal is to partition this linear order into intervals (partitions) so
1028 that all the partitions have approximately the same size and the number of
1029 callgraph or IPA reference edges crossing boundaries is minimal.
1030
1031 This is a lot faster (O(n) in size of callgraph) than algorithms doing
1032 priority-based graph clustering that are generally O(n^2) and, since
1033 WHOPR is designed to make things go well across partitions, it leads
1034 to good results.
1035
1036 We compute the expected size of a partition as:
1037
1038 max (total_size / lto_partitions, min_partition_size)
1039
1040 We use dynamic expected size of partition so small programs are partitioned
1041 into enough partitions to allow use of multiple CPUs, while large programs
1042 are not partitioned too much. Creating too many partitions significantly
1043 increases the streaming overhead.
1044
1045 In the future, we would like to bound the maximal size of partitions so as
1046 to prevent the LTRANS stage from consuming too much memory. At the moment,
1047 however, the WPA stage is the most memory intensive for large benchmarks,
1048 since too many types and declarations are read into memory.
1049
1050 The function implements a simple greedy algorithm. Nodes are being added
1051 to the current partition until after 3/4 of the expected partition size is
1052 reached. Past this threshold, we keep track of boundary size (number of
1053 edges going to other partitions) and continue adding functions until after
1054 the current partition has grown to twice the expected partition size. Then
1055 the process is undone to the point where the minimal ratio of boundary size
1056 and in-partition calls was reached. */
1057
1058 void
1059 lto_balanced_map (int n_lto_partitions, int max_partition_size)
1060 {
1061 int n_varpool_nodes = 0, varpool_pos = 0, best_varpool_pos = 0;
1062 int best_noreorder_pos = 0;
1063 auto_vec <cgraph_node *> order (symtab->cgraph_count);
1064 auto_vec<cgraph_node *> noreorder;
1065 auto_vec<varpool_node *> varpool_order;
1066 struct cgraph_node *node;
1067 int64_t original_total_size, total_size = 0;
1068 int64_t partition_size;
1069 ltrans_partition partition;
1070 int last_visited_node = 0;
1071 varpool_node *vnode;
1072 int64_t cost = 0, internal = 0;
1073 unsigned int best_n_nodes = 0, best_i = 0;
1074 int64_t best_cost = -1, best_internal = 0, best_size = 0;
1075 int npartitions;
1076 int current_order = -1;
1077 int noreorder_pos = 0;
1078
1079 FOR_EACH_VARIABLE (vnode)
1080 gcc_assert (!vnode->aux);
1081
1082 FOR_EACH_DEFINED_FUNCTION (node)
1083 if (node->get_partitioning_class () == SYMBOL_PARTITION)
1084 {
1085 if (node->no_reorder)
1086 noreorder.safe_push (node);
1087 else
1088 order.safe_push (node);
1089 if (!node->alias)
1090 total_size += ipa_size_summaries->get (node)->size;
1091 }
1092
1093 original_total_size = total_size;
1094
1095 /* Streaming works best when the source units do not cross partition
1096 boundaries much. This is because importing function from a source
1097 unit tends to import a lot of global trees defined there. We should
1098 get better about minimizing the function bounday, but until that
1099 things works smoother if we order in source order. */
1100 order.qsort (tp_first_run_node_cmp);
1101 noreorder.qsort (node_cmp);
1102
1103 if (dump_file)
1104 {
1105 for (unsigned i = 0; i < order.length (); i++)
1106 fprintf (dump_file, "Balanced map symbol order:%s:%u\n",
1107 order[i]->dump_name (), order[i]->tp_first_run);
1108 for (unsigned i = 0; i < noreorder.length (); i++)
1109 fprintf (dump_file, "Balanced map symbol no_reorder:%s:%u\n",
1110 noreorder[i]->dump_name (), noreorder[i]->tp_first_run);
1111 }
1112
1113 /* Collect all variables that should not be reordered. */
1114 FOR_EACH_VARIABLE (vnode)
1115 if (vnode->get_partitioning_class () == SYMBOL_PARTITION
1116 && vnode->no_reorder)
1117 varpool_order.safe_push (vnode);
1118 n_varpool_nodes = varpool_order.length ();
1119 varpool_order.qsort (node_cmp);
1120
1121 /* Compute partition size and create the first partition. */
1122 if (param_min_partition_size > max_partition_size)
1123 fatal_error (input_location, "min partition size cannot be greater "
1124 "than max partition size");
1125
1126 partition_size = total_size / n_lto_partitions;
1127 if (partition_size < param_min_partition_size)
1128 partition_size = param_min_partition_size;
1129 npartitions = 1;
1130 partition = new_partition ("");
1131 if (dump_file)
1132 fprintf (dump_file, "Total unit size: %" PRId64 ", partition size: %" PRId64 "\n",
1133 total_size, partition_size);
1134
1135 auto_vec<symtab_node *> next_nodes;
1136
1137 for (unsigned i = 0; i < order.length (); i++)
1138 {
1139 if (symbol_partitioned_p (order[i]))
1140 continue;
1141
1142 current_order = order[i]->order;
1143
1144 /* Output noreorder and varpool in program order first. */
1145 next_nodes.truncate (0);
1146 while (varpool_pos < n_varpool_nodes
1147 && varpool_order[varpool_pos]->order < current_order)
1148 next_nodes.safe_push (varpool_order[varpool_pos++]);
1149 while (noreorder_pos < (int)noreorder.length ()
1150 && noreorder[noreorder_pos]->order < current_order)
1151 next_nodes.safe_push (noreorder[noreorder_pos++]);
1152 add_sorted_nodes (next_nodes, partition);
1153
1154 if (!symbol_partitioned_p (order[i]))
1155 add_symbol_to_partition (partition, order[i]);
1156
1157
1158 /* Once we added a new node to the partition, we also want to add
1159 all referenced variables unless they was already added into some
1160 earlier partition.
1161 add_symbol_to_partition adds possibly multiple nodes and
1162 variables that are needed to satisfy needs of ORDER[i].
1163 We remember last visited cgraph and varpool node from last iteration
1164 of outer loop that allows us to process every new addition.
1165
1166 At the same time we compute size of the boundary into COST. Every
1167 callgraph or IPA reference edge leaving the partition contributes into
1168 COST. Every edge inside partition was earlier computed as one leaving
1169 it and thus we need to subtract it from COST. */
1170 while (last_visited_node < lto_symtab_encoder_size (partition->encoder))
1171 {
1172 int j;
1173 struct ipa_ref *ref = NULL;
1174 symtab_node *snode = lto_symtab_encoder_deref (partition->encoder,
1175 last_visited_node);
1176
1177 if (cgraph_node *node = dyn_cast <cgraph_node *> (snode))
1178 {
1179 struct cgraph_edge *edge;
1180
1181
1182 last_visited_node++;
1183
1184 gcc_assert (node->definition || node->weakref);
1185
1186 /* Compute boundary cost of callgraph edges. */
1187 for (edge = node->callees; edge; edge = edge->next_callee)
1188 /* Inline edges will always end up local. */
1189 if (edge->inline_failed
1190 && account_reference_p (node, edge->callee))
1191 {
1192 int edge_cost = edge->frequency ();
1193 int index;
1194
1195 if (!edge_cost)
1196 edge_cost = 1;
1197 gcc_assert (edge_cost > 0);
1198 index = lto_symtab_encoder_lookup (partition->encoder,
1199 edge->callee);
1200 if (index != LCC_NOT_FOUND
1201 && index < last_visited_node - 1)
1202 cost -= edge_cost, internal += edge_cost;
1203 else
1204 cost += edge_cost;
1205 }
1206 for (edge = node->callers; edge; edge = edge->next_caller)
1207 if (edge->inline_failed
1208 && account_reference_p (edge->caller, node))
1209 {
1210 int edge_cost = edge->frequency ();
1211 int index;
1212
1213 gcc_assert (edge->caller->definition);
1214 if (!edge_cost)
1215 edge_cost = 1;
1216 gcc_assert (edge_cost > 0);
1217 index = lto_symtab_encoder_lookup (partition->encoder,
1218 edge->caller);
1219 if (index != LCC_NOT_FOUND
1220 && index < last_visited_node - 1)
1221 cost -= edge_cost, internal += edge_cost;
1222 else
1223 cost += edge_cost;
1224 }
1225 }
1226 else
1227 last_visited_node++;
1228
1229 /* Compute boundary cost of IPA REF edges and at the same time look into
1230 variables referenced from current partition and try to add them. */
1231 for (j = 0; snode->iterate_reference (j, ref); j++)
1232 if (!account_reference_p (snode, ref->referred))
1233 ;
1234 else if (is_a <varpool_node *> (ref->referred))
1235 {
1236 int index;
1237
1238 vnode = dyn_cast <varpool_node *> (ref->referred);
1239 if (!symbol_partitioned_p (vnode)
1240 && !vnode->no_reorder
1241 && vnode->get_partitioning_class () == SYMBOL_PARTITION)
1242 add_symbol_to_partition (partition, vnode);
1243 index = lto_symtab_encoder_lookup (partition->encoder,
1244 vnode);
1245 if (index != LCC_NOT_FOUND
1246 && index < last_visited_node - 1)
1247 cost--, internal++;
1248 else
1249 cost++;
1250 }
1251 else
1252 {
1253 int index;
1254
1255 node = dyn_cast <cgraph_node *> (ref->referred);
1256 index = lto_symtab_encoder_lookup (partition->encoder,
1257 node);
1258 if (index != LCC_NOT_FOUND
1259 && index < last_visited_node - 1)
1260 cost--, internal++;
1261 else
1262 cost++;
1263 }
1264 for (j = 0; snode->iterate_referring (j, ref); j++)
1265 if (!account_reference_p (ref->referring, snode))
1266 ;
1267 else if (is_a <varpool_node *> (ref->referring))
1268 {
1269 int index;
1270
1271 vnode = dyn_cast <varpool_node *> (ref->referring);
1272 gcc_assert (vnode->definition);
1273 /* It is better to couple variables with their users,
1274 because it allows them to be removed. Coupling
1275 with objects they refer to only helps to reduce
1276 number of symbols promoted to hidden. */
1277 if (!symbol_partitioned_p (vnode)
1278 && !vnode->no_reorder
1279 && !vnode->can_remove_if_no_refs_p ()
1280 && vnode->get_partitioning_class () == SYMBOL_PARTITION)
1281 add_symbol_to_partition (partition, vnode);
1282 index = lto_symtab_encoder_lookup (partition->encoder,
1283 vnode);
1284 if (index != LCC_NOT_FOUND
1285 && index < last_visited_node - 1)
1286 cost--, internal++;
1287 else
1288 cost++;
1289 }
1290 else
1291 {
1292 int index;
1293
1294 node = dyn_cast <cgraph_node *> (ref->referring);
1295 gcc_assert (node->definition);
1296 index = lto_symtab_encoder_lookup (partition->encoder,
1297 node);
1298 if (index != LCC_NOT_FOUND
1299 && index < last_visited_node - 1)
1300 cost--, internal++;
1301 else
1302 cost++;
1303 }
1304 }
1305
1306 gcc_assert (cost >= 0 && internal >= 0);
1307
1308 /* If the partition is large enough, start looking for smallest boundary cost.
1309 If partition still seems too small (less than 7/8 of target weight) accept
1310 any cost. If partition has right size, optimize for highest internal/cost.
1311 Later we stop building partition if its size is 9/8 of the target wight. */
1312 if (partition->insns < partition_size * 7 / 8
1313 || best_cost == -1
1314 || (!cost
1315 || ((sreal)best_internal * (sreal) cost
1316 < ((sreal) internal * (sreal)best_cost))))
1317 {
1318 best_cost = cost;
1319 best_internal = internal;
1320 best_size = partition->insns;
1321 best_i = i;
1322 best_n_nodes = lto_symtab_encoder_size (partition->encoder);
1323 best_varpool_pos = varpool_pos;
1324 best_noreorder_pos = noreorder_pos;
1325 }
1326 if (dump_file)
1327 fprintf (dump_file, "Step %i: added %s, size %i, "
1328 "cost %" PRId64 "/%" PRId64 " "
1329 "best %" PRId64 "/%" PRId64", step %i\n", i,
1330 order[i]->dump_name (),
1331 partition->insns, cost, internal,
1332 best_cost, best_internal, best_i);
1333 /* Partition is too large, unwind into step when best cost was reached and
1334 start new partition. */
1335 if (partition->insns > 9 * partition_size / 8
1336 || partition->insns > max_partition_size)
1337 {
1338 if (best_i != i)
1339 {
1340 if (dump_file)
1341 fprintf (dump_file, "Unwinding %i insertions to step %i\n",
1342 i - best_i, best_i);
1343 undo_partition (partition, best_n_nodes);
1344 varpool_pos = best_varpool_pos;
1345 noreorder_pos = best_noreorder_pos;
1346 }
1347 gcc_assert (best_size == partition->insns);
1348 i = best_i;
1349 if (dump_file)
1350 fprintf (dump_file,
1351 "Partition insns: %i (want %" PRId64 ")\n",
1352 partition->insns, partition_size);
1353 /* When we are finished, avoid creating empty partition. */
1354 while (i < order.length () - 1 && symbol_partitioned_p (order[i + 1]))
1355 i++;
1356 if (i == order.length () - 1)
1357 break;
1358 total_size -= partition->insns;
1359 partition = new_partition ("");
1360 last_visited_node = 0;
1361 cost = 0;
1362
1363 if (dump_file)
1364 fprintf (dump_file, "New partition\n");
1365 best_n_nodes = 0;
1366 best_cost = -1;
1367
1368 /* Since the size of partitions is just approximate, update the size after
1369 we finished current one. */
1370 if (npartitions < n_lto_partitions)
1371 partition_size = total_size / (n_lto_partitions - npartitions);
1372 else
1373 /* Watch for overflow. */
1374 partition_size = INT_MAX / 16;
1375
1376 if (dump_file)
1377 fprintf (dump_file,
1378 "Total size: %" PRId64 " partition_size: %" PRId64 "\n",
1379 total_size, partition_size);
1380 if (partition_size < param_min_partition_size)
1381 partition_size = param_min_partition_size;
1382 npartitions ++;
1383 }
1384 }
1385
1386 next_nodes.truncate (0);
1387
1388 /* Varables that are not reachable from the code go into last partition. */
1389 FOR_EACH_VARIABLE (vnode)
1390 if (vnode->get_partitioning_class () == SYMBOL_PARTITION
1391 && !symbol_partitioned_p (vnode))
1392 next_nodes.safe_push (vnode);
1393
1394 /* Output remaining ordered symbols. */
1395 while (varpool_pos < n_varpool_nodes)
1396 next_nodes.safe_push (varpool_order[varpool_pos++]);
1397 while (noreorder_pos < (int)noreorder.length ())
1398 next_nodes.safe_push (noreorder[noreorder_pos++]);
1399 /* For one partition the cost of boundary should be 0 unless we added final
1400 symbols here (these are not accounted) or we have accounting bug. */
1401 gcc_assert (next_nodes.length () || npartitions != 1 || !best_cost || best_cost == -1);
1402 add_sorted_nodes (next_nodes, partition);
1403
1404 if (dump_file)
1405 {
1406 fprintf (dump_file, "\nPartition sizes:\n");
1407 unsigned partitions = ltrans_partitions.length ();
1408
1409 for (unsigned i = 0; i < partitions ; i++)
1410 {
1411 ltrans_partition p = ltrans_partitions[i];
1412 fprintf (dump_file, "partition %d contains %d (%2.2f%%)"
1413 " symbols and %d (%2.2f%%) insns\n", i, p->symbols,
1414 100.0 * p->symbols / order.length (), p->insns,
1415 100.0 * p->insns / original_total_size);
1416 }
1417
1418 fprintf (dump_file, "\n");
1419 }
1420 }
1421
1422 /* Add all references of NODE into PARTITION. */
1423
1424 static void
1425 add_node_references_to_partition (ltrans_partition partition, symtab_node *node)
1426 {
1427 struct ipa_ref *ref = NULL;
1428 varpool_node *vnode;
1429 for (int j = 0; node->iterate_reference (j, ref); j++)
1430 if (is_a <varpool_node *> (ref->referred))
1431 {
1432 vnode = dyn_cast <varpool_node *> (ref->referred);
1433 if (!symbol_partitioned_p (vnode)
1434 && !vnode->no_reorder
1435 && vnode->get_partitioning_class () == SYMBOL_PARTITION)
1436 {
1437 add_symbol_to_partition (partition, vnode);
1438 if (dump_file)
1439 fprintf (dump_file, "Varpool Node: %s\n", vnode->dump_asm_name ());
1440 add_node_references_to_partition (partition, vnode);
1441 }
1442 }
1443
1444 for (int j = 0; node->iterate_referring (j, ref); j++)
1445 if (is_a <varpool_node *> (ref->referring))
1446 {
1447 vnode = dyn_cast <varpool_node *> (ref->referring);
1448 gcc_assert (vnode->definition);
1449 if (!symbol_partitioned_p (vnode)
1450 && !vnode->no_reorder
1451 && !vnode->can_remove_if_no_refs_p ()
1452 && vnode->get_partitioning_class () == SYMBOL_PARTITION)
1453 {
1454 add_symbol_to_partition (partition, vnode);
1455 if (dump_file)
1456 fprintf (dump_file, "Varpool Node: %s\n", vnode->dump_asm_name ());
1457 add_node_references_to_partition (partition, vnode);
1458 }
1459 }
1460 if (cgraph_node *cnode = dyn_cast <cgraph_node *> (node))
1461 {
1462 struct cgraph_edge *e;
1463
1464 /* Add all inline clones and callees that are duplicated. */
1465 for (e = cnode->callees; e; e = e->next_callee)
1466 if (e->callee->get_partitioning_class () == SYMBOL_DUPLICATE)
1467 add_node_references_to_partition (partition, e->callee);
1468
1469 /* Add all thunks associated with the function. */
1470 for (e = cnode->callers; e; e = e->next_caller)
1471 if (e->caller->thunk && !e->caller->inlined_to)
1472 add_node_references_to_partition (partition, e->caller);
1473 }
1474
1475 }
1476
1477 /* Create and return the created partition of name NAME. */
1478
1479 static ltrans_partition
1480 create_partition (int &npartitions, const char *name)
1481 {
1482 npartitions++;
1483 return new_partition (name);
1484 }
1485
1486 /* Partitioning for code locality.
1487 The partitioning plan (and prerequisite cloning) will have been done by the
1488 IPA locality cloning pass. This function just implements that plan by
1489 assigning those partitions to ltrans_parititions. */
1490
1491 void
1492 lto_locality_map (int max_partition_size)
1493 {
1494 symtab_node *snode;
1495 int npartitions = 0;
1496
1497 auto_vec<varpool_node *> varpool_order;
1498 struct cgraph_node *node;
1499
1500 if (locality_partitions.length () == 0)
1501 {
1502 if (dump_file)
1503 {
1504 fprintf (dump_file, "Locality partition: falling back to balanced "
1505 "model\n");
1506 }
1507 lto_balanced_map (param_lto_partitions, param_max_partition_size);
1508 return;
1509 }
1510 ltrans_partition partition = nullptr;
1511 for (auto part : locality_partitions)
1512 {
1513 partition = create_partition (npartitions, "");
1514 for (unsigned j = 0; j < part->nodes.length (); j++)
1515 {
1516 node = part->nodes[j];
1517 if (symbol_partitioned_p (node))
1518 continue;
1519
1520 add_symbol_to_partition (partition, node);
1521 add_node_references_to_partition (partition, node);
1522 }
1523 }
1524
1525 int64_t partition_size = max_partition_size;
1526 /* All other unpartitioned symbols. */
1527 FOR_EACH_SYMBOL (snode)
1528 {
1529 if (snode->get_partitioning_class () == SYMBOL_PARTITION
1530 && !symbol_partitioned_p (snode))
1531 {
1532 if (partition->insns > partition_size)
1533 partition = create_partition (npartitions, "");
1534
1535 add_symbol_to_partition (partition, snode);
1536 if (dump_file)
1537 fprintf (dump_file, "Un-ordered Node: %s\n", snode->dump_asm_name ());
1538 }
1539 }
1540 }
1541
1542 /* Return true if we must not change the name of the NODE. The name as
1543 extracted from the corresponding decl should be passed in NAME. */
1544
1545 static bool
1546 must_not_rename (symtab_node *node, const char *name)
1547 {
1548 /* Our renaming machinery do not handle more than one change of assembler name.
1549 We should not need more than one anyway. */
1550 if (node->lto_file_data
1551 && lto_get_decl_name_mapping (node->lto_file_data, name) != name)
1552 {
1553 if (dump_file)
1554 fprintf (dump_file,
1555 "Not privatizing symbol name: %s. It privatized already.\n",
1556 name);
1557 return true;
1558 }
1559 /* Avoid mangling of already mangled clones.
1560 ??? should have a flag whether a symbol has a 'private' name already,
1561 since we produce some symbols like that i.e. for global constructors
1562 that are not really clones.
1563 ??? it is what unique_name means. We only need to set it when doing
1564 private symbols. */
1565 if (node->unique_name)
1566 {
1567 if (dump_file)
1568 fprintf (dump_file,
1569 "Not privatizing symbol name: %s. Has unique name.\n",
1570 name);
1571 return true;
1572 }
1573 return false;
1574 }
1575
1576 /* If we are an offload compiler, we may have to rewrite symbols to be
1577 valid on this target. Return either PTR or a modified version of it. */
1578
1579 static const char *
1580 maybe_rewrite_identifier (const char *ptr)
1581 {
1582 #if defined ACCEL_COMPILER && (defined NO_DOT_IN_LABEL || defined NO_DOLLAR_IN_LABEL)
1583 #ifndef NO_DOT_IN_LABEL
1584 char valid = '.';
1585 const char reject[] = "$";
1586 #elif !defined NO_DOLLAR_IN_LABEL
1587 char valid = '$';
1588 const char reject[] = ".";
1589 #else
1590 char valid = '_';
1591 const char reject[] = ".$";
1592 #endif
1593
1594 char *copy = NULL;
1595 const char *match = ptr;
1596 for (;;)
1597 {
1598 size_t off = strcspn (match, reject);
1599 if (match[off] == '\0')
1600 break;
1601 if (copy == NULL)
1602 {
1603 copy = xstrdup (ptr);
1604 match = copy;
1605 }
1606 copy[off] = valid;
1607 }
1608 if (copy)
1609 {
1610 match = IDENTIFIER_POINTER (get_identifier (copy));
1611 free (copy);
1612 }
1613 return match;
1614 #else
1615 return ptr;
1616 #endif
1617 }
1618
1619 /* Ensure that the symbol in NODE is valid for the target, and if not,
1620 rewrite it. */
1621
1622 static void
1623 validize_symbol_for_target (symtab_node *node)
1624 {
1625 tree decl = node->decl;
1626 const char *name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
1627
1628 if (must_not_rename (node, name))
1629 return;
1630
1631 const char *name2 = maybe_rewrite_identifier (name);
1632 if (name2 != name)
1633 {
1634 symtab->change_decl_assembler_name (decl, get_identifier (name2));
1635 if (node->lto_file_data)
1636 lto_record_renamed_decl (node->lto_file_data, name, name2);
1637 }
1638 }
1639
1640 /* Maps symbol names to unique lto clone counters. */
1641 static hash_map<const char *, unsigned> *lto_clone_numbers;
1642
1643 /* Helper for privatize_symbol_name. Mangle NODE symbol name
1644 represented by DECL. */
1645
1646 static bool
1647 privatize_symbol_name_1 (symtab_node *node, tree decl)
1648 {
1649 const char *name0 = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
1650
1651 if (must_not_rename (node, name0))
1652 return false;
1653
1654 const char *name = maybe_rewrite_identifier (name0);
1655 unsigned &clone_number = lto_clone_numbers->get_or_insert (name);
1656 symtab->change_decl_assembler_name (decl,
1657 clone_function_name (
1658 name, "lto_priv", clone_number));
1659 clone_number++;
1660
1661 if (node->lto_file_data)
1662 lto_record_renamed_decl (node->lto_file_data, name0,
1663 IDENTIFIER_POINTER
1664 (DECL_ASSEMBLER_NAME (decl)));
1665
1666 if (dump_file)
1667 fprintf (dump_file,
1668 "Privatizing symbol name: %s -> %s\n",
1669 name, IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)));
1670
1671 return true;
1672 }
1673
1674 /* Mangle NODE symbol name into a local name.
1675 This is necessary to do
1676 1) if two or more static vars of same assembler name
1677 are merged into single ltrans unit.
1678 2) if previously static var was promoted hidden to avoid possible conflict
1679 with symbols defined out of the LTO world. */
1680
1681 static bool
1682 privatize_symbol_name (symtab_node *node)
1683 {
1684 if (!privatize_symbol_name_1 (node, node->decl))
1685 return false;
1686
1687 return true;
1688 }
1689
1690 /* Promote variable VNODE to be static. */
1691
1692 static void
1693 promote_symbol (symtab_node *node)
1694 {
1695 /* We already promoted ... */
1696 if (DECL_VISIBILITY (node->decl) == VISIBILITY_HIDDEN
1697 && DECL_VISIBILITY_SPECIFIED (node->decl)
1698 && TREE_PUBLIC (node->decl))
1699 {
1700 validize_symbol_for_target (node);
1701 return;
1702 }
1703
1704 gcc_checking_assert (!TREE_PUBLIC (node->decl)
1705 && !DECL_EXTERNAL (node->decl));
1706 /* Be sure that newly public symbol does not conflict with anything already
1707 defined by the non-LTO part. */
1708 privatize_symbol_name (node);
1709 TREE_PUBLIC (node->decl) = 1;
1710 /* After privatization the node should not conflict with any other symbol,
1711 so it is prevailing. This is important to keep binds_to_current_def_p
1712 to work across partitions. */
1713 node->resolution = LDPR_PREVAILING_DEF_IRONLY;
1714 node->semantic_interposition = false;
1715 DECL_VISIBILITY (node->decl) = VISIBILITY_HIDDEN;
1716 DECL_VISIBILITY_SPECIFIED (node->decl) = true;
1717 if (dump_file)
1718 fprintf (dump_file,
1719 "Promoting as hidden: %s (%s)\n", node->dump_name (),
1720 IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (node->decl)));
1721
1722 /* Promoting a symbol also promotes all transparent aliases with exception
1723 of weakref where the visibility flags are always wrong and set to
1724 !PUBLIC. */
1725 ipa_ref *ref;
1726 for (unsigned i = 0; node->iterate_direct_aliases (i, ref); i++)
1727 {
1728 struct symtab_node *alias = ref->referring;
1729 if (alias->transparent_alias && !alias->weakref)
1730 {
1731 TREE_PUBLIC (alias->decl) = 1;
1732 DECL_VISIBILITY (alias->decl) = VISIBILITY_HIDDEN;
1733 DECL_VISIBILITY_SPECIFIED (alias->decl) = true;
1734 if (dump_file)
1735 fprintf (dump_file,
1736 "Promoting alias as hidden: %s\n",
1737 IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (node->decl)));
1738 }
1739 gcc_assert (!alias->weakref || TREE_PUBLIC (alias->decl));
1740 }
1741 }
1742
1743 /* Return true if NODE needs named section even if it won't land in
1744 the partition symbol table.
1745
1746 FIXME: we should really not use named sections for master clones. */
1747
1748 static bool
1749 may_need_named_section_p (lto_symtab_encoder_t encoder, symtab_node *node)
1750 {
1751 struct cgraph_node *cnode = dyn_cast <cgraph_node *> (node);
1752 /* We do not need to handle variables since we never clone them. */
1753 if (!cnode)
1754 return false;
1755 /* Only master clones will have bodies streamed. */
1756 if (cnode->clone_of)
1757 return false;
1758 if (node->real_symbol_p ())
1759 return false;
1760 return (!encoder
1761 || (lto_symtab_encoder_lookup (encoder, node) != LCC_NOT_FOUND
1762 && lto_symtab_encoder_encode_body_p (encoder,
1763 cnode)));
1764 }
1765
1766 /* If NODE represents a static variable. See if there are other variables
1767 of the same name in partition ENCODER (or in whole compilation unit if
1768 ENCODER is NULL) and if so, mangle the statics. Always mangle all
1769 conflicting statics, so we reduce changes of silently miscompiling
1770 asm statements referring to them by symbol name. */
1771
1772 static void
1773 rename_statics (lto_symtab_encoder_t encoder, symtab_node *node)
1774 {
1775 tree decl = node->decl;
1776 symtab_node *s;
1777 tree name = DECL_ASSEMBLER_NAME (decl);
1778
1779 /* See if this is static symbol. */
1780 if (((node->externally_visible && !node->weakref)
1781 /* FIXME: externally_visible is somewhat illogically not set for
1782 external symbols (i.e. those not defined). Remove this test
1783 once this is fixed. */
1784 || DECL_EXTERNAL (node->decl)
1785 || !node->real_symbol_p ())
1786 && !may_need_named_section_p (encoder, node))
1787 return;
1788
1789 /* Now walk symbols sharing the same name and see if there are any conflicts.
1790 (all types of symbols counts here, since we cannot have static of the
1791 same name as external or public symbol.) */
1792 for (s = symtab_node::get_for_asmname (name);
1793 s; s = s->next_sharing_asm_name)
1794 if ((s->real_symbol_p () || may_need_named_section_p (encoder, s))
1795 && s->decl != node->decl
1796 && (!encoder
1797 || lto_symtab_encoder_lookup (encoder, s) != LCC_NOT_FOUND))
1798 break;
1799
1800 /* OK, no confict, so we have nothing to do. */
1801 if (!s)
1802 return;
1803
1804 if (dump_file)
1805 fprintf (dump_file,
1806 "Renaming statics with asm name: %s\n", node->dump_name ());
1807
1808 /* Assign every symbol in the set that shares the same ASM name an unique
1809 mangled name. */
1810 for (s = symtab_node::get_for_asmname (name); s;)
1811 if ((!s->externally_visible || s->weakref)
1812 /* Transparent aliases having same name as target are renamed at a
1813 time their target gets new name. Transparent aliases that use
1814 separate assembler name require the name to be unique. */
1815 && (!s->transparent_alias || !s->definition || s->weakref
1816 || !symbol_table::assembler_names_equal_p
1817 (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (s->decl)),
1818 IDENTIFIER_POINTER
1819 (DECL_ASSEMBLER_NAME (s->get_alias_target()->decl))))
1820 && ((s->real_symbol_p ()
1821 && !DECL_EXTERNAL (s->decl)
1822 && !TREE_PUBLIC (s->decl))
1823 || may_need_named_section_p (encoder, s))
1824 && (!encoder
1825 || lto_symtab_encoder_lookup (encoder, s) != LCC_NOT_FOUND))
1826 {
1827 if (privatize_symbol_name (s))
1828 /* Re-start from beginning since we do not know how many
1829 symbols changed a name. */
1830 s = symtab_node::get_for_asmname (name);
1831 else s = s->next_sharing_asm_name;
1832 }
1833 else s = s->next_sharing_asm_name;
1834 }
1835
1836 /* Find out all static decls that need to be promoted to global because
1837 of cross file sharing. This function must be run in the WPA mode after
1838 all inlinees are added. */
1839
1840 void
1841 lto_promote_cross_file_statics (void)
1842 {
1843 unsigned i, n_sets;
1844
1845 gcc_assert (flag_wpa);
1846
1847 lto_stream_offload_p = false;
1848 select_what_to_stream ();
1849
1850 /* First compute boundaries. */
1851 n_sets = ltrans_partitions.length ();
1852 for (i = 0; i < n_sets; i++)
1853 {
1854 ltrans_partition part
1855 = ltrans_partitions[i];
1856 if (dump_file)
1857 fprintf (dump_file, "lto_promote_cross_file_statics for part %s %p\n",
1858 part->name, (void *)part->encoder);
1859 part->encoder = compute_ltrans_boundary (part->encoder);
1860 if (dump_file)
1861 fprintf (dump_file, "new encoder %p\n", (void *)part->encoder);
1862 }
1863
1864 lto_clone_numbers = new hash_map<const char *, unsigned>;
1865
1866 /* Look at boundaries and promote symbols as needed. */
1867 for (i = 0; i < n_sets; i++)
1868 {
1869 lto_symtab_encoder_iterator lsei;
1870 lto_symtab_encoder_t encoder = ltrans_partitions[i]->encoder;
1871
1872 for (lsei = lsei_start (encoder); !lsei_end_p (lsei);
1873 lsei_next (&lsei))
1874 {
1875 symtab_node *node = lsei_node (lsei);
1876
1877 /* If symbol is static, rename it if its assembler name
1878 clashes with anything else in this unit. */
1879 rename_statics (encoder, node);
1880
1881 /* No need to promote if symbol already is externally visible ... */
1882 if (node->externally_visible
1883 /* ... or if it is part of current partition ... */
1884 || lto_symtab_encoder_in_partition_p (encoder, node)
1885 /* ... or if we do not partition it. This mean that it will
1886 appear in every partition referencing it. */
1887 || node->get_partitioning_class () != SYMBOL_PARTITION)
1888 {
1889 validize_symbol_for_target (node);
1890 continue;
1891 }
1892
1893 promote_symbol (node);
1894 }
1895 }
1896 delete lto_clone_numbers;
1897 }
1898
1899 /* Rename statics in the whole unit in the case that
1900 we do -flto-partition=none. */
1901
1902 void
1903 lto_promote_statics_nonwpa (void)
1904 {
1905 symtab_node *node;
1906
1907 lto_clone_numbers = new hash_map<const char *, unsigned>;
1908 FOR_EACH_SYMBOL (node)
1909 {
1910 rename_statics (NULL, node);
1911 validize_symbol_for_target (node);
1912 }
1913 delete lto_clone_numbers;
1914 }