2 Copyright (C) 2006-2025 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
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
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
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
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.
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
94 #include "coretypes.h"
99 #include "tree-pass.h"
101 #include "gimple-pretty-print.h"
102 #include "fold-const.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"
114 #include "tree-scalar-evolution.h"
115 #include "tree-vectorizer.h"
117 #include "gimple-fold.h"
118 #include "tree-affine.h"
121 #include "memmodel.h"
123 #include "tree-ssa-loop-niter.h"
126 #define MAX_DATAREFS_NUM \
127 ((unsigned) param_loop_max_datarefs_for_datadeps)
129 /* Threshold controlling number of distributed partitions. Given it may
130 be unnecessary if a memory stream cost model is invented in the future,
131 we define it as a temporary macro, rather than a parameter. */
132 #define NUM_PARTITION_THRESHOLD (4)
134 /* Hashtable helpers. */
136 struct ddr_hasher
: nofree_ptr_hash
<struct data_dependence_relation
>
138 static inline hashval_t
hash (const data_dependence_relation
*);
139 static inline bool equal (const data_dependence_relation
*,
140 const data_dependence_relation
*);
143 /* Hash function for data dependence. */
146 ddr_hasher::hash (const data_dependence_relation
*ddr
)
149 h
.add_ptr (DDR_A (ddr
));
150 h
.add_ptr (DDR_B (ddr
));
154 /* Hash table equality function for data dependence. */
157 ddr_hasher::equal (const data_dependence_relation
*ddr1
,
158 const data_dependence_relation
*ddr2
)
160 return (DDR_A (ddr1
) == DDR_A (ddr2
) && DDR_B (ddr1
) == DDR_B (ddr2
));
165 #define DR_INDEX(dr) ((uintptr_t) (dr)->aux)
167 /* A Reduced Dependence Graph (RDG) vertex representing a statement. */
170 /* The statement represented by this vertex. */
173 /* Vector of data-references in this statement. */
174 vec
<data_reference_p
> datarefs
;
176 /* True when the statement contains a write to memory. */
179 /* True when the statement contains a read from memory. */
183 #define RDGV_STMT(V) ((struct rdg_vertex *) ((V)->data))->stmt
184 #define RDGV_DATAREFS(V) ((struct rdg_vertex *) ((V)->data))->datarefs
185 #define RDGV_HAS_MEM_WRITE(V) ((struct rdg_vertex *) ((V)->data))->has_mem_write
186 #define RDGV_HAS_MEM_READS(V) ((struct rdg_vertex *) ((V)->data))->has_mem_reads
187 #define RDG_STMT(RDG, I) RDGV_STMT (&(RDG->vertices[I]))
188 #define RDG_DATAREFS(RDG, I) RDGV_DATAREFS (&(RDG->vertices[I]))
189 #define RDG_MEM_WRITE_STMT(RDG, I) RDGV_HAS_MEM_WRITE (&(RDG->vertices[I]))
190 #define RDG_MEM_READS_STMT(RDG, I) RDGV_HAS_MEM_READS (&(RDG->vertices[I]))
192 /* Data dependence type. */
196 /* Read After Write (RAW). */
199 /* Control dependence (execute conditional on). */
203 /* Dependence information attached to an edge of the RDG. */
207 /* Type of the dependence. */
208 enum rdg_dep_type type
;
211 #define RDGE_TYPE(E) ((struct rdg_edge *) ((E)->data))->type
213 /* Kind of distributed loop. */
214 enum partition_kind
{
216 /* Partial memset stands for a paritition can be distributed into a loop
217 of memset calls, rather than a single memset call. It's handled just
218 like a normal parition, i.e, distributed as separate loop, no memset
221 Note: This is a hacking fix trying to distribute ZERO-ing stmt in a
222 loop nest as deep as possible. As a result, parloop achieves better
223 parallelization by parallelizing deeper loop nest. This hack should
224 be unnecessary and removed once distributed memset can be understood
225 and analyzed in data reference analysis. See PR82604 for more. */
226 PKIND_PARTIAL_MEMSET
,
227 PKIND_MEMSET
, PKIND_MEMCPY
, PKIND_MEMMOVE
230 /* Type of distributed loop. */
231 enum partition_type
{
232 /* The distributed loop can be executed parallelly. */
234 /* The distributed loop has to be executed sequentially. */
238 /* Builtin info for loop distribution. */
241 /* data-references a kind != PKIND_NORMAL partition is about. */
242 data_reference_p dst_dr
;
243 data_reference_p src_dr
;
244 /* Base address and size of memory objects operated by the builtin. Note
245 both dest and source memory objects must have the same size. */
249 /* Base and offset part of dst_base after stripping constant offset. This
250 is only used in memset builtin distribution for now. */
252 unsigned HOST_WIDE_INT dst_base_offset
;
255 /* Partition for loop distribution. */
258 /* Statements of the partition. */
260 /* True if the partition defines variable which is used outside of loop. */
263 enum partition_kind kind
;
264 enum partition_type type
;
265 /* Data references in the partition. */
267 /* Information of builtin parition. */
268 struct builtin_info
*builtin
;
271 /* Partitions are fused because of different reasons. */
274 FUSE_NON_BUILTIN
= 0,
281 /* Description on different fusing reason. */
282 static const char *fuse_message
[] = {
283 "they are non-builtins",
284 "they have reductions",
285 "they have shared memory refs",
286 "they are in the same dependence scc",
287 "there is no point to distribute loop"};
290 /* Dump vertex I in RDG to FILE. */
293 dump_rdg_vertex (FILE *file
, struct graph
*rdg
, int i
)
295 struct vertex
*v
= &(rdg
->vertices
[i
]);
296 struct graph_edge
*e
;
298 fprintf (file
, "(vertex %d: (%s%s) (in:", i
,
299 RDG_MEM_WRITE_STMT (rdg
, i
) ? "w" : "",
300 RDG_MEM_READS_STMT (rdg
, i
) ? "r" : "");
303 for (e
= v
->pred
; e
; e
= e
->pred_next
)
304 fprintf (file
, " %d", e
->src
);
306 fprintf (file
, ") (out:");
309 for (e
= v
->succ
; e
; e
= e
->succ_next
)
310 fprintf (file
, " %d", e
->dest
);
312 fprintf (file
, ")\n");
313 print_gimple_stmt (file
, RDGV_STMT (v
), 0, TDF_VOPS
|TDF_MEMSYMS
);
314 fprintf (file
, ")\n");
317 /* Call dump_rdg_vertex on stderr. */
320 debug_rdg_vertex (struct graph
*rdg
, int i
)
322 dump_rdg_vertex (stderr
, rdg
, i
);
325 /* Dump the reduced dependence graph RDG to FILE. */
328 dump_rdg (FILE *file
, struct graph
*rdg
)
330 fprintf (file
, "(rdg\n");
331 for (int i
= 0; i
< rdg
->n_vertices
; i
++)
332 dump_rdg_vertex (file
, rdg
, i
);
333 fprintf (file
, ")\n");
336 /* Call dump_rdg on stderr. */
339 debug_rdg (struct graph
*rdg
)
341 dump_rdg (stderr
, rdg
);
345 dot_rdg_1 (FILE *file
, struct graph
*rdg
)
349 pp_needs_newline (&pp
) = false;
350 pp
.set_output_stream (file
);
352 fprintf (file
, "digraph RDG {\n");
354 for (i
= 0; i
< rdg
->n_vertices
; i
++)
356 struct vertex
*v
= &(rdg
->vertices
[i
]);
357 struct graph_edge
*e
;
359 fprintf (file
, "%d [label=\"[%d] ", i
, i
);
360 pp_gimple_stmt_1 (&pp
, RDGV_STMT (v
), 0, TDF_SLIM
);
362 fprintf (file
, "\"]\n");
364 /* Highlight reads from memory. */
365 if (RDG_MEM_READS_STMT (rdg
, i
))
366 fprintf (file
, "%d [style=filled, fillcolor=green]\n", i
);
368 /* Highlight stores to memory. */
369 if (RDG_MEM_WRITE_STMT (rdg
, i
))
370 fprintf (file
, "%d [style=filled, fillcolor=red]\n", i
);
373 for (e
= v
->succ
; e
; e
= e
->succ_next
)
374 switch (RDGE_TYPE (e
))
377 /* These are the most common dependences: don't print these. */
378 fprintf (file
, "%d -> %d \n", i
, e
->dest
);
382 fprintf (file
, "%d -> %d [label=control] \n", i
, e
->dest
);
390 fprintf (file
, "}\n\n");
393 /* Display the Reduced Dependence Graph using dotty. */
396 dot_rdg (struct graph
*rdg
)
398 /* When debugging, you may want to enable the following code. */
400 FILE *file
= popen ("dot -Tx11", "w");
403 dot_rdg_1 (file
, rdg
);
405 close (fileno (file
));
408 dot_rdg_1 (stderr
, rdg
);
412 /* Returns the index of STMT in RDG. */
415 rdg_vertex_for_stmt (struct graph
*rdg ATTRIBUTE_UNUSED
, gimple
*stmt
)
417 int index
= gimple_uid (stmt
);
418 gcc_checking_assert (index
== -1 || RDG_STMT (rdg
, index
) == stmt
);
422 /* Creates dependence edges in RDG for all the uses of DEF. IDEF is
423 the index of DEF in RDG. */
426 create_rdg_edges_for_scalar (struct graph
*rdg
, tree def
, int idef
)
428 use_operand_p imm_use_p
;
429 imm_use_iterator iterator
;
431 FOR_EACH_IMM_USE_FAST (imm_use_p
, iterator
, def
)
433 struct graph_edge
*e
;
434 int use
= rdg_vertex_for_stmt (rdg
, USE_STMT (imm_use_p
));
439 e
= add_edge (rdg
, idef
, use
);
440 e
->data
= XNEW (struct rdg_edge
);
441 RDGE_TYPE (e
) = flow_dd
;
445 /* Creates an edge for the control dependences of BB to the vertex V. */
448 create_edge_for_control_dependence (struct graph
*rdg
, basic_block bb
,
449 int v
, control_dependences
*cd
)
453 EXECUTE_IF_SET_IN_BITMAP (cd
->get_edges_dependent_on (bb
->index
),
456 basic_block cond_bb
= cd
->get_edge_src (edge_n
);
457 gimple
*stmt
= *gsi_last_bb (cond_bb
);
458 if (stmt
&& is_ctrl_stmt (stmt
))
460 struct graph_edge
*e
;
461 int c
= rdg_vertex_for_stmt (rdg
, stmt
);
465 e
= add_edge (rdg
, c
, v
);
466 e
->data
= XNEW (struct rdg_edge
);
467 RDGE_TYPE (e
) = control_dd
;
472 /* Creates the edges of the reduced dependence graph RDG. */
475 create_rdg_flow_edges (struct graph
*rdg
)
481 for (i
= 0; i
< rdg
->n_vertices
; i
++)
482 FOR_EACH_PHI_OR_STMT_DEF (def_p
, RDG_STMT (rdg
, i
),
484 create_rdg_edges_for_scalar (rdg
, DEF_FROM_PTR (def_p
), i
);
487 /* Creates the edges of the reduced dependence graph RDG. */
490 create_rdg_cd_edges (struct graph
*rdg
, control_dependences
*cd
, loop_p loop
)
494 for (i
= 0; i
< rdg
->n_vertices
; i
++)
496 gimple
*stmt
= RDG_STMT (rdg
, i
);
497 if (gimple_code (stmt
) == GIMPLE_PHI
)
501 FOR_EACH_EDGE (e
, ei
, gimple_bb (stmt
)->preds
)
502 if (flow_bb_inside_loop_p (loop
, e
->src
))
503 create_edge_for_control_dependence (rdg
, e
->src
, i
, cd
);
506 create_edge_for_control_dependence (rdg
, gimple_bb (stmt
), i
, cd
);
511 class loop_distribution
514 /* The loop (nest) to be distributed. */
515 vec
<loop_p
> loop_nest
;
517 /* Vector of data references in the loop to be distributed. */
518 vec
<data_reference_p
> datarefs_vec
;
520 /* If there is nonaddressable data reference in above vector. */
521 bool has_nonaddressable_dataref_p
;
523 /* Store index of data reference in aux field. */
525 /* Hash table for data dependence relation in the loop to be distributed. */
526 hash_table
<ddr_hasher
> *ddrs_table
;
528 /* Array mapping basic block's index to its topological order. */
529 int *bb_top_order_index
;
530 /* And size of the array. */
531 int bb_top_order_index_size
;
533 /* Build the vertices of the reduced dependence graph RDG. Return false
535 bool create_rdg_vertices (struct graph
*rdg
, const vec
<gimple
*> &stmts
,
538 /* Initialize STMTS with all the statements of LOOP. We use topological
539 order to discover all statements. The order is important because
540 generate_loops_for_partition is using the same traversal for identifying
541 statements in loop copies. */
542 void stmts_from_loop (class loop
*loop
, vec
<gimple
*> *stmts
);
545 /* Build the Reduced Dependence Graph (RDG) with one vertex per statement of
546 LOOP, and one edge per flow dependence or control dependence from control
547 dependence CD. During visiting each statement, data references are also
548 collected and recorded in global data DATAREFS_VEC. */
549 struct graph
* build_rdg (class loop
*loop
, control_dependences
*cd
);
551 /* Merge PARTITION into the partition DEST. RDG is the reduced dependence
552 graph and we update type for result partition if it is non-NULL. */
553 void partition_merge_into (struct graph
*rdg
,
554 partition
*dest
, partition
*partition
,
558 /* Return data dependence relation for data references A and B. The two
559 data references must be in lexicographic order wrto reduced dependence
560 graph RDG. We firstly try to find ddr from global ddr hash table. If
561 it doesn't exist, compute the ddr and cache it. */
562 data_dependence_relation
* get_data_dependence (struct graph
*rdg
,
567 /* In reduced dependence graph RDG for loop distribution, return true if
568 dependence between references DR1 and DR2 leads to a dependence cycle
569 and such dependence cycle can't be resolved by runtime alias check. */
570 bool data_dep_in_cycle_p (struct graph
*rdg
, data_reference_p dr1
,
571 data_reference_p dr2
);
574 /* Given reduced dependence graph RDG, PARTITION1 and PARTITION2, update
575 PARTITION1's type after merging PARTITION2 into PARTITION1. */
576 void update_type_for_merge (struct graph
*rdg
,
577 partition
*partition1
, partition
*partition2
);
580 /* Returns a partition with all the statements needed for computing
581 the vertex V of the RDG, also including the loop exit conditions. */
582 partition
*build_rdg_partition_for_vertex (struct graph
*rdg
, int v
);
584 /* Given data references DST_DR and SRC_DR in loop nest LOOP and RDG, classify
585 if it forms builtin memcpy or memmove call. */
586 void classify_builtin_ldst (loop_p loop
, struct graph
*rdg
, partition
*partition
,
587 data_reference_p dst_dr
, data_reference_p src_dr
);
589 /* Classifies the builtin kind we can generate for PARTITION of RDG and LOOP.
590 For the moment we detect memset, memcpy and memmove patterns. Bitmap
591 STMT_IN_ALL_PARTITIONS contains statements belonging to all partitions.
592 Returns true if there is a reduction in all partitions and we
593 possibly did not mark PARTITION as having one for this reason. */
596 classify_partition (loop_p loop
,
597 struct graph
*rdg
, partition
*partition
,
598 bitmap stmt_in_all_partitions
);
601 /* Returns true when PARTITION1 and PARTITION2 access the same memory
603 bool share_memory_accesses (struct graph
*rdg
,
604 partition
*partition1
, partition
*partition2
);
606 /* For each seed statement in STARTING_STMTS, this function builds
607 partition for it by adding depended statements according to RDG.
608 All partitions are recorded in PARTITIONS. */
609 void rdg_build_partitions (struct graph
*rdg
,
610 vec
<gimple
*> starting_stmts
,
611 vec
<partition
*> *partitions
);
613 /* Compute partition dependence created by the data references in DRS1
614 and DRS2, modify and return DIR according to that. IF ALIAS_DDR is
615 not NULL, we record dependence introduced by possible alias between
616 two data references in ALIAS_DDRS; otherwise, we simply ignore such
617 dependence as if it doesn't exist at all. */
618 int pg_add_dependence_edges (struct graph
*rdg
, int dir
, bitmap drs1
,
619 bitmap drs2
, vec
<ddr_p
> *alias_ddrs
);
622 /* Build and return partition dependence graph for PARTITIONS. RDG is
623 reduced dependence graph for the loop to be distributed. If IGNORE_ALIAS_P
624 is true, data dependence caused by possible alias between references
625 is ignored, as if it doesn't exist at all; otherwise all depdendences
627 struct graph
*build_partition_graph (struct graph
*rdg
,
628 vec
<struct partition
*> *partitions
,
629 bool ignore_alias_p
);
631 /* Given reduced dependence graph RDG merge strong connected components
632 of PARTITIONS. If IGNORE_ALIAS_P is true, data dependence caused by
633 possible alias between references is ignored, as if it doesn't exist
634 at all; otherwise all depdendences are considered. */
635 void merge_dep_scc_partitions (struct graph
*rdg
, vec
<struct partition
*>
636 *partitions
, bool ignore_alias_p
);
638 /* This is the main function breaking strong conected components in
639 PARTITIONS giving reduced depdendence graph RDG. Store data dependence
640 relations for runtime alias check in ALIAS_DDRS. */
641 void break_alias_scc_partitions (struct graph
*rdg
, vec
<struct partition
*>
642 *partitions
, vec
<ddr_p
> *alias_ddrs
);
645 /* Fuse PARTITIONS of LOOP if necessary before finalizing distribution.
646 ALIAS_DDRS contains ddrs which need runtime alias check. */
647 void finalize_partitions (class loop
*loop
, vec
<struct partition
*>
648 *partitions
, vec
<ddr_p
> *alias_ddrs
);
650 /* Distributes the code from LOOP in such a way that producer statements
651 are placed before consumer statements. Tries to separate only the
652 statements from STMTS into separate loops. Returns the number of
653 distributed loops. Set NB_CALLS to number of generated builtin calls.
654 Set *DESTROY_P to whether LOOP needs to be destroyed. */
655 int distribute_loop (class loop
*loop
, const vec
<gimple
*> &stmts
,
656 control_dependences
*cd
, int *nb_calls
, bool *destroy_p
,
657 bool only_patterns_p
);
659 /* Transform loops which mimic the effects of builtins rawmemchr or strlen and
660 replace them accordingly. */
661 bool transform_reduction_loop (loop_p loop
);
663 /* Compute topological order for basic blocks. Topological order is
664 needed because data dependence is computed for data references in
665 lexicographical order. */
666 void bb_top_order_init (void);
668 void bb_top_order_destroy (void);
672 /* Getter for bb_top_order. */
674 inline int get_bb_top_order_index_size (void)
676 return bb_top_order_index_size
;
679 inline int get_bb_top_order_index (int i
)
681 return bb_top_order_index
[i
];
684 unsigned int execute (function
*fun
);
688 /* If X has a smaller topological sort number than Y, returns -1;
689 if greater, returns 1. */
691 bb_top_order_cmp_r (const void *x
, const void *y
, void *loop
)
693 loop_distribution
*_loop
=
694 (loop_distribution
*) loop
;
696 basic_block bb1
= *(const basic_block
*) x
;
697 basic_block bb2
= *(const basic_block
*) y
;
699 int bb_top_order_index_size
= _loop
->get_bb_top_order_index_size ();
701 gcc_assert (bb1
->index
< bb_top_order_index_size
702 && bb2
->index
< bb_top_order_index_size
);
703 gcc_assert (bb1
== bb2
704 || _loop
->get_bb_top_order_index(bb1
->index
)
705 != _loop
->get_bb_top_order_index(bb2
->index
));
707 return (_loop
->get_bb_top_order_index(bb1
->index
) -
708 _loop
->get_bb_top_order_index(bb2
->index
));
712 loop_distribution::create_rdg_vertices (struct graph
*rdg
,
713 const vec
<gimple
*> &stmts
,
719 FOR_EACH_VEC_ELT (stmts
, i
, stmt
)
721 struct vertex
*v
= &(rdg
->vertices
[i
]);
723 /* Record statement to vertex mapping. */
724 gimple_set_uid (stmt
, i
);
726 v
->data
= XNEW (struct rdg_vertex
);
727 RDGV_STMT (v
) = stmt
;
728 RDGV_DATAREFS (v
).create (0);
729 RDGV_HAS_MEM_WRITE (v
) = false;
730 RDGV_HAS_MEM_READS (v
) = false;
731 if (gimple_code (stmt
) == GIMPLE_PHI
)
734 unsigned drp
= datarefs_vec
.length ();
735 if (!find_data_references_in_stmt (loop
, stmt
, &datarefs_vec
))
737 for (unsigned j
= drp
; j
< datarefs_vec
.length (); ++j
)
739 data_reference_p dr
= datarefs_vec
[j
];
741 RDGV_HAS_MEM_READS (v
) = true;
743 RDGV_HAS_MEM_WRITE (v
) = true;
744 RDGV_DATAREFS (v
).safe_push (dr
);
745 has_nonaddressable_dataref_p
|= may_be_nonaddressable_p (dr
->ref
);
752 loop_distribution::stmts_from_loop (class loop
*loop
, vec
<gimple
*> *stmts
)
755 basic_block
*bbs
= get_loop_body_in_custom_order (loop
, this, bb_top_order_cmp_r
);
757 for (i
= 0; i
< loop
->num_nodes
; i
++)
759 basic_block bb
= bbs
[i
];
761 for (gphi_iterator bsi
= gsi_start_phis (bb
); !gsi_end_p (bsi
);
763 if (!virtual_operand_p (gimple_phi_result (bsi
.phi ())))
764 stmts
->safe_push (bsi
.phi ());
766 for (gimple_stmt_iterator bsi
= gsi_start_bb (bb
); !gsi_end_p (bsi
);
769 gimple
*stmt
= gsi_stmt (bsi
);
770 if (gimple_code (stmt
) != GIMPLE_LABEL
&& !is_gimple_debug (stmt
))
771 stmts
->safe_push (stmt
);
778 /* Free the reduced dependence graph RDG. */
781 free_rdg (struct graph
*rdg
, loop_p loop
)
785 for (i
= 0; i
< rdg
->n_vertices
; i
++)
787 struct vertex
*v
= &(rdg
->vertices
[i
]);
788 struct graph_edge
*e
;
790 for (e
= v
->succ
; e
; e
= e
->succ_next
)
795 (RDGV_DATAREFS (v
)).release ();
802 /* Reset UIDs of stmts still in the loop. */
803 basic_block
*bbs
= get_loop_body (loop
);
804 for (unsigned i
= 0; i
< loop
->num_nodes
; ++i
)
806 basic_block bb
= bbs
[i
];
807 gimple_stmt_iterator gsi
;
808 for (gsi
= gsi_start_phis (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
809 gimple_set_uid (gsi_stmt (gsi
), -1);
810 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
811 gimple_set_uid (gsi_stmt (gsi
), -1);
817 loop_distribution::build_rdg (class loop
*loop
, control_dependences
*cd
)
821 /* Create the RDG vertices from the stmts of the loop nest. */
822 auto_vec
<gimple
*, 10> stmts
;
823 stmts_from_loop (loop
, &stmts
);
824 rdg
= new_graph (stmts
.length ());
825 if (!create_rdg_vertices (rdg
, stmts
, loop
))
827 free_rdg (rdg
, loop
);
832 create_rdg_flow_edges (rdg
);
834 create_rdg_cd_edges (rdg
, cd
, loop
);
840 /* Allocate and initialize a partition from BITMAP. */
843 partition_alloc (void)
845 partition
*partition
= XCNEW (struct partition
);
846 partition
->stmts
= BITMAP_ALLOC (NULL
);
847 partition
->reduction_p
= false;
848 partition
->loc
= UNKNOWN_LOCATION
;
849 partition
->kind
= PKIND_NORMAL
;
850 partition
->type
= PTYPE_PARALLEL
;
851 partition
->datarefs
= BITMAP_ALLOC (NULL
);
855 /* Free PARTITION. */
858 partition_free (partition
*partition
)
860 BITMAP_FREE (partition
->stmts
);
861 BITMAP_FREE (partition
->datarefs
);
862 if (partition
->builtin
)
863 free (partition
->builtin
);
868 /* Returns true if the partition can be generated as a builtin. */
871 partition_builtin_p (partition
*partition
)
873 return partition
->kind
> PKIND_PARTIAL_MEMSET
;
876 /* Returns true if the partition contains a reduction. */
879 partition_reduction_p (partition
*partition
)
881 return partition
->reduction_p
;
885 loop_distribution::partition_merge_into (struct graph
*rdg
,
886 partition
*dest
, partition
*partition
, enum fuse_type ft
)
888 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
890 fprintf (dump_file
, "Fuse partitions because %s:\n", fuse_message
[ft
]);
891 fprintf (dump_file
, " Part 1: ");
892 dump_bitmap (dump_file
, dest
->stmts
);
893 fprintf (dump_file
, " Part 2: ");
894 dump_bitmap (dump_file
, partition
->stmts
);
897 dest
->kind
= PKIND_NORMAL
;
898 if (dest
->type
== PTYPE_PARALLEL
)
899 dest
->type
= partition
->type
;
901 bitmap_ior_into (dest
->stmts
, partition
->stmts
);
902 if (partition_reduction_p (partition
))
903 dest
->reduction_p
= true;
905 /* Further check if any data dependence prevents us from executing the
906 new partition parallelly. */
907 if (dest
->type
== PTYPE_PARALLEL
&& rdg
!= NULL
)
908 update_type_for_merge (rdg
, dest
, partition
);
910 bitmap_ior_into (dest
->datarefs
, partition
->datarefs
);
914 /* Returns true when DEF is an SSA_NAME defined in LOOP and used after
918 ssa_name_has_uses_outside_loop_p (tree def
, loop_p loop
)
920 imm_use_iterator imm_iter
;
923 FOR_EACH_IMM_USE_FAST (use_p
, imm_iter
, def
)
925 if (is_gimple_debug (USE_STMT (use_p
)))
928 basic_block use_bb
= gimple_bb (USE_STMT (use_p
));
929 if (!flow_bb_inside_loop_p (loop
, use_bb
))
936 /* Returns true when STMT defines a scalar variable used after the
940 stmt_has_scalar_dependences_outside_loop (loop_p loop
, gimple
*stmt
)
945 if (gimple_code (stmt
) == GIMPLE_PHI
)
946 return ssa_name_has_uses_outside_loop_p (gimple_phi_result (stmt
), loop
);
948 FOR_EACH_SSA_DEF_OPERAND (def_p
, stmt
, op_iter
, SSA_OP_DEF
)
949 if (ssa_name_has_uses_outside_loop_p (DEF_FROM_PTR (def_p
), loop
))
955 /* Return a copy of LOOP placed before LOOP. */
958 copy_loop_before (class loop
*loop
, bool redirect_lc_phi_defs
)
961 edge preheader
= loop_preheader_edge (loop
);
963 initialize_original_copy_tables ();
964 res
= slpeel_tree_duplicate_loop_to_edge_cfg (loop
, single_exit (loop
), NULL
,
965 NULL
, preheader
, NULL
, false);
966 gcc_assert (res
!= NULL
);
968 /* When a not last partition is supposed to keep the LC PHIs computed
969 adjust their definitions. */
970 if (redirect_lc_phi_defs
)
972 edge exit
= single_exit (loop
);
973 for (gphi_iterator si
= gsi_start_phis (exit
->dest
); !gsi_end_p (si
);
976 gphi
*phi
= si
.phi ();
977 if (virtual_operand_p (gimple_phi_result (phi
)))
979 use_operand_p use_p
= PHI_ARG_DEF_PTR_FROM_EDGE (phi
, exit
);
980 if (TREE_CODE (USE_FROM_PTR (use_p
)) == SSA_NAME
)
982 tree new_def
= get_current_def (USE_FROM_PTR (use_p
));
984 /* Something defined outside of the loop. */
986 SET_USE (use_p
, new_def
);
991 free_original_copy_tables ();
992 delete_update_ssa ();
997 /* Creates an empty basic block after LOOP. */
1000 create_bb_after_loop (class loop
*loop
)
1002 edge exit
= single_exit (loop
);
1010 /* Generate code for PARTITION from the code in LOOP. The loop is
1011 copied when COPY_P is true. All the statements not flagged in the
1012 PARTITION bitmap are removed from the loop or from its copy. The
1013 statements are indexed in sequence inside a basic block, and the
1014 basic blocks of a loop are taken in dom order. */
1017 generate_loops_for_partition (class loop
*loop
, partition
*partition
,
1018 bool copy_p
, bool keep_lc_phis_p
)
1025 int orig_loop_num
= loop
->orig_loop_num
;
1026 loop
= copy_loop_before (loop
, keep_lc_phis_p
);
1027 gcc_assert (loop
!= NULL
);
1028 loop
->orig_loop_num
= orig_loop_num
;
1029 create_preheader (loop
, CP_SIMPLE_PREHEADERS
);
1030 create_bb_after_loop (loop
);
1034 /* Origin number is set to the new versioned loop's num. */
1035 gcc_assert (loop
->orig_loop_num
!= loop
->num
);
1038 /* Remove stmts not in the PARTITION bitmap. */
1039 bbs
= get_loop_body_in_dom_order (loop
);
1041 if (MAY_HAVE_DEBUG_BIND_STMTS
)
1042 for (i
= 0; i
< loop
->num_nodes
; i
++)
1044 basic_block bb
= bbs
[i
];
1046 for (gphi_iterator bsi
= gsi_start_phis (bb
); !gsi_end_p (bsi
);
1049 gphi
*phi
= bsi
.phi ();
1050 if (!virtual_operand_p (gimple_phi_result (phi
))
1051 && !bitmap_bit_p (partition
->stmts
, gimple_uid (phi
)))
1052 reset_debug_uses (phi
);
1055 for (gimple_stmt_iterator bsi
= gsi_start_bb (bb
); !gsi_end_p (bsi
); gsi_next (&bsi
))
1057 gimple
*stmt
= gsi_stmt (bsi
);
1058 if (gimple_code (stmt
) != GIMPLE_LABEL
1059 && !is_gimple_debug (stmt
)
1060 && !bitmap_bit_p (partition
->stmts
, gimple_uid (stmt
)))
1061 reset_debug_uses (stmt
);
1065 for (i
= 0; i
< loop
->num_nodes
; i
++)
1067 basic_block bb
= bbs
[i
];
1068 edge inner_exit
= NULL
;
1070 if (loop
!= bb
->loop_father
)
1071 inner_exit
= single_exit (bb
->loop_father
);
1073 for (gphi_iterator bsi
= gsi_start_phis (bb
); !gsi_end_p (bsi
);)
1075 gphi
*phi
= bsi
.phi ();
1076 if (!virtual_operand_p (gimple_phi_result (phi
))
1077 && !bitmap_bit_p (partition
->stmts
, gimple_uid (phi
)))
1078 remove_phi_node (&bsi
, true);
1083 for (gimple_stmt_iterator bsi
= gsi_start_bb (bb
); !gsi_end_p (bsi
);)
1085 gimple
*stmt
= gsi_stmt (bsi
);
1086 if (gimple_code (stmt
) != GIMPLE_LABEL
1087 && !is_gimple_debug (stmt
)
1088 && !bitmap_bit_p (partition
->stmts
, gimple_uid (stmt
)))
1090 /* In distribution of loop nest, if bb is inner loop's exit_bb,
1091 we choose its exit edge/path in order to avoid generating
1092 infinite loop. For all other cases, we choose an arbitrary
1093 path through the empty CFG part that this unnecessary
1094 control stmt controls. */
1095 if (gcond
*cond_stmt
= dyn_cast
<gcond
*> (stmt
))
1097 if (inner_exit
&& inner_exit
->flags
& EDGE_TRUE_VALUE
)
1098 gimple_cond_make_true (cond_stmt
);
1100 gimple_cond_make_false (cond_stmt
);
1103 else if (gimple_code (stmt
) == GIMPLE_SWITCH
)
1105 gswitch
*switch_stmt
= as_a
<gswitch
*> (stmt
);
1106 gimple_switch_set_index
1107 (switch_stmt
, CASE_LOW (gimple_switch_label (switch_stmt
, 1)));
1112 unlink_stmt_vdef (stmt
);
1113 gsi_remove (&bsi
, true);
1114 release_defs (stmt
);
1125 /* If VAL memory representation contains the same value in all bytes,
1126 return that value, otherwise return -1.
1127 E.g. for 0x24242424 return 0x24, for IEEE double
1128 747708026454360457216.0 return 0x44, etc. */
1131 const_with_all_bytes_same (tree val
)
1133 unsigned char buf
[64];
1136 if (integer_zerop (val
)
1137 || (TREE_CODE (val
) == CONSTRUCTOR
1138 && !TREE_CLOBBER_P (val
)
1139 && CONSTRUCTOR_NELTS (val
) == 0))
1142 if (real_zerop (val
))
1144 /* Only return 0 for +0.0, not for -0.0, which doesn't have
1145 an all bytes same memory representation. Don't transform
1146 -0.0 stores into +0.0 even for !HONOR_SIGNED_ZEROS. */
1147 switch (TREE_CODE (val
))
1150 if (!real_isneg (TREE_REAL_CST_PTR (val
)))
1154 if (!const_with_all_bytes_same (TREE_REALPART (val
))
1155 && !const_with_all_bytes_same (TREE_IMAGPART (val
)))
1160 unsigned int count
= vector_cst_encoded_nelts (val
);
1162 for (j
= 0; j
< count
; ++j
)
1163 if (const_with_all_bytes_same (VECTOR_CST_ENCODED_ELT (val
, j
)))
1174 if (CHAR_BIT
!= 8 || BITS_PER_UNIT
!= 8)
1177 len
= native_encode_expr (val
, buf
, sizeof (buf
));
1180 for (i
= 1; i
< len
; i
++)
1181 if (buf
[i
] != buf
[0])
1186 /* Generate a call to memset for PARTITION in LOOP. */
1189 generate_memset_builtin (class loop
*loop
, partition
*partition
)
1191 gimple_stmt_iterator gsi
;
1192 tree mem
, fn
, nb_bytes
;
1194 struct builtin_info
*builtin
= partition
->builtin
;
1197 /* The new statements will be placed before LOOP. */
1198 gsi
= gsi_last_bb (loop_preheader_edge (loop
)->src
);
1200 nb_bytes
= rewrite_to_non_trapping_overflow (builtin
->size
);
1201 nb_bytes
= force_gimple_operand_gsi (&gsi
, nb_bytes
, true, NULL_TREE
,
1202 false, GSI_CONTINUE_LINKING
);
1203 mem
= rewrite_to_non_trapping_overflow (builtin
->dst_base
);
1204 mem
= force_gimple_operand_gsi (&gsi
, mem
, true, NULL_TREE
,
1205 false, GSI_CONTINUE_LINKING
);
1207 /* This exactly matches the pattern recognition in classify_partition. */
1208 val
= gimple_assign_rhs1 (DR_STMT (builtin
->dst_dr
));
1209 /* Handle constants like 0x15151515 and similarly
1210 floating point constants etc. where all bytes are the same. */
1211 int bytev
= const_with_all_bytes_same (val
);
1213 val
= build_int_cst (integer_type_node
, bytev
);
1214 else if (TREE_CODE (val
) == INTEGER_CST
)
1215 val
= fold_convert (integer_type_node
, val
);
1216 else if (!useless_type_conversion_p (integer_type_node
, TREE_TYPE (val
)))
1218 tree tem
= make_ssa_name (integer_type_node
);
1219 gimple
*cstmt
= gimple_build_assign (tem
, NOP_EXPR
, val
);
1220 gsi_insert_after (&gsi
, cstmt
, GSI_CONTINUE_LINKING
);
1224 fn
= build_fold_addr_expr (builtin_decl_implicit (BUILT_IN_MEMSET
));
1225 fn_call
= gimple_build_call (fn
, 3, mem
, val
, nb_bytes
);
1226 gimple_set_location (fn_call
, partition
->loc
);
1227 gsi_insert_after (&gsi
, fn_call
, GSI_CONTINUE_LINKING
);
1230 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1232 fprintf (dump_file
, "generated memset");
1234 fprintf (dump_file
, " zero\n");
1236 fprintf (dump_file
, "\n");
1240 /* Generate a call to memcpy for PARTITION in LOOP. */
1243 generate_memcpy_builtin (class loop
*loop
, partition
*partition
)
1245 gimple_stmt_iterator gsi
;
1247 tree dest
, src
, fn
, nb_bytes
;
1248 enum built_in_function kind
;
1249 struct builtin_info
*builtin
= partition
->builtin
;
1251 /* The new statements will be placed before LOOP. */
1252 gsi
= gsi_last_bb (loop_preheader_edge (loop
)->src
);
1254 nb_bytes
= rewrite_to_non_trapping_overflow (builtin
->size
);
1255 nb_bytes
= force_gimple_operand_gsi (&gsi
, nb_bytes
, true, NULL_TREE
,
1256 false, GSI_CONTINUE_LINKING
);
1257 dest
= rewrite_to_non_trapping_overflow (builtin
->dst_base
);
1258 src
= rewrite_to_non_trapping_overflow (builtin
->src_base
);
1259 if (partition
->kind
== PKIND_MEMCPY
1260 || ! ptr_derefs_may_alias_p (dest
, src
))
1261 kind
= BUILT_IN_MEMCPY
;
1263 kind
= BUILT_IN_MEMMOVE
;
1264 /* Try harder if we're copying a constant size. */
1265 if (kind
== BUILT_IN_MEMMOVE
&& poly_int_tree_p (nb_bytes
))
1267 aff_tree asrc
, adest
;
1268 tree_to_aff_combination (src
, ptr_type_node
, &asrc
);
1269 tree_to_aff_combination (dest
, ptr_type_node
, &adest
);
1270 aff_combination_scale (&adest
, -1);
1271 aff_combination_add (&asrc
, &adest
);
1272 if (aff_comb_cannot_overlap_p (&asrc
, wi::to_poly_widest (nb_bytes
),
1273 wi::to_poly_widest (nb_bytes
)))
1274 kind
= BUILT_IN_MEMCPY
;
1277 dest
= force_gimple_operand_gsi (&gsi
, dest
, true, NULL_TREE
,
1278 false, GSI_CONTINUE_LINKING
);
1279 src
= force_gimple_operand_gsi (&gsi
, src
, true, NULL_TREE
,
1280 false, GSI_CONTINUE_LINKING
);
1281 fn
= build_fold_addr_expr (builtin_decl_implicit (kind
));
1282 fn_call
= gimple_build_call (fn
, 3, dest
, src
, nb_bytes
);
1283 gimple_set_location (fn_call
, partition
->loc
);
1284 gsi_insert_after (&gsi
, fn_call
, GSI_CONTINUE_LINKING
);
1287 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1289 if (kind
== BUILT_IN_MEMCPY
)
1290 fprintf (dump_file
, "generated memcpy\n");
1292 fprintf (dump_file
, "generated memmove\n");
1296 /* Remove and destroy the loop LOOP. */
1299 destroy_loop (class loop
*loop
)
1301 unsigned nbbs
= loop
->num_nodes
;
1302 edge exit
= single_exit (loop
);
1303 basic_block src
= loop_preheader_edge (loop
)->src
, dest
= exit
->dest
;
1307 bbs
= get_loop_body_in_dom_order (loop
);
1309 gimple_stmt_iterator dst_gsi
= gsi_after_labels (exit
->dest
);
1310 bool safe_p
= single_pred_p (exit
->dest
);
1311 for (unsigned i
= 0; i
< nbbs
; ++i
)
1313 /* We have made sure to not leave any dangling uses of SSA
1314 names defined in the loop. With the exception of virtuals.
1315 Make sure we replace all uses of virtual defs that will remain
1316 outside of the loop with the bare symbol as delete_basic_block
1317 will release them. */
1318 for (gphi_iterator gsi
= gsi_start_phis (bbs
[i
]); !gsi_end_p (gsi
);
1321 gphi
*phi
= gsi
.phi ();
1322 if (virtual_operand_p (gimple_phi_result (phi
)))
1323 mark_virtual_phi_result_for_renaming (phi
);
1325 for (gimple_stmt_iterator gsi
= gsi_start_bb (bbs
[i
]); !gsi_end_p (gsi
);)
1327 gimple
*stmt
= gsi_stmt (gsi
);
1328 tree vdef
= gimple_vdef (stmt
);
1329 if (vdef
&& TREE_CODE (vdef
) == SSA_NAME
)
1330 mark_virtual_operand_for_renaming (vdef
);
1331 /* Also move and eventually reset debug stmts. We can leave
1332 constant values in place in case the stmt dominates the exit.
1333 ??? Non-constant values from the last iteration can be
1334 replaced with final values if we can compute them. */
1335 if (gimple_debug_bind_p (stmt
))
1337 tree val
= gimple_debug_bind_get_value (stmt
);
1338 gsi_move_before (&gsi
, &dst_gsi
);
1341 || !is_gimple_min_invariant (val
)
1342 || !dominated_by_p (CDI_DOMINATORS
, exit
->src
, bbs
[i
])))
1344 gimple_debug_bind_reset_value (stmt
);
1353 redirect_edge_pred (exit
, src
);
1354 exit
->flags
&= ~(EDGE_TRUE_VALUE
|EDGE_FALSE_VALUE
);
1355 exit
->flags
|= EDGE_FALLTHRU
;
1356 cancel_loop_tree (loop
);
1357 rescan_loop_exit (exit
, false, true);
1363 delete_basic_block (bbs
[i
]);
1369 set_immediate_dominator (CDI_DOMINATORS
, dest
,
1370 recompute_dominator (CDI_DOMINATORS
, dest
));
1373 /* Generates code for PARTITION. Return whether LOOP needs to be destroyed. */
1376 generate_code_for_partition (class loop
*loop
,
1377 partition
*partition
, bool copy_p
,
1378 bool keep_lc_phis_p
)
1380 switch (partition
->kind
)
1383 case PKIND_PARTIAL_MEMSET
:
1384 /* Reductions all have to be in the last partition. */
1385 gcc_assert (!partition_reduction_p (partition
)
1387 generate_loops_for_partition (loop
, partition
, copy_p
,
1392 generate_memset_builtin (loop
, partition
);
1397 generate_memcpy_builtin (loop
, partition
);
1404 /* Common tail for partitions we turn into a call. If this was the last
1405 partition for which we generate code, we have to destroy the loop. */
1411 data_dependence_relation
*
1412 loop_distribution::get_data_dependence (struct graph
*rdg
, data_reference_p a
,
1415 struct data_dependence_relation ent
, **slot
;
1416 struct data_dependence_relation
*ddr
;
1418 gcc_assert (DR_IS_WRITE (a
) || DR_IS_WRITE (b
));
1419 gcc_assert (rdg_vertex_for_stmt (rdg
, DR_STMT (a
))
1420 <= rdg_vertex_for_stmt (rdg
, DR_STMT (b
)));
1423 slot
= ddrs_table
->find_slot (&ent
, INSERT
);
1426 ddr
= initialize_data_dependence_relation (a
, b
, loop_nest
);
1427 compute_affine_dependence (ddr
, loop_nest
[0]);
1435 loop_distribution::data_dep_in_cycle_p (struct graph
*rdg
,
1436 data_reference_p dr1
,
1437 data_reference_p dr2
)
1439 struct data_dependence_relation
*ddr
;
1441 /* Re-shuffle data-refs to be in topological order. */
1442 if (rdg_vertex_for_stmt (rdg
, DR_STMT (dr1
))
1443 > rdg_vertex_for_stmt (rdg
, DR_STMT (dr2
)))
1444 std::swap (dr1
, dr2
);
1446 ddr
= get_data_dependence (rdg
, dr1
, dr2
);
1448 /* In case of no data dependence. */
1449 if (DDR_ARE_DEPENDENT (ddr
) == chrec_known
)
1451 /* For unknown data dependence or known data dependence which can't be
1452 expressed in classic distance vector, we check if it can be resolved
1453 by runtime alias check. If yes, we still consider data dependence
1454 as won't introduce data dependence cycle. */
1455 else if (DDR_ARE_DEPENDENT (ddr
) == chrec_dont_know
1456 || DDR_NUM_DIST_VECTS (ddr
) == 0)
1457 return !runtime_alias_check_p (ddr
, NULL
, true);
1458 else if (DDR_NUM_DIST_VECTS (ddr
) > 1)
1460 else if (DDR_REVERSED_P (ddr
)
1461 || lambda_vector_zerop (DDR_DIST_VECT (ddr
, 0), DDR_NB_LOOPS (ddr
)))
1468 loop_distribution::update_type_for_merge (struct graph
*rdg
,
1469 partition
*partition1
,
1470 partition
*partition2
)
1473 bitmap_iterator bi
, bj
;
1474 data_reference_p dr1
, dr2
;
1476 EXECUTE_IF_SET_IN_BITMAP (partition1
->datarefs
, 0, i
, bi
)
1478 unsigned start
= (partition1
== partition2
) ? i
+ 1 : 0;
1480 dr1
= datarefs_vec
[i
];
1481 EXECUTE_IF_SET_IN_BITMAP (partition2
->datarefs
, start
, j
, bj
)
1483 dr2
= datarefs_vec
[j
];
1484 if (DR_IS_READ (dr1
) && DR_IS_READ (dr2
))
1487 /* Partition can only be executed sequentially if there is any
1488 data dependence cycle. */
1489 if (data_dep_in_cycle_p (rdg
, dr1
, dr2
))
1491 partition1
->type
= PTYPE_SEQUENTIAL
;
1499 loop_distribution::build_rdg_partition_for_vertex (struct graph
*rdg
, int v
)
1501 partition
*partition
= partition_alloc ();
1502 auto_vec
<int, 3> nodes
;
1505 data_reference_p dr
;
1507 graphds_dfs (rdg
, &v
, 1, &nodes
, false, NULL
);
1509 FOR_EACH_VEC_ELT (nodes
, i
, x
)
1511 bitmap_set_bit (partition
->stmts
, x
);
1513 for (j
= 0; RDG_DATAREFS (rdg
, x
).iterate (j
, &dr
); ++j
)
1515 unsigned idx
= (unsigned) DR_INDEX (dr
);
1516 gcc_assert (idx
< datarefs_vec
.length ());
1518 /* Partition can only be executed sequentially if there is any
1519 unknown data reference. */
1520 if (!DR_BASE_ADDRESS (dr
) || !DR_OFFSET (dr
)
1521 || !DR_INIT (dr
) || !DR_STEP (dr
))
1522 partition
->type
= PTYPE_SEQUENTIAL
;
1524 bitmap_set_bit (partition
->datarefs
, idx
);
1528 if (partition
->type
== PTYPE_SEQUENTIAL
)
1531 /* Further check if any data dependence prevents us from executing the
1532 partition parallelly. */
1533 update_type_for_merge (rdg
, partition
, partition
);
1538 /* Given PARTITION of LOOP and RDG, record single load/store data references
1539 for builtin partition in SRC_DR/DST_DR, return false if there is no such
1543 find_single_drs (class loop
*loop
, struct graph
*rdg
, const bitmap
&partition_stmts
,
1544 data_reference_p
*dst_dr
, data_reference_p
*src_dr
)
1547 data_reference_p single_ld
= NULL
, single_st
= NULL
;
1550 EXECUTE_IF_SET_IN_BITMAP (partition_stmts
, 0, i
, bi
)
1552 gimple
*stmt
= RDG_STMT (rdg
, i
);
1553 data_reference_p dr
;
1555 if (gimple_code (stmt
) == GIMPLE_PHI
)
1558 /* Any scalar stmts are ok. */
1559 if (!gimple_vuse (stmt
))
1562 /* Otherwise just regular loads/stores. */
1563 if (!gimple_assign_single_p (stmt
))
1566 /* But exactly one store and/or load. */
1567 for (unsigned j
= 0; RDG_DATAREFS (rdg
, i
).iterate (j
, &dr
); ++j
)
1569 tree type
= TREE_TYPE (DR_REF (dr
));
1571 /* The memset, memcpy and memmove library calls are only
1572 able to deal with generic address space. */
1573 if (!ADDR_SPACE_GENERIC_P (TYPE_ADDR_SPACE (type
)))
1576 if (DR_IS_READ (dr
))
1578 if (single_ld
!= NULL
)
1584 if (single_st
!= NULL
)
1591 if (!single_ld
&& !single_st
)
1594 basic_block bb_ld
= NULL
;
1595 basic_block bb_st
= NULL
;
1596 edge exit
= single_exit (loop
);
1600 /* Bail out if this is a bitfield memory reference. */
1601 if (TREE_CODE (DR_REF (single_ld
)) == COMPONENT_REF
1602 && DECL_BIT_FIELD (TREE_OPERAND (DR_REF (single_ld
), 1)))
1605 /* Data reference must be executed exactly once per iteration of each
1606 loop in the loop nest. We only need to check dominance information
1607 against the outermost one in a perfect loop nest because a bb can't
1608 dominate outermost loop's latch without dominating inner loop's. */
1609 bb_ld
= gimple_bb (DR_STMT (single_ld
));
1610 if (!dominated_by_p (CDI_DOMINATORS
, loop
->latch
, bb_ld
))
1613 /* The data reference must also be executed before possibly exiting
1614 the loop as otherwise we'd for example unconditionally execute
1615 memset (ptr, 0, n) which even with n == 0 implies ptr is non-NULL. */
1616 if (bb_ld
!= loop
->header
1618 || !dominated_by_p (CDI_DOMINATORS
, exit
->src
, bb_ld
)))
1624 /* Bail out if this is a bitfield memory reference. */
1625 if (TREE_CODE (DR_REF (single_st
)) == COMPONENT_REF
1626 && DECL_BIT_FIELD (TREE_OPERAND (DR_REF (single_st
), 1)))
1629 /* Data reference must be executed exactly once per iteration.
1630 Same as single_ld, we only need to check against the outermost
1632 bb_st
= gimple_bb (DR_STMT (single_st
));
1633 if (!dominated_by_p (CDI_DOMINATORS
, loop
->latch
, bb_st
))
1636 /* And before exiting the loop. */
1637 if (bb_st
!= loop
->header
1639 || !dominated_by_p (CDI_DOMINATORS
, exit
->src
, bb_st
)))
1643 if (single_ld
&& single_st
)
1645 /* Load and store must be in the same loop nest. */
1646 if (bb_st
->loop_father
!= bb_ld
->loop_father
)
1649 edge e
= single_exit (bb_st
->loop_father
);
1650 bool dom_ld
= dominated_by_p (CDI_DOMINATORS
, e
->src
, bb_ld
);
1651 bool dom_st
= dominated_by_p (CDI_DOMINATORS
, e
->src
, bb_st
);
1652 if (dom_ld
!= dom_st
)
1656 *src_dr
= single_ld
;
1657 *dst_dr
= single_st
;
1661 /* Given data reference DR in LOOP_NEST, this function checks the enclosing
1662 loops from inner to outer to see if loop's step equals to access size at
1663 each level of loop. Return 2 if we can prove this at all level loops;
1664 record access base and size in BASE and SIZE; save loop's step at each
1665 level of loop in STEPS if it is not null. For example:
1667 int arr[100][100][100];
1668 for (i = 0; i < 100; i++) ;steps[2] = 40000
1669 for (j = 100; j > 0; j--) ;steps[1] = -400
1670 for (k = 0; k < 100; k++) ;steps[0] = 4
1671 arr[i][j - 1][k] = 0; ;base = &arr, size = 4000000
1673 Return 1 if we can prove the equality at the innermost loop, but not all
1674 level loops. In this case, no information is recorded.
1676 Return 0 if no equality can be proven at any level loops. */
1679 compute_access_range (loop_p loop_nest
, data_reference_p dr
, tree
*base
,
1680 tree
*size
, vec
<tree
> *steps
= NULL
)
1682 location_t loc
= gimple_location (DR_STMT (dr
));
1683 basic_block bb
= gimple_bb (DR_STMT (dr
));
1684 class loop
*loop
= bb
->loop_father
;
1685 tree ref
= DR_REF (dr
);
1686 tree access_base
= build_fold_addr_expr (ref
);
1687 tree access_size
= TYPE_SIZE_UNIT (TREE_TYPE (ref
));
1691 tree scev_fn
= analyze_scalar_evolution (loop
, access_base
);
1692 if (TREE_CODE (scev_fn
) != POLYNOMIAL_CHREC
)
1695 access_base
= CHREC_LEFT (scev_fn
);
1696 if (tree_contains_chrecs (access_base
, NULL
))
1699 tree scev_step
= CHREC_RIGHT (scev_fn
);
1700 /* Only support constant steps. */
1701 if (TREE_CODE (scev_step
) != INTEGER_CST
)
1704 enum ev_direction access_dir
= scev_direction (scev_fn
);
1705 if (access_dir
== EV_DIR_UNKNOWN
)
1709 steps
->safe_push (scev_step
);
1711 scev_step
= fold_convert_loc (loc
, sizetype
, scev_step
);
1712 /* Compute absolute value of scev step. */
1713 if (access_dir
== EV_DIR_DECREASES
)
1714 scev_step
= fold_build1_loc (loc
, NEGATE_EXPR
, sizetype
, scev_step
);
1716 /* At each level of loop, scev step must equal to access size. In other
1717 words, DR must access consecutive memory between loop iterations. */
1718 if (!operand_equal_p (scev_step
, access_size
, 0))
1721 /* Access stride can be computed for data reference at least for the
1725 /* Compute DR's execution times in loop. */
1726 tree niters
= number_of_latch_executions (loop
);
1727 niters
= fold_convert_loc (loc
, sizetype
, niters
);
1728 if (dominated_by_p (CDI_DOMINATORS
, single_exit (loop
)->src
, bb
))
1729 niters
= size_binop_loc (loc
, PLUS_EXPR
, niters
, size_one_node
);
1731 /* Compute DR's overall access size in loop. */
1732 access_size
= fold_build2_loc (loc
, MULT_EXPR
, sizetype
,
1734 /* Adjust base address in case of negative step. */
1735 if (access_dir
== EV_DIR_DECREASES
)
1737 tree adj
= fold_build2_loc (loc
, MINUS_EXPR
, sizetype
,
1738 scev_step
, access_size
);
1739 access_base
= fold_build_pointer_plus_loc (loc
, access_base
, adj
);
1741 } while (loop
!= loop_nest
&& (loop
= loop_outer (loop
)) != NULL
);
1743 *base
= access_base
;
1744 *size
= access_size
;
1745 /* Access stride can be computed for data reference at each level loop. */
1749 /* Allocate and return builtin struct. Record information like DST_DR,
1750 SRC_DR, DST_BASE, SRC_BASE and SIZE in the allocated struct. */
1752 static struct builtin_info
*
1753 alloc_builtin (data_reference_p dst_dr
, data_reference_p src_dr
,
1754 tree dst_base
, tree src_base
, tree size
)
1756 struct builtin_info
*builtin
= XNEW (struct builtin_info
);
1757 builtin
->dst_dr
= dst_dr
;
1758 builtin
->src_dr
= src_dr
;
1759 builtin
->dst_base
= dst_base
;
1760 builtin
->src_base
= src_base
;
1761 builtin
->size
= size
;
1765 /* Given data reference DR in loop nest LOOP, classify if it forms builtin
1769 classify_builtin_st (loop_p loop
, partition
*partition
, data_reference_p dr
)
1771 gimple
*stmt
= DR_STMT (dr
);
1772 tree base
, size
, rhs
= gimple_assign_rhs1 (stmt
);
1774 if (const_with_all_bytes_same (rhs
) == -1
1775 && (!INTEGRAL_TYPE_P (TREE_TYPE (rhs
))
1776 || (TYPE_MODE (TREE_TYPE (rhs
))
1777 != TYPE_MODE (unsigned_char_type_node
))))
1780 if (TREE_CODE (rhs
) == SSA_NAME
1781 && !SSA_NAME_IS_DEFAULT_DEF (rhs
)
1782 && flow_bb_inside_loop_p (loop
, gimple_bb (SSA_NAME_DEF_STMT (rhs
))))
1785 int res
= compute_access_range (loop
, dr
, &base
, &size
);
1790 partition
->kind
= PKIND_PARTIAL_MEMSET
;
1796 split_constant_offset (base
, &base_base
, &base_offset
);
1797 if (!cst_and_fits_in_hwi (base_offset
))
1799 unsigned HOST_WIDE_INT const_base_offset
= int_cst_value (base_offset
);
1801 struct builtin_info
*builtin
;
1802 builtin
= alloc_builtin (dr
, NULL
, base
, NULL_TREE
, size
);
1803 builtin
->dst_base_base
= base_base
;
1804 builtin
->dst_base_offset
= const_base_offset
;
1805 partition
->builtin
= builtin
;
1806 partition
->kind
= PKIND_MEMSET
;
1809 /* Given data references DST_DR and SRC_DR in loop nest LOOP and RDG, classify
1810 if it forms builtin memcpy or memmove call. */
1813 loop_distribution::classify_builtin_ldst (loop_p loop
, struct graph
*rdg
,
1814 partition
*partition
,
1815 data_reference_p dst_dr
,
1816 data_reference_p src_dr
)
1818 tree base
, size
, src_base
, src_size
;
1819 auto_vec
<tree
> dst_steps
, src_steps
;
1821 /* Compute access range of both load and store. */
1822 int res
= compute_access_range (loop
, dst_dr
, &base
, &size
, &dst_steps
);
1825 res
= compute_access_range (loop
, src_dr
, &src_base
, &src_size
, &src_steps
);
1829 /* They must have the same access size. */
1830 if (!operand_equal_p (size
, src_size
, 0))
1833 /* They must have the same storage order. */
1834 if (reverse_storage_order_for_component_p (DR_REF (dst_dr
))
1835 != reverse_storage_order_for_component_p (DR_REF (src_dr
)))
1838 /* Load and store in loop nest must access memory in the same way, i.e,
1839 their must have the same steps in each loop of the nest. */
1840 if (dst_steps
.length () != src_steps
.length ())
1842 for (unsigned i
= 0; i
< dst_steps
.length (); ++i
)
1843 if (!operand_equal_p (dst_steps
[i
], src_steps
[i
], 0))
1846 /* Now check that if there is a dependence. */
1847 ddr_p ddr
= get_data_dependence (rdg
, src_dr
, dst_dr
);
1849 /* Classify as memcpy if no dependence between load and store. */
1850 if (DDR_ARE_DEPENDENT (ddr
) == chrec_known
)
1852 partition
->builtin
= alloc_builtin (dst_dr
, src_dr
, base
, src_base
, size
);
1853 partition
->kind
= PKIND_MEMCPY
;
1857 /* Can't do memmove in case of unknown dependence or dependence without
1858 classical distance vector. */
1859 if (DDR_ARE_DEPENDENT (ddr
) == chrec_dont_know
1860 || DDR_NUM_DIST_VECTS (ddr
) == 0)
1864 lambda_vector dist_v
;
1865 int num_lev
= (DDR_LOOP_NEST (ddr
)).length ();
1866 FOR_EACH_VEC_ELT (DDR_DIST_VECTS (ddr
), i
, dist_v
)
1868 unsigned dep_lev
= dependence_level (dist_v
, num_lev
);
1869 /* Can't do memmove if load depends on store. */
1870 if (dep_lev
> 0 && dist_v
[dep_lev
- 1] > 0 && !DDR_REVERSED_P (ddr
))
1874 partition
->builtin
= alloc_builtin (dst_dr
, src_dr
, base
, src_base
, size
);
1875 partition
->kind
= PKIND_MEMMOVE
;
1880 loop_distribution::classify_partition (loop_p loop
,
1881 struct graph
*rdg
, partition
*partition
,
1882 bitmap stmt_in_all_partitions
)
1886 data_reference_p single_ld
= NULL
, single_st
= NULL
;
1887 bool volatiles_p
= false, has_reduction
= false;
1889 EXECUTE_IF_SET_IN_BITMAP (partition
->stmts
, 0, i
, bi
)
1891 gimple
*stmt
= RDG_STMT (rdg
, i
);
1893 if (gimple_has_volatile_ops (stmt
))
1896 /* If the stmt is not included by all partitions and there is uses
1897 outside of the loop, then mark the partition as reduction. */
1898 if (stmt_has_scalar_dependences_outside_loop (loop
, stmt
))
1900 /* Due to limitation in the transform phase we have to fuse all
1901 reduction partitions. As a result, this could cancel valid
1902 loop distribution especially for loop that induction variable
1903 is used outside of loop. To workaround this issue, we skip
1904 marking partition as reudction if the reduction stmt belongs
1905 to all partitions. In such case, reduction will be computed
1906 correctly no matter how partitions are fused/distributed. */
1907 if (!bitmap_bit_p (stmt_in_all_partitions
, i
))
1908 partition
->reduction_p
= true;
1910 has_reduction
= true;
1914 /* Simple workaround to prevent classifying the partition as builtin
1915 if it contains any use outside of loop. For the case where all
1916 partitions have the reduction this simple workaround is delayed
1917 to only affect the last partition. */
1918 if (partition
->reduction_p
)
1919 return has_reduction
;
1921 /* Perform general partition disqualification for builtins. */
1923 || !flag_tree_loop_distribute_patterns
)
1924 return has_reduction
;
1926 /* Find single load/store data references for builtin partition. */
1927 if (!find_single_drs (loop
, rdg
, partition
->stmts
, &single_st
, &single_ld
)
1929 return has_reduction
;
1931 if (single_ld
&& single_st
)
1933 gimple
*store
= DR_STMT (single_st
), *load
= DR_STMT (single_ld
);
1934 /* Direct aggregate copy or via an SSA name temporary. */
1936 && gimple_assign_lhs (load
) != gimple_assign_rhs1 (store
))
1937 return has_reduction
;
1940 partition
->loc
= gimple_location (DR_STMT (single_st
));
1942 /* Classify the builtin kind. */
1943 if (single_ld
== NULL
)
1944 classify_builtin_st (loop
, partition
, single_st
);
1946 classify_builtin_ldst (loop
, rdg
, partition
, single_st
, single_ld
);
1947 return has_reduction
;
1951 loop_distribution::share_memory_accesses (struct graph
*rdg
,
1952 partition
*partition1
, partition
*partition2
)
1955 bitmap_iterator bi
, bj
;
1956 data_reference_p dr1
, dr2
;
1958 /* First check whether in the intersection of the two partitions are
1959 any loads or stores. Common loads are the situation that happens
1961 EXECUTE_IF_AND_IN_BITMAP (partition1
->stmts
, partition2
->stmts
, 0, i
, bi
)
1962 if (RDG_MEM_WRITE_STMT (rdg
, i
)
1963 || RDG_MEM_READS_STMT (rdg
, i
))
1966 /* Then check whether the two partitions access the same memory object. */
1967 EXECUTE_IF_SET_IN_BITMAP (partition1
->datarefs
, 0, i
, bi
)
1969 dr1
= datarefs_vec
[i
];
1971 if (!DR_BASE_ADDRESS (dr1
)
1972 || !DR_OFFSET (dr1
) || !DR_INIT (dr1
) || !DR_STEP (dr1
))
1975 EXECUTE_IF_SET_IN_BITMAP (partition2
->datarefs
, 0, j
, bj
)
1977 dr2
= datarefs_vec
[j
];
1979 if (!DR_BASE_ADDRESS (dr2
)
1980 || !DR_OFFSET (dr2
) || !DR_INIT (dr2
) || !DR_STEP (dr2
))
1983 if (operand_equal_p (DR_BASE_ADDRESS (dr1
), DR_BASE_ADDRESS (dr2
), 0)
1984 && operand_equal_p (DR_OFFSET (dr1
), DR_OFFSET (dr2
), 0)
1985 && operand_equal_p (DR_INIT (dr1
), DR_INIT (dr2
), 0)
1986 && operand_equal_p (DR_STEP (dr1
), DR_STEP (dr2
), 0))
1994 /* For each seed statement in STARTING_STMTS, this function builds
1995 partition for it by adding depended statements according to RDG.
1996 All partitions are recorded in PARTITIONS. */
1999 loop_distribution::rdg_build_partitions (struct graph
*rdg
,
2000 vec
<gimple
*> starting_stmts
,
2001 vec
<partition
*> *partitions
)
2003 auto_bitmap processed
;
2007 FOR_EACH_VEC_ELT (starting_stmts
, i
, stmt
)
2009 int v
= rdg_vertex_for_stmt (rdg
, stmt
);
2011 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2013 "ldist asked to generate code for vertex %d\n", v
);
2015 /* If the vertex is already contained in another partition so
2016 is the partition rooted at it. */
2017 if (bitmap_bit_p (processed
, v
))
2020 partition
*partition
= build_rdg_partition_for_vertex (rdg
, v
);
2021 bitmap_ior_into (processed
, partition
->stmts
);
2023 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2025 fprintf (dump_file
, "ldist creates useful %s partition:\n",
2026 partition
->type
== PTYPE_PARALLEL
? "parallel" : "sequent");
2027 bitmap_print (dump_file
, partition
->stmts
, " ", "\n");
2030 partitions
->safe_push (partition
);
2033 /* All vertices should have been assigned to at least one partition now,
2034 other than vertices belonging to dead code. */
2037 /* Dump to FILE the PARTITIONS. */
2040 dump_rdg_partitions (FILE *file
, const vec
<partition
*> &partitions
)
2043 partition
*partition
;
2045 FOR_EACH_VEC_ELT (partitions
, i
, partition
)
2046 debug_bitmap_file (file
, partition
->stmts
);
2049 /* Debug PARTITIONS. */
2050 extern void debug_rdg_partitions (const vec
<partition
*> &);
2053 debug_rdg_partitions (const vec
<partition
*> &partitions
)
2055 dump_rdg_partitions (stderr
, partitions
);
2058 /* Returns the number of read and write operations in the RDG. */
2061 number_of_rw_in_rdg (struct graph
*rdg
)
2065 for (i
= 0; i
< rdg
->n_vertices
; i
++)
2067 if (RDG_MEM_WRITE_STMT (rdg
, i
))
2070 if (RDG_MEM_READS_STMT (rdg
, i
))
2077 /* Returns the number of read and write operations in a PARTITION of
2081 number_of_rw_in_partition (struct graph
*rdg
, partition
*partition
)
2087 EXECUTE_IF_SET_IN_BITMAP (partition
->stmts
, 0, i
, ii
)
2089 if (RDG_MEM_WRITE_STMT (rdg
, i
))
2092 if (RDG_MEM_READS_STMT (rdg
, i
))
2099 /* Returns true when one of the PARTITIONS contains all the read or
2100 write operations of RDG. */
2103 partition_contains_all_rw (struct graph
*rdg
,
2104 const vec
<partition
*> &partitions
)
2107 partition
*partition
;
2108 int nrw
= number_of_rw_in_rdg (rdg
);
2110 FOR_EACH_VEC_ELT (partitions
, i
, partition
)
2111 if (nrw
== number_of_rw_in_partition (rdg
, partition
))
2118 loop_distribution::pg_add_dependence_edges (struct graph
*rdg
, int dir
,
2119 bitmap drs1
, bitmap drs2
, vec
<ddr_p
> *alias_ddrs
)
2122 bitmap_iterator bi
, bj
;
2123 data_reference_p dr1
, dr2
, saved_dr1
;
2125 /* dependence direction - 0 is no dependence, -1 is back,
2126 1 is forth, 2 is both (we can stop then, merging will occur). */
2127 EXECUTE_IF_SET_IN_BITMAP (drs1
, 0, i
, bi
)
2129 dr1
= datarefs_vec
[i
];
2131 EXECUTE_IF_SET_IN_BITMAP (drs2
, 0, j
, bj
)
2133 int res
, this_dir
= 1;
2136 dr2
= datarefs_vec
[j
];
2138 /* Skip all <read, read> data dependence. */
2139 if (DR_IS_READ (dr1
) && DR_IS_READ (dr2
))
2143 /* Re-shuffle data-refs to be in topological order. */
2144 if (rdg_vertex_for_stmt (rdg
, DR_STMT (dr1
))
2145 > rdg_vertex_for_stmt (rdg
, DR_STMT (dr2
)))
2147 std::swap (dr1
, dr2
);
2148 this_dir
= -this_dir
;
2150 ddr
= get_data_dependence (rdg
, dr1
, dr2
);
2151 if (DDR_ARE_DEPENDENT (ddr
) == chrec_dont_know
)
2154 res
= data_ref_compare_tree (DR_BASE_ADDRESS (dr1
),
2155 DR_BASE_ADDRESS (dr2
));
2156 /* Be conservative. If data references are not well analyzed,
2157 or the two data references have the same base address and
2158 offset, add dependence and consider it alias to each other.
2159 In other words, the dependence cannot be resolved by
2160 runtime alias check. */
2161 if (!DR_BASE_ADDRESS (dr1
) || !DR_BASE_ADDRESS (dr2
)
2162 || !DR_OFFSET (dr1
) || !DR_OFFSET (dr2
)
2163 || !DR_INIT (dr1
) || !DR_INIT (dr2
)
2164 || !DR_STEP (dr1
) || !tree_fits_uhwi_p (DR_STEP (dr1
))
2165 || !DR_STEP (dr2
) || !tree_fits_uhwi_p (DR_STEP (dr2
))
2168 /* Data dependence could be resolved by runtime alias check,
2169 record it in ALIAS_DDRS. */
2170 else if (alias_ddrs
!= NULL
)
2171 alias_ddrs
->safe_push (ddr
);
2172 /* Or simply ignore it. */
2174 else if (DDR_ARE_DEPENDENT (ddr
) == NULL_TREE
)
2176 /* Known dependences can still be unordered througout the
2177 iteration space, see gcc.dg/tree-ssa/ldist-16.c and
2178 gcc.dg/tree-ssa/pr94969.c. */
2179 if (DDR_NUM_DIST_VECTS (ddr
) != 1)
2183 /* If the overlap is exact preserve stmt order. */
2184 if (lambda_vector_zerop (DDR_DIST_VECT (ddr
, 0),
2185 DDR_NB_LOOPS (ddr
)))
2187 /* Else as the distance vector is lexicographic positive swap
2188 the dependence direction. */
2191 if (DDR_REVERSED_P (ddr
))
2192 this_dir
= -this_dir
;
2193 this_dir
= -this_dir
;
2195 /* When then dependence distance of the innermost common
2196 loop of the DRs is zero we have a conflict. This is
2197 due to wonky dependence analysis which sometimes
2198 ends up using a zero distance in place of unknown. */
2199 auto l1
= gimple_bb (DR_STMT (dr1
))->loop_father
;
2200 auto l2
= gimple_bb (DR_STMT (dr2
))->loop_father
;
2201 int idx
= index_in_loop_nest (find_common_loop (l1
, l2
)->num
,
2202 DDR_LOOP_NEST (ddr
));
2203 if (DDR_DIST_VECT (ddr
, 0)[idx
] == 0
2204 /* Unless it is the outermost loop which is the one
2205 we eventually distribute. */
2216 else if (this_dir
!= 0 && dir
!= this_dir
)
2218 /* Shuffle "back" dr1. */
2225 /* Compare postorder number of the partition graph vertices V1 and V2. */
2228 pgcmp (const void *v1_
, const void *v2_
)
2230 const vertex
*v1
= (const vertex
*)v1_
;
2231 const vertex
*v2
= (const vertex
*)v2_
;
2232 return v2
->post
- v1
->post
;
2235 /* Data attached to vertices of partition dependence graph. */
2238 /* ID of the corresponding partition. */
2240 /* The partition. */
2241 struct partition
*partition
;
2244 /* Data attached to edges of partition dependence graph. */
2247 /* If the dependence edge can be resolved by runtime alias check,
2248 this vector contains data dependence relations for runtime alias
2249 check. On the other hand, if the dependence edge is introduced
2250 because of compilation time known data dependence, this vector
2251 contains nothing. */
2252 vec
<ddr_p
> alias_ddrs
;
2255 /* Callback data for traversing edges in graph. */
2256 struct pg_edge_callback_data
2258 /* Bitmap contains strong connected components should be merged. */
2259 bitmap sccs_to_merge
;
2260 /* Array constains component information for all vertices. */
2261 int *vertices_component
;
2262 /* Vector to record all data dependence relations which are needed
2263 to break strong connected components by runtime alias checks. */
2264 vec
<ddr_p
> *alias_ddrs
;
2267 /* Initialize vertice's data for partition dependence graph PG with
2271 init_partition_graph_vertices (struct graph
*pg
,
2272 vec
<struct partition
*> *partitions
)
2275 partition
*partition
;
2276 struct pg_vdata
*data
;
2278 for (i
= 0; partitions
->iterate (i
, &partition
); ++i
)
2280 data
= new pg_vdata
;
2281 pg
->vertices
[i
].data
= data
;
2283 data
->partition
= partition
;
2287 /* Add edge <I, J> to partition dependence graph PG. Attach vector of data
2288 dependence relations to the EDGE if DDRS isn't NULL. */
2291 add_partition_graph_edge (struct graph
*pg
, int i
, int j
, vec
<ddr_p
> *ddrs
)
2293 struct graph_edge
*e
= add_edge (pg
, i
, j
);
2295 /* If the edge is attached with data dependence relations, it means this
2296 dependence edge can be resolved by runtime alias checks. */
2299 struct pg_edata
*data
= new pg_edata
;
2301 gcc_assert (ddrs
->length () > 0);
2303 data
->alias_ddrs
= vNULL
;
2304 data
->alias_ddrs
.safe_splice (*ddrs
);
2308 /* Callback function for graph travesal algorithm. It returns true
2309 if edge E should skipped when traversing the graph. */
2312 pg_skip_alias_edge (struct graph_edge
*e
)
2314 struct pg_edata
*data
= (struct pg_edata
*)e
->data
;
2315 return (data
!= NULL
&& data
->alias_ddrs
.length () > 0);
2318 /* Callback function freeing data attached to edge E of graph. */
2321 free_partition_graph_edata_cb (struct graph
*, struct graph_edge
*e
, void *)
2323 if (e
->data
!= NULL
)
2325 struct pg_edata
*data
= (struct pg_edata
*)e
->data
;
2326 data
->alias_ddrs
.release ();
2331 /* Free data attached to vertice of partition dependence graph PG. */
2334 free_partition_graph_vdata (struct graph
*pg
)
2337 struct pg_vdata
*data
;
2339 for (i
= 0; i
< pg
->n_vertices
; ++i
)
2341 data
= (struct pg_vdata
*)pg
->vertices
[i
].data
;
2346 /* Build and return partition dependence graph for PARTITIONS. RDG is
2347 reduced dependence graph for the loop to be distributed. If IGNORE_ALIAS_P
2348 is true, data dependence caused by possible alias between references
2349 is ignored, as if it doesn't exist at all; otherwise all depdendences
2353 loop_distribution::build_partition_graph (struct graph
*rdg
,
2354 vec
<struct partition
*> *partitions
,
2355 bool ignore_alias_p
)
2358 struct partition
*partition1
, *partition2
;
2359 graph
*pg
= new_graph (partitions
->length ());
2360 auto_vec
<ddr_p
> alias_ddrs
, *alias_ddrs_p
;
2362 alias_ddrs_p
= ignore_alias_p
? NULL
: &alias_ddrs
;
2364 init_partition_graph_vertices (pg
, partitions
);
2366 for (i
= 0; partitions
->iterate (i
, &partition1
); ++i
)
2368 for (j
= i
+ 1; partitions
->iterate (j
, &partition2
); ++j
)
2370 /* dependence direction - 0 is no dependence, -1 is back,
2371 1 is forth, 2 is both (we can stop then, merging will occur). */
2374 /* If the first partition has reduction, add back edge; if the
2375 second partition has reduction, add forth edge. This makes
2376 sure that reduction partition will be sorted as the last one. */
2377 if (partition_reduction_p (partition1
))
2379 else if (partition_reduction_p (partition2
))
2382 /* Cleanup the temporary vector. */
2383 alias_ddrs
.truncate (0);
2385 dir
= pg_add_dependence_edges (rdg
, dir
, partition1
->datarefs
,
2386 partition2
->datarefs
, alias_ddrs_p
);
2388 /* Add edge to partition graph if there exists dependence. There
2389 are two types of edges. One type edge is caused by compilation
2390 time known dependence, this type cannot be resolved by runtime
2391 alias check. The other type can be resolved by runtime alias
2393 if (dir
== 1 || dir
== 2
2394 || alias_ddrs
.length () > 0)
2396 /* Attach data dependence relations to edge that can be resolved
2397 by runtime alias check. */
2398 bool alias_edge_p
= (dir
!= 1 && dir
!= 2);
2399 add_partition_graph_edge (pg
, i
, j
,
2400 (alias_edge_p
) ? &alias_ddrs
: NULL
);
2402 if (dir
== -1 || dir
== 2
2403 || alias_ddrs
.length () > 0)
2405 /* Attach data dependence relations to edge that can be resolved
2406 by runtime alias check. */
2407 bool alias_edge_p
= (dir
!= -1 && dir
!= 2);
2408 add_partition_graph_edge (pg
, j
, i
,
2409 (alias_edge_p
) ? &alias_ddrs
: NULL
);
2416 /* Sort partitions in PG in descending post order and store them in
2420 sort_partitions_by_post_order (struct graph
*pg
,
2421 vec
<struct partition
*> *partitions
)
2424 struct pg_vdata
*data
;
2426 /* Now order the remaining nodes in descending postorder. */
2427 qsort (pg
->vertices
, pg
->n_vertices
, sizeof (vertex
), pgcmp
);
2428 partitions
->truncate (0);
2429 for (i
= 0; i
< pg
->n_vertices
; ++i
)
2431 data
= (struct pg_vdata
*)pg
->vertices
[i
].data
;
2432 if (data
->partition
)
2433 partitions
->safe_push (data
->partition
);
2438 loop_distribution::merge_dep_scc_partitions (struct graph
*rdg
,
2439 vec
<struct partition
*> *partitions
,
2440 bool ignore_alias_p
)
2442 struct partition
*partition1
, *partition2
;
2443 struct pg_vdata
*data
;
2444 graph
*pg
= build_partition_graph (rdg
, partitions
, ignore_alias_p
);
2445 int i
, j
, num_sccs
= graphds_scc (pg
, NULL
);
2447 /* Strong connected compoenent means dependence cycle, we cannot distribute
2448 them. So fuse them together. */
2449 if ((unsigned) num_sccs
< partitions
->length ())
2451 for (i
= 0; i
< num_sccs
; ++i
)
2453 for (j
= 0; partitions
->iterate (j
, &partition1
); ++j
)
2454 if (pg
->vertices
[j
].component
== i
)
2456 for (j
= j
+ 1; partitions
->iterate (j
, &partition2
); ++j
)
2457 if (pg
->vertices
[j
].component
== i
)
2459 partition_merge_into (NULL
, partition1
,
2460 partition2
, FUSE_SAME_SCC
);
2461 partition1
->type
= PTYPE_SEQUENTIAL
;
2462 (*partitions
)[j
] = NULL
;
2463 partition_free (partition2
);
2464 data
= (struct pg_vdata
*)pg
->vertices
[j
].data
;
2465 data
->partition
= NULL
;
2470 sort_partitions_by_post_order (pg
, partitions
);
2471 gcc_assert (partitions
->length () == (unsigned)num_sccs
);
2472 free_partition_graph_vdata (pg
);
2473 for_each_edge (pg
, free_partition_graph_edata_cb
, NULL
);
2477 /* Callback function for traversing edge E in graph G. DATA is private
2481 pg_collect_alias_ddrs (struct graph
*g
, struct graph_edge
*e
, void *data
)
2483 int i
, j
, component
;
2484 struct pg_edge_callback_data
*cbdata
;
2485 struct pg_edata
*edata
= (struct pg_edata
*) e
->data
;
2487 /* If the edge doesn't have attached data dependence, it represents
2488 compilation time known dependences. This type dependence cannot
2489 be resolved by runtime alias check. */
2490 if (edata
== NULL
|| edata
->alias_ddrs
.length () == 0)
2493 cbdata
= (struct pg_edge_callback_data
*) data
;
2496 component
= cbdata
->vertices_component
[i
];
2497 /* Vertices are topologically sorted according to compilation time
2498 known dependences, so we can break strong connected components
2499 by removing edges of the opposite direction, i.e, edges pointing
2500 from vertice with smaller post number to vertice with bigger post
2502 if (g
->vertices
[i
].post
< g
->vertices
[j
].post
2503 /* We only need to remove edges connecting vertices in the same
2504 strong connected component to break it. */
2505 && component
== cbdata
->vertices_component
[j
]
2506 /* Check if we want to break the strong connected component or not. */
2507 && !bitmap_bit_p (cbdata
->sccs_to_merge
, component
))
2508 cbdata
->alias_ddrs
->safe_splice (edata
->alias_ddrs
);
2511 /* Callback function for traversing edge E. DATA is private
2515 pg_unmark_merged_alias_ddrs (struct graph
*, struct graph_edge
*e
, void *data
)
2517 int i
, j
, component
;
2518 struct pg_edge_callback_data
*cbdata
;
2519 struct pg_edata
*edata
= (struct pg_edata
*) e
->data
;
2521 if (edata
== NULL
|| edata
->alias_ddrs
.length () == 0)
2524 cbdata
= (struct pg_edge_callback_data
*) data
;
2527 component
= cbdata
->vertices_component
[i
];
2528 /* Make sure to not skip vertices inside SCCs we are going to merge. */
2529 if (component
== cbdata
->vertices_component
[j
]
2530 && bitmap_bit_p (cbdata
->sccs_to_merge
, component
))
2532 edata
->alias_ddrs
.release ();
2538 /* This is the main function breaking strong conected components in
2539 PARTITIONS giving reduced depdendence graph RDG. Store data dependence
2540 relations for runtime alias check in ALIAS_DDRS. */
2542 loop_distribution::break_alias_scc_partitions (struct graph
*rdg
,
2543 vec
<struct partition
*> *partitions
,
2544 vec
<ddr_p
> *alias_ddrs
)
2546 int i
, j
, k
, num_sccs
, num_sccs_no_alias
= 0;
2547 /* Build partition dependence graph. */
2548 graph
*pg
= build_partition_graph (rdg
, partitions
, false);
2550 alias_ddrs
->truncate (0);
2551 /* Find strong connected components in the graph, with all dependence edges
2553 num_sccs
= graphds_scc (pg
, NULL
);
2554 /* All SCCs now can be broken by runtime alias checks because SCCs caused by
2555 compilation time known dependences are merged before this function. */
2556 if ((unsigned) num_sccs
< partitions
->length ())
2558 struct pg_edge_callback_data cbdata
;
2559 auto_bitmap sccs_to_merge
;
2560 auto_vec
<enum partition_type
> scc_types
;
2561 struct partition
*partition
, *first
;
2563 /* If all partitions in a SCC have the same type, we can simply merge the
2564 SCC. This loop finds out such SCCS and record them in bitmap. */
2565 bitmap_set_range (sccs_to_merge
, 0, (unsigned) num_sccs
);
2566 for (i
= 0; i
< num_sccs
; ++i
)
2568 for (j
= 0; partitions
->iterate (j
, &first
); ++j
)
2569 if (pg
->vertices
[j
].component
== i
)
2572 bool same_type
= true, all_builtins
= partition_builtin_p (first
);
2573 for (++j
; partitions
->iterate (j
, &partition
); ++j
)
2575 if (pg
->vertices
[j
].component
!= i
)
2578 if (first
->type
!= partition
->type
)
2583 all_builtins
&= partition_builtin_p (partition
);
2585 /* Merge SCC if all partitions in SCC have the same type, though the
2586 result partition is sequential, because vectorizer can do better
2587 runtime alias check. One expecption is all partitions in SCC are
2589 if (!same_type
|| all_builtins
)
2590 bitmap_clear_bit (sccs_to_merge
, i
);
2593 /* Initialize callback data for traversing. */
2594 cbdata
.sccs_to_merge
= sccs_to_merge
;
2595 cbdata
.alias_ddrs
= alias_ddrs
;
2596 cbdata
.vertices_component
= XNEWVEC (int, pg
->n_vertices
);
2597 /* Record the component information which will be corrupted by next
2598 graph scc finding call. */
2599 for (i
= 0; i
< pg
->n_vertices
; ++i
)
2600 cbdata
.vertices_component
[i
] = pg
->vertices
[i
].component
;
2602 /* Collect data dependences for runtime alias checks to break SCCs. */
2603 if (bitmap_count_bits (sccs_to_merge
) != (unsigned) num_sccs
)
2605 /* For SCCs we want to merge clear all alias_ddrs for edges
2606 inside the component. */
2607 for_each_edge (pg
, pg_unmark_merged_alias_ddrs
, &cbdata
);
2609 /* Run SCC finding algorithm again, with alias dependence edges
2610 skipped. This is to topologically sort partitions according to
2611 compilation time known dependence. Note the topological order
2612 is stored in the form of pg's post order number. */
2613 num_sccs_no_alias
= graphds_scc (pg
, NULL
, pg_skip_alias_edge
);
2614 /* We cannot assert partitions->length () == num_sccs_no_alias
2615 since we are not ignoring alias edges in cycles we are
2616 going to merge. That's required to compute correct postorder. */
2617 /* With topological order, we can construct two subgraphs L and R.
2618 L contains edge <x, y> where x < y in terms of post order, while
2619 R contains edge <x, y> where x > y. Edges for compilation time
2620 known dependence all fall in R, so we break SCCs by removing all
2621 (alias) edges of in subgraph L. */
2622 for_each_edge (pg
, pg_collect_alias_ddrs
, &cbdata
);
2625 /* For SCC that doesn't need to be broken, merge it. */
2626 for (i
= 0; i
< num_sccs
; ++i
)
2628 if (!bitmap_bit_p (sccs_to_merge
, i
))
2631 for (j
= 0; partitions
->iterate (j
, &first
); ++j
)
2632 if (cbdata
.vertices_component
[j
] == i
)
2634 for (k
= j
+ 1; partitions
->iterate (k
, &partition
); ++k
)
2636 struct pg_vdata
*data
;
2638 if (cbdata
.vertices_component
[k
] != i
)
2641 partition_merge_into (NULL
, first
, partition
, FUSE_SAME_SCC
);
2642 (*partitions
)[k
] = NULL
;
2643 partition_free (partition
);
2644 data
= (struct pg_vdata
*)pg
->vertices
[k
].data
;
2645 gcc_assert (data
->id
== k
);
2646 data
->partition
= NULL
;
2647 /* The result partition of merged SCC must be sequential. */
2648 first
->type
= PTYPE_SEQUENTIAL
;
2651 /* If reduction partition's SCC is broken by runtime alias checks,
2652 we force a negative post order to it making sure it will be scheduled
2654 if (num_sccs_no_alias
> 0)
2657 for (i
= 0; i
< pg
->n_vertices
; ++i
)
2659 struct pg_vdata
*data
= (struct pg_vdata
*)pg
->vertices
[i
].data
;
2660 if (data
->partition
&& partition_reduction_p (data
->partition
))
2662 gcc_assert (j
== -1);
2667 pg
->vertices
[j
].post
= -1;
2670 free (cbdata
.vertices_component
);
2673 sort_partitions_by_post_order (pg
, partitions
);
2674 free_partition_graph_vdata (pg
);
2675 for_each_edge (pg
, free_partition_graph_edata_cb
, NULL
);
2678 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2680 fprintf (dump_file
, "Possible alias data dependence to break:\n");
2681 dump_data_dependence_relations (dump_file
, *alias_ddrs
);
2685 /* Compute and return an expression whose value is the segment length which
2686 will be accessed by DR in NITERS iterations. */
2689 data_ref_segment_size (struct data_reference
*dr
, tree niters
)
2691 niters
= size_binop (MINUS_EXPR
,
2692 fold_convert (sizetype
, niters
),
2694 return size_binop (MULT_EXPR
,
2695 fold_convert (sizetype
, DR_STEP (dr
)),
2696 fold_convert (sizetype
, niters
));
2699 /* Return true if LOOP's latch is dominated by statement for data reference
2703 latch_dominated_by_data_ref (class loop
*loop
, data_reference
*dr
)
2705 return dominated_by_p (CDI_DOMINATORS
, single_exit (loop
)->src
,
2706 gimple_bb (DR_STMT (dr
)));
2709 /* Compute alias check pairs and store them in COMP_ALIAS_PAIRS for LOOP's
2710 data dependence relations ALIAS_DDRS. */
2713 compute_alias_check_pairs (class loop
*loop
, vec
<ddr_p
> *alias_ddrs
,
2714 vec
<dr_with_seg_len_pair_t
> *comp_alias_pairs
)
2717 unsigned HOST_WIDE_INT factor
= 1;
2718 tree niters_plus_one
, niters
= number_of_latch_executions (loop
);
2720 gcc_assert (niters
!= NULL_TREE
&& niters
!= chrec_dont_know
);
2721 niters
= fold_convert (sizetype
, niters
);
2722 niters_plus_one
= size_binop (PLUS_EXPR
, niters
, size_one_node
);
2724 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2725 fprintf (dump_file
, "Creating alias check pairs:\n");
2727 /* Iterate all data dependence relations and compute alias check pairs. */
2728 for (i
= 0; i
< alias_ddrs
->length (); i
++)
2730 ddr_p ddr
= (*alias_ddrs
)[i
];
2731 struct data_reference
*dr_a
= DDR_A (ddr
);
2732 struct data_reference
*dr_b
= DDR_B (ddr
);
2733 tree seg_length_a
, seg_length_b
;
2735 if (latch_dominated_by_data_ref (loop
, dr_a
))
2736 seg_length_a
= data_ref_segment_size (dr_a
, niters_plus_one
);
2738 seg_length_a
= data_ref_segment_size (dr_a
, niters
);
2740 if (latch_dominated_by_data_ref (loop
, dr_b
))
2741 seg_length_b
= data_ref_segment_size (dr_b
, niters_plus_one
);
2743 seg_length_b
= data_ref_segment_size (dr_b
, niters
);
2745 unsigned HOST_WIDE_INT access_size_a
2746 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr_a
))));
2747 unsigned HOST_WIDE_INT access_size_b
2748 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr_b
))));
2749 unsigned int align_a
= TYPE_ALIGN_UNIT (TREE_TYPE (DR_REF (dr_a
)));
2750 unsigned int align_b
= TYPE_ALIGN_UNIT (TREE_TYPE (DR_REF (dr_b
)));
2752 dr_with_seg_len_pair_t dr_with_seg_len_pair
2753 (dr_with_seg_len (dr_a
, seg_length_a
, access_size_a
, align_a
),
2754 dr_with_seg_len (dr_b
, seg_length_b
, access_size_b
, align_b
),
2755 /* ??? Would WELL_ORDERED be safe? */
2756 dr_with_seg_len_pair_t::REORDERED
);
2758 comp_alias_pairs
->safe_push (dr_with_seg_len_pair
);
2761 if (tree_fits_uhwi_p (niters
))
2762 factor
= tree_to_uhwi (niters
);
2764 /* Prune alias check pairs. */
2765 prune_runtime_alias_test_list (comp_alias_pairs
, factor
);
2766 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2768 "Improved number of alias checks from %d to %d\n",
2769 alias_ddrs
->length (), comp_alias_pairs
->length ());
2772 /* Given data dependence relations in ALIAS_DDRS, generate runtime alias
2773 checks and version LOOP under condition of these runtime alias checks. */
2776 version_loop_by_alias_check (vec
<struct partition
*> *partitions
,
2777 class loop
*loop
, vec
<ddr_p
> *alias_ddrs
)
2779 profile_probability prob
;
2780 basic_block cond_bb
;
2782 tree lhs
, arg0
, cond_expr
= NULL_TREE
;
2783 gimple_seq cond_stmts
= NULL
;
2784 gimple
*call_stmt
= NULL
;
2785 auto_vec
<dr_with_seg_len_pair_t
> comp_alias_pairs
;
2787 /* Generate code for runtime alias checks if necessary. */
2788 gcc_assert (alias_ddrs
->length () > 0);
2790 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2792 "Version loop <%d> with runtime alias check\n", loop
->num
);
2794 compute_alias_check_pairs (loop
, alias_ddrs
, &comp_alias_pairs
);
2795 create_runtime_alias_checks (loop
, &comp_alias_pairs
, &cond_expr
);
2796 cond_expr
= force_gimple_operand_1 (cond_expr
, &cond_stmts
,
2797 is_gimple_val
, NULL_TREE
);
2799 /* Depend on vectorizer to fold IFN_LOOP_DIST_ALIAS. */
2800 bool cancelable_p
= flag_tree_loop_vectorize
;
2804 struct partition
*partition
;
2805 for (; partitions
->iterate (i
, &partition
); ++i
)
2806 if (!partition_builtin_p (partition
))
2809 /* If all partitions are builtins, distributing it would be profitable and
2810 we don't want to cancel the runtime alias checks. */
2811 if (i
== partitions
->length ())
2812 cancelable_p
= false;
2815 /* Generate internal function call for loop distribution alias check if the
2816 runtime alias check should be cancelable. */
2819 call_stmt
= gimple_build_call_internal (IFN_LOOP_DIST_ALIAS
,
2820 2, NULL_TREE
, cond_expr
);
2821 lhs
= make_ssa_name (boolean_type_node
);
2822 gimple_call_set_lhs (call_stmt
, lhs
);
2827 prob
= profile_probability::guessed_always ().apply_scale (9, 10);
2828 initialize_original_copy_tables ();
2829 nloop
= loop_version (loop
, lhs
, &cond_bb
, prob
, prob
.invert (),
2830 prob
, prob
.invert (), true);
2831 free_original_copy_tables ();
2832 /* Record the original loop number in newly generated loops. In case of
2833 distribution, the original loop will be distributed and the new loop
2835 loop
->orig_loop_num
= nloop
->num
;
2836 nloop
->orig_loop_num
= nloop
->num
;
2837 nloop
->dont_vectorize
= true;
2838 nloop
->force_vectorize
= false;
2842 /* Record new loop's num in IFN_LOOP_DIST_ALIAS because the original
2843 loop could be destroyed. */
2844 arg0
= build_int_cst (integer_type_node
, loop
->orig_loop_num
);
2845 gimple_call_set_arg (call_stmt
, 0, arg0
);
2846 gimple_seq_add_stmt_without_update (&cond_stmts
, call_stmt
);
2851 gimple_stmt_iterator cond_gsi
= gsi_last_bb (cond_bb
);
2852 gsi_insert_seq_before (&cond_gsi
, cond_stmts
, GSI_SAME_STMT
);
2854 update_ssa (TODO_update_ssa_no_phi
);
2857 /* Return true if loop versioning is needed to distrubute PARTITIONS.
2858 ALIAS_DDRS are data dependence relations for runtime alias check. */
2861 version_for_distribution_p (vec
<struct partition
*> *partitions
,
2862 vec
<ddr_p
> *alias_ddrs
)
2864 /* No need to version loop if we have only one partition. */
2865 if (partitions
->length () == 1)
2868 /* Need to version loop if runtime alias check is necessary. */
2869 return (alias_ddrs
->length () > 0);
2872 /* Compare base offset of builtin mem* partitions P1 and P2. */
2875 offset_cmp (const void *vp1
, const void *vp2
)
2877 struct partition
*p1
= *(struct partition
*const *) vp1
;
2878 struct partition
*p2
= *(struct partition
*const *) vp2
;
2879 unsigned HOST_WIDE_INT o1
= p1
->builtin
->dst_base_offset
;
2880 unsigned HOST_WIDE_INT o2
= p2
->builtin
->dst_base_offset
;
2881 return (o2
< o1
) - (o1
< o2
);
2884 /* Fuse adjacent memset builtin PARTITIONS if possible. This is a special
2885 case optimization transforming below code:
2887 __builtin_memset (&obj, 0, 100);
2889 __builtin_memset (_1, 0, 200);
2891 __builtin_memset (_2, 0, 100);
2895 __builtin_memset (&obj, 0, 400);
2897 Note we don't have dependence information between different partitions
2898 at this point, as a result, we can't handle nonadjacent memset builtin
2899 partitions since dependence might be broken. */
2902 fuse_memset_builtins (vec
<struct partition
*> *partitions
)
2905 struct partition
*part1
, *part2
;
2908 for (i
= 0; partitions
->iterate (i
, &part1
);)
2910 if (part1
->kind
!= PKIND_MEMSET
)
2916 /* Find sub-array of memset builtins of the same base. Index range
2917 of the sub-array is [i, j) with "j > i". */
2918 for (j
= i
+ 1; partitions
->iterate (j
, &part2
); ++j
)
2920 if (part2
->kind
!= PKIND_MEMSET
2921 || !operand_equal_p (part1
->builtin
->dst_base_base
,
2922 part2
->builtin
->dst_base_base
, 0))
2925 /* Memset calls setting different values can't be merged. */
2926 rhs1
= gimple_assign_rhs1 (DR_STMT (part1
->builtin
->dst_dr
));
2927 rhs2
= gimple_assign_rhs1 (DR_STMT (part2
->builtin
->dst_dr
));
2928 if (!operand_equal_p (rhs1
, rhs2
, 0))
2932 /* Stable sort is required in order to avoid breaking dependence. */
2933 gcc_stablesort (&(*partitions
)[i
], j
- i
, sizeof (*partitions
)[i
],
2935 /* Continue with next partition. */
2939 /* Merge all consecutive memset builtin partitions. */
2940 for (i
= 0; i
< partitions
->length () - 1;)
2942 part1
= (*partitions
)[i
];
2943 if (part1
->kind
!= PKIND_MEMSET
)
2949 part2
= (*partitions
)[i
+ 1];
2950 /* Only merge memset partitions of the same base and with constant
2952 if (part2
->kind
!= PKIND_MEMSET
2953 || TREE_CODE (part1
->builtin
->size
) != INTEGER_CST
2954 || TREE_CODE (part2
->builtin
->size
) != INTEGER_CST
2955 || !operand_equal_p (part1
->builtin
->dst_base_base
,
2956 part2
->builtin
->dst_base_base
, 0))
2961 rhs1
= gimple_assign_rhs1 (DR_STMT (part1
->builtin
->dst_dr
));
2962 rhs2
= gimple_assign_rhs1 (DR_STMT (part2
->builtin
->dst_dr
));
2963 int bytev1
= const_with_all_bytes_same (rhs1
);
2964 int bytev2
= const_with_all_bytes_same (rhs2
);
2965 /* Only merge memset partitions of the same value. */
2966 if (bytev1
!= bytev2
|| bytev1
== -1)
2971 wide_int end1
= wi::add (part1
->builtin
->dst_base_offset
,
2972 wi::to_wide (part1
->builtin
->size
));
2973 /* Only merge adjacent memset partitions. */
2974 if (wi::ne_p (end1
, part2
->builtin
->dst_base_offset
))
2979 /* Merge partitions[i] and partitions[i+1]. */
2980 part1
->builtin
->size
= fold_build2 (PLUS_EXPR
, sizetype
,
2981 part1
->builtin
->size
,
2982 part2
->builtin
->size
);
2983 partition_free (part2
);
2984 partitions
->ordered_remove (i
+ 1);
2989 loop_distribution::finalize_partitions (class loop
*loop
,
2990 vec
<struct partition
*> *partitions
,
2991 vec
<ddr_p
> *alias_ddrs
)
2994 struct partition
*partition
, *a
;
2996 if (partitions
->length () == 1
2997 || alias_ddrs
->length () > 0)
3000 unsigned num_builtin
= 0, num_normal
= 0, num_partial_memset
= 0;
3001 bool same_type_p
= true;
3002 enum partition_type type
= ((*partitions
)[0])->type
;
3003 for (i
= 0; partitions
->iterate (i
, &partition
); ++i
)
3005 same_type_p
&= (type
== partition
->type
);
3006 if (partition_builtin_p (partition
))
3012 if (partition
->kind
== PKIND_PARTIAL_MEMSET
)
3013 num_partial_memset
++;
3016 /* Don't distribute current loop into too many loops given we don't have
3017 memory stream cost model. Be even more conservative in case of loop
3018 nest distribution. */
3019 if ((same_type_p
&& num_builtin
== 0
3020 && (loop
->inner
== NULL
|| num_normal
!= 2 || num_partial_memset
!= 1))
3021 || (loop
->inner
!= NULL
3022 && i
>= NUM_PARTITION_THRESHOLD
&& num_normal
> 1)
3023 || (loop
->inner
== NULL
3024 && i
>= NUM_PARTITION_THRESHOLD
&& num_normal
> num_builtin
))
3026 a
= (*partitions
)[0];
3027 for (i
= 1; partitions
->iterate (i
, &partition
); ++i
)
3029 partition_merge_into (NULL
, a
, partition
, FUSE_FINALIZE
);
3030 partition_free (partition
);
3032 partitions
->truncate (1);
3035 /* Fuse memset builtins if possible. */
3036 if (partitions
->length () > 1)
3037 fuse_memset_builtins (partitions
);
3040 /* Distributes the code from LOOP in such a way that producer statements
3041 are placed before consumer statements. Tries to separate only the
3042 statements from STMTS into separate loops. Returns the number of
3043 distributed loops. Set NB_CALLS to number of generated builtin calls.
3044 Set *DESTROY_P to whether LOOP needs to be destroyed. */
3047 loop_distribution::distribute_loop (class loop
*loop
,
3048 const vec
<gimple
*> &stmts
,
3049 control_dependences
*cd
, int *nb_calls
, bool *destroy_p
,
3050 bool only_patterns_p
)
3052 ddrs_table
= new hash_table
<ddr_hasher
> (389);
3054 partition
*partition
;
3059 loop_nest
.create (0);
3060 if (!find_loop_nest (loop
, &loop_nest
))
3062 loop_nest
.release ();
3067 datarefs_vec
.create (20);
3068 has_nonaddressable_dataref_p
= false;
3069 rdg
= build_rdg (loop
, cd
);
3072 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3074 "Loop %d not distributed: failed to build the RDG.\n",
3077 loop_nest
.release ();
3078 free_data_refs (datarefs_vec
);
3083 if (datarefs_vec
.length () > MAX_DATAREFS_NUM
)
3085 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3087 "Loop %d not distributed: too many memory references.\n",
3090 free_rdg (rdg
, loop
);
3091 loop_nest
.release ();
3092 free_data_refs (datarefs_vec
);
3097 data_reference_p dref
;
3098 for (i
= 0; datarefs_vec
.iterate (i
, &dref
); ++i
)
3099 dref
->aux
= (void *) (uintptr_t) i
;
3101 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3102 dump_rdg (dump_file
, rdg
);
3104 auto_vec
<struct partition
*, 3> partitions
;
3105 rdg_build_partitions (rdg
, stmts
, &partitions
);
3107 auto_vec
<ddr_p
> alias_ddrs
;
3109 auto_bitmap stmt_in_all_partitions
;
3110 bitmap_copy (stmt_in_all_partitions
, partitions
[0]->stmts
);
3111 for (i
= 1; partitions
.iterate (i
, &partition
); ++i
)
3112 bitmap_and_into (stmt_in_all_partitions
, partitions
[i
]->stmts
);
3114 bool any_builtin
= false;
3115 bool reduction_in_all
= false;
3116 int reduction_partition_num
= -1;
3117 FOR_EACH_VEC_ELT (partitions
, i
, partition
)
3120 |= classify_partition (loop
, rdg
, partition
, stmt_in_all_partitions
);
3121 any_builtin
|= partition_builtin_p (partition
);
3124 /* If we are only distributing patterns but did not detect any,
3133 /* If we are only distributing patterns fuse all partitions that
3134 were not classified as builtins. This also avoids chopping
3135 a loop into pieces, separated by builtin calls. That is, we
3136 only want no or a single loop body remaining. */
3137 struct partition
*into
;
3138 if (only_patterns_p
)
3140 for (i
= 0; partitions
.iterate (i
, &into
); ++i
)
3141 if (!partition_builtin_p (into
))
3143 for (++i
; partitions
.iterate (i
, &partition
); ++i
)
3144 if (!partition_builtin_p (partition
))
3146 partition_merge_into (NULL
, into
, partition
, FUSE_NON_BUILTIN
);
3147 partitions
.unordered_remove (i
);
3148 partition_free (partition
);
3153 /* Due to limitations in the transform phase we have to fuse all
3154 reduction partitions into the last partition so the existing
3155 loop will contain all loop-closed PHI nodes. */
3156 for (i
= 0; partitions
.iterate (i
, &into
); ++i
)
3157 if (partition_reduction_p (into
))
3159 for (i
= i
+ 1; partitions
.iterate (i
, &partition
); ++i
)
3160 if (partition_reduction_p (partition
))
3162 partition_merge_into (rdg
, into
, partition
, FUSE_REDUCTION
);
3163 partitions
.unordered_remove (i
);
3164 partition_free (partition
);
3168 /* Apply our simple cost model - fuse partitions with similar
3170 for (i
= 0; partitions
.iterate (i
, &into
); ++i
)
3172 bool changed
= false;
3173 for (int j
= i
+ 1; partitions
.iterate (j
, &partition
); ++j
)
3175 if (share_memory_accesses (rdg
, into
, partition
))
3177 partition_merge_into (rdg
, into
, partition
, FUSE_SHARE_REF
);
3178 partitions
.unordered_remove (j
);
3179 partition_free (partition
);
3184 /* If we fused 0 1 2 in step 1 to 0,2 1 as 0 and 2 have similar
3185 accesses when 1 and 2 have similar accesses but not 0 and 1
3186 then in the next iteration we will fail to consider merging
3187 1 into 0,2. So try again if we did any merging into 0. */
3192 /* Put a non-builtin partition last if we need to preserve a reduction.
3193 In most cases this helps to keep a normal partition last avoiding to
3194 spill a reduction result across builtin calls.
3195 ??? The proper way would be to use dependences to see whether we
3196 can move builtin partitions earlier during merge_dep_scc_partitions
3197 and its sort_partitions_by_post_order. Especially when the
3198 dependence graph is composed of multiple independent subgraphs the
3199 heuristic does not work reliably. */
3200 if (reduction_in_all
3201 && partition_builtin_p (partitions
.last()))
3202 FOR_EACH_VEC_ELT (partitions
, i
, partition
)
3203 if (!partition_builtin_p (partition
))
3205 partitions
.unordered_remove (i
);
3206 partitions
.quick_push (partition
);
3210 /* Build the partition dependency graph and fuse partitions in strong
3211 connected component. */
3212 if (partitions
.length () > 1)
3214 /* Don't support loop nest distribution under runtime alias check
3215 since it's not likely to enable many vectorization opportunities.
3216 Also if loop has any data reference which may be not addressable
3217 since alias check needs to take, compare address of the object. */
3218 if (loop
->inner
|| has_nonaddressable_dataref_p
)
3219 merge_dep_scc_partitions (rdg
, &partitions
, false);
3222 merge_dep_scc_partitions (rdg
, &partitions
, true);
3223 if (partitions
.length () > 1)
3224 break_alias_scc_partitions (rdg
, &partitions
, &alias_ddrs
);
3228 finalize_partitions (loop
, &partitions
, &alias_ddrs
);
3230 /* If there is a reduction in all partitions make sure the last
3231 non-builtin partition provides the LC PHI defs. */
3232 if (reduction_in_all
)
3234 FOR_EACH_VEC_ELT (partitions
, i
, partition
)
3235 if (!partition_builtin_p (partition
))
3236 reduction_partition_num
= i
;
3237 if (reduction_partition_num
== -1)
3239 /* If all partitions are builtin, force the last one to
3240 be code generated as normal partition. */
3241 partition
= partitions
.last ();
3242 partition
->kind
= PKIND_NORMAL
;
3246 nbp
= partitions
.length ();
3248 || (nbp
== 1 && !partition_builtin_p (partitions
[0]))
3249 || (nbp
> 1 && partition_contains_all_rw (rdg
, partitions
)))
3255 if (version_for_distribution_p (&partitions
, &alias_ddrs
))
3256 version_loop_by_alias_check (&partitions
, loop
, &alias_ddrs
);
3258 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3261 "distribute loop <%d> into partitions:\n", loop
->num
);
3262 dump_rdg_partitions (dump_file
, partitions
);
3265 FOR_EACH_VEC_ELT (partitions
, i
, partition
)
3267 if (partition_builtin_p (partition
))
3269 *destroy_p
|= generate_code_for_partition (loop
, partition
, i
< nbp
- 1,
3270 i
== reduction_partition_num
);
3274 loop_nest
.release ();
3275 free_data_refs (datarefs_vec
);
3276 for (hash_table
<ddr_hasher
>::iterator iter
= ddrs_table
->begin ();
3277 iter
!= ddrs_table
->end (); ++iter
)
3279 free_dependence_relation (*iter
);
3284 FOR_EACH_VEC_ELT (partitions
, i
, partition
)
3285 partition_free (partition
);
3287 free_rdg (rdg
, loop
);
3288 return nbp
- *nb_calls
;
3292 void loop_distribution::bb_top_order_init (void)
3295 int *rpo
= XNEWVEC (int, n_basic_blocks_for_fn (cfun
) - NUM_FIXED_BLOCKS
);
3296 edge entry
= single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun
));
3297 bitmap exit_bbs
= BITMAP_ALLOC (NULL
);
3299 bb_top_order_index
= XNEWVEC (int, last_basic_block_for_fn (cfun
));
3300 bb_top_order_index_size
= last_basic_block_for_fn (cfun
);
3302 entry
->flags
&= ~EDGE_DFS_BACK
;
3303 bitmap_set_bit (exit_bbs
, EXIT_BLOCK
);
3304 rpo_num
= rev_post_order_and_mark_dfs_back_seme (cfun
, entry
, exit_bbs
, true,
3306 BITMAP_FREE (exit_bbs
);
3308 for (int i
= 0; i
< rpo_num
; i
++)
3309 bb_top_order_index
[rpo
[i
]] = i
;
3314 void loop_distribution::bb_top_order_destroy ()
3316 free (bb_top_order_index
);
3317 bb_top_order_index
= NULL
;
3318 bb_top_order_index_size
= 0;
3322 /* Given LOOP, this function records seed statements for distribution in
3323 WORK_LIST. Return false if there is nothing for distribution. */
3326 find_seed_stmts_for_distribution (class loop
*loop
, vec
<gimple
*> *work_list
)
3328 basic_block
*bbs
= get_loop_body_in_dom_order (loop
);
3330 /* Initialize the worklist with stmts we seed the partitions with. */
3331 for (unsigned i
= 0; i
< loop
->num_nodes
; ++i
)
3333 /* In irreducible sub-regions we don't know how to redirect
3334 conditions, so fail. See PR100492. */
3335 if (bbs
[i
]->flags
& BB_IRREDUCIBLE_LOOP
)
3337 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3338 fprintf (dump_file
, "loop %d contains an irreducible region.\n",
3340 work_list
->truncate (0);
3343 for (gphi_iterator gsi
= gsi_start_phis (bbs
[i
]);
3344 !gsi_end_p (gsi
); gsi_next (&gsi
))
3346 gphi
*phi
= gsi
.phi ();
3347 if (virtual_operand_p (gimple_phi_result (phi
)))
3349 /* Distribute stmts which have defs that are used outside of
3351 if (!stmt_has_scalar_dependences_outside_loop (loop
, phi
))
3353 work_list
->safe_push (phi
);
3355 for (gimple_stmt_iterator gsi
= gsi_start_bb (bbs
[i
]);
3356 !gsi_end_p (gsi
); gsi_next (&gsi
))
3358 gimple
*stmt
= gsi_stmt (gsi
);
3360 /* Ignore clobbers, they do not have true side effects. */
3361 if (gimple_clobber_p (stmt
))
3364 /* If there is a stmt with side-effects bail out - we
3365 cannot and should not distribute this loop. */
3366 if (gimple_has_side_effects (stmt
))
3372 /* Distribute stmts which have defs that are used outside of
3374 if (stmt_has_scalar_dependences_outside_loop (loop
, stmt
))
3376 /* Otherwise only distribute stores for now. */
3377 else if (!gimple_vdef (stmt
))
3380 work_list
->safe_push (stmt
);
3383 bool res
= work_list
->length () > 0;
3384 if (res
&& !can_copy_bbs_p (bbs
, loop
->num_nodes
))
3386 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3387 fprintf (dump_file
, "cannot copy loop %d.\n", loop
->num
);
3394 /* A helper function for generate_{rawmemchr,strlen}_builtin functions in order
3395 to place new statements SEQ before LOOP and replace the old reduction
3396 variable with the new one. */
3399 generate_reduction_builtin_1 (loop_p loop
, gimple_seq
&seq
,
3400 tree reduction_var_old
, tree reduction_var_new
,
3401 const char *info
, machine_mode load_mode
)
3403 gcc_assert (flag_tree_loop_distribute_patterns
);
3405 /* Place new statements before LOOP. */
3406 gimple_stmt_iterator gsi
= gsi_last_bb (loop_preheader_edge (loop
)->src
);
3407 gsi_insert_seq_after (&gsi
, seq
, GSI_CONTINUE_LINKING
);
3409 /* Replace old reduction variable with new one. */
3410 imm_use_iterator iter
;
3412 use_operand_p use_p
;
3413 FOR_EACH_IMM_USE_STMT (stmt
, iter
, reduction_var_old
)
3415 FOR_EACH_IMM_USE_ON_STMT (use_p
, iter
)
3416 SET_USE (use_p
, reduction_var_new
);
3421 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3422 fprintf (dump_file
, info
, GET_MODE_NAME (load_mode
));
3425 /* Generate a call to rawmemchr and place it before LOOP. REDUCTION_VAR is
3426 replaced with a fresh SSA name representing the result of the call. */
3429 generate_rawmemchr_builtin (loop_p loop
, tree reduction_var
,
3430 data_reference_p store_dr
, tree base
, tree pattern
,
3433 gimple_seq seq
= NULL
;
3435 tree mem
= force_gimple_operand (base
, &seq
, true, NULL_TREE
);
3436 gimple
*fn_call
= gimple_build_call_internal (IFN_RAWMEMCHR
, 2, mem
, pattern
);
3437 tree reduction_var_new
= copy_ssa_name (reduction_var
);
3438 gimple_call_set_lhs (fn_call
, reduction_var_new
);
3439 gimple_set_location (fn_call
, loc
);
3440 gimple_seq_add_stmt (&seq
, fn_call
);
3444 gassign
*g
= gimple_build_assign (DR_REF (store_dr
), reduction_var_new
);
3445 gimple_seq_add_stmt (&seq
, g
);
3448 generate_reduction_builtin_1 (loop
, seq
, reduction_var
, reduction_var_new
,
3449 "generated rawmemchr%s\n",
3450 TYPE_MODE (TREE_TYPE (TREE_TYPE (base
))));
3453 /* Helper function for generate_strlen_builtin(,_using_rawmemchr) */
3456 generate_strlen_builtin_1 (loop_p loop
, gimple_seq
&seq
,
3457 tree reduction_var_old
, tree reduction_var_new
,
3458 machine_mode mode
, tree start_len
)
3460 /* REDUCTION_VAR_NEW has either size type or ptrdiff type and must be
3461 converted if types of old and new reduction variable are not compatible. */
3462 reduction_var_new
= gimple_convert (&seq
, TREE_TYPE (reduction_var_old
),
3465 /* Loops of the form `for (i=42; s[i]; ++i);` have an additional start
3467 if (!integer_zerop (start_len
))
3469 tree lhs
= make_ssa_name (TREE_TYPE (reduction_var_new
));
3470 gimple
*g
= gimple_build_assign (lhs
, PLUS_EXPR
, reduction_var_new
,
3472 gimple_seq_add_stmt (&seq
, g
);
3473 reduction_var_new
= lhs
;
3476 generate_reduction_builtin_1 (loop
, seq
, reduction_var_old
, reduction_var_new
,
3477 "generated strlen%s\n", mode
);
3480 /* Generate a call to strlen and place it before LOOP. REDUCTION_VAR is
3481 replaced with a fresh SSA name representing the result of the call. */
3484 generate_strlen_builtin (loop_p loop
, tree reduction_var
, tree base
,
3485 tree start_len
, location_t loc
)
3487 gimple_seq seq
= NULL
;
3489 tree reduction_var_new
= make_ssa_name (size_type_node
);
3491 tree mem
= force_gimple_operand (base
, &seq
, true, NULL_TREE
);
3492 tree fn
= build_fold_addr_expr (builtin_decl_implicit (BUILT_IN_STRLEN
));
3493 gimple
*fn_call
= gimple_build_call (fn
, 1, mem
);
3494 gimple_call_set_lhs (fn_call
, reduction_var_new
);
3495 gimple_set_location (fn_call
, loc
);
3496 gimple_seq_add_stmt (&seq
, fn_call
);
3498 generate_strlen_builtin_1 (loop
, seq
, reduction_var
, reduction_var_new
,
3502 /* Generate code in order to mimic the behaviour of strlen but this time over
3503 an array of elements with mode different than QI. REDUCTION_VAR is replaced
3504 with a fresh SSA name representing the result, i.e., the length. */
3507 generate_strlen_builtin_using_rawmemchr (loop_p loop
, tree reduction_var
,
3508 tree base
, tree load_type
,
3509 tree start_len
, location_t loc
)
3511 gimple_seq seq
= NULL
;
3513 tree start
= force_gimple_operand (base
, &seq
, true, NULL_TREE
);
3514 tree zero
= build_zero_cst (load_type
);
3515 gimple
*fn_call
= gimple_build_call_internal (IFN_RAWMEMCHR
, 2, start
, zero
);
3516 tree end
= make_ssa_name (TREE_TYPE (base
));
3517 gimple_call_set_lhs (fn_call
, end
);
3518 gimple_set_location (fn_call
, loc
);
3519 gimple_seq_add_stmt (&seq
, fn_call
);
3521 /* Determine the number of elements between START and END by
3522 evaluating (END - START) / sizeof (*START). */
3523 tree diff
= make_ssa_name (ptrdiff_type_node
);
3524 gimple
*diff_stmt
= gimple_build_assign (diff
, POINTER_DIFF_EXPR
, end
, start
);
3525 gimple_seq_add_stmt (&seq
, diff_stmt
);
3526 /* Let SIZE be the size of each character. */
3527 tree size
= gimple_convert (&seq
, ptrdiff_type_node
,
3528 TYPE_SIZE_UNIT (load_type
));
3529 tree count
= make_ssa_name (ptrdiff_type_node
);
3530 gimple
*count_stmt
= gimple_build_assign (count
, TRUNC_DIV_EXPR
, diff
, size
);
3531 gimple_seq_add_stmt (&seq
, count_stmt
);
3533 generate_strlen_builtin_1 (loop
, seq
, reduction_var
, count
,
3534 TYPE_MODE (load_type
),
3538 /* Return true if we can count at least as many characters by taking pointer
3539 difference as we can count via reduction_var without an overflow. Thus
3540 compute 2^n < (2^(m-1) / s) where n = TYPE_PRECISION (reduction_var_type),
3541 m = TYPE_PRECISION (ptrdiff_type_node), and s = size of each character. */
3543 reduction_var_overflows_first (tree reduction_var_type
, tree load_type
)
3545 widest_int n2
= wi::lshift (1, TYPE_PRECISION (reduction_var_type
));;
3546 widest_int m2
= wi::lshift (1, TYPE_PRECISION (ptrdiff_type_node
) - 1);
3547 widest_int s
= wi::to_widest (TYPE_SIZE_UNIT (load_type
));
3548 return wi::ltu_p (n2
, wi::udiv_trunc (m2
, s
));
3552 determine_reduction_stmt_1 (const loop_p loop
, const basic_block
*bbs
)
3554 gimple
*reduction_stmt
= NULL
;
3556 for (unsigned i
= 0, ninsns
= 0; i
< loop
->num_nodes
; ++i
)
3558 basic_block bb
= bbs
[i
];
3560 for (gphi_iterator bsi
= gsi_start_phis (bb
); !gsi_end_p (bsi
);
3563 gphi
*phi
= bsi
.phi ();
3564 if (virtual_operand_p (gimple_phi_result (phi
)))
3566 if (stmt_has_scalar_dependences_outside_loop (loop
, phi
))
3570 reduction_stmt
= phi
;
3574 for (gimple_stmt_iterator bsi
= gsi_start_nondebug_bb (bb
);
3575 !gsi_end_p (bsi
); gsi_next_nondebug (&bsi
), ++ninsns
)
3577 /* Bail out early for loops which are unlikely to match. */
3580 gimple
*stmt
= gsi_stmt (bsi
);
3581 if (gimple_clobber_p (stmt
))
3583 if (gimple_code (stmt
) == GIMPLE_LABEL
)
3585 if (gimple_has_volatile_ops (stmt
))
3587 if (stmt_has_scalar_dependences_outside_loop (loop
, stmt
))
3591 reduction_stmt
= stmt
;
3596 return reduction_stmt
;
3599 /* If LOOP has a single non-volatile reduction statement, then return a pointer
3600 to it. Otherwise return NULL. */
3602 determine_reduction_stmt (const loop_p loop
)
3604 basic_block
*bbs
= get_loop_body (loop
);
3605 gimple
*reduction_stmt
= determine_reduction_stmt_1 (loop
, bbs
);
3607 return reduction_stmt
;
3610 /* Transform loops which mimic the effects of builtins rawmemchr or strlen and
3611 replace them accordingly. For example, a loop of the form
3613 for (; *p != 42; ++p);
3617 p = rawmemchr<MODE> (p, 42);
3619 under the assumption that rawmemchr is available for a particular MODE.
3623 for (i = 42; s[i]; ++i);
3625 which is replaced by
3627 i = (int)strlen (&s[42]) + 42;
3629 for some character array S. In case array S is not of type character array
3632 i = (int)(rawmemchr<MODE> (&s[42], 0) - &s[42]) + 42;
3634 assuming that rawmemchr is available for a particular MODE. */
3637 loop_distribution::transform_reduction_loop (loop_p loop
)
3639 gimple
*reduction_stmt
;
3640 data_reference_p load_dr
= NULL
, store_dr
= NULL
;
3642 edge e
= single_exit (loop
);
3643 gcond
*cond
= safe_dyn_cast
<gcond
*> (*gsi_last_bb (e
->src
));
3646 /* Ensure loop condition is an (in)equality test and loop is exited either if
3647 the inequality test fails or the equality test succeeds. */
3648 if (!(e
->flags
& EDGE_FALSE_VALUE
&& gimple_cond_code (cond
) == NE_EXPR
)
3649 && !(e
->flags
& EDGE_TRUE_VALUE
&& gimple_cond_code (cond
) == EQ_EXPR
))
3651 /* A limitation of the current implementation is that we only support
3652 constant patterns in (in)equality tests. */
3653 tree pattern
= gimple_cond_rhs (cond
);
3654 if (TREE_CODE (pattern
) != INTEGER_CST
)
3657 reduction_stmt
= determine_reduction_stmt (loop
);
3659 /* A limitation of the current implementation is that we require a reduction
3660 statement. Therefore, loops without a reduction statement as in the
3661 following are not recognized:
3663 void foo (void) { for (; *p; ++p); } */
3664 if (reduction_stmt
== NULL
)
3667 /* Reduction variables are guaranteed to be SSA names. */
3669 switch (gimple_code (reduction_stmt
))
3673 reduction_var
= gimple_get_lhs (reduction_stmt
);
3676 /* Bail out e.g. for GIMPLE_CALL. */
3680 struct graph
*rdg
= build_rdg (loop
, NULL
);
3683 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3685 "Loop %d not transformed: failed to build the RDG.\n",
3690 auto_bitmap partition_stmts
;
3691 bitmap_set_range (partition_stmts
, 0, rdg
->n_vertices
);
3692 find_single_drs (loop
, rdg
, partition_stmts
, &store_dr
, &load_dr
);
3693 free_rdg (rdg
, loop
);
3695 /* Bail out if there is no single load. */
3696 if (load_dr
== NULL
)
3699 /* Reaching this point we have a loop with a single reduction variable,
3700 a single load, and an optional single store. */
3702 tree load_ref
= DR_REF (load_dr
);
3703 tree load_type
= TREE_TYPE (load_ref
);
3704 tree load_access_base
= build_fold_addr_expr (load_ref
);
3705 tree load_access_size
= TYPE_SIZE_UNIT (load_type
);
3706 affine_iv load_iv
, reduction_iv
;
3708 if (!INTEGRAL_TYPE_P (load_type
)
3709 || !type_has_mode_precision_p (load_type
))
3712 /* We already ensured that the loop condition tests for (in)equality where the
3713 rhs is a constant pattern. Now ensure that the lhs is the result of the
3715 if (gimple_cond_lhs (cond
) != gimple_assign_lhs (DR_STMT (load_dr
)))
3718 /* Bail out if no affine induction variable with constant step can be
3720 if (!simple_iv (loop
, loop
, load_access_base
, &load_iv
, false))
3723 /* Bail out if memory accesses are not consecutive or not growing. */
3724 if (!operand_equal_p (load_iv
.step
, load_access_size
, 0))
3727 if (!simple_iv (loop
, loop
, reduction_var
, &reduction_iv
, false))
3730 /* Handle rawmemchr like loops. */
3731 if (operand_equal_p (load_iv
.base
, reduction_iv
.base
)
3732 && operand_equal_p (load_iv
.step
, reduction_iv
.step
))
3736 /* Ensure that we store to X and load from X+I where I>0. */
3737 if (TREE_CODE (load_iv
.base
) != POINTER_PLUS_EXPR
3738 || !integer_onep (TREE_OPERAND (load_iv
.base
, 1)))
3740 tree ptr_base
= TREE_OPERAND (load_iv
.base
, 0);
3741 if (TREE_CODE (ptr_base
) != SSA_NAME
)
3743 gimple
*def
= SSA_NAME_DEF_STMT (ptr_base
);
3744 if (!gimple_assign_single_p (def
)
3745 || gimple_assign_rhs1 (def
) != DR_REF (store_dr
))
3747 /* Ensure that the reduction value is stored. */
3748 if (gimple_assign_rhs1 (DR_STMT (store_dr
)) != reduction_var
)
3751 /* Bail out if target does not provide rawmemchr for a certain mode. */
3752 machine_mode mode
= TYPE_MODE (load_type
);
3753 if (direct_optab_handler (rawmemchr_optab
, mode
) == CODE_FOR_nothing
)
3755 location_t loc
= gimple_location (DR_STMT (load_dr
));
3756 generate_rawmemchr_builtin (loop
, reduction_var
, store_dr
, load_iv
.base
,
3761 /* Handle strlen like loops. */
3762 if (store_dr
== NULL
3763 && integer_zerop (pattern
)
3764 && INTEGRAL_TYPE_P (TREE_TYPE (reduction_var
))
3765 && TREE_CODE (reduction_iv
.base
) == INTEGER_CST
3766 && TREE_CODE (reduction_iv
.step
) == INTEGER_CST
3767 && integer_onep (reduction_iv
.step
))
3769 location_t loc
= gimple_location (DR_STMT (load_dr
));
3770 tree reduction_var_type
= TREE_TYPE (reduction_var
);
3771 /* While determining the length of a string an overflow might occur.
3772 If an overflow only occurs in the loop implementation and not in the
3773 strlen implementation, then either the overflow is undefined or the
3774 truncated result of strlen equals the one of the loop. Otherwise if
3775 an overflow may also occur in the strlen implementation, then
3776 replacing a loop by a call to strlen is sound whenever we ensure that
3777 if an overflow occurs in the strlen implementation, then also an
3778 overflow occurs in the loop implementation which is undefined. It
3779 seems reasonable to relax this and assume that the strlen
3780 implementation cannot overflow in case sizetype is big enough in the
3781 sense that an overflow can only happen for string objects which are
3782 bigger than half of the address space; at least for 32-bit targets and
3785 For strlen which makes use of rawmemchr the maximal length of a string
3786 which can be determined without an overflow is PTRDIFF_MAX / S where
3787 each character has size S. Since an overflow for ptrdiff type is
3788 undefined we have to make sure that if an overflow occurs, then an
3789 overflow occurs in the loop implementation, too, and this is
3790 undefined, too. Similar as before we relax this and assume that no
3791 string object is larger than half of the address space; at least for
3792 32-bit targets and up. */
3793 if (TYPE_MODE (load_type
) == TYPE_MODE (char_type_node
)
3794 && TYPE_PRECISION (load_type
) == TYPE_PRECISION (char_type_node
)
3795 && ((TYPE_PRECISION (sizetype
) >= TYPE_PRECISION (ptr_type_node
) - 1
3796 && TYPE_PRECISION (ptr_type_node
) >= 32)
3797 || (TYPE_OVERFLOW_UNDEFINED (reduction_var_type
)
3798 && TYPE_PRECISION (reduction_var_type
) <= TYPE_PRECISION (sizetype
)))
3799 && builtin_decl_implicit (BUILT_IN_STRLEN
))
3800 generate_strlen_builtin (loop
, reduction_var
, load_iv
.base
,
3801 reduction_iv
.base
, loc
);
3802 else if (direct_optab_handler (rawmemchr_optab
, TYPE_MODE (load_type
))
3804 && ((TYPE_PRECISION (ptrdiff_type_node
) == TYPE_PRECISION (ptr_type_node
)
3805 && TYPE_PRECISION (ptrdiff_type_node
) >= 32)
3806 || (TYPE_OVERFLOW_UNDEFINED (reduction_var_type
)
3807 && reduction_var_overflows_first (reduction_var_type
, load_type
))))
3808 generate_strlen_builtin_using_rawmemchr (loop
, reduction_var
,
3811 reduction_iv
.base
, loc
);
3820 /* Given innermost LOOP, return the outermost enclosing loop that forms a
3821 perfect loop nest. */
3824 prepare_perfect_loop_nest (class loop
*loop
)
3826 class loop
*outer
= loop_outer (loop
);
3827 tree niters
= number_of_latch_executions (loop
);
3829 /* TODO: We only support the innermost 3-level loop nest distribution
3830 because of compilation time issue for now. This should be relaxed
3831 in the future. Note we only allow 3-level loop nest distribution
3832 when parallelizing loops. */
3833 while ((loop
->inner
== NULL
3834 || (loop
->inner
->inner
== NULL
&& flag_tree_parallelize_loops
> 1))
3835 && loop_outer (outer
)
3836 && outer
->inner
== loop
&& loop
->next
== NULL
3837 && single_exit (outer
)
3838 && !chrec_contains_symbols_defined_in_loop (niters
, outer
->num
)
3839 && (niters
= number_of_latch_executions (outer
)) != NULL_TREE
3840 && niters
!= chrec_dont_know
)
3843 outer
= loop_outer (loop
);
3851 loop_distribution::execute (function
*fun
)
3853 bool changed
= false;
3855 control_dependences
*cd
= NULL
;
3856 auto_vec
<loop_p
> loops_to_be_destroyed
;
3858 if (number_of_loops (fun
) <= 1)
3861 bb_top_order_init ();
3863 FOR_ALL_BB_FN (bb
, fun
)
3865 gimple_stmt_iterator gsi
;
3866 for (gsi
= gsi_start_phis (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
3867 gimple_set_uid (gsi_stmt (gsi
), -1);
3868 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
3869 gimple_set_uid (gsi_stmt (gsi
), -1);
3872 /* We can at the moment only distribute non-nested loops, thus restrict
3873 walking to innermost loops. */
3874 for (auto loop
: loops_list (cfun
, LI_ONLY_INNERMOST
))
3876 /* Don't distribute multiple exit edges loop, or cold loop when
3877 not doing pattern detection. */
3878 if (!single_exit (loop
)
3879 || (!flag_tree_loop_distribute_patterns
3880 && !optimize_loop_for_speed_p (loop
)))
3883 /* If niters is unknown don't distribute loop but rather try to transform
3884 it to a call to a builtin. */
3885 tree niters
= number_of_latch_executions (loop
);
3886 if (niters
== NULL_TREE
|| niters
== chrec_dont_know
)
3888 datarefs_vec
.create (20);
3889 if (flag_tree_loop_distribute_patterns
3890 && transform_reduction_loop (loop
))
3893 loops_to_be_destroyed
.safe_push (loop
);
3894 if (dump_enabled_p ())
3896 dump_user_location_t loc
= find_loop_location (loop
);
3897 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS
,
3898 loc
, "Loop %d transformed into a builtin.\n",
3902 free_data_refs (datarefs_vec
);
3906 /* Get the perfect loop nest for distribution. */
3907 loop
= prepare_perfect_loop_nest (loop
);
3908 for (; loop
; loop
= loop
->inner
)
3910 auto_vec
<gimple
*> work_list
;
3911 if (!find_seed_stmts_for_distribution (loop
, &work_list
))
3914 const char *str
= loop
->inner
? " nest" : "";
3915 dump_user_location_t loc
= find_loop_location (loop
);
3918 calculate_dominance_info (CDI_DOMINATORS
);
3919 calculate_dominance_info (CDI_POST_DOMINATORS
);
3920 cd
= new control_dependences ();
3921 free_dominance_info (CDI_POST_DOMINATORS
);
3925 int nb_generated_loops
, nb_generated_calls
;
3926 bool only_patterns
= !optimize_loop_for_speed_p (loop
)
3927 || !flag_tree_loop_distribution
;
3928 /* do not try to distribute loops that are not expected to iterate. */
3931 HOST_WIDE_INT iterations
= estimated_loop_iterations_int (loop
);
3933 iterations
= likely_max_loop_iterations_int (loop
);
3935 only_patterns
= true;
3938 = distribute_loop (loop
, work_list
, cd
, &nb_generated_calls
,
3939 &destroy_p
, only_patterns
);
3941 loops_to_be_destroyed
.safe_push (loop
);
3943 if (nb_generated_loops
+ nb_generated_calls
> 0)
3946 if (dump_enabled_p ())
3947 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS
,
3948 loc
, "Loop%s %d distributed: split to %d loops "
3949 "and %d library calls.\n", str
, loop
->num
,
3950 nb_generated_loops
, nb_generated_calls
);
3955 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3956 fprintf (dump_file
, "Loop%s %d not distributed.\n", str
, loop
->num
);
3963 if (bb_top_order_index
!= NULL
)
3964 bb_top_order_destroy ();
3968 /* Destroy loop bodies that could not be reused. Do this late as we
3969 otherwise can end up refering to stale data in control dependences. */
3972 FOR_EACH_VEC_ELT (loops_to_be_destroyed
, i
, loop
)
3973 destroy_loop (loop
);
3975 /* Cached scalar evolutions now may refer to wrong or non-existing
3978 mark_virtual_operands_for_renaming (fun
);
3979 rewrite_into_loop_closed_ssa (NULL
, TODO_update_ssa
);
3982 checking_verify_loop_structure ();
3984 return changed
? TODO_cleanup_cfg
: 0;
3988 /* Distribute all loops in the current function. */
3992 const pass_data pass_data_loop_distribution
=
3994 GIMPLE_PASS
, /* type */
3996 OPTGROUP_LOOP
, /* optinfo_flags */
3997 TV_TREE_LOOP_DISTRIBUTION
, /* tv_id */
3998 ( PROP_cfg
| PROP_ssa
), /* properties_required */
3999 0, /* properties_provided */
4000 0, /* properties_destroyed */
4001 0, /* todo_flags_start */
4002 0, /* todo_flags_finish */
4005 class pass_loop_distribution
: public gimple_opt_pass
4008 pass_loop_distribution (gcc::context
*ctxt
)
4009 : gimple_opt_pass (pass_data_loop_distribution
, ctxt
)
4012 /* opt_pass methods: */
4013 bool gate (function
*) final override
4015 return flag_tree_loop_distribution
4016 || flag_tree_loop_distribute_patterns
;
4019 unsigned int execute (function
*) final override
;
4021 }; // class pass_loop_distribution
4024 pass_loop_distribution::execute (function
*fun
)
4026 return loop_distribution ().execute (fun
);
4032 make_pass_loop_distribution (gcc::context
*ctxt
)
4034 return new pass_loop_distribution (ctxt
);