Fix typo in t-dimode
[official-gcc.git] / gcc / tree-loop-distribution.c
blobc9e18739165fa1d224239610adabbac4dcdf6fef
1 /* Loop distribution.
2 Copyright (C) 2006-2021 Free Software Foundation, Inc.
3 Contributed by Georges-Andre Silber <Georges-Andre.Silber@ensmp.fr>
4 and Sebastian Pop <sebastian.pop@amd.com>.
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 3, or (at your option) any
11 later version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 /* This pass performs loop distribution: for example, the loop
24 |DO I = 2, N
25 | A(I) = B(I) + C
26 | D(I) = A(I-1)*E
27 |ENDDO
29 is transformed to
31 |DOALL I = 2, N
32 | A(I) = B(I) + C
33 |ENDDO
35 |DOALL I = 2, N
36 | D(I) = A(I-1)*E
37 |ENDDO
39 Loop distribution is the dual of loop fusion. It separates statements
40 of a loop (or loop nest) into multiple loops (or loop nests) with the
41 same loop header. The major goal is to separate statements which may
42 be vectorized from those that can't. This pass implements distribution
43 in the following steps:
45 1) Seed partitions with specific type statements. For now we support
46 two types seed statements: statement defining variable used outside
47 of loop; statement storing to memory.
48 2) Build reduced dependence graph (RDG) for loop to be distributed.
49 The vertices (RDG:V) model all statements in the loop and the edges
50 (RDG:E) model flow and control dependencies between statements.
51 3) Apart from RDG, compute data dependencies between memory references.
52 4) Starting from seed statement, build up partition by adding depended
53 statements according to RDG's dependence information. Partition is
54 classified as parallel type if it can be executed paralleled; or as
55 sequential type if it can't. Parallel type partition is further
56 classified as different builtin kinds if it can be implemented as
57 builtin function calls.
58 5) Build partition dependence graph (PG) based on data dependencies.
59 The vertices (PG:V) model all partitions and the edges (PG:E) model
60 all data dependencies between every partitions pair. In general,
61 data dependence is either compilation time known or unknown. In C
62 family languages, there exists quite amount compilation time unknown
63 dependencies because of possible alias relation of data references.
64 We categorize PG's edge to two types: "true" edge that represents
65 compilation time known data dependencies; "alias" edge for all other
66 data dependencies.
67 6) Traverse subgraph of PG as if all "alias" edges don't exist. Merge
68 partitions in each strong connected component (SCC) correspondingly.
69 Build new PG for merged partitions.
70 7) Traverse PG again and this time with both "true" and "alias" edges
71 included. We try to break SCCs by removing some edges. Because
72 SCCs by "true" edges are all fused in step 6), we can break SCCs
73 by removing some "alias" edges. It's NP-hard to choose optimal
74 edge set, fortunately simple approximation is good enough for us
75 given the small problem scale.
76 8) Collect all data dependencies of the removed "alias" edges. Create
77 runtime alias checks for collected data dependencies.
78 9) Version loop under the condition of runtime alias checks. Given
79 loop distribution generally introduces additional overhead, it is
80 only useful if vectorization is achieved in distributed loop. We
81 version loop with internal function call IFN_LOOP_DIST_ALIAS. If
82 no distributed loop can be vectorized, we simply remove distributed
83 loops and recover to the original one.
85 TODO:
86 1) We only distribute innermost two-level loop nest now. We should
87 extend it for arbitrary loop nests in the future.
88 2) We only fuse partitions in SCC now. A better fusion algorithm is
89 desired to minimize loop overhead, maximize parallelism and maximize
90 data reuse. */
92 #include "config.h"
93 #include "system.h"
94 #include "coretypes.h"
95 #include "backend.h"
96 #include "tree.h"
97 #include "gimple.h"
98 #include "cfghooks.h"
99 #include "tree-pass.h"
100 #include "ssa.h"
101 #include "gimple-pretty-print.h"
102 #include "fold-const.h"
103 #include "cfganal.h"
104 #include "gimple-iterator.h"
105 #include "gimplify-me.h"
106 #include "stor-layout.h"
107 #include "tree-cfg.h"
108 #include "tree-ssa-loop-manip.h"
109 #include "tree-ssa-loop-ivopts.h"
110 #include "tree-ssa-loop.h"
111 #include "tree-into-ssa.h"
112 #include "tree-ssa.h"
113 #include "cfgloop.h"
114 #include "tree-scalar-evolution.h"
115 #include "tree-vectorizer.h"
116 #include "tree-eh.h"
117 #include "gimple-fold.h"
118 #include "tree-affine.h"
119 #include "intl.h"
120 #include "rtl.h"
121 #include "memmodel.h"
122 #include "optabs.h"
125 #define MAX_DATAREFS_NUM \
126 ((unsigned) param_loop_max_datarefs_for_datadeps)
128 /* Threshold controlling number of distributed partitions. Given it may
129 be unnecessary if a memory stream cost model is invented in the future,
130 we define it as a temporary macro, rather than a parameter. */
131 #define NUM_PARTITION_THRESHOLD (4)
133 /* Hashtable helpers. */
135 struct ddr_hasher : nofree_ptr_hash <struct data_dependence_relation>
137 static inline hashval_t hash (const data_dependence_relation *);
138 static inline bool equal (const data_dependence_relation *,
139 const data_dependence_relation *);
142 /* Hash function for data dependence. */
144 inline hashval_t
145 ddr_hasher::hash (const data_dependence_relation *ddr)
147 inchash::hash h;
148 h.add_ptr (DDR_A (ddr));
149 h.add_ptr (DDR_B (ddr));
150 return h.end ();
153 /* Hash table equality function for data dependence. */
155 inline bool
156 ddr_hasher::equal (const data_dependence_relation *ddr1,
157 const data_dependence_relation *ddr2)
159 return (DDR_A (ddr1) == DDR_A (ddr2) && DDR_B (ddr1) == DDR_B (ddr2));
164 #define DR_INDEX(dr) ((uintptr_t) (dr)->aux)
166 /* A Reduced Dependence Graph (RDG) vertex representing a statement. */
167 struct rdg_vertex
169 /* The statement represented by this vertex. */
170 gimple *stmt;
172 /* Vector of data-references in this statement. */
173 vec<data_reference_p> datarefs;
175 /* True when the statement contains a write to memory. */
176 bool has_mem_write;
178 /* True when the statement contains a read from memory. */
179 bool has_mem_reads;
182 #define RDGV_STMT(V) ((struct rdg_vertex *) ((V)->data))->stmt
183 #define RDGV_DATAREFS(V) ((struct rdg_vertex *) ((V)->data))->datarefs
184 #define RDGV_HAS_MEM_WRITE(V) ((struct rdg_vertex *) ((V)->data))->has_mem_write
185 #define RDGV_HAS_MEM_READS(V) ((struct rdg_vertex *) ((V)->data))->has_mem_reads
186 #define RDG_STMT(RDG, I) RDGV_STMT (&(RDG->vertices[I]))
187 #define RDG_DATAREFS(RDG, I) RDGV_DATAREFS (&(RDG->vertices[I]))
188 #define RDG_MEM_WRITE_STMT(RDG, I) RDGV_HAS_MEM_WRITE (&(RDG->vertices[I]))
189 #define RDG_MEM_READS_STMT(RDG, I) RDGV_HAS_MEM_READS (&(RDG->vertices[I]))
191 /* Data dependence type. */
193 enum rdg_dep_type
195 /* Read After Write (RAW). */
196 flow_dd = 'f',
198 /* Control dependence (execute conditional on). */
199 control_dd = 'c'
202 /* Dependence information attached to an edge of the RDG. */
204 struct rdg_edge
206 /* Type of the dependence. */
207 enum rdg_dep_type type;
210 #define RDGE_TYPE(E) ((struct rdg_edge *) ((E)->data))->type
212 /* Kind of distributed loop. */
213 enum partition_kind {
214 PKIND_NORMAL,
215 /* Partial memset stands for a paritition can be distributed into a loop
216 of memset calls, rather than a single memset call. It's handled just
217 like a normal parition, i.e, distributed as separate loop, no memset
218 call is generated.
220 Note: This is a hacking fix trying to distribute ZERO-ing stmt in a
221 loop nest as deep as possible. As a result, parloop achieves better
222 parallelization by parallelizing deeper loop nest. This hack should
223 be unnecessary and removed once distributed memset can be understood
224 and analyzed in data reference analysis. See PR82604 for more. */
225 PKIND_PARTIAL_MEMSET,
226 PKIND_MEMSET, PKIND_MEMCPY, PKIND_MEMMOVE
229 /* Type of distributed loop. */
230 enum partition_type {
231 /* The distributed loop can be executed parallelly. */
232 PTYPE_PARALLEL = 0,
233 /* The distributed loop has to be executed sequentially. */
234 PTYPE_SEQUENTIAL
237 /* Builtin info for loop distribution. */
238 struct builtin_info
240 /* data-references a kind != PKIND_NORMAL partition is about. */
241 data_reference_p dst_dr;
242 data_reference_p src_dr;
243 /* Base address and size of memory objects operated by the builtin. Note
244 both dest and source memory objects must have the same size. */
245 tree dst_base;
246 tree src_base;
247 tree size;
248 /* Base and offset part of dst_base after stripping constant offset. This
249 is only used in memset builtin distribution for now. */
250 tree dst_base_base;
251 unsigned HOST_WIDE_INT dst_base_offset;
254 /* Partition for loop distribution. */
255 struct partition
257 /* Statements of the partition. */
258 bitmap stmts;
259 /* True if the partition defines variable which is used outside of loop. */
260 bool reduction_p;
261 location_t loc;
262 enum partition_kind kind;
263 enum partition_type type;
264 /* Data references in the partition. */
265 bitmap datarefs;
266 /* Information of builtin parition. */
267 struct builtin_info *builtin;
270 /* Partitions are fused because of different reasons. */
271 enum fuse_type
273 FUSE_NON_BUILTIN = 0,
274 FUSE_REDUCTION = 1,
275 FUSE_SHARE_REF = 2,
276 FUSE_SAME_SCC = 3,
277 FUSE_FINALIZE = 4
280 /* Description on different fusing reason. */
281 static const char *fuse_message[] = {
282 "they are non-builtins",
283 "they have reductions",
284 "they have shared memory refs",
285 "they are in the same dependence scc",
286 "there is no point to distribute loop"};
289 /* Dump vertex I in RDG to FILE. */
291 static void
292 dump_rdg_vertex (FILE *file, struct graph *rdg, int i)
294 struct vertex *v = &(rdg->vertices[i]);
295 struct graph_edge *e;
297 fprintf (file, "(vertex %d: (%s%s) (in:", i,
298 RDG_MEM_WRITE_STMT (rdg, i) ? "w" : "",
299 RDG_MEM_READS_STMT (rdg, i) ? "r" : "");
301 if (v->pred)
302 for (e = v->pred; e; e = e->pred_next)
303 fprintf (file, " %d", e->src);
305 fprintf (file, ") (out:");
307 if (v->succ)
308 for (e = v->succ; e; e = e->succ_next)
309 fprintf (file, " %d", e->dest);
311 fprintf (file, ")\n");
312 print_gimple_stmt (file, RDGV_STMT (v), 0, TDF_VOPS|TDF_MEMSYMS);
313 fprintf (file, ")\n");
316 /* Call dump_rdg_vertex on stderr. */
318 DEBUG_FUNCTION void
319 debug_rdg_vertex (struct graph *rdg, int i)
321 dump_rdg_vertex (stderr, rdg, i);
324 /* Dump the reduced dependence graph RDG to FILE. */
326 static void
327 dump_rdg (FILE *file, struct graph *rdg)
329 fprintf (file, "(rdg\n");
330 for (int i = 0; i < rdg->n_vertices; i++)
331 dump_rdg_vertex (file, rdg, i);
332 fprintf (file, ")\n");
335 /* Call dump_rdg on stderr. */
337 DEBUG_FUNCTION void
338 debug_rdg (struct graph *rdg)
340 dump_rdg (stderr, rdg);
343 static void
344 dot_rdg_1 (FILE *file, struct graph *rdg)
346 int i;
347 pretty_printer buffer;
348 pp_needs_newline (&buffer) = false;
349 buffer.buffer->stream = file;
351 fprintf (file, "digraph RDG {\n");
353 for (i = 0; i < rdg->n_vertices; i++)
355 struct vertex *v = &(rdg->vertices[i]);
356 struct graph_edge *e;
358 fprintf (file, "%d [label=\"[%d] ", i, i);
359 pp_gimple_stmt_1 (&buffer, RDGV_STMT (v), 0, TDF_SLIM);
360 pp_flush (&buffer);
361 fprintf (file, "\"]\n");
363 /* Highlight reads from memory. */
364 if (RDG_MEM_READS_STMT (rdg, i))
365 fprintf (file, "%d [style=filled, fillcolor=green]\n", i);
367 /* Highlight stores to memory. */
368 if (RDG_MEM_WRITE_STMT (rdg, i))
369 fprintf (file, "%d [style=filled, fillcolor=red]\n", i);
371 if (v->succ)
372 for (e = v->succ; e; e = e->succ_next)
373 switch (RDGE_TYPE (e))
375 case flow_dd:
376 /* These are the most common dependences: don't print these. */
377 fprintf (file, "%d -> %d \n", i, e->dest);
378 break;
380 case control_dd:
381 fprintf (file, "%d -> %d [label=control] \n", i, e->dest);
382 break;
384 default:
385 gcc_unreachable ();
389 fprintf (file, "}\n\n");
392 /* Display the Reduced Dependence Graph using dotty. */
394 DEBUG_FUNCTION void
395 dot_rdg (struct graph *rdg)
397 /* When debugging, you may want to enable the following code. */
398 #ifdef HAVE_POPEN
399 FILE *file = popen ("dot -Tx11", "w");
400 if (!file)
401 return;
402 dot_rdg_1 (file, rdg);
403 fflush (file);
404 close (fileno (file));
405 pclose (file);
406 #else
407 dot_rdg_1 (stderr, rdg);
408 #endif
411 /* Returns the index of STMT in RDG. */
413 static int
414 rdg_vertex_for_stmt (struct graph *rdg ATTRIBUTE_UNUSED, gimple *stmt)
416 int index = gimple_uid (stmt);
417 gcc_checking_assert (index == -1 || RDG_STMT (rdg, index) == stmt);
418 return index;
421 /* Creates dependence edges in RDG for all the uses of DEF. IDEF is
422 the index of DEF in RDG. */
424 static void
425 create_rdg_edges_for_scalar (struct graph *rdg, tree def, int idef)
427 use_operand_p imm_use_p;
428 imm_use_iterator iterator;
430 FOR_EACH_IMM_USE_FAST (imm_use_p, iterator, def)
432 struct graph_edge *e;
433 int use = rdg_vertex_for_stmt (rdg, USE_STMT (imm_use_p));
435 if (use < 0)
436 continue;
438 e = add_edge (rdg, idef, use);
439 e->data = XNEW (struct rdg_edge);
440 RDGE_TYPE (e) = flow_dd;
444 /* Creates an edge for the control dependences of BB to the vertex V. */
446 static void
447 create_edge_for_control_dependence (struct graph *rdg, basic_block bb,
448 int v, control_dependences *cd)
450 bitmap_iterator bi;
451 unsigned edge_n;
452 EXECUTE_IF_SET_IN_BITMAP (cd->get_edges_dependent_on (bb->index),
453 0, edge_n, bi)
455 basic_block cond_bb = cd->get_edge_src (edge_n);
456 gimple *stmt = last_stmt (cond_bb);
457 if (stmt && is_ctrl_stmt (stmt))
459 struct graph_edge *e;
460 int c = rdg_vertex_for_stmt (rdg, stmt);
461 if (c < 0)
462 continue;
464 e = add_edge (rdg, c, v);
465 e->data = XNEW (struct rdg_edge);
466 RDGE_TYPE (e) = control_dd;
471 /* Creates the edges of the reduced dependence graph RDG. */
473 static void
474 create_rdg_flow_edges (struct graph *rdg)
476 int i;
477 def_operand_p def_p;
478 ssa_op_iter iter;
480 for (i = 0; i < rdg->n_vertices; i++)
481 FOR_EACH_PHI_OR_STMT_DEF (def_p, RDG_STMT (rdg, i),
482 iter, SSA_OP_DEF)
483 create_rdg_edges_for_scalar (rdg, DEF_FROM_PTR (def_p), i);
486 /* Creates the edges of the reduced dependence graph RDG. */
488 static void
489 create_rdg_cd_edges (struct graph *rdg, control_dependences *cd, loop_p loop)
491 int i;
493 for (i = 0; i < rdg->n_vertices; i++)
495 gimple *stmt = RDG_STMT (rdg, i);
496 if (gimple_code (stmt) == GIMPLE_PHI)
498 edge_iterator ei;
499 edge e;
500 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->preds)
501 if (flow_bb_inside_loop_p (loop, e->src))
502 create_edge_for_control_dependence (rdg, e->src, i, cd);
504 else
505 create_edge_for_control_dependence (rdg, gimple_bb (stmt), i, cd);
510 class loop_distribution
512 private:
513 /* The loop (nest) to be distributed. */
514 vec<loop_p> loop_nest;
516 /* Vector of data references in the loop to be distributed. */
517 vec<data_reference_p> datarefs_vec;
519 /* If there is nonaddressable data reference in above vector. */
520 bool has_nonaddressable_dataref_p;
522 /* Store index of data reference in aux field. */
524 /* Hash table for data dependence relation in the loop to be distributed. */
525 hash_table<ddr_hasher> *ddrs_table;
527 /* Array mapping basic block's index to its topological order. */
528 int *bb_top_order_index;
529 /* And size of the array. */
530 int bb_top_order_index_size;
532 /* Build the vertices of the reduced dependence graph RDG. Return false
533 if that failed. */
534 bool create_rdg_vertices (struct graph *rdg, const vec<gimple *> &stmts,
535 loop_p loop);
537 /* Initialize STMTS with all the statements of LOOP. We use topological
538 order to discover all statements. The order is important because
539 generate_loops_for_partition is using the same traversal for identifying
540 statements in loop copies. */
541 void stmts_from_loop (class loop *loop, vec<gimple *> *stmts);
544 /* Build the Reduced Dependence Graph (RDG) with one vertex per statement of
545 LOOP, and one edge per flow dependence or control dependence from control
546 dependence CD. During visiting each statement, data references are also
547 collected and recorded in global data DATAREFS_VEC. */
548 struct graph * build_rdg (class loop *loop, control_dependences *cd);
550 /* Merge PARTITION into the partition DEST. RDG is the reduced dependence
551 graph and we update type for result partition if it is non-NULL. */
552 void partition_merge_into (struct graph *rdg,
553 partition *dest, partition *partition,
554 enum fuse_type ft);
557 /* Return data dependence relation for data references A and B. The two
558 data references must be in lexicographic order wrto reduced dependence
559 graph RDG. We firstly try to find ddr from global ddr hash table. If
560 it doesn't exist, compute the ddr and cache it. */
561 data_dependence_relation * get_data_dependence (struct graph *rdg,
562 data_reference_p a,
563 data_reference_p b);
566 /* In reduced dependence graph RDG for loop distribution, return true if
567 dependence between references DR1 and DR2 leads to a dependence cycle
568 and such dependence cycle can't be resolved by runtime alias check. */
569 bool data_dep_in_cycle_p (struct graph *rdg, data_reference_p dr1,
570 data_reference_p dr2);
573 /* Given reduced dependence graph RDG, PARTITION1 and PARTITION2, update
574 PARTITION1's type after merging PARTITION2 into PARTITION1. */
575 void update_type_for_merge (struct graph *rdg,
576 partition *partition1, partition *partition2);
579 /* Returns a partition with all the statements needed for computing
580 the vertex V of the RDG, also including the loop exit conditions. */
581 partition *build_rdg_partition_for_vertex (struct graph *rdg, int v);
583 /* Given data references DST_DR and SRC_DR in loop nest LOOP and RDG, classify
584 if it forms builtin memcpy or memmove call. */
585 void classify_builtin_ldst (loop_p loop, struct graph *rdg, partition *partition,
586 data_reference_p dst_dr, data_reference_p src_dr);
588 /* Classifies the builtin kind we can generate for PARTITION of RDG and LOOP.
589 For the moment we detect memset, memcpy and memmove patterns. Bitmap
590 STMT_IN_ALL_PARTITIONS contains statements belonging to all partitions.
591 Returns true if there is a reduction in all partitions and we
592 possibly did not mark PARTITION as having one for this reason. */
594 bool
595 classify_partition (loop_p loop,
596 struct graph *rdg, partition *partition,
597 bitmap stmt_in_all_partitions);
600 /* Returns true when PARTITION1 and PARTITION2 access the same memory
601 object in RDG. */
602 bool share_memory_accesses (struct graph *rdg,
603 partition *partition1, partition *partition2);
605 /* For each seed statement in STARTING_STMTS, this function builds
606 partition for it by adding depended statements according to RDG.
607 All partitions are recorded in PARTITIONS. */
608 void rdg_build_partitions (struct graph *rdg,
609 vec<gimple *> starting_stmts,
610 vec<partition *> *partitions);
612 /* Compute partition dependence created by the data references in DRS1
613 and DRS2, modify and return DIR according to that. IF ALIAS_DDR is
614 not NULL, we record dependence introduced by possible alias between
615 two data references in ALIAS_DDRS; otherwise, we simply ignore such
616 dependence as if it doesn't exist at all. */
617 int pg_add_dependence_edges (struct graph *rdg, int dir, bitmap drs1,
618 bitmap drs2, vec<ddr_p> *alias_ddrs);
621 /* Build and return partition dependence graph for PARTITIONS. RDG is
622 reduced dependence graph for the loop to be distributed. If IGNORE_ALIAS_P
623 is true, data dependence caused by possible alias between references
624 is ignored, as if it doesn't exist at all; otherwise all depdendences
625 are considered. */
626 struct graph *build_partition_graph (struct graph *rdg,
627 vec<struct partition *> *partitions,
628 bool ignore_alias_p);
630 /* Given reduced dependence graph RDG merge strong connected components
631 of PARTITIONS. If IGNORE_ALIAS_P is true, data dependence caused by
632 possible alias between references is ignored, as if it doesn't exist
633 at all; otherwise all depdendences are considered. */
634 void merge_dep_scc_partitions (struct graph *rdg, vec<struct partition *>
635 *partitions, bool ignore_alias_p);
637 /* This is the main function breaking strong conected components in
638 PARTITIONS giving reduced depdendence graph RDG. Store data dependence
639 relations for runtime alias check in ALIAS_DDRS. */
640 void break_alias_scc_partitions (struct graph *rdg, vec<struct partition *>
641 *partitions, vec<ddr_p> *alias_ddrs);
644 /* Fuse PARTITIONS of LOOP if necessary before finalizing distribution.
645 ALIAS_DDRS contains ddrs which need runtime alias check. */
646 void finalize_partitions (class loop *loop, vec<struct partition *>
647 *partitions, vec<ddr_p> *alias_ddrs);
649 /* Distributes the code from LOOP in such a way that producer statements
650 are placed before consumer statements. Tries to separate only the
651 statements from STMTS into separate loops. Returns the number of
652 distributed loops. Set NB_CALLS to number of generated builtin calls.
653 Set *DESTROY_P to whether LOOP needs to be destroyed. */
654 int distribute_loop (class loop *loop, const vec<gimple *> &stmts,
655 control_dependences *cd, int *nb_calls, bool *destroy_p,
656 bool only_patterns_p);
658 /* Transform loops which mimic the effects of builtins rawmemchr or strlen and
659 replace them accordingly. */
660 bool transform_reduction_loop (loop_p loop);
662 /* Compute topological order for basic blocks. Topological order is
663 needed because data dependence is computed for data references in
664 lexicographical order. */
665 void bb_top_order_init (void);
667 void bb_top_order_destroy (void);
669 public:
671 /* Getter for bb_top_order. */
673 inline int get_bb_top_order_index_size (void)
675 return bb_top_order_index_size;
678 inline int get_bb_top_order_index (int i)
680 return bb_top_order_index[i];
683 unsigned int execute (function *fun);
687 /* If X has a smaller topological sort number than Y, returns -1;
688 if greater, returns 1. */
689 static int
690 bb_top_order_cmp_r (const void *x, const void *y, void *loop)
692 loop_distribution *_loop =
693 (loop_distribution *) loop;
695 basic_block bb1 = *(const basic_block *) x;
696 basic_block bb2 = *(const basic_block *) y;
698 int bb_top_order_index_size = _loop->get_bb_top_order_index_size ();
700 gcc_assert (bb1->index < bb_top_order_index_size
701 && bb2->index < bb_top_order_index_size);
702 gcc_assert (bb1 == bb2
703 || _loop->get_bb_top_order_index(bb1->index)
704 != _loop->get_bb_top_order_index(bb2->index));
706 return (_loop->get_bb_top_order_index(bb1->index) -
707 _loop->get_bb_top_order_index(bb2->index));
710 bool
711 loop_distribution::create_rdg_vertices (struct graph *rdg,
712 const vec<gimple *> &stmts,
713 loop_p loop)
715 int i;
716 gimple *stmt;
718 FOR_EACH_VEC_ELT (stmts, i, stmt)
720 struct vertex *v = &(rdg->vertices[i]);
722 /* Record statement to vertex mapping. */
723 gimple_set_uid (stmt, i);
725 v->data = XNEW (struct rdg_vertex);
726 RDGV_STMT (v) = stmt;
727 RDGV_DATAREFS (v).create (0);
728 RDGV_HAS_MEM_WRITE (v) = false;
729 RDGV_HAS_MEM_READS (v) = false;
730 if (gimple_code (stmt) == GIMPLE_PHI)
731 continue;
733 unsigned drp = datarefs_vec.length ();
734 if (!find_data_references_in_stmt (loop, stmt, &datarefs_vec))
735 return false;
736 for (unsigned j = drp; j < datarefs_vec.length (); ++j)
738 data_reference_p dr = datarefs_vec[j];
739 if (DR_IS_READ (dr))
740 RDGV_HAS_MEM_READS (v) = true;
741 else
742 RDGV_HAS_MEM_WRITE (v) = true;
743 RDGV_DATAREFS (v).safe_push (dr);
744 has_nonaddressable_dataref_p |= may_be_nonaddressable_p (dr->ref);
747 return true;
750 void
751 loop_distribution::stmts_from_loop (class loop *loop, vec<gimple *> *stmts)
753 unsigned int i;
754 basic_block *bbs = get_loop_body_in_custom_order (loop, this, bb_top_order_cmp_r);
756 for (i = 0; i < loop->num_nodes; i++)
758 basic_block bb = bbs[i];
760 for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi);
761 gsi_next (&bsi))
762 if (!virtual_operand_p (gimple_phi_result (bsi.phi ())))
763 stmts->safe_push (bsi.phi ());
765 for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi);
766 gsi_next (&bsi))
768 gimple *stmt = gsi_stmt (bsi);
769 if (gimple_code (stmt) != GIMPLE_LABEL && !is_gimple_debug (stmt))
770 stmts->safe_push (stmt);
774 free (bbs);
777 /* Free the reduced dependence graph RDG. */
779 static void
780 free_rdg (struct graph *rdg)
782 int i;
784 for (i = 0; i < rdg->n_vertices; i++)
786 struct vertex *v = &(rdg->vertices[i]);
787 struct graph_edge *e;
789 for (e = v->succ; e; e = e->succ_next)
790 free (e->data);
792 if (v->data)
794 gimple_set_uid (RDGV_STMT (v), -1);
795 (RDGV_DATAREFS (v)).release ();
796 free (v->data);
800 free_graph (rdg);
803 struct graph *
804 loop_distribution::build_rdg (class loop *loop, control_dependences *cd)
806 struct graph *rdg;
808 /* Create the RDG vertices from the stmts of the loop nest. */
809 auto_vec<gimple *, 10> stmts;
810 stmts_from_loop (loop, &stmts);
811 rdg = new_graph (stmts.length ());
812 if (!create_rdg_vertices (rdg, stmts, loop))
814 free_rdg (rdg);
815 return NULL;
817 stmts.release ();
819 create_rdg_flow_edges (rdg);
820 if (cd)
821 create_rdg_cd_edges (rdg, cd, loop);
823 return rdg;
827 /* Allocate and initialize a partition from BITMAP. */
829 static partition *
830 partition_alloc (void)
832 partition *partition = XCNEW (struct partition);
833 partition->stmts = BITMAP_ALLOC (NULL);
834 partition->reduction_p = false;
835 partition->loc = UNKNOWN_LOCATION;
836 partition->kind = PKIND_NORMAL;
837 partition->type = PTYPE_PARALLEL;
838 partition->datarefs = BITMAP_ALLOC (NULL);
839 return partition;
842 /* Free PARTITION. */
844 static void
845 partition_free (partition *partition)
847 BITMAP_FREE (partition->stmts);
848 BITMAP_FREE (partition->datarefs);
849 if (partition->builtin)
850 free (partition->builtin);
852 free (partition);
855 /* Returns true if the partition can be generated as a builtin. */
857 static bool
858 partition_builtin_p (partition *partition)
860 return partition->kind > PKIND_PARTIAL_MEMSET;
863 /* Returns true if the partition contains a reduction. */
865 static bool
866 partition_reduction_p (partition *partition)
868 return partition->reduction_p;
871 void
872 loop_distribution::partition_merge_into (struct graph *rdg,
873 partition *dest, partition *partition, enum fuse_type ft)
875 if (dump_file && (dump_flags & TDF_DETAILS))
877 fprintf (dump_file, "Fuse partitions because %s:\n", fuse_message[ft]);
878 fprintf (dump_file, " Part 1: ");
879 dump_bitmap (dump_file, dest->stmts);
880 fprintf (dump_file, " Part 2: ");
881 dump_bitmap (dump_file, partition->stmts);
884 dest->kind = PKIND_NORMAL;
885 if (dest->type == PTYPE_PARALLEL)
886 dest->type = partition->type;
888 bitmap_ior_into (dest->stmts, partition->stmts);
889 if (partition_reduction_p (partition))
890 dest->reduction_p = true;
892 /* Further check if any data dependence prevents us from executing the
893 new partition parallelly. */
894 if (dest->type == PTYPE_PARALLEL && rdg != NULL)
895 update_type_for_merge (rdg, dest, partition);
897 bitmap_ior_into (dest->datarefs, partition->datarefs);
901 /* Returns true when DEF is an SSA_NAME defined in LOOP and used after
902 the LOOP. */
904 static bool
905 ssa_name_has_uses_outside_loop_p (tree def, loop_p loop)
907 imm_use_iterator imm_iter;
908 use_operand_p use_p;
910 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, def)
912 if (is_gimple_debug (USE_STMT (use_p)))
913 continue;
915 basic_block use_bb = gimple_bb (USE_STMT (use_p));
916 if (!flow_bb_inside_loop_p (loop, use_bb))
917 return true;
920 return false;
923 /* Returns true when STMT defines a scalar variable used after the
924 loop LOOP. */
926 static bool
927 stmt_has_scalar_dependences_outside_loop (loop_p loop, gimple *stmt)
929 def_operand_p def_p;
930 ssa_op_iter op_iter;
932 if (gimple_code (stmt) == GIMPLE_PHI)
933 return ssa_name_has_uses_outside_loop_p (gimple_phi_result (stmt), loop);
935 FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, op_iter, SSA_OP_DEF)
936 if (ssa_name_has_uses_outside_loop_p (DEF_FROM_PTR (def_p), loop))
937 return true;
939 return false;
942 /* Return a copy of LOOP placed before LOOP. */
944 static class loop *
945 copy_loop_before (class loop *loop)
947 class loop *res;
948 edge preheader = loop_preheader_edge (loop);
950 initialize_original_copy_tables ();
951 res = slpeel_tree_duplicate_loop_to_edge_cfg (loop, NULL, preheader);
952 gcc_assert (res != NULL);
953 free_original_copy_tables ();
954 delete_update_ssa ();
956 return res;
959 /* Creates an empty basic block after LOOP. */
961 static void
962 create_bb_after_loop (class loop *loop)
964 edge exit = single_exit (loop);
966 if (!exit)
967 return;
969 split_edge (exit);
972 /* Generate code for PARTITION from the code in LOOP. The loop is
973 copied when COPY_P is true. All the statements not flagged in the
974 PARTITION bitmap are removed from the loop or from its copy. The
975 statements are indexed in sequence inside a basic block, and the
976 basic blocks of a loop are taken in dom order. */
978 static void
979 generate_loops_for_partition (class loop *loop, partition *partition,
980 bool copy_p)
982 unsigned i;
983 basic_block *bbs;
985 if (copy_p)
987 int orig_loop_num = loop->orig_loop_num;
988 loop = copy_loop_before (loop);
989 gcc_assert (loop != NULL);
990 loop->orig_loop_num = orig_loop_num;
991 create_preheader (loop, CP_SIMPLE_PREHEADERS);
992 create_bb_after_loop (loop);
994 else
996 /* Origin number is set to the new versioned loop's num. */
997 gcc_assert (loop->orig_loop_num != loop->num);
1000 /* Remove stmts not in the PARTITION bitmap. */
1001 bbs = get_loop_body_in_dom_order (loop);
1003 if (MAY_HAVE_DEBUG_BIND_STMTS)
1004 for (i = 0; i < loop->num_nodes; i++)
1006 basic_block bb = bbs[i];
1008 for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi);
1009 gsi_next (&bsi))
1011 gphi *phi = bsi.phi ();
1012 if (!virtual_operand_p (gimple_phi_result (phi))
1013 && !bitmap_bit_p (partition->stmts, gimple_uid (phi)))
1014 reset_debug_uses (phi);
1017 for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1019 gimple *stmt = gsi_stmt (bsi);
1020 if (gimple_code (stmt) != GIMPLE_LABEL
1021 && !is_gimple_debug (stmt)
1022 && !bitmap_bit_p (partition->stmts, gimple_uid (stmt)))
1023 reset_debug_uses (stmt);
1027 for (i = 0; i < loop->num_nodes; i++)
1029 basic_block bb = bbs[i];
1030 edge inner_exit = NULL;
1032 if (loop != bb->loop_father)
1033 inner_exit = single_exit (bb->loop_father);
1035 for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi);)
1037 gphi *phi = bsi.phi ();
1038 if (!virtual_operand_p (gimple_phi_result (phi))
1039 && !bitmap_bit_p (partition->stmts, gimple_uid (phi)))
1040 remove_phi_node (&bsi, true);
1041 else
1042 gsi_next (&bsi);
1045 for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi);)
1047 gimple *stmt = gsi_stmt (bsi);
1048 if (gimple_code (stmt) != GIMPLE_LABEL
1049 && !is_gimple_debug (stmt)
1050 && !bitmap_bit_p (partition->stmts, gimple_uid (stmt)))
1052 /* In distribution of loop nest, if bb is inner loop's exit_bb,
1053 we choose its exit edge/path in order to avoid generating
1054 infinite loop. For all other cases, we choose an arbitrary
1055 path through the empty CFG part that this unnecessary
1056 control stmt controls. */
1057 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
1059 if (inner_exit && inner_exit->flags & EDGE_TRUE_VALUE)
1060 gimple_cond_make_true (cond_stmt);
1061 else
1062 gimple_cond_make_false (cond_stmt);
1063 update_stmt (stmt);
1065 else if (gimple_code (stmt) == GIMPLE_SWITCH)
1067 gswitch *switch_stmt = as_a <gswitch *> (stmt);
1068 gimple_switch_set_index
1069 (switch_stmt, CASE_LOW (gimple_switch_label (switch_stmt, 1)));
1070 update_stmt (stmt);
1072 else
1074 unlink_stmt_vdef (stmt);
1075 gsi_remove (&bsi, true);
1076 release_defs (stmt);
1077 continue;
1080 gsi_next (&bsi);
1084 free (bbs);
1087 /* If VAL memory representation contains the same value in all bytes,
1088 return that value, otherwise return -1.
1089 E.g. for 0x24242424 return 0x24, for IEEE double
1090 747708026454360457216.0 return 0x44, etc. */
1092 static int
1093 const_with_all_bytes_same (tree val)
1095 unsigned char buf[64];
1096 int i, len;
1098 if (integer_zerop (val)
1099 || (TREE_CODE (val) == CONSTRUCTOR
1100 && !TREE_CLOBBER_P (val)
1101 && CONSTRUCTOR_NELTS (val) == 0))
1102 return 0;
1104 if (real_zerop (val))
1106 /* Only return 0 for +0.0, not for -0.0, which doesn't have
1107 an all bytes same memory representation. Don't transform
1108 -0.0 stores into +0.0 even for !HONOR_SIGNED_ZEROS. */
1109 switch (TREE_CODE (val))
1111 case REAL_CST:
1112 if (!real_isneg (TREE_REAL_CST_PTR (val)))
1113 return 0;
1114 break;
1115 case COMPLEX_CST:
1116 if (!const_with_all_bytes_same (TREE_REALPART (val))
1117 && !const_with_all_bytes_same (TREE_IMAGPART (val)))
1118 return 0;
1119 break;
1120 case VECTOR_CST:
1122 unsigned int count = vector_cst_encoded_nelts (val);
1123 unsigned int j;
1124 for (j = 0; j < count; ++j)
1125 if (const_with_all_bytes_same (VECTOR_CST_ENCODED_ELT (val, j)))
1126 break;
1127 if (j == count)
1128 return 0;
1129 break;
1131 default:
1132 break;
1136 if (CHAR_BIT != 8 || BITS_PER_UNIT != 8)
1137 return -1;
1139 len = native_encode_expr (val, buf, sizeof (buf));
1140 if (len == 0)
1141 return -1;
1142 for (i = 1; i < len; i++)
1143 if (buf[i] != buf[0])
1144 return -1;
1145 return buf[0];
1148 /* Generate a call to memset for PARTITION in LOOP. */
1150 static void
1151 generate_memset_builtin (class loop *loop, partition *partition)
1153 gimple_stmt_iterator gsi;
1154 tree mem, fn, nb_bytes;
1155 tree val;
1156 struct builtin_info *builtin = partition->builtin;
1157 gimple *fn_call;
1159 /* The new statements will be placed before LOOP. */
1160 gsi = gsi_last_bb (loop_preheader_edge (loop)->src);
1162 nb_bytes = rewrite_to_non_trapping_overflow (builtin->size);
1163 nb_bytes = force_gimple_operand_gsi (&gsi, nb_bytes, true, NULL_TREE,
1164 false, GSI_CONTINUE_LINKING);
1165 mem = rewrite_to_non_trapping_overflow (builtin->dst_base);
1166 mem = force_gimple_operand_gsi (&gsi, mem, true, NULL_TREE,
1167 false, GSI_CONTINUE_LINKING);
1169 /* This exactly matches the pattern recognition in classify_partition. */
1170 val = gimple_assign_rhs1 (DR_STMT (builtin->dst_dr));
1171 /* Handle constants like 0x15151515 and similarly
1172 floating point constants etc. where all bytes are the same. */
1173 int bytev = const_with_all_bytes_same (val);
1174 if (bytev != -1)
1175 val = build_int_cst (integer_type_node, bytev);
1176 else if (TREE_CODE (val) == INTEGER_CST)
1177 val = fold_convert (integer_type_node, val);
1178 else if (!useless_type_conversion_p (integer_type_node, TREE_TYPE (val)))
1180 tree tem = make_ssa_name (integer_type_node);
1181 gimple *cstmt = gimple_build_assign (tem, NOP_EXPR, val);
1182 gsi_insert_after (&gsi, cstmt, GSI_CONTINUE_LINKING);
1183 val = tem;
1186 fn = build_fold_addr_expr (builtin_decl_implicit (BUILT_IN_MEMSET));
1187 fn_call = gimple_build_call (fn, 3, mem, val, nb_bytes);
1188 gimple_set_location (fn_call, partition->loc);
1189 gsi_insert_after (&gsi, fn_call, GSI_CONTINUE_LINKING);
1190 fold_stmt (&gsi);
1192 if (dump_file && (dump_flags & TDF_DETAILS))
1194 fprintf (dump_file, "generated memset");
1195 if (bytev == 0)
1196 fprintf (dump_file, " zero\n");
1197 else
1198 fprintf (dump_file, "\n");
1202 /* Generate a call to memcpy for PARTITION in LOOP. */
1204 static void
1205 generate_memcpy_builtin (class loop *loop, partition *partition)
1207 gimple_stmt_iterator gsi;
1208 gimple *fn_call;
1209 tree dest, src, fn, nb_bytes;
1210 enum built_in_function kind;
1211 struct builtin_info *builtin = partition->builtin;
1213 /* The new statements will be placed before LOOP. */
1214 gsi = gsi_last_bb (loop_preheader_edge (loop)->src);
1216 nb_bytes = rewrite_to_non_trapping_overflow (builtin->size);
1217 nb_bytes = force_gimple_operand_gsi (&gsi, nb_bytes, true, NULL_TREE,
1218 false, GSI_CONTINUE_LINKING);
1219 dest = rewrite_to_non_trapping_overflow (builtin->dst_base);
1220 src = rewrite_to_non_trapping_overflow (builtin->src_base);
1221 if (partition->kind == PKIND_MEMCPY
1222 || ! ptr_derefs_may_alias_p (dest, src))
1223 kind = BUILT_IN_MEMCPY;
1224 else
1225 kind = BUILT_IN_MEMMOVE;
1226 /* Try harder if we're copying a constant size. */
1227 if (kind == BUILT_IN_MEMMOVE && poly_int_tree_p (nb_bytes))
1229 aff_tree asrc, adest;
1230 tree_to_aff_combination (src, ptr_type_node, &asrc);
1231 tree_to_aff_combination (dest, ptr_type_node, &adest);
1232 aff_combination_scale (&adest, -1);
1233 aff_combination_add (&asrc, &adest);
1234 if (aff_comb_cannot_overlap_p (&asrc, wi::to_poly_widest (nb_bytes),
1235 wi::to_poly_widest (nb_bytes)))
1236 kind = BUILT_IN_MEMCPY;
1239 dest = force_gimple_operand_gsi (&gsi, dest, true, NULL_TREE,
1240 false, GSI_CONTINUE_LINKING);
1241 src = force_gimple_operand_gsi (&gsi, src, true, NULL_TREE,
1242 false, GSI_CONTINUE_LINKING);
1243 fn = build_fold_addr_expr (builtin_decl_implicit (kind));
1244 fn_call = gimple_build_call (fn, 3, dest, src, nb_bytes);
1245 gimple_set_location (fn_call, partition->loc);
1246 gsi_insert_after (&gsi, fn_call, GSI_CONTINUE_LINKING);
1247 fold_stmt (&gsi);
1249 if (dump_file && (dump_flags & TDF_DETAILS))
1251 if (kind == BUILT_IN_MEMCPY)
1252 fprintf (dump_file, "generated memcpy\n");
1253 else
1254 fprintf (dump_file, "generated memmove\n");
1258 /* Remove and destroy the loop LOOP. */
1260 static void
1261 destroy_loop (class loop *loop)
1263 unsigned nbbs = loop->num_nodes;
1264 edge exit = single_exit (loop);
1265 basic_block src = loop_preheader_edge (loop)->src, dest = exit->dest;
1266 basic_block *bbs;
1267 unsigned i;
1269 bbs = get_loop_body_in_dom_order (loop);
1271 gimple_stmt_iterator dst_gsi = gsi_after_labels (exit->dest);
1272 bool safe_p = single_pred_p (exit->dest);
1273 for (unsigned i = 0; i < nbbs; ++i)
1275 /* We have made sure to not leave any dangling uses of SSA
1276 names defined in the loop. With the exception of virtuals.
1277 Make sure we replace all uses of virtual defs that will remain
1278 outside of the loop with the bare symbol as delete_basic_block
1279 will release them. */
1280 for (gphi_iterator gsi = gsi_start_phis (bbs[i]); !gsi_end_p (gsi);
1281 gsi_next (&gsi))
1283 gphi *phi = gsi.phi ();
1284 if (virtual_operand_p (gimple_phi_result (phi)))
1285 mark_virtual_phi_result_for_renaming (phi);
1287 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]); !gsi_end_p (gsi);)
1289 gimple *stmt = gsi_stmt (gsi);
1290 tree vdef = gimple_vdef (stmt);
1291 if (vdef && TREE_CODE (vdef) == SSA_NAME)
1292 mark_virtual_operand_for_renaming (vdef);
1293 /* Also move and eventually reset debug stmts. We can leave
1294 constant values in place in case the stmt dominates the exit.
1295 ??? Non-constant values from the last iteration can be
1296 replaced with final values if we can compute them. */
1297 if (gimple_debug_bind_p (stmt))
1299 tree val = gimple_debug_bind_get_value (stmt);
1300 gsi_move_before (&gsi, &dst_gsi);
1301 if (val
1302 && (!safe_p
1303 || !is_gimple_min_invariant (val)
1304 || !dominated_by_p (CDI_DOMINATORS, exit->src, bbs[i])))
1306 gimple_debug_bind_reset_value (stmt);
1307 update_stmt (stmt);
1310 else
1311 gsi_next (&gsi);
1315 redirect_edge_pred (exit, src);
1316 exit->flags &= ~(EDGE_TRUE_VALUE|EDGE_FALSE_VALUE);
1317 exit->flags |= EDGE_FALLTHRU;
1318 cancel_loop_tree (loop);
1319 rescan_loop_exit (exit, false, true);
1321 i = nbbs;
1324 --i;
1325 delete_basic_block (bbs[i]);
1327 while (i != 0);
1329 free (bbs);
1331 set_immediate_dominator (CDI_DOMINATORS, dest,
1332 recompute_dominator (CDI_DOMINATORS, dest));
1335 /* Generates code for PARTITION. Return whether LOOP needs to be destroyed. */
1337 static bool
1338 generate_code_for_partition (class loop *loop,
1339 partition *partition, bool copy_p)
1341 switch (partition->kind)
1343 case PKIND_NORMAL:
1344 case PKIND_PARTIAL_MEMSET:
1345 /* Reductions all have to be in the last partition. */
1346 gcc_assert (!partition_reduction_p (partition)
1347 || !copy_p);
1348 generate_loops_for_partition (loop, partition, copy_p);
1349 return false;
1351 case PKIND_MEMSET:
1352 generate_memset_builtin (loop, partition);
1353 break;
1355 case PKIND_MEMCPY:
1356 case PKIND_MEMMOVE:
1357 generate_memcpy_builtin (loop, partition);
1358 break;
1360 default:
1361 gcc_unreachable ();
1364 /* Common tail for partitions we turn into a call. If this was the last
1365 partition for which we generate code, we have to destroy the loop. */
1366 if (!copy_p)
1367 return true;
1368 return false;
1371 data_dependence_relation *
1372 loop_distribution::get_data_dependence (struct graph *rdg, data_reference_p a,
1373 data_reference_p b)
1375 struct data_dependence_relation ent, **slot;
1376 struct data_dependence_relation *ddr;
1378 gcc_assert (DR_IS_WRITE (a) || DR_IS_WRITE (b));
1379 gcc_assert (rdg_vertex_for_stmt (rdg, DR_STMT (a))
1380 <= rdg_vertex_for_stmt (rdg, DR_STMT (b)));
1381 ent.a = a;
1382 ent.b = b;
1383 slot = ddrs_table->find_slot (&ent, INSERT);
1384 if (*slot == NULL)
1386 ddr = initialize_data_dependence_relation (a, b, loop_nest);
1387 compute_affine_dependence (ddr, loop_nest[0]);
1388 *slot = ddr;
1391 return *slot;
1394 bool
1395 loop_distribution::data_dep_in_cycle_p (struct graph *rdg,
1396 data_reference_p dr1,
1397 data_reference_p dr2)
1399 struct data_dependence_relation *ddr;
1401 /* Re-shuffle data-refs to be in topological order. */
1402 if (rdg_vertex_for_stmt (rdg, DR_STMT (dr1))
1403 > rdg_vertex_for_stmt (rdg, DR_STMT (dr2)))
1404 std::swap (dr1, dr2);
1406 ddr = get_data_dependence (rdg, dr1, dr2);
1408 /* In case of no data dependence. */
1409 if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
1410 return false;
1411 /* For unknown data dependence or known data dependence which can't be
1412 expressed in classic distance vector, we check if it can be resolved
1413 by runtime alias check. If yes, we still consider data dependence
1414 as won't introduce data dependence cycle. */
1415 else if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know
1416 || DDR_NUM_DIST_VECTS (ddr) == 0)
1417 return !runtime_alias_check_p (ddr, NULL, true);
1418 else if (DDR_NUM_DIST_VECTS (ddr) > 1)
1419 return true;
1420 else if (DDR_REVERSED_P (ddr)
1421 || lambda_vector_zerop (DDR_DIST_VECT (ddr, 0), 1))
1422 return false;
1424 return true;
1427 void
1428 loop_distribution::update_type_for_merge (struct graph *rdg,
1429 partition *partition1,
1430 partition *partition2)
1432 unsigned i, j;
1433 bitmap_iterator bi, bj;
1434 data_reference_p dr1, dr2;
1436 EXECUTE_IF_SET_IN_BITMAP (partition1->datarefs, 0, i, bi)
1438 unsigned start = (partition1 == partition2) ? i + 1 : 0;
1440 dr1 = datarefs_vec[i];
1441 EXECUTE_IF_SET_IN_BITMAP (partition2->datarefs, start, j, bj)
1443 dr2 = datarefs_vec[j];
1444 if (DR_IS_READ (dr1) && DR_IS_READ (dr2))
1445 continue;
1447 /* Partition can only be executed sequentially if there is any
1448 data dependence cycle. */
1449 if (data_dep_in_cycle_p (rdg, dr1, dr2))
1451 partition1->type = PTYPE_SEQUENTIAL;
1452 return;
1458 partition *
1459 loop_distribution::build_rdg_partition_for_vertex (struct graph *rdg, int v)
1461 partition *partition = partition_alloc ();
1462 auto_vec<int, 3> nodes;
1463 unsigned i, j;
1464 int x;
1465 data_reference_p dr;
1467 graphds_dfs (rdg, &v, 1, &nodes, false, NULL);
1469 FOR_EACH_VEC_ELT (nodes, i, x)
1471 bitmap_set_bit (partition->stmts, x);
1473 for (j = 0; RDG_DATAREFS (rdg, x).iterate (j, &dr); ++j)
1475 unsigned idx = (unsigned) DR_INDEX (dr);
1476 gcc_assert (idx < datarefs_vec.length ());
1478 /* Partition can only be executed sequentially if there is any
1479 unknown data reference. */
1480 if (!DR_BASE_ADDRESS (dr) || !DR_OFFSET (dr)
1481 || !DR_INIT (dr) || !DR_STEP (dr))
1482 partition->type = PTYPE_SEQUENTIAL;
1484 bitmap_set_bit (partition->datarefs, idx);
1488 if (partition->type == PTYPE_SEQUENTIAL)
1489 return partition;
1491 /* Further check if any data dependence prevents us from executing the
1492 partition parallelly. */
1493 update_type_for_merge (rdg, partition, partition);
1495 return partition;
1498 /* Given PARTITION of LOOP and RDG, record single load/store data references
1499 for builtin partition in SRC_DR/DST_DR, return false if there is no such
1500 data references. */
1502 static bool
1503 find_single_drs (class loop *loop, struct graph *rdg, const bitmap &partition_stmts,
1504 data_reference_p *dst_dr, data_reference_p *src_dr)
1506 unsigned i;
1507 data_reference_p single_ld = NULL, single_st = NULL;
1508 bitmap_iterator bi;
1510 EXECUTE_IF_SET_IN_BITMAP (partition_stmts, 0, i, bi)
1512 gimple *stmt = RDG_STMT (rdg, i);
1513 data_reference_p dr;
1515 if (gimple_code (stmt) == GIMPLE_PHI)
1516 continue;
1518 /* Any scalar stmts are ok. */
1519 if (!gimple_vuse (stmt))
1520 continue;
1522 /* Otherwise just regular loads/stores. */
1523 if (!gimple_assign_single_p (stmt))
1524 return false;
1526 /* But exactly one store and/or load. */
1527 for (unsigned j = 0; RDG_DATAREFS (rdg, i).iterate (j, &dr); ++j)
1529 tree type = TREE_TYPE (DR_REF (dr));
1531 /* The memset, memcpy and memmove library calls are only
1532 able to deal with generic address space. */
1533 if (!ADDR_SPACE_GENERIC_P (TYPE_ADDR_SPACE (type)))
1534 return false;
1536 if (DR_IS_READ (dr))
1538 if (single_ld != NULL)
1539 return false;
1540 single_ld = dr;
1542 else
1544 if (single_st != NULL)
1545 return false;
1546 single_st = dr;
1551 if (!single_ld && !single_st)
1552 return false;
1554 basic_block bb_ld = NULL;
1555 basic_block bb_st = NULL;
1557 if (single_ld)
1559 /* Bail out if this is a bitfield memory reference. */
1560 if (TREE_CODE (DR_REF (single_ld)) == COMPONENT_REF
1561 && DECL_BIT_FIELD (TREE_OPERAND (DR_REF (single_ld), 1)))
1562 return false;
1564 /* Data reference must be executed exactly once per iteration of each
1565 loop in the loop nest. We only need to check dominance information
1566 against the outermost one in a perfect loop nest because a bb can't
1567 dominate outermost loop's latch without dominating inner loop's. */
1568 bb_ld = gimple_bb (DR_STMT (single_ld));
1569 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb_ld))
1570 return false;
1573 if (single_st)
1575 /* Bail out if this is a bitfield memory reference. */
1576 if (TREE_CODE (DR_REF (single_st)) == COMPONENT_REF
1577 && DECL_BIT_FIELD (TREE_OPERAND (DR_REF (single_st), 1)))
1578 return false;
1580 /* Data reference must be executed exactly once per iteration.
1581 Same as single_ld, we only need to check against the outermost
1582 loop. */
1583 bb_st = gimple_bb (DR_STMT (single_st));
1584 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb_st))
1585 return false;
1588 if (single_ld && single_st)
1590 /* Load and store must be in the same loop nest. */
1591 if (bb_st->loop_father != bb_ld->loop_father)
1592 return false;
1594 edge e = single_exit (bb_st->loop_father);
1595 bool dom_ld = dominated_by_p (CDI_DOMINATORS, e->src, bb_ld);
1596 bool dom_st = dominated_by_p (CDI_DOMINATORS, e->src, bb_st);
1597 if (dom_ld != dom_st)
1598 return false;
1601 *src_dr = single_ld;
1602 *dst_dr = single_st;
1603 return true;
1606 /* Given data reference DR in LOOP_NEST, this function checks the enclosing
1607 loops from inner to outer to see if loop's step equals to access size at
1608 each level of loop. Return 2 if we can prove this at all level loops;
1609 record access base and size in BASE and SIZE; save loop's step at each
1610 level of loop in STEPS if it is not null. For example:
1612 int arr[100][100][100];
1613 for (i = 0; i < 100; i++) ;steps[2] = 40000
1614 for (j = 100; j > 0; j--) ;steps[1] = -400
1615 for (k = 0; k < 100; k++) ;steps[0] = 4
1616 arr[i][j - 1][k] = 0; ;base = &arr, size = 4000000
1618 Return 1 if we can prove the equality at the innermost loop, but not all
1619 level loops. In this case, no information is recorded.
1621 Return 0 if no equality can be proven at any level loops. */
1623 static int
1624 compute_access_range (loop_p loop_nest, data_reference_p dr, tree *base,
1625 tree *size, vec<tree> *steps = NULL)
1627 location_t loc = gimple_location (DR_STMT (dr));
1628 basic_block bb = gimple_bb (DR_STMT (dr));
1629 class loop *loop = bb->loop_father;
1630 tree ref = DR_REF (dr);
1631 tree access_base = build_fold_addr_expr (ref);
1632 tree access_size = TYPE_SIZE_UNIT (TREE_TYPE (ref));
1633 int res = 0;
1635 do {
1636 tree scev_fn = analyze_scalar_evolution (loop, access_base);
1637 if (TREE_CODE (scev_fn) != POLYNOMIAL_CHREC)
1638 return res;
1640 access_base = CHREC_LEFT (scev_fn);
1641 if (tree_contains_chrecs (access_base, NULL))
1642 return res;
1644 tree scev_step = CHREC_RIGHT (scev_fn);
1645 /* Only support constant steps. */
1646 if (TREE_CODE (scev_step) != INTEGER_CST)
1647 return res;
1649 enum ev_direction access_dir = scev_direction (scev_fn);
1650 if (access_dir == EV_DIR_UNKNOWN)
1651 return res;
1653 if (steps != NULL)
1654 steps->safe_push (scev_step);
1656 scev_step = fold_convert_loc (loc, sizetype, scev_step);
1657 /* Compute absolute value of scev step. */
1658 if (access_dir == EV_DIR_DECREASES)
1659 scev_step = fold_build1_loc (loc, NEGATE_EXPR, sizetype, scev_step);
1661 /* At each level of loop, scev step must equal to access size. In other
1662 words, DR must access consecutive memory between loop iterations. */
1663 if (!operand_equal_p (scev_step, access_size, 0))
1664 return res;
1666 /* Access stride can be computed for data reference at least for the
1667 innermost loop. */
1668 res = 1;
1670 /* Compute DR's execution times in loop. */
1671 tree niters = number_of_latch_executions (loop);
1672 niters = fold_convert_loc (loc, sizetype, niters);
1673 if (dominated_by_p (CDI_DOMINATORS, single_exit (loop)->src, bb))
1674 niters = size_binop_loc (loc, PLUS_EXPR, niters, size_one_node);
1676 /* Compute DR's overall access size in loop. */
1677 access_size = fold_build2_loc (loc, MULT_EXPR, sizetype,
1678 niters, scev_step);
1679 /* Adjust base address in case of negative step. */
1680 if (access_dir == EV_DIR_DECREASES)
1682 tree adj = fold_build2_loc (loc, MINUS_EXPR, sizetype,
1683 scev_step, access_size);
1684 access_base = fold_build_pointer_plus_loc (loc, access_base, adj);
1686 } while (loop != loop_nest && (loop = loop_outer (loop)) != NULL);
1688 *base = access_base;
1689 *size = access_size;
1690 /* Access stride can be computed for data reference at each level loop. */
1691 return 2;
1694 /* Allocate and return builtin struct. Record information like DST_DR,
1695 SRC_DR, DST_BASE, SRC_BASE and SIZE in the allocated struct. */
1697 static struct builtin_info *
1698 alloc_builtin (data_reference_p dst_dr, data_reference_p src_dr,
1699 tree dst_base, tree src_base, tree size)
1701 struct builtin_info *builtin = XNEW (struct builtin_info);
1702 builtin->dst_dr = dst_dr;
1703 builtin->src_dr = src_dr;
1704 builtin->dst_base = dst_base;
1705 builtin->src_base = src_base;
1706 builtin->size = size;
1707 return builtin;
1710 /* Given data reference DR in loop nest LOOP, classify if it forms builtin
1711 memset call. */
1713 static void
1714 classify_builtin_st (loop_p loop, partition *partition, data_reference_p dr)
1716 gimple *stmt = DR_STMT (dr);
1717 tree base, size, rhs = gimple_assign_rhs1 (stmt);
1719 if (const_with_all_bytes_same (rhs) == -1
1720 && (!INTEGRAL_TYPE_P (TREE_TYPE (rhs))
1721 || (TYPE_MODE (TREE_TYPE (rhs))
1722 != TYPE_MODE (unsigned_char_type_node))))
1723 return;
1725 if (TREE_CODE (rhs) == SSA_NAME
1726 && !SSA_NAME_IS_DEFAULT_DEF (rhs)
1727 && flow_bb_inside_loop_p (loop, gimple_bb (SSA_NAME_DEF_STMT (rhs))))
1728 return;
1730 int res = compute_access_range (loop, dr, &base, &size);
1731 if (res == 0)
1732 return;
1733 if (res == 1)
1735 partition->kind = PKIND_PARTIAL_MEMSET;
1736 return;
1739 poly_uint64 base_offset;
1740 unsigned HOST_WIDE_INT const_base_offset;
1741 tree base_base = strip_offset (base, &base_offset);
1742 if (!base_offset.is_constant (&const_base_offset))
1743 return;
1745 struct builtin_info *builtin;
1746 builtin = alloc_builtin (dr, NULL, base, NULL_TREE, size);
1747 builtin->dst_base_base = base_base;
1748 builtin->dst_base_offset = const_base_offset;
1749 partition->builtin = builtin;
1750 partition->kind = PKIND_MEMSET;
1753 /* Given data references DST_DR and SRC_DR in loop nest LOOP and RDG, classify
1754 if it forms builtin memcpy or memmove call. */
1756 void
1757 loop_distribution::classify_builtin_ldst (loop_p loop, struct graph *rdg,
1758 partition *partition,
1759 data_reference_p dst_dr,
1760 data_reference_p src_dr)
1762 tree base, size, src_base, src_size;
1763 auto_vec<tree> dst_steps, src_steps;
1765 /* Compute access range of both load and store. */
1766 int res = compute_access_range (loop, dst_dr, &base, &size, &dst_steps);
1767 if (res != 2)
1768 return;
1769 res = compute_access_range (loop, src_dr, &src_base, &src_size, &src_steps);
1770 if (res != 2)
1771 return;
1773 /* They much have the same access size. */
1774 if (!operand_equal_p (size, src_size, 0))
1775 return;
1777 /* Load and store in loop nest must access memory in the same way, i.e,
1778 their must have the same steps in each loop of the nest. */
1779 if (dst_steps.length () != src_steps.length ())
1780 return;
1781 for (unsigned i = 0; i < dst_steps.length (); ++i)
1782 if (!operand_equal_p (dst_steps[i], src_steps[i], 0))
1783 return;
1785 /* Now check that if there is a dependence. */
1786 ddr_p ddr = get_data_dependence (rdg, src_dr, dst_dr);
1788 /* Classify as memmove if no dependence between load and store. */
1789 if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
1791 partition->builtin = alloc_builtin (dst_dr, src_dr, base, src_base, size);
1792 partition->kind = PKIND_MEMMOVE;
1793 return;
1796 /* Can't do memmove in case of unknown dependence or dependence without
1797 classical distance vector. */
1798 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know
1799 || DDR_NUM_DIST_VECTS (ddr) == 0)
1800 return;
1802 unsigned i;
1803 lambda_vector dist_v;
1804 int num_lev = (DDR_LOOP_NEST (ddr)).length ();
1805 FOR_EACH_VEC_ELT (DDR_DIST_VECTS (ddr), i, dist_v)
1807 unsigned dep_lev = dependence_level (dist_v, num_lev);
1808 /* Can't do memmove if load depends on store. */
1809 if (dep_lev > 0 && dist_v[dep_lev - 1] > 0 && !DDR_REVERSED_P (ddr))
1810 return;
1813 partition->builtin = alloc_builtin (dst_dr, src_dr, base, src_base, size);
1814 partition->kind = PKIND_MEMMOVE;
1815 return;
1818 bool
1819 loop_distribution::classify_partition (loop_p loop,
1820 struct graph *rdg, partition *partition,
1821 bitmap stmt_in_all_partitions)
1823 bitmap_iterator bi;
1824 unsigned i;
1825 data_reference_p single_ld = NULL, single_st = NULL;
1826 bool volatiles_p = false, has_reduction = false;
1828 EXECUTE_IF_SET_IN_BITMAP (partition->stmts, 0, i, bi)
1830 gimple *stmt = RDG_STMT (rdg, i);
1832 if (gimple_has_volatile_ops (stmt))
1833 volatiles_p = true;
1835 /* If the stmt is not included by all partitions and there is uses
1836 outside of the loop, then mark the partition as reduction. */
1837 if (stmt_has_scalar_dependences_outside_loop (loop, stmt))
1839 /* Due to limitation in the transform phase we have to fuse all
1840 reduction partitions. As a result, this could cancel valid
1841 loop distribution especially for loop that induction variable
1842 is used outside of loop. To workaround this issue, we skip
1843 marking partition as reudction if the reduction stmt belongs
1844 to all partitions. In such case, reduction will be computed
1845 correctly no matter how partitions are fused/distributed. */
1846 if (!bitmap_bit_p (stmt_in_all_partitions, i))
1847 partition->reduction_p = true;
1848 else
1849 has_reduction = true;
1853 /* Simple workaround to prevent classifying the partition as builtin
1854 if it contains any use outside of loop. For the case where all
1855 partitions have the reduction this simple workaround is delayed
1856 to only affect the last partition. */
1857 if (partition->reduction_p)
1858 return has_reduction;
1860 /* Perform general partition disqualification for builtins. */
1861 if (volatiles_p
1862 || !flag_tree_loop_distribute_patterns)
1863 return has_reduction;
1865 /* Find single load/store data references for builtin partition. */
1866 if (!find_single_drs (loop, rdg, partition->stmts, &single_st, &single_ld)
1867 || !single_st)
1868 return has_reduction;
1870 if (single_ld && single_st)
1872 gimple *store = DR_STMT (single_st), *load = DR_STMT (single_ld);
1873 /* Direct aggregate copy or via an SSA name temporary. */
1874 if (load != store
1875 && gimple_assign_lhs (load) != gimple_assign_rhs1 (store))
1876 return has_reduction;
1879 partition->loc = gimple_location (DR_STMT (single_st));
1881 /* Classify the builtin kind. */
1882 if (single_ld == NULL)
1883 classify_builtin_st (loop, partition, single_st);
1884 else
1885 classify_builtin_ldst (loop, rdg, partition, single_st, single_ld);
1886 return has_reduction;
1889 bool
1890 loop_distribution::share_memory_accesses (struct graph *rdg,
1891 partition *partition1, partition *partition2)
1893 unsigned i, j;
1894 bitmap_iterator bi, bj;
1895 data_reference_p dr1, dr2;
1897 /* First check whether in the intersection of the two partitions are
1898 any loads or stores. Common loads are the situation that happens
1899 most often. */
1900 EXECUTE_IF_AND_IN_BITMAP (partition1->stmts, partition2->stmts, 0, i, bi)
1901 if (RDG_MEM_WRITE_STMT (rdg, i)
1902 || RDG_MEM_READS_STMT (rdg, i))
1903 return true;
1905 /* Then check whether the two partitions access the same memory object. */
1906 EXECUTE_IF_SET_IN_BITMAP (partition1->datarefs, 0, i, bi)
1908 dr1 = datarefs_vec[i];
1910 if (!DR_BASE_ADDRESS (dr1)
1911 || !DR_OFFSET (dr1) || !DR_INIT (dr1) || !DR_STEP (dr1))
1912 continue;
1914 EXECUTE_IF_SET_IN_BITMAP (partition2->datarefs, 0, j, bj)
1916 dr2 = datarefs_vec[j];
1918 if (!DR_BASE_ADDRESS (dr2)
1919 || !DR_OFFSET (dr2) || !DR_INIT (dr2) || !DR_STEP (dr2))
1920 continue;
1922 if (operand_equal_p (DR_BASE_ADDRESS (dr1), DR_BASE_ADDRESS (dr2), 0)
1923 && operand_equal_p (DR_OFFSET (dr1), DR_OFFSET (dr2), 0)
1924 && operand_equal_p (DR_INIT (dr1), DR_INIT (dr2), 0)
1925 && operand_equal_p (DR_STEP (dr1), DR_STEP (dr2), 0))
1926 return true;
1930 return false;
1933 /* For each seed statement in STARTING_STMTS, this function builds
1934 partition for it by adding depended statements according to RDG.
1935 All partitions are recorded in PARTITIONS. */
1937 void
1938 loop_distribution::rdg_build_partitions (struct graph *rdg,
1939 vec<gimple *> starting_stmts,
1940 vec<partition *> *partitions)
1942 auto_bitmap processed;
1943 int i;
1944 gimple *stmt;
1946 FOR_EACH_VEC_ELT (starting_stmts, i, stmt)
1948 int v = rdg_vertex_for_stmt (rdg, stmt);
1950 if (dump_file && (dump_flags & TDF_DETAILS))
1951 fprintf (dump_file,
1952 "ldist asked to generate code for vertex %d\n", v);
1954 /* If the vertex is already contained in another partition so
1955 is the partition rooted at it. */
1956 if (bitmap_bit_p (processed, v))
1957 continue;
1959 partition *partition = build_rdg_partition_for_vertex (rdg, v);
1960 bitmap_ior_into (processed, partition->stmts);
1962 if (dump_file && (dump_flags & TDF_DETAILS))
1964 fprintf (dump_file, "ldist creates useful %s partition:\n",
1965 partition->type == PTYPE_PARALLEL ? "parallel" : "sequent");
1966 bitmap_print (dump_file, partition->stmts, " ", "\n");
1969 partitions->safe_push (partition);
1972 /* All vertices should have been assigned to at least one partition now,
1973 other than vertices belonging to dead code. */
1976 /* Dump to FILE the PARTITIONS. */
1978 static void
1979 dump_rdg_partitions (FILE *file, const vec<partition *> &partitions)
1981 int i;
1982 partition *partition;
1984 FOR_EACH_VEC_ELT (partitions, i, partition)
1985 debug_bitmap_file (file, partition->stmts);
1988 /* Debug PARTITIONS. */
1989 extern void debug_rdg_partitions (const vec<partition *> &);
1991 DEBUG_FUNCTION void
1992 debug_rdg_partitions (const vec<partition *> &partitions)
1994 dump_rdg_partitions (stderr, partitions);
1997 /* Returns the number of read and write operations in the RDG. */
1999 static int
2000 number_of_rw_in_rdg (struct graph *rdg)
2002 int i, res = 0;
2004 for (i = 0; i < rdg->n_vertices; i++)
2006 if (RDG_MEM_WRITE_STMT (rdg, i))
2007 ++res;
2009 if (RDG_MEM_READS_STMT (rdg, i))
2010 ++res;
2013 return res;
2016 /* Returns the number of read and write operations in a PARTITION of
2017 the RDG. */
2019 static int
2020 number_of_rw_in_partition (struct graph *rdg, partition *partition)
2022 int res = 0;
2023 unsigned i;
2024 bitmap_iterator ii;
2026 EXECUTE_IF_SET_IN_BITMAP (partition->stmts, 0, i, ii)
2028 if (RDG_MEM_WRITE_STMT (rdg, i))
2029 ++res;
2031 if (RDG_MEM_READS_STMT (rdg, i))
2032 ++res;
2035 return res;
2038 /* Returns true when one of the PARTITIONS contains all the read or
2039 write operations of RDG. */
2041 static bool
2042 partition_contains_all_rw (struct graph *rdg,
2043 const vec<partition *> &partitions)
2045 int i;
2046 partition *partition;
2047 int nrw = number_of_rw_in_rdg (rdg);
2049 FOR_EACH_VEC_ELT (partitions, i, partition)
2050 if (nrw == number_of_rw_in_partition (rdg, partition))
2051 return true;
2053 return false;
2057 loop_distribution::pg_add_dependence_edges (struct graph *rdg, int dir,
2058 bitmap drs1, bitmap drs2, vec<ddr_p> *alias_ddrs)
2060 unsigned i, j;
2061 bitmap_iterator bi, bj;
2062 data_reference_p dr1, dr2, saved_dr1;
2064 /* dependence direction - 0 is no dependence, -1 is back,
2065 1 is forth, 2 is both (we can stop then, merging will occur). */
2066 EXECUTE_IF_SET_IN_BITMAP (drs1, 0, i, bi)
2068 dr1 = datarefs_vec[i];
2070 EXECUTE_IF_SET_IN_BITMAP (drs2, 0, j, bj)
2072 int res, this_dir = 1;
2073 ddr_p ddr;
2075 dr2 = datarefs_vec[j];
2077 /* Skip all <read, read> data dependence. */
2078 if (DR_IS_READ (dr1) && DR_IS_READ (dr2))
2079 continue;
2081 saved_dr1 = dr1;
2082 /* Re-shuffle data-refs to be in topological order. */
2083 if (rdg_vertex_for_stmt (rdg, DR_STMT (dr1))
2084 > rdg_vertex_for_stmt (rdg, DR_STMT (dr2)))
2086 std::swap (dr1, dr2);
2087 this_dir = -this_dir;
2089 ddr = get_data_dependence (rdg, dr1, dr2);
2090 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
2092 this_dir = 0;
2093 res = data_ref_compare_tree (DR_BASE_ADDRESS (dr1),
2094 DR_BASE_ADDRESS (dr2));
2095 /* Be conservative. If data references are not well analyzed,
2096 or the two data references have the same base address and
2097 offset, add dependence and consider it alias to each other.
2098 In other words, the dependence cannot be resolved by
2099 runtime alias check. */
2100 if (!DR_BASE_ADDRESS (dr1) || !DR_BASE_ADDRESS (dr2)
2101 || !DR_OFFSET (dr1) || !DR_OFFSET (dr2)
2102 || !DR_INIT (dr1) || !DR_INIT (dr2)
2103 || !DR_STEP (dr1) || !tree_fits_uhwi_p (DR_STEP (dr1))
2104 || !DR_STEP (dr2) || !tree_fits_uhwi_p (DR_STEP (dr2))
2105 || res == 0)
2106 this_dir = 2;
2107 /* Data dependence could be resolved by runtime alias check,
2108 record it in ALIAS_DDRS. */
2109 else if (alias_ddrs != NULL)
2110 alias_ddrs->safe_push (ddr);
2111 /* Or simply ignore it. */
2113 else if (DDR_ARE_DEPENDENT (ddr) == NULL_TREE)
2115 if (DDR_REVERSED_P (ddr))
2116 this_dir = -this_dir;
2118 /* Known dependences can still be unordered througout the
2119 iteration space, see gcc.dg/tree-ssa/ldist-16.c and
2120 gcc.dg/tree-ssa/pr94969.c. */
2121 if (DDR_NUM_DIST_VECTS (ddr) != 1)
2122 this_dir = 2;
2123 /* If the overlap is exact preserve stmt order. */
2124 else if (lambda_vector_zerop (DDR_DIST_VECT (ddr, 0),
2125 DDR_NB_LOOPS (ddr)))
2127 /* Else as the distance vector is lexicographic positive swap
2128 the dependence direction. */
2129 else
2130 this_dir = -this_dir;
2132 else
2133 this_dir = 0;
2134 if (this_dir == 2)
2135 return 2;
2136 else if (dir == 0)
2137 dir = this_dir;
2138 else if (this_dir != 0 && dir != this_dir)
2139 return 2;
2140 /* Shuffle "back" dr1. */
2141 dr1 = saved_dr1;
2144 return dir;
2147 /* Compare postorder number of the partition graph vertices V1 and V2. */
2149 static int
2150 pgcmp (const void *v1_, const void *v2_)
2152 const vertex *v1 = (const vertex *)v1_;
2153 const vertex *v2 = (const vertex *)v2_;
2154 return v2->post - v1->post;
2157 /* Data attached to vertices of partition dependence graph. */
2158 struct pg_vdata
2160 /* ID of the corresponding partition. */
2161 int id;
2162 /* The partition. */
2163 struct partition *partition;
2166 /* Data attached to edges of partition dependence graph. */
2167 struct pg_edata
2169 /* If the dependence edge can be resolved by runtime alias check,
2170 this vector contains data dependence relations for runtime alias
2171 check. On the other hand, if the dependence edge is introduced
2172 because of compilation time known data dependence, this vector
2173 contains nothing. */
2174 vec<ddr_p> alias_ddrs;
2177 /* Callback data for traversing edges in graph. */
2178 struct pg_edge_callback_data
2180 /* Bitmap contains strong connected components should be merged. */
2181 bitmap sccs_to_merge;
2182 /* Array constains component information for all vertices. */
2183 int *vertices_component;
2184 /* Array constains postorder information for all vertices. */
2185 int *vertices_post;
2186 /* Vector to record all data dependence relations which are needed
2187 to break strong connected components by runtime alias checks. */
2188 vec<ddr_p> *alias_ddrs;
2191 /* Initialize vertice's data for partition dependence graph PG with
2192 PARTITIONS. */
2194 static void
2195 init_partition_graph_vertices (struct graph *pg,
2196 vec<struct partition *> *partitions)
2198 int i;
2199 partition *partition;
2200 struct pg_vdata *data;
2202 for (i = 0; partitions->iterate (i, &partition); ++i)
2204 data = new pg_vdata;
2205 pg->vertices[i].data = data;
2206 data->id = i;
2207 data->partition = partition;
2211 /* Add edge <I, J> to partition dependence graph PG. Attach vector of data
2212 dependence relations to the EDGE if DDRS isn't NULL. */
2214 static void
2215 add_partition_graph_edge (struct graph *pg, int i, int j, vec<ddr_p> *ddrs)
2217 struct graph_edge *e = add_edge (pg, i, j);
2219 /* If the edge is attached with data dependence relations, it means this
2220 dependence edge can be resolved by runtime alias checks. */
2221 if (ddrs != NULL)
2223 struct pg_edata *data = new pg_edata;
2225 gcc_assert (ddrs->length () > 0);
2226 e->data = data;
2227 data->alias_ddrs = vNULL;
2228 data->alias_ddrs.safe_splice (*ddrs);
2232 /* Callback function for graph travesal algorithm. It returns true
2233 if edge E should skipped when traversing the graph. */
2235 static bool
2236 pg_skip_alias_edge (struct graph_edge *e)
2238 struct pg_edata *data = (struct pg_edata *)e->data;
2239 return (data != NULL && data->alias_ddrs.length () > 0);
2242 /* Callback function freeing data attached to edge E of graph. */
2244 static void
2245 free_partition_graph_edata_cb (struct graph *, struct graph_edge *e, void *)
2247 if (e->data != NULL)
2249 struct pg_edata *data = (struct pg_edata *)e->data;
2250 data->alias_ddrs.release ();
2251 delete data;
2255 /* Free data attached to vertice of partition dependence graph PG. */
2257 static void
2258 free_partition_graph_vdata (struct graph *pg)
2260 int i;
2261 struct pg_vdata *data;
2263 for (i = 0; i < pg->n_vertices; ++i)
2265 data = (struct pg_vdata *)pg->vertices[i].data;
2266 delete data;
2270 /* Build and return partition dependence graph for PARTITIONS. RDG is
2271 reduced dependence graph for the loop to be distributed. If IGNORE_ALIAS_P
2272 is true, data dependence caused by possible alias between references
2273 is ignored, as if it doesn't exist at all; otherwise all depdendences
2274 are considered. */
2276 struct graph *
2277 loop_distribution::build_partition_graph (struct graph *rdg,
2278 vec<struct partition *> *partitions,
2279 bool ignore_alias_p)
2281 int i, j;
2282 struct partition *partition1, *partition2;
2283 graph *pg = new_graph (partitions->length ());
2284 auto_vec<ddr_p> alias_ddrs, *alias_ddrs_p;
2286 alias_ddrs_p = ignore_alias_p ? NULL : &alias_ddrs;
2288 init_partition_graph_vertices (pg, partitions);
2290 for (i = 0; partitions->iterate (i, &partition1); ++i)
2292 for (j = i + 1; partitions->iterate (j, &partition2); ++j)
2294 /* dependence direction - 0 is no dependence, -1 is back,
2295 1 is forth, 2 is both (we can stop then, merging will occur). */
2296 int dir = 0;
2298 /* If the first partition has reduction, add back edge; if the
2299 second partition has reduction, add forth edge. This makes
2300 sure that reduction partition will be sorted as the last one. */
2301 if (partition_reduction_p (partition1))
2302 dir = -1;
2303 else if (partition_reduction_p (partition2))
2304 dir = 1;
2306 /* Cleanup the temporary vector. */
2307 alias_ddrs.truncate (0);
2309 dir = pg_add_dependence_edges (rdg, dir, partition1->datarefs,
2310 partition2->datarefs, alias_ddrs_p);
2312 /* Add edge to partition graph if there exists dependence. There
2313 are two types of edges. One type edge is caused by compilation
2314 time known dependence, this type cannot be resolved by runtime
2315 alias check. The other type can be resolved by runtime alias
2316 check. */
2317 if (dir == 1 || dir == 2
2318 || alias_ddrs.length () > 0)
2320 /* Attach data dependence relations to edge that can be resolved
2321 by runtime alias check. */
2322 bool alias_edge_p = (dir != 1 && dir != 2);
2323 add_partition_graph_edge (pg, i, j,
2324 (alias_edge_p) ? &alias_ddrs : NULL);
2326 if (dir == -1 || dir == 2
2327 || alias_ddrs.length () > 0)
2329 /* Attach data dependence relations to edge that can be resolved
2330 by runtime alias check. */
2331 bool alias_edge_p = (dir != -1 && dir != 2);
2332 add_partition_graph_edge (pg, j, i,
2333 (alias_edge_p) ? &alias_ddrs : NULL);
2337 return pg;
2340 /* Sort partitions in PG in descending post order and store them in
2341 PARTITIONS. */
2343 static void
2344 sort_partitions_by_post_order (struct graph *pg,
2345 vec<struct partition *> *partitions)
2347 int i;
2348 struct pg_vdata *data;
2350 /* Now order the remaining nodes in descending postorder. */
2351 qsort (pg->vertices, pg->n_vertices, sizeof (vertex), pgcmp);
2352 partitions->truncate (0);
2353 for (i = 0; i < pg->n_vertices; ++i)
2355 data = (struct pg_vdata *)pg->vertices[i].data;
2356 if (data->partition)
2357 partitions->safe_push (data->partition);
2361 void
2362 loop_distribution::merge_dep_scc_partitions (struct graph *rdg,
2363 vec<struct partition *> *partitions,
2364 bool ignore_alias_p)
2366 struct partition *partition1, *partition2;
2367 struct pg_vdata *data;
2368 graph *pg = build_partition_graph (rdg, partitions, ignore_alias_p);
2369 int i, j, num_sccs = graphds_scc (pg, NULL);
2371 /* Strong connected compoenent means dependence cycle, we cannot distribute
2372 them. So fuse them together. */
2373 if ((unsigned) num_sccs < partitions->length ())
2375 for (i = 0; i < num_sccs; ++i)
2377 for (j = 0; partitions->iterate (j, &partition1); ++j)
2378 if (pg->vertices[j].component == i)
2379 break;
2380 for (j = j + 1; partitions->iterate (j, &partition2); ++j)
2381 if (pg->vertices[j].component == i)
2383 partition_merge_into (NULL, partition1,
2384 partition2, FUSE_SAME_SCC);
2385 partition1->type = PTYPE_SEQUENTIAL;
2386 (*partitions)[j] = NULL;
2387 partition_free (partition2);
2388 data = (struct pg_vdata *)pg->vertices[j].data;
2389 data->partition = NULL;
2394 sort_partitions_by_post_order (pg, partitions);
2395 gcc_assert (partitions->length () == (unsigned)num_sccs);
2396 free_partition_graph_vdata (pg);
2397 for_each_edge (pg, free_partition_graph_edata_cb, NULL);
2398 free_graph (pg);
2401 /* Callback function for traversing edge E in graph G. DATA is private
2402 callback data. */
2404 static void
2405 pg_collect_alias_ddrs (struct graph *g, struct graph_edge *e, void *data)
2407 int i, j, component;
2408 struct pg_edge_callback_data *cbdata;
2409 struct pg_edata *edata = (struct pg_edata *) e->data;
2411 /* If the edge doesn't have attached data dependence, it represents
2412 compilation time known dependences. This type dependence cannot
2413 be resolved by runtime alias check. */
2414 if (edata == NULL || edata->alias_ddrs.length () == 0)
2415 return;
2417 cbdata = (struct pg_edge_callback_data *) data;
2418 i = e->src;
2419 j = e->dest;
2420 component = cbdata->vertices_component[i];
2421 /* Vertices are topologically sorted according to compilation time
2422 known dependences, so we can break strong connected components
2423 by removing edges of the opposite direction, i.e, edges pointing
2424 from vertice with smaller post number to vertice with bigger post
2425 number. */
2426 if (g->vertices[i].post < g->vertices[j].post
2427 /* We only need to remove edges connecting vertices in the same
2428 strong connected component to break it. */
2429 && component == cbdata->vertices_component[j]
2430 /* Check if we want to break the strong connected component or not. */
2431 && !bitmap_bit_p (cbdata->sccs_to_merge, component))
2432 cbdata->alias_ddrs->safe_splice (edata->alias_ddrs);
2435 /* This is the main function breaking strong conected components in
2436 PARTITIONS giving reduced depdendence graph RDG. Store data dependence
2437 relations for runtime alias check in ALIAS_DDRS. */
2438 void
2439 loop_distribution::break_alias_scc_partitions (struct graph *rdg,
2440 vec<struct partition *> *partitions,
2441 vec<ddr_p> *alias_ddrs)
2443 int i, j, k, num_sccs, num_sccs_no_alias = 0;
2444 /* Build partition dependence graph. */
2445 graph *pg = build_partition_graph (rdg, partitions, false);
2447 alias_ddrs->truncate (0);
2448 /* Find strong connected components in the graph, with all dependence edges
2449 considered. */
2450 num_sccs = graphds_scc (pg, NULL);
2451 /* All SCCs now can be broken by runtime alias checks because SCCs caused by
2452 compilation time known dependences are merged before this function. */
2453 if ((unsigned) num_sccs < partitions->length ())
2455 struct pg_edge_callback_data cbdata;
2456 auto_bitmap sccs_to_merge;
2457 auto_vec<enum partition_type> scc_types;
2458 struct partition *partition, *first;
2460 /* If all partitions in a SCC have the same type, we can simply merge the
2461 SCC. This loop finds out such SCCS and record them in bitmap. */
2462 bitmap_set_range (sccs_to_merge, 0, (unsigned) num_sccs);
2463 for (i = 0; i < num_sccs; ++i)
2465 for (j = 0; partitions->iterate (j, &first); ++j)
2466 if (pg->vertices[j].component == i)
2467 break;
2469 bool same_type = true, all_builtins = partition_builtin_p (first);
2470 for (++j; partitions->iterate (j, &partition); ++j)
2472 if (pg->vertices[j].component != i)
2473 continue;
2475 if (first->type != partition->type)
2477 same_type = false;
2478 break;
2480 all_builtins &= partition_builtin_p (partition);
2482 /* Merge SCC if all partitions in SCC have the same type, though the
2483 result partition is sequential, because vectorizer can do better
2484 runtime alias check. One expecption is all partitions in SCC are
2485 builtins. */
2486 if (!same_type || all_builtins)
2487 bitmap_clear_bit (sccs_to_merge, i);
2490 /* Initialize callback data for traversing. */
2491 cbdata.sccs_to_merge = sccs_to_merge;
2492 cbdata.alias_ddrs = alias_ddrs;
2493 cbdata.vertices_component = XNEWVEC (int, pg->n_vertices);
2494 cbdata.vertices_post = XNEWVEC (int, pg->n_vertices);
2495 /* Record the component information which will be corrupted by next
2496 graph scc finding call. */
2497 for (i = 0; i < pg->n_vertices; ++i)
2498 cbdata.vertices_component[i] = pg->vertices[i].component;
2500 /* Collect data dependences for runtime alias checks to break SCCs. */
2501 if (bitmap_count_bits (sccs_to_merge) != (unsigned) num_sccs)
2503 /* Record the postorder information which will be corrupted by next
2504 graph SCC finding call. */
2505 for (i = 0; i < pg->n_vertices; ++i)
2506 cbdata.vertices_post[i] = pg->vertices[i].post;
2508 /* Run SCC finding algorithm again, with alias dependence edges
2509 skipped. This is to topologically sort partitions according to
2510 compilation time known dependence. Note the topological order
2511 is stored in the form of pg's post order number. */
2512 num_sccs_no_alias = graphds_scc (pg, NULL, pg_skip_alias_edge);
2513 gcc_assert (partitions->length () == (unsigned) num_sccs_no_alias);
2514 /* With topological order, we can construct two subgraphs L and R.
2515 L contains edge <x, y> where x < y in terms of post order, while
2516 R contains edge <x, y> where x > y. Edges for compilation time
2517 known dependence all fall in R, so we break SCCs by removing all
2518 (alias) edges of in subgraph L. */
2519 for_each_edge (pg, pg_collect_alias_ddrs, &cbdata);
2522 /* For SCC that doesn't need to be broken, merge it. */
2523 for (i = 0; i < num_sccs; ++i)
2525 if (!bitmap_bit_p (sccs_to_merge, i))
2526 continue;
2528 for (j = 0; partitions->iterate (j, &first); ++j)
2529 if (cbdata.vertices_component[j] == i)
2530 break;
2531 for (k = j + 1; partitions->iterate (k, &partition); ++k)
2533 struct pg_vdata *data;
2535 if (cbdata.vertices_component[k] != i)
2536 continue;
2538 partition_merge_into (NULL, first, partition, FUSE_SAME_SCC);
2539 (*partitions)[k] = NULL;
2540 partition_free (partition);
2541 data = (struct pg_vdata *)pg->vertices[k].data;
2542 gcc_assert (data->id == k);
2543 data->partition = NULL;
2544 /* The result partition of merged SCC must be sequential. */
2545 first->type = PTYPE_SEQUENTIAL;
2548 /* Restore the postorder information if it's corrupted in finding SCC
2549 with alias dependence edges skipped. If reduction partition's SCC is
2550 broken by runtime alias checks, we force a negative post order to it
2551 making sure it will be scheduled in the last. */
2552 if (num_sccs_no_alias > 0)
2554 j = -1;
2555 for (i = 0; i < pg->n_vertices; ++i)
2557 pg->vertices[i].post = cbdata.vertices_post[i];
2558 struct pg_vdata *data = (struct pg_vdata *)pg->vertices[i].data;
2559 if (data->partition && partition_reduction_p (data->partition))
2561 gcc_assert (j == -1);
2562 j = i;
2565 if (j >= 0)
2566 pg->vertices[j].post = -1;
2569 free (cbdata.vertices_component);
2570 free (cbdata.vertices_post);
2573 sort_partitions_by_post_order (pg, partitions);
2574 free_partition_graph_vdata (pg);
2575 for_each_edge (pg, free_partition_graph_edata_cb, NULL);
2576 free_graph (pg);
2578 if (dump_file && (dump_flags & TDF_DETAILS))
2580 fprintf (dump_file, "Possible alias data dependence to break:\n");
2581 dump_data_dependence_relations (dump_file, *alias_ddrs);
2585 /* Compute and return an expression whose value is the segment length which
2586 will be accessed by DR in NITERS iterations. */
2588 static tree
2589 data_ref_segment_size (struct data_reference *dr, tree niters)
2591 niters = size_binop (MINUS_EXPR,
2592 fold_convert (sizetype, niters),
2593 size_one_node);
2594 return size_binop (MULT_EXPR,
2595 fold_convert (sizetype, DR_STEP (dr)),
2596 fold_convert (sizetype, niters));
2599 /* Return true if LOOP's latch is dominated by statement for data reference
2600 DR. */
2602 static inline bool
2603 latch_dominated_by_data_ref (class loop *loop, data_reference *dr)
2605 return dominated_by_p (CDI_DOMINATORS, single_exit (loop)->src,
2606 gimple_bb (DR_STMT (dr)));
2609 /* Compute alias check pairs and store them in COMP_ALIAS_PAIRS for LOOP's
2610 data dependence relations ALIAS_DDRS. */
2612 static void
2613 compute_alias_check_pairs (class loop *loop, vec<ddr_p> *alias_ddrs,
2614 vec<dr_with_seg_len_pair_t> *comp_alias_pairs)
2616 unsigned int i;
2617 unsigned HOST_WIDE_INT factor = 1;
2618 tree niters_plus_one, niters = number_of_latch_executions (loop);
2620 gcc_assert (niters != NULL_TREE && niters != chrec_dont_know);
2621 niters = fold_convert (sizetype, niters);
2622 niters_plus_one = size_binop (PLUS_EXPR, niters, size_one_node);
2624 if (dump_file && (dump_flags & TDF_DETAILS))
2625 fprintf (dump_file, "Creating alias check pairs:\n");
2627 /* Iterate all data dependence relations and compute alias check pairs. */
2628 for (i = 0; i < alias_ddrs->length (); i++)
2630 ddr_p ddr = (*alias_ddrs)[i];
2631 struct data_reference *dr_a = DDR_A (ddr);
2632 struct data_reference *dr_b = DDR_B (ddr);
2633 tree seg_length_a, seg_length_b;
2635 if (latch_dominated_by_data_ref (loop, dr_a))
2636 seg_length_a = data_ref_segment_size (dr_a, niters_plus_one);
2637 else
2638 seg_length_a = data_ref_segment_size (dr_a, niters);
2640 if (latch_dominated_by_data_ref (loop, dr_b))
2641 seg_length_b = data_ref_segment_size (dr_b, niters_plus_one);
2642 else
2643 seg_length_b = data_ref_segment_size (dr_b, niters);
2645 unsigned HOST_WIDE_INT access_size_a
2646 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr_a))));
2647 unsigned HOST_WIDE_INT access_size_b
2648 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr_b))));
2649 unsigned int align_a = TYPE_ALIGN_UNIT (TREE_TYPE (DR_REF (dr_a)));
2650 unsigned int align_b = TYPE_ALIGN_UNIT (TREE_TYPE (DR_REF (dr_b)));
2652 dr_with_seg_len_pair_t dr_with_seg_len_pair
2653 (dr_with_seg_len (dr_a, seg_length_a, access_size_a, align_a),
2654 dr_with_seg_len (dr_b, seg_length_b, access_size_b, align_b),
2655 /* ??? Would WELL_ORDERED be safe? */
2656 dr_with_seg_len_pair_t::REORDERED);
2658 comp_alias_pairs->safe_push (dr_with_seg_len_pair);
2661 if (tree_fits_uhwi_p (niters))
2662 factor = tree_to_uhwi (niters);
2664 /* Prune alias check pairs. */
2665 prune_runtime_alias_test_list (comp_alias_pairs, factor);
2666 if (dump_file && (dump_flags & TDF_DETAILS))
2667 fprintf (dump_file,
2668 "Improved number of alias checks from %d to %d\n",
2669 alias_ddrs->length (), comp_alias_pairs->length ());
2672 /* Given data dependence relations in ALIAS_DDRS, generate runtime alias
2673 checks and version LOOP under condition of these runtime alias checks. */
2675 static void
2676 version_loop_by_alias_check (vec<struct partition *> *partitions,
2677 class loop *loop, vec<ddr_p> *alias_ddrs)
2679 profile_probability prob;
2680 basic_block cond_bb;
2681 class loop *nloop;
2682 tree lhs, arg0, cond_expr = NULL_TREE;
2683 gimple_seq cond_stmts = NULL;
2684 gimple *call_stmt = NULL;
2685 auto_vec<dr_with_seg_len_pair_t> comp_alias_pairs;
2687 /* Generate code for runtime alias checks if necessary. */
2688 gcc_assert (alias_ddrs->length () > 0);
2690 if (dump_file && (dump_flags & TDF_DETAILS))
2691 fprintf (dump_file,
2692 "Version loop <%d> with runtime alias check\n", loop->num);
2694 compute_alias_check_pairs (loop, alias_ddrs, &comp_alias_pairs);
2695 create_runtime_alias_checks (loop, &comp_alias_pairs, &cond_expr);
2696 cond_expr = force_gimple_operand_1 (cond_expr, &cond_stmts,
2697 is_gimple_val, NULL_TREE);
2699 /* Depend on vectorizer to fold IFN_LOOP_DIST_ALIAS. */
2700 bool cancelable_p = flag_tree_loop_vectorize;
2701 if (cancelable_p)
2703 unsigned i = 0;
2704 struct partition *partition;
2705 for (; partitions->iterate (i, &partition); ++i)
2706 if (!partition_builtin_p (partition))
2707 break;
2709 /* If all partitions are builtins, distributing it would be profitable and
2710 we don't want to cancel the runtime alias checks. */
2711 if (i == partitions->length ())
2712 cancelable_p = false;
2715 /* Generate internal function call for loop distribution alias check if the
2716 runtime alias check should be cancelable. */
2717 if (cancelable_p)
2719 call_stmt = gimple_build_call_internal (IFN_LOOP_DIST_ALIAS,
2720 2, NULL_TREE, cond_expr);
2721 lhs = make_ssa_name (boolean_type_node);
2722 gimple_call_set_lhs (call_stmt, lhs);
2724 else
2725 lhs = cond_expr;
2727 prob = profile_probability::guessed_always ().apply_scale (9, 10);
2728 initialize_original_copy_tables ();
2729 nloop = loop_version (loop, lhs, &cond_bb, prob, prob.invert (),
2730 prob, prob.invert (), true);
2731 free_original_copy_tables ();
2732 /* Record the original loop number in newly generated loops. In case of
2733 distribution, the original loop will be distributed and the new loop
2734 is kept. */
2735 loop->orig_loop_num = nloop->num;
2736 nloop->orig_loop_num = nloop->num;
2737 nloop->dont_vectorize = true;
2738 nloop->force_vectorize = false;
2740 if (call_stmt)
2742 /* Record new loop's num in IFN_LOOP_DIST_ALIAS because the original
2743 loop could be destroyed. */
2744 arg0 = build_int_cst (integer_type_node, loop->orig_loop_num);
2745 gimple_call_set_arg (call_stmt, 0, arg0);
2746 gimple_seq_add_stmt_without_update (&cond_stmts, call_stmt);
2749 if (cond_stmts)
2751 gimple_stmt_iterator cond_gsi = gsi_last_bb (cond_bb);
2752 gsi_insert_seq_before (&cond_gsi, cond_stmts, GSI_SAME_STMT);
2754 update_ssa (TODO_update_ssa);
2757 /* Return true if loop versioning is needed to distrubute PARTITIONS.
2758 ALIAS_DDRS are data dependence relations for runtime alias check. */
2760 static inline bool
2761 version_for_distribution_p (vec<struct partition *> *partitions,
2762 vec<ddr_p> *alias_ddrs)
2764 /* No need to version loop if we have only one partition. */
2765 if (partitions->length () == 1)
2766 return false;
2768 /* Need to version loop if runtime alias check is necessary. */
2769 return (alias_ddrs->length () > 0);
2772 /* Compare base offset of builtin mem* partitions P1 and P2. */
2774 static int
2775 offset_cmp (const void *vp1, const void *vp2)
2777 struct partition *p1 = *(struct partition *const *) vp1;
2778 struct partition *p2 = *(struct partition *const *) vp2;
2779 unsigned HOST_WIDE_INT o1 = p1->builtin->dst_base_offset;
2780 unsigned HOST_WIDE_INT o2 = p2->builtin->dst_base_offset;
2781 return (o2 < o1) - (o1 < o2);
2784 /* Fuse adjacent memset builtin PARTITIONS if possible. This is a special
2785 case optimization transforming below code:
2787 __builtin_memset (&obj, 0, 100);
2788 _1 = &obj + 100;
2789 __builtin_memset (_1, 0, 200);
2790 _2 = &obj + 300;
2791 __builtin_memset (_2, 0, 100);
2793 into:
2795 __builtin_memset (&obj, 0, 400);
2797 Note we don't have dependence information between different partitions
2798 at this point, as a result, we can't handle nonadjacent memset builtin
2799 partitions since dependence might be broken. */
2801 static void
2802 fuse_memset_builtins (vec<struct partition *> *partitions)
2804 unsigned i, j;
2805 struct partition *part1, *part2;
2806 tree rhs1, rhs2;
2808 for (i = 0; partitions->iterate (i, &part1);)
2810 if (part1->kind != PKIND_MEMSET)
2812 i++;
2813 continue;
2816 /* Find sub-array of memset builtins of the same base. Index range
2817 of the sub-array is [i, j) with "j > i". */
2818 for (j = i + 1; partitions->iterate (j, &part2); ++j)
2820 if (part2->kind != PKIND_MEMSET
2821 || !operand_equal_p (part1->builtin->dst_base_base,
2822 part2->builtin->dst_base_base, 0))
2823 break;
2825 /* Memset calls setting different values can't be merged. */
2826 rhs1 = gimple_assign_rhs1 (DR_STMT (part1->builtin->dst_dr));
2827 rhs2 = gimple_assign_rhs1 (DR_STMT (part2->builtin->dst_dr));
2828 if (!operand_equal_p (rhs1, rhs2, 0))
2829 break;
2832 /* Stable sort is required in order to avoid breaking dependence. */
2833 gcc_stablesort (&(*partitions)[i], j - i, sizeof (*partitions)[i],
2834 offset_cmp);
2835 /* Continue with next partition. */
2836 i = j;
2839 /* Merge all consecutive memset builtin partitions. */
2840 for (i = 0; i < partitions->length () - 1;)
2842 part1 = (*partitions)[i];
2843 if (part1->kind != PKIND_MEMSET)
2845 i++;
2846 continue;
2849 part2 = (*partitions)[i + 1];
2850 /* Only merge memset partitions of the same base and with constant
2851 access sizes. */
2852 if (part2->kind != PKIND_MEMSET
2853 || TREE_CODE (part1->builtin->size) != INTEGER_CST
2854 || TREE_CODE (part2->builtin->size) != INTEGER_CST
2855 || !operand_equal_p (part1->builtin->dst_base_base,
2856 part2->builtin->dst_base_base, 0))
2858 i++;
2859 continue;
2861 rhs1 = gimple_assign_rhs1 (DR_STMT (part1->builtin->dst_dr));
2862 rhs2 = gimple_assign_rhs1 (DR_STMT (part2->builtin->dst_dr));
2863 int bytev1 = const_with_all_bytes_same (rhs1);
2864 int bytev2 = const_with_all_bytes_same (rhs2);
2865 /* Only merge memset partitions of the same value. */
2866 if (bytev1 != bytev2 || bytev1 == -1)
2868 i++;
2869 continue;
2871 wide_int end1 = wi::add (part1->builtin->dst_base_offset,
2872 wi::to_wide (part1->builtin->size));
2873 /* Only merge adjacent memset partitions. */
2874 if (wi::ne_p (end1, part2->builtin->dst_base_offset))
2876 i++;
2877 continue;
2879 /* Merge partitions[i] and partitions[i+1]. */
2880 part1->builtin->size = fold_build2 (PLUS_EXPR, sizetype,
2881 part1->builtin->size,
2882 part2->builtin->size);
2883 partition_free (part2);
2884 partitions->ordered_remove (i + 1);
2888 void
2889 loop_distribution::finalize_partitions (class loop *loop,
2890 vec<struct partition *> *partitions,
2891 vec<ddr_p> *alias_ddrs)
2893 unsigned i;
2894 struct partition *partition, *a;
2896 if (partitions->length () == 1
2897 || alias_ddrs->length () > 0)
2898 return;
2900 unsigned num_builtin = 0, num_normal = 0, num_partial_memset = 0;
2901 bool same_type_p = true;
2902 enum partition_type type = ((*partitions)[0])->type;
2903 for (i = 0; partitions->iterate (i, &partition); ++i)
2905 same_type_p &= (type == partition->type);
2906 if (partition_builtin_p (partition))
2908 num_builtin++;
2909 continue;
2911 num_normal++;
2912 if (partition->kind == PKIND_PARTIAL_MEMSET)
2913 num_partial_memset++;
2916 /* Don't distribute current loop into too many loops given we don't have
2917 memory stream cost model. Be even more conservative in case of loop
2918 nest distribution. */
2919 if ((same_type_p && num_builtin == 0
2920 && (loop->inner == NULL || num_normal != 2 || num_partial_memset != 1))
2921 || (loop->inner != NULL
2922 && i >= NUM_PARTITION_THRESHOLD && num_normal > 1)
2923 || (loop->inner == NULL
2924 && i >= NUM_PARTITION_THRESHOLD && num_normal > num_builtin))
2926 a = (*partitions)[0];
2927 for (i = 1; partitions->iterate (i, &partition); ++i)
2929 partition_merge_into (NULL, a, partition, FUSE_FINALIZE);
2930 partition_free (partition);
2932 partitions->truncate (1);
2935 /* Fuse memset builtins if possible. */
2936 if (partitions->length () > 1)
2937 fuse_memset_builtins (partitions);
2940 /* Distributes the code from LOOP in such a way that producer statements
2941 are placed before consumer statements. Tries to separate only the
2942 statements from STMTS into separate loops. Returns the number of
2943 distributed loops. Set NB_CALLS to number of generated builtin calls.
2944 Set *DESTROY_P to whether LOOP needs to be destroyed. */
2947 loop_distribution::distribute_loop (class loop *loop,
2948 const vec<gimple *> &stmts,
2949 control_dependences *cd, int *nb_calls, bool *destroy_p,
2950 bool only_patterns_p)
2952 ddrs_table = new hash_table<ddr_hasher> (389);
2953 struct graph *rdg;
2954 partition *partition;
2955 int i, nbp;
2957 *destroy_p = false;
2958 *nb_calls = 0;
2959 loop_nest.create (0);
2960 if (!find_loop_nest (loop, &loop_nest))
2962 loop_nest.release ();
2963 delete ddrs_table;
2964 return 0;
2967 datarefs_vec.create (20);
2968 has_nonaddressable_dataref_p = false;
2969 rdg = build_rdg (loop, cd);
2970 if (!rdg)
2972 if (dump_file && (dump_flags & TDF_DETAILS))
2973 fprintf (dump_file,
2974 "Loop %d not distributed: failed to build the RDG.\n",
2975 loop->num);
2977 loop_nest.release ();
2978 free_data_refs (datarefs_vec);
2979 delete ddrs_table;
2980 return 0;
2983 if (datarefs_vec.length () > MAX_DATAREFS_NUM)
2985 if (dump_file && (dump_flags & TDF_DETAILS))
2986 fprintf (dump_file,
2987 "Loop %d not distributed: too many memory references.\n",
2988 loop->num);
2990 free_rdg (rdg);
2991 loop_nest.release ();
2992 free_data_refs (datarefs_vec);
2993 delete ddrs_table;
2994 return 0;
2997 data_reference_p dref;
2998 for (i = 0; datarefs_vec.iterate (i, &dref); ++i)
2999 dref->aux = (void *) (uintptr_t) i;
3001 if (dump_file && (dump_flags & TDF_DETAILS))
3002 dump_rdg (dump_file, rdg);
3004 auto_vec<struct partition *, 3> partitions;
3005 rdg_build_partitions (rdg, stmts, &partitions);
3007 auto_vec<ddr_p> alias_ddrs;
3009 auto_bitmap stmt_in_all_partitions;
3010 bitmap_copy (stmt_in_all_partitions, partitions[0]->stmts);
3011 for (i = 1; partitions.iterate (i, &partition); ++i)
3012 bitmap_and_into (stmt_in_all_partitions, partitions[i]->stmts);
3014 bool any_builtin = false;
3015 bool reduction_in_all = false;
3016 FOR_EACH_VEC_ELT (partitions, i, partition)
3018 reduction_in_all
3019 |= classify_partition (loop, rdg, partition, stmt_in_all_partitions);
3020 any_builtin |= partition_builtin_p (partition);
3023 /* If we are only distributing patterns but did not detect any,
3024 simply bail out. */
3025 if (only_patterns_p
3026 && !any_builtin)
3028 nbp = 0;
3029 goto ldist_done;
3032 /* If we are only distributing patterns fuse all partitions that
3033 were not classified as builtins. This also avoids chopping
3034 a loop into pieces, separated by builtin calls. That is, we
3035 only want no or a single loop body remaining. */
3036 struct partition *into;
3037 if (only_patterns_p)
3039 for (i = 0; partitions.iterate (i, &into); ++i)
3040 if (!partition_builtin_p (into))
3041 break;
3042 for (++i; partitions.iterate (i, &partition); ++i)
3043 if (!partition_builtin_p (partition))
3045 partition_merge_into (NULL, into, partition, FUSE_NON_BUILTIN);
3046 partitions.unordered_remove (i);
3047 partition_free (partition);
3048 i--;
3052 /* Due to limitations in the transform phase we have to fuse all
3053 reduction partitions into the last partition so the existing
3054 loop will contain all loop-closed PHI nodes. */
3055 for (i = 0; partitions.iterate (i, &into); ++i)
3056 if (partition_reduction_p (into))
3057 break;
3058 for (i = i + 1; partitions.iterate (i, &partition); ++i)
3059 if (partition_reduction_p (partition))
3061 partition_merge_into (rdg, into, partition, FUSE_REDUCTION);
3062 partitions.unordered_remove (i);
3063 partition_free (partition);
3064 i--;
3067 /* Apply our simple cost model - fuse partitions with similar
3068 memory accesses. */
3069 for (i = 0; partitions.iterate (i, &into); ++i)
3071 bool changed = false;
3072 if (partition_builtin_p (into) || into->kind == PKIND_PARTIAL_MEMSET)
3073 continue;
3074 for (int j = i + 1;
3075 partitions.iterate (j, &partition); ++j)
3077 if (share_memory_accesses (rdg, into, partition))
3079 partition_merge_into (rdg, into, partition, FUSE_SHARE_REF);
3080 partitions.unordered_remove (j);
3081 partition_free (partition);
3082 j--;
3083 changed = true;
3086 /* If we fused 0 1 2 in step 1 to 0,2 1 as 0 and 2 have similar
3087 accesses when 1 and 2 have similar accesses but not 0 and 1
3088 then in the next iteration we will fail to consider merging
3089 1 into 0,2. So try again if we did any merging into 0. */
3090 if (changed)
3091 i--;
3094 /* Put a non-builtin partition last if we need to preserve a reduction.
3095 ??? This is a workaround that makes sort_partitions_by_post_order do
3096 the correct thing while in reality it should sort each component
3097 separately and then put the component with a reduction or a non-builtin
3098 last. */
3099 if (reduction_in_all
3100 && partition_builtin_p (partitions.last()))
3101 FOR_EACH_VEC_ELT (partitions, i, partition)
3102 if (!partition_builtin_p (partition))
3104 partitions.unordered_remove (i);
3105 partitions.quick_push (partition);
3106 break;
3109 /* Build the partition dependency graph and fuse partitions in strong
3110 connected component. */
3111 if (partitions.length () > 1)
3113 /* Don't support loop nest distribution under runtime alias check
3114 since it's not likely to enable many vectorization opportunities.
3115 Also if loop has any data reference which may be not addressable
3116 since alias check needs to take, compare address of the object. */
3117 if (loop->inner || has_nonaddressable_dataref_p)
3118 merge_dep_scc_partitions (rdg, &partitions, false);
3119 else
3121 merge_dep_scc_partitions (rdg, &partitions, true);
3122 if (partitions.length () > 1)
3123 break_alias_scc_partitions (rdg, &partitions, &alias_ddrs);
3127 finalize_partitions (loop, &partitions, &alias_ddrs);
3129 /* If there is a reduction in all partitions make sure the last one
3130 is not classified for builtin code generation. */
3131 if (reduction_in_all)
3133 partition = partitions.last ();
3134 if (only_patterns_p
3135 && partition_builtin_p (partition)
3136 && !partition_builtin_p (partitions[0]))
3138 nbp = 0;
3139 goto ldist_done;
3141 partition->kind = PKIND_NORMAL;
3144 nbp = partitions.length ();
3145 if (nbp == 0
3146 || (nbp == 1 && !partition_builtin_p (partitions[0]))
3147 || (nbp > 1 && partition_contains_all_rw (rdg, partitions)))
3149 nbp = 0;
3150 goto ldist_done;
3153 if (version_for_distribution_p (&partitions, &alias_ddrs))
3154 version_loop_by_alias_check (&partitions, loop, &alias_ddrs);
3156 if (dump_file && (dump_flags & TDF_DETAILS))
3158 fprintf (dump_file,
3159 "distribute loop <%d> into partitions:\n", loop->num);
3160 dump_rdg_partitions (dump_file, partitions);
3163 FOR_EACH_VEC_ELT (partitions, i, partition)
3165 if (partition_builtin_p (partition))
3166 (*nb_calls)++;
3167 *destroy_p |= generate_code_for_partition (loop, partition, i < nbp - 1);
3170 ldist_done:
3171 loop_nest.release ();
3172 free_data_refs (datarefs_vec);
3173 for (hash_table<ddr_hasher>::iterator iter = ddrs_table->begin ();
3174 iter != ddrs_table->end (); ++iter)
3176 free_dependence_relation (*iter);
3177 *iter = NULL;
3179 delete ddrs_table;
3181 FOR_EACH_VEC_ELT (partitions, i, partition)
3182 partition_free (partition);
3184 free_rdg (rdg);
3185 return nbp - *nb_calls;
3189 void loop_distribution::bb_top_order_init (void)
3191 int rpo_num;
3192 int *rpo = XNEWVEC (int, n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS);
3193 edge entry = single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun));
3194 bitmap exit_bbs = BITMAP_ALLOC (NULL);
3196 bb_top_order_index = XNEWVEC (int, last_basic_block_for_fn (cfun));
3197 bb_top_order_index_size = last_basic_block_for_fn (cfun);
3199 entry->flags &= ~EDGE_DFS_BACK;
3200 bitmap_set_bit (exit_bbs, EXIT_BLOCK);
3201 rpo_num = rev_post_order_and_mark_dfs_back_seme (cfun, entry, exit_bbs, true,
3202 rpo, NULL);
3203 BITMAP_FREE (exit_bbs);
3205 for (int i = 0; i < rpo_num; i++)
3206 bb_top_order_index[rpo[i]] = i;
3208 free (rpo);
3211 void loop_distribution::bb_top_order_destroy ()
3213 free (bb_top_order_index);
3214 bb_top_order_index = NULL;
3215 bb_top_order_index_size = 0;
3219 /* Given LOOP, this function records seed statements for distribution in
3220 WORK_LIST. Return false if there is nothing for distribution. */
3222 static bool
3223 find_seed_stmts_for_distribution (class loop *loop, vec<gimple *> *work_list)
3225 basic_block *bbs = get_loop_body_in_dom_order (loop);
3227 /* Initialize the worklist with stmts we seed the partitions with. */
3228 for (unsigned i = 0; i < loop->num_nodes; ++i)
3230 /* In irreducible sub-regions we don't know how to redirect
3231 conditions, so fail. See PR100492. */
3232 if (bbs[i]->flags & BB_IRREDUCIBLE_LOOP)
3234 if (dump_file && (dump_flags & TDF_DETAILS))
3235 fprintf (dump_file, "loop %d contains an irreducible region.\n",
3236 loop->num);
3237 work_list->truncate (0);
3238 break;
3240 for (gphi_iterator gsi = gsi_start_phis (bbs[i]);
3241 !gsi_end_p (gsi); gsi_next (&gsi))
3243 gphi *phi = gsi.phi ();
3244 if (virtual_operand_p (gimple_phi_result (phi)))
3245 continue;
3246 /* Distribute stmts which have defs that are used outside of
3247 the loop. */
3248 if (!stmt_has_scalar_dependences_outside_loop (loop, phi))
3249 continue;
3250 work_list->safe_push (phi);
3252 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
3253 !gsi_end_p (gsi); gsi_next (&gsi))
3255 gimple *stmt = gsi_stmt (gsi);
3257 /* Ignore clobbers, they do not have true side effects. */
3258 if (gimple_clobber_p (stmt))
3259 continue;
3261 /* If there is a stmt with side-effects bail out - we
3262 cannot and should not distribute this loop. */
3263 if (gimple_has_side_effects (stmt))
3265 free (bbs);
3266 return false;
3269 /* Distribute stmts which have defs that are used outside of
3270 the loop. */
3271 if (stmt_has_scalar_dependences_outside_loop (loop, stmt))
3273 /* Otherwise only distribute stores for now. */
3274 else if (!gimple_vdef (stmt))
3275 continue;
3277 work_list->safe_push (stmt);
3280 free (bbs);
3281 return work_list->length () > 0;
3284 /* A helper function for generate_{rawmemchr,strlen}_builtin functions in order
3285 to place new statements SEQ before LOOP and replace the old reduction
3286 variable with the new one. */
3288 static void
3289 generate_reduction_builtin_1 (loop_p loop, gimple_seq &seq,
3290 tree reduction_var_old, tree reduction_var_new,
3291 const char *info, machine_mode load_mode)
3293 /* Place new statements before LOOP. */
3294 gimple_stmt_iterator gsi = gsi_last_bb (loop_preheader_edge (loop)->src);
3295 gsi_insert_seq_after (&gsi, seq, GSI_CONTINUE_LINKING);
3297 /* Replace old reduction variable with new one. */
3298 imm_use_iterator iter;
3299 gimple *stmt;
3300 use_operand_p use_p;
3301 FOR_EACH_IMM_USE_STMT (stmt, iter, reduction_var_old)
3303 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
3304 SET_USE (use_p, reduction_var_new);
3306 update_stmt (stmt);
3309 if (dump_file && (dump_flags & TDF_DETAILS))
3310 fprintf (dump_file, info, GET_MODE_NAME (load_mode));
3313 /* Generate a call to rawmemchr and place it before LOOP. REDUCTION_VAR is
3314 replaced with a fresh SSA name representing the result of the call. */
3316 static void
3317 generate_rawmemchr_builtin (loop_p loop, tree reduction_var,
3318 data_reference_p store_dr, tree base, tree pattern,
3319 location_t loc)
3321 gimple_seq seq = NULL;
3323 tree mem = force_gimple_operand (base, &seq, true, NULL_TREE);
3324 gimple *fn_call = gimple_build_call_internal (IFN_RAWMEMCHR, 2, mem, pattern);
3325 tree reduction_var_new = copy_ssa_name (reduction_var);
3326 gimple_call_set_lhs (fn_call, reduction_var_new);
3327 gimple_set_location (fn_call, loc);
3328 gimple_seq_add_stmt (&seq, fn_call);
3330 if (store_dr)
3332 gassign *g = gimple_build_assign (DR_REF (store_dr), reduction_var_new);
3333 gimple_seq_add_stmt (&seq, g);
3336 generate_reduction_builtin_1 (loop, seq, reduction_var, reduction_var_new,
3337 "generated rawmemchr%s\n",
3338 TYPE_MODE (TREE_TYPE (TREE_TYPE (base))));
3341 /* Helper function for generate_strlen_builtin(,_using_rawmemchr) */
3343 static void
3344 generate_strlen_builtin_1 (loop_p loop, gimple_seq &seq,
3345 tree reduction_var_old, tree reduction_var_new,
3346 machine_mode mode, tree start_len)
3348 /* REDUCTION_VAR_NEW has either size type or ptrdiff type and must be
3349 converted if types of old and new reduction variable are not compatible. */
3350 reduction_var_new = gimple_convert (&seq, TREE_TYPE (reduction_var_old),
3351 reduction_var_new);
3353 /* Loops of the form `for (i=42; s[i]; ++i);` have an additional start
3354 length. */
3355 if (!integer_zerop (start_len))
3357 tree lhs = make_ssa_name (TREE_TYPE (reduction_var_new));
3358 gimple *g = gimple_build_assign (lhs, PLUS_EXPR, reduction_var_new,
3359 start_len);
3360 gimple_seq_add_stmt (&seq, g);
3361 reduction_var_new = lhs;
3364 generate_reduction_builtin_1 (loop, seq, reduction_var_old, reduction_var_new,
3365 "generated strlen%s\n", mode);
3368 /* Generate a call to strlen and place it before LOOP. REDUCTION_VAR is
3369 replaced with a fresh SSA name representing the result of the call. */
3371 static void
3372 generate_strlen_builtin (loop_p loop, tree reduction_var, tree base,
3373 tree start_len, location_t loc)
3375 gimple_seq seq = NULL;
3377 tree reduction_var_new = make_ssa_name (size_type_node);
3379 tree mem = force_gimple_operand (base, &seq, true, NULL_TREE);
3380 tree fn = build_fold_addr_expr (builtin_decl_implicit (BUILT_IN_STRLEN));
3381 gimple *fn_call = gimple_build_call (fn, 1, mem);
3382 gimple_call_set_lhs (fn_call, reduction_var_new);
3383 gimple_set_location (fn_call, loc);
3384 gimple_seq_add_stmt (&seq, fn_call);
3386 generate_strlen_builtin_1 (loop, seq, reduction_var, reduction_var_new,
3387 QImode, start_len);
3390 /* Generate code in order to mimic the behaviour of strlen but this time over
3391 an array of elements with mode different than QI. REDUCTION_VAR is replaced
3392 with a fresh SSA name representing the result, i.e., the length. */
3394 static void
3395 generate_strlen_builtin_using_rawmemchr (loop_p loop, tree reduction_var,
3396 tree base, tree load_type,
3397 tree start_len, location_t loc)
3399 gimple_seq seq = NULL;
3401 tree start = force_gimple_operand (base, &seq, true, NULL_TREE);
3402 tree zero = build_zero_cst (load_type);
3403 gimple *fn_call = gimple_build_call_internal (IFN_RAWMEMCHR, 2, start, zero);
3404 tree end = make_ssa_name (TREE_TYPE (base));
3405 gimple_call_set_lhs (fn_call, end);
3406 gimple_set_location (fn_call, loc);
3407 gimple_seq_add_stmt (&seq, fn_call);
3409 /* Determine the number of elements between START and END by
3410 evaluating (END - START) / sizeof (*START). */
3411 tree diff = make_ssa_name (ptrdiff_type_node);
3412 gimple *diff_stmt = gimple_build_assign (diff, POINTER_DIFF_EXPR, end, start);
3413 gimple_seq_add_stmt (&seq, diff_stmt);
3414 /* Let SIZE be the size of each character. */
3415 tree size = gimple_convert (&seq, ptrdiff_type_node,
3416 TYPE_SIZE_UNIT (load_type));
3417 tree count = make_ssa_name (ptrdiff_type_node);
3418 gimple *count_stmt = gimple_build_assign (count, TRUNC_DIV_EXPR, diff, size);
3419 gimple_seq_add_stmt (&seq, count_stmt);
3421 generate_strlen_builtin_1 (loop, seq, reduction_var, count,
3422 TYPE_MODE (load_type),
3423 start_len);
3426 /* Return true if we can count at least as many characters by taking pointer
3427 difference as we can count via reduction_var without an overflow. Thus
3428 compute 2^n < (2^(m-1) / s) where n = TYPE_PRECISION (reduction_var_type),
3429 m = TYPE_PRECISION (ptrdiff_type_node), and s = size of each character. */
3430 static bool
3431 reduction_var_overflows_first (tree reduction_var_type, tree load_type)
3433 widest_int n2 = wi::lshift (1, TYPE_PRECISION (reduction_var_type));;
3434 widest_int m2 = wi::lshift (1, TYPE_PRECISION (ptrdiff_type_node) - 1);
3435 widest_int s = wi::to_widest (TYPE_SIZE_UNIT (load_type));
3436 return wi::ltu_p (n2, wi::udiv_trunc (m2, s));
3439 static gimple *
3440 determine_reduction_stmt_1 (const loop_p loop, const basic_block *bbs)
3442 gimple *reduction_stmt = NULL;
3444 for (unsigned i = 0, ninsns = 0; i < loop->num_nodes; ++i)
3446 basic_block bb = bbs[i];
3448 for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi);
3449 gsi_next_nondebug (&bsi))
3451 gphi *phi = bsi.phi ();
3452 if (virtual_operand_p (gimple_phi_result (phi)))
3453 continue;
3454 if (stmt_has_scalar_dependences_outside_loop (loop, phi))
3456 if (reduction_stmt)
3457 return NULL;
3458 reduction_stmt = phi;
3462 for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi);
3463 gsi_next_nondebug (&bsi), ++ninsns)
3465 /* Bail out early for loops which are unlikely to match. */
3466 if (ninsns > 16)
3467 return NULL;
3468 gimple *stmt = gsi_stmt (bsi);
3469 if (gimple_clobber_p (stmt))
3470 continue;
3471 if (gimple_code (stmt) == GIMPLE_LABEL)
3472 continue;
3473 if (gimple_has_volatile_ops (stmt))
3474 return NULL;
3475 if (stmt_has_scalar_dependences_outside_loop (loop, stmt))
3477 if (reduction_stmt)
3478 return NULL;
3479 reduction_stmt = stmt;
3484 return reduction_stmt;
3487 /* If LOOP has a single non-volatile reduction statement, then return a pointer
3488 to it. Otherwise return NULL. */
3489 static gimple *
3490 determine_reduction_stmt (const loop_p loop)
3492 basic_block *bbs = get_loop_body (loop);
3493 gimple *reduction_stmt = determine_reduction_stmt_1 (loop, bbs);
3494 XDELETEVEC (bbs);
3495 return reduction_stmt;
3498 /* Transform loops which mimic the effects of builtins rawmemchr or strlen and
3499 replace them accordingly. For example, a loop of the form
3501 for (; *p != 42; ++p);
3503 is replaced by
3505 p = rawmemchr<MODE> (p, 42);
3507 under the assumption that rawmemchr is available for a particular MODE.
3508 Another example is
3510 int i;
3511 for (i = 42; s[i]; ++i);
3513 which is replaced by
3515 i = (int)strlen (&s[42]) + 42;
3517 for some character array S. In case array S is not of type character array
3518 we end up with
3520 i = (int)(rawmemchr<MODE> (&s[42], 0) - &s[42]) + 42;
3522 assuming that rawmemchr is available for a particular MODE. */
3524 bool
3525 loop_distribution::transform_reduction_loop (loop_p loop)
3527 gimple *reduction_stmt;
3528 data_reference_p load_dr = NULL, store_dr = NULL;
3530 edge e = single_exit (loop);
3531 gcond *cond = safe_dyn_cast <gcond *> (last_stmt (e->src));
3532 if (!cond)
3533 return false;
3534 /* Ensure loop condition is an (in)equality test and loop is exited either if
3535 the inequality test fails or the equality test succeeds. */
3536 if (!(e->flags & EDGE_FALSE_VALUE && gimple_cond_code (cond) == NE_EXPR)
3537 && !(e->flags & EDGE_TRUE_VALUE && gimple_cond_code (cond) == EQ_EXPR))
3538 return false;
3539 /* A limitation of the current implementation is that we only support
3540 constant patterns in (in)equality tests. */
3541 tree pattern = gimple_cond_rhs (cond);
3542 if (TREE_CODE (pattern) != INTEGER_CST)
3543 return false;
3545 reduction_stmt = determine_reduction_stmt (loop);
3547 /* A limitation of the current implementation is that we require a reduction
3548 statement. Therefore, loops without a reduction statement as in the
3549 following are not recognized:
3550 int *p;
3551 void foo (void) { for (; *p; ++p); } */
3552 if (reduction_stmt == NULL)
3553 return false;
3555 /* Reduction variables are guaranteed to be SSA names. */
3556 tree reduction_var;
3557 switch (gimple_code (reduction_stmt))
3559 case GIMPLE_ASSIGN:
3560 case GIMPLE_PHI:
3561 reduction_var = gimple_get_lhs (reduction_stmt);
3562 break;
3563 default:
3564 /* Bail out e.g. for GIMPLE_CALL. */
3565 return false;
3568 struct graph *rdg = build_rdg (loop, NULL);
3569 if (rdg == NULL)
3571 if (dump_file && (dump_flags & TDF_DETAILS))
3572 fprintf (dump_file,
3573 "Loop %d not transformed: failed to build the RDG.\n",
3574 loop->num);
3576 return false;
3578 auto_bitmap partition_stmts;
3579 bitmap_set_range (partition_stmts, 0, rdg->n_vertices);
3580 find_single_drs (loop, rdg, partition_stmts, &store_dr, &load_dr);
3581 free_rdg (rdg);
3583 /* Bail out if there is no single load. */
3584 if (load_dr == NULL)
3585 return false;
3587 /* Reaching this point we have a loop with a single reduction variable,
3588 a single load, and an optional single store. */
3590 tree load_ref = DR_REF (load_dr);
3591 tree load_type = TREE_TYPE (load_ref);
3592 tree load_access_base = build_fold_addr_expr (load_ref);
3593 tree load_access_size = TYPE_SIZE_UNIT (load_type);
3594 affine_iv load_iv, reduction_iv;
3596 if (!INTEGRAL_TYPE_P (load_type)
3597 || !type_has_mode_precision_p (load_type))
3598 return false;
3600 /* We already ensured that the loop condition tests for (in)equality where the
3601 rhs is a constant pattern. Now ensure that the lhs is the result of the
3602 load. */
3603 if (gimple_cond_lhs (cond) != gimple_assign_lhs (DR_STMT (load_dr)))
3604 return false;
3606 /* Bail out if no affine induction variable with constant step can be
3607 determined. */
3608 if (!simple_iv (loop, loop, load_access_base, &load_iv, false))
3609 return false;
3611 /* Bail out if memory accesses are not consecutive or not growing. */
3612 if (!operand_equal_p (load_iv.step, load_access_size, 0))
3613 return false;
3615 if (!simple_iv (loop, loop, reduction_var, &reduction_iv, false))
3616 return false;
3618 /* Handle rawmemchr like loops. */
3619 if (operand_equal_p (load_iv.base, reduction_iv.base)
3620 && operand_equal_p (load_iv.step, reduction_iv.step))
3622 if (store_dr)
3624 /* Ensure that we store to X and load from X+I where I>0. */
3625 if (TREE_CODE (load_iv.base) != POINTER_PLUS_EXPR
3626 || !integer_onep (TREE_OPERAND (load_iv.base, 1)))
3627 return false;
3628 tree ptr_base = TREE_OPERAND (load_iv.base, 0);
3629 if (TREE_CODE (ptr_base) != SSA_NAME)
3630 return false;
3631 gimple *def = SSA_NAME_DEF_STMT (ptr_base);
3632 if (!gimple_assign_single_p (def)
3633 || gimple_assign_rhs1 (def) != DR_REF (store_dr))
3634 return false;
3635 /* Ensure that the reduction value is stored. */
3636 if (gimple_assign_rhs1 (DR_STMT (store_dr)) != reduction_var)
3637 return false;
3639 /* Bail out if target does not provide rawmemchr for a certain mode. */
3640 machine_mode mode = TYPE_MODE (load_type);
3641 if (direct_optab_handler (rawmemchr_optab, mode) == CODE_FOR_nothing)
3642 return false;
3643 location_t loc = gimple_location (DR_STMT (load_dr));
3644 generate_rawmemchr_builtin (loop, reduction_var, store_dr, load_iv.base,
3645 pattern, loc);
3646 return true;
3649 /* Handle strlen like loops. */
3650 if (store_dr == NULL
3651 && integer_zerop (pattern)
3652 && TREE_CODE (reduction_iv.base) == INTEGER_CST
3653 && TREE_CODE (reduction_iv.step) == INTEGER_CST
3654 && integer_onep (reduction_iv.step))
3656 location_t loc = gimple_location (DR_STMT (load_dr));
3657 tree reduction_var_type = TREE_TYPE (reduction_var);
3658 /* While determining the length of a string an overflow might occur.
3659 If an overflow only occurs in the loop implementation and not in the
3660 strlen implementation, then either the overflow is undefined or the
3661 truncated result of strlen equals the one of the loop. Otherwise if
3662 an overflow may also occur in the strlen implementation, then
3663 replacing a loop by a call to strlen is sound whenever we ensure that
3664 if an overflow occurs in the strlen implementation, then also an
3665 overflow occurs in the loop implementation which is undefined. It
3666 seems reasonable to relax this and assume that the strlen
3667 implementation cannot overflow in case sizetype is big enough in the
3668 sense that an overflow can only happen for string objects which are
3669 bigger than half of the address space; at least for 32-bit targets and
3672 For strlen which makes use of rawmemchr the maximal length of a string
3673 which can be determined without an overflow is PTRDIFF_MAX / S where
3674 each character has size S. Since an overflow for ptrdiff type is
3675 undefined we have to make sure that if an overflow occurs, then an
3676 overflow occurs in the loop implementation, too, and this is
3677 undefined, too. Similar as before we relax this and assume that no
3678 string object is larger than half of the address space; at least for
3679 32-bit targets and up. */
3680 if (TYPE_MODE (load_type) == TYPE_MODE (char_type_node)
3681 && TYPE_PRECISION (load_type) == TYPE_PRECISION (char_type_node)
3682 && ((TYPE_PRECISION (sizetype) >= TYPE_PRECISION (ptr_type_node) - 1
3683 && TYPE_PRECISION (ptr_type_node) >= 32)
3684 || (TYPE_OVERFLOW_UNDEFINED (reduction_var_type)
3685 && TYPE_PRECISION (reduction_var_type) <= TYPE_PRECISION (sizetype)))
3686 && builtin_decl_implicit (BUILT_IN_STRLEN))
3687 generate_strlen_builtin (loop, reduction_var, load_iv.base,
3688 reduction_iv.base, loc);
3689 else if (direct_optab_handler (rawmemchr_optab, TYPE_MODE (load_type))
3690 != CODE_FOR_nothing
3691 && ((TYPE_PRECISION (ptrdiff_type_node) == TYPE_PRECISION (ptr_type_node)
3692 && TYPE_PRECISION (ptrdiff_type_node) >= 32)
3693 || (TYPE_OVERFLOW_UNDEFINED (reduction_var_type)
3694 && reduction_var_overflows_first (reduction_var_type, load_type))))
3695 generate_strlen_builtin_using_rawmemchr (loop, reduction_var,
3696 load_iv.base,
3697 load_type,
3698 reduction_iv.base, loc);
3699 else
3700 return false;
3701 return true;
3704 return false;
3707 /* Given innermost LOOP, return the outermost enclosing loop that forms a
3708 perfect loop nest. */
3710 static class loop *
3711 prepare_perfect_loop_nest (class loop *loop)
3713 class loop *outer = loop_outer (loop);
3714 tree niters = number_of_latch_executions (loop);
3716 /* TODO: We only support the innermost 3-level loop nest distribution
3717 because of compilation time issue for now. This should be relaxed
3718 in the future. Note we only allow 3-level loop nest distribution
3719 when parallelizing loops. */
3720 while ((loop->inner == NULL
3721 || (loop->inner->inner == NULL && flag_tree_parallelize_loops > 1))
3722 && loop_outer (outer)
3723 && outer->inner == loop && loop->next == NULL
3724 && single_exit (outer)
3725 && !chrec_contains_symbols_defined_in_loop (niters, outer->num)
3726 && (niters = number_of_latch_executions (outer)) != NULL_TREE
3727 && niters != chrec_dont_know)
3729 loop = outer;
3730 outer = loop_outer (loop);
3733 return loop;
3737 unsigned int
3738 loop_distribution::execute (function *fun)
3740 bool changed = false;
3741 basic_block bb;
3742 control_dependences *cd = NULL;
3743 auto_vec<loop_p> loops_to_be_destroyed;
3745 if (number_of_loops (fun) <= 1)
3746 return 0;
3748 bb_top_order_init ();
3750 FOR_ALL_BB_FN (bb, fun)
3752 gimple_stmt_iterator gsi;
3753 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3754 gimple_set_uid (gsi_stmt (gsi), -1);
3755 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3756 gimple_set_uid (gsi_stmt (gsi), -1);
3759 /* We can at the moment only distribute non-nested loops, thus restrict
3760 walking to innermost loops. */
3761 for (auto loop : loops_list (cfun, LI_ONLY_INNERMOST))
3763 /* Don't distribute multiple exit edges loop, or cold loop when
3764 not doing pattern detection. */
3765 if (!single_exit (loop)
3766 || (!flag_tree_loop_distribute_patterns
3767 && !optimize_loop_for_speed_p (loop)))
3768 continue;
3770 /* If niters is unknown don't distribute loop but rather try to transform
3771 it to a call to a builtin. */
3772 tree niters = number_of_latch_executions (loop);
3773 if (niters == NULL_TREE || niters == chrec_dont_know)
3775 datarefs_vec.create (20);
3776 if (transform_reduction_loop (loop))
3778 changed = true;
3779 loops_to_be_destroyed.safe_push (loop);
3780 if (dump_enabled_p ())
3782 dump_user_location_t loc = find_loop_location (loop);
3783 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS,
3784 loc, "Loop %d transformed into a builtin.\n",
3785 loop->num);
3788 free_data_refs (datarefs_vec);
3789 continue;
3792 /* Get the perfect loop nest for distribution. */
3793 loop = prepare_perfect_loop_nest (loop);
3794 for (; loop; loop = loop->inner)
3796 auto_vec<gimple *> work_list;
3797 if (!find_seed_stmts_for_distribution (loop, &work_list))
3798 break;
3800 const char *str = loop->inner ? " nest" : "";
3801 dump_user_location_t loc = find_loop_location (loop);
3802 if (!cd)
3804 calculate_dominance_info (CDI_DOMINATORS);
3805 calculate_dominance_info (CDI_POST_DOMINATORS);
3806 cd = new control_dependences ();
3807 free_dominance_info (CDI_POST_DOMINATORS);
3810 bool destroy_p;
3811 int nb_generated_loops, nb_generated_calls;
3812 nb_generated_loops
3813 = distribute_loop (loop, work_list, cd, &nb_generated_calls,
3814 &destroy_p, (!optimize_loop_for_speed_p (loop)
3815 || !flag_tree_loop_distribution));
3816 if (destroy_p)
3817 loops_to_be_destroyed.safe_push (loop);
3819 if (nb_generated_loops + nb_generated_calls > 0)
3821 changed = true;
3822 if (dump_enabled_p ())
3823 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS,
3824 loc, "Loop%s %d distributed: split to %d loops "
3825 "and %d library calls.\n", str, loop->num,
3826 nb_generated_loops, nb_generated_calls);
3828 break;
3831 if (dump_file && (dump_flags & TDF_DETAILS))
3832 fprintf (dump_file, "Loop%s %d not distributed.\n", str, loop->num);
3836 if (cd)
3837 delete cd;
3839 if (bb_top_order_index != NULL)
3840 bb_top_order_destroy ();
3842 if (changed)
3844 /* Destroy loop bodies that could not be reused. Do this late as we
3845 otherwise can end up refering to stale data in control dependences. */
3846 unsigned i;
3847 class loop *loop;
3848 FOR_EACH_VEC_ELT (loops_to_be_destroyed, i, loop)
3849 destroy_loop (loop);
3851 /* Cached scalar evolutions now may refer to wrong or non-existing
3852 loops. */
3853 scev_reset_htab ();
3854 mark_virtual_operands_for_renaming (fun);
3855 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
3858 checking_verify_loop_structure ();
3860 return changed ? TODO_cleanup_cfg : 0;
3864 /* Distribute all loops in the current function. */
3866 namespace {
3868 const pass_data pass_data_loop_distribution =
3870 GIMPLE_PASS, /* type */
3871 "ldist", /* name */
3872 OPTGROUP_LOOP, /* optinfo_flags */
3873 TV_TREE_LOOP_DISTRIBUTION, /* tv_id */
3874 ( PROP_cfg | PROP_ssa ), /* properties_required */
3875 0, /* properties_provided */
3876 0, /* properties_destroyed */
3877 0, /* todo_flags_start */
3878 0, /* todo_flags_finish */
3881 class pass_loop_distribution : public gimple_opt_pass
3883 public:
3884 pass_loop_distribution (gcc::context *ctxt)
3885 : gimple_opt_pass (pass_data_loop_distribution, ctxt)
3888 /* opt_pass methods: */
3889 virtual bool gate (function *)
3891 return flag_tree_loop_distribution
3892 || flag_tree_loop_distribute_patterns;
3895 virtual unsigned int execute (function *);
3897 }; // class pass_loop_distribution
3899 unsigned int
3900 pass_loop_distribution::execute (function *fun)
3902 return loop_distribution ().execute (fun);
3905 } // anon namespace
3907 gimple_opt_pass *
3908 make_pass_loop_distribution (gcc::context *ctxt)
3910 return new pass_loop_distribution (ctxt);