mirrored from git://gcc.gnu.org/git/gcc.git
/
gimple-loop-interchange.cc
2086 lines (1767 loc) · 63.7 KB
/
gimple-loop-interchange.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Loop interchange.
Copyright (C) 2017-2018 Free Software Foundation, Inc.
Contributed by ARM Ltd.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3, or (at your option) any
later version.
GCC is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "backend.h"
#include "is-a.h"
#include "tree.h"
#include "gimple.h"
#include "tree-pass.h"
#include "ssa.h"
#include "gimple-pretty-print.h"
#include "fold-const.h"
#include "gimplify.h"
#include "gimple-iterator.h"
#include "gimplify-me.h"
#include "cfgloop.h"
#include "params.h"
#include "tree-ssa.h"
#include "tree-scalar-evolution.h"
#include "tree-ssa-loop-manip.h"
#include "tree-ssa-loop-niter.h"
#include "tree-ssa-loop-ivopts.h"
#include "tree-ssa-dce.h"
#include "tree-data-ref.h"
#include "tree-vectorizer.h"
/* This pass performs loop interchange: for example, the loop nest
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
for (int i = 0; i < N; i++)
c[i][j] = c[i][j] + a[i][k]*b[k][j];
is transformed to
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
c[i][j] = c[i][j] + a[i][k]*b[k][j];
This pass implements loop interchange in the following steps:
1) Find perfect loop nest for each innermost loop and compute data
dependence relations for it. For above example, loop nest is
<loop_j, loop_k, loop_i>.
2) From innermost to outermost loop, this pass tries to interchange
each loop pair. For above case, it firstly tries to interchange
<loop_k, loop_i> and loop nest becomes <loop_j, loop_i, loop_k>.
Then it tries to interchange <loop_j, loop_i> and loop nest becomes
<loop_i, loop_j, loop_k>. The overall effect is to move innermost
loop to the outermost position. For loop pair <loop_i, loop_j>
to be interchanged, we:
3) Check if data dependence relations are valid for loop interchange.
4) Check if both loops can be interchanged in terms of transformation.
5) Check if interchanging the two loops is profitable.
6) Interchange the two loops by mapping induction variables.
This pass also handles reductions in loop nest. So far we only support
simple reduction of inner loop and double reduction of the loop nest. */
/* Maximum number of stmts in each loop that should be interchanged. */
#define MAX_NUM_STMT (PARAM_VALUE (PARAM_LOOP_INTERCHANGE_MAX_NUM_STMTS))
/* Maximum number of data references in loop nest. */
#define MAX_DATAREFS (PARAM_VALUE (PARAM_LOOP_MAX_DATAREFS_FOR_DATADEPS))
/* Comparison ratio of access stride between inner/outer loops to be
interchanged. This is the minimum stride ratio for loop interchange
to be profitable. */
#define OUTER_STRIDE_RATIO (PARAM_VALUE (PARAM_LOOP_INTERCHANGE_STRIDE_RATIO))
/* The same as above, but we require higher ratio for interchanging the
innermost two loops. */
#define INNER_STRIDE_RATIO ((OUTER_STRIDE_RATIO) + 1)
/* Comparison ratio of stmt cost between inner/outer loops. Loops won't
be interchanged if outer loop has too many stmts. */
#define STMT_COST_RATIO (3)
/* Vector of strides that DR accesses in each level loop of a loop nest. */
#define DR_ACCESS_STRIDE(dr) ((vec<tree> *) dr->aux)
/* Structure recording loop induction variable. */
typedef struct induction
{
/* IV itself. */
tree var;
/* IV's initializing value, which is the init arg of the IV PHI node. */
tree init_val;
/* IV's initializing expr, which is (the expanded result of) init_val. */
tree init_expr;
/* IV's step. */
tree step;
} *induction_p;
/* Enum type for loop reduction variable. */
enum reduction_type
{
UNKNOWN_RTYPE = 0,
SIMPLE_RTYPE,
DOUBLE_RTYPE
};
/* Structure recording loop reduction variable. */
typedef struct reduction
{
/* Reduction itself. */
tree var;
/* PHI node defining reduction variable. */
gphi *phi;
/* Init and next variables of the reduction. */
tree init;
tree next;
/* Lcssa PHI node if reduction is used outside of its definition loop. */
gphi *lcssa_phi;
/* Stmts defining init and next. */
gimple *producer;
gimple *consumer;
/* If init is loaded from memory, this is the loading memory reference. */
tree init_ref;
/* If reduction is finally stored to memory, this is the stored memory
reference. */
tree fini_ref;
enum reduction_type type;
} *reduction_p;
/* Dump reduction RE. */
static void
dump_reduction (reduction_p re)
{
if (re->type == SIMPLE_RTYPE)
fprintf (dump_file, " Simple reduction: ");
else if (re->type == DOUBLE_RTYPE)
fprintf (dump_file, " Double reduction: ");
else
fprintf (dump_file, " Unknown reduction: ");
print_gimple_stmt (dump_file, re->phi, 0);
}
/* Dump LOOP's induction IV. */
static void
dump_induction (struct loop *loop, induction_p iv)
{
fprintf (dump_file, " Induction: ");
print_generic_expr (dump_file, iv->var, TDF_SLIM);
fprintf (dump_file, " = {");
print_generic_expr (dump_file, iv->init_expr, TDF_SLIM);
fprintf (dump_file, ", ");
print_generic_expr (dump_file, iv->step, TDF_SLIM);
fprintf (dump_file, "}_%d\n", loop->num);
}
/* Loop candidate for interchange. */
struct loop_cand
{
loop_cand (struct loop *, struct loop *);
~loop_cand ();
reduction_p find_reduction_by_stmt (gimple *);
void classify_simple_reduction (reduction_p);
bool analyze_iloop_reduction_var (tree);
bool analyze_oloop_reduction_var (loop_cand *, tree);
bool analyze_induction_var (tree, tree);
bool analyze_carried_vars (loop_cand *);
bool analyze_lcssa_phis (void);
bool can_interchange_p (loop_cand *);
void undo_simple_reduction (reduction_p, bitmap);
/* The loop itself. */
struct loop *m_loop;
/* The outer loop for interchange. It equals to loop if this loop cand
itself represents the outer loop. */
struct loop *m_outer;
/* Vector of induction variables in loop. */
vec<induction_p> m_inductions;
/* Vector of reduction variables in loop. */
vec<reduction_p> m_reductions;
/* Lcssa PHI nodes of this loop. */
vec<gphi *> m_lcssa_nodes;
/* Single exit edge of this loop. */
edge m_exit;
/* Basic blocks of this loop. */
basic_block *m_bbs;
/* Number of stmts of this loop. Inner loops' stmts are not included. */
int m_num_stmts;
/* Number of constant initialized simple reduction. */
int m_const_init_reduc;
};
/* Constructor. */
loop_cand::loop_cand (struct loop *loop, struct loop *outer)
: m_loop (loop), m_outer (outer), m_exit (single_exit (loop)),
m_bbs (get_loop_body (loop)), m_num_stmts (0), m_const_init_reduc (0)
{
m_inductions.create (3);
m_reductions.create (3);
m_lcssa_nodes.create (3);
}
/* Destructor. */
loop_cand::~loop_cand ()
{
induction_p iv;
for (unsigned i = 0; m_inductions.iterate (i, &iv); ++i)
free (iv);
reduction_p re;
for (unsigned i = 0; m_reductions.iterate (i, &re); ++i)
free (re);
m_inductions.release ();
m_reductions.release ();
m_lcssa_nodes.release ();
free (m_bbs);
}
/* Return single use stmt of VAR in LOOP, otherwise return NULL. */
static gimple *
single_use_in_loop (tree var, struct loop *loop)
{
gimple *stmt, *res = NULL;
use_operand_p use_p;
imm_use_iterator iterator;
FOR_EACH_IMM_USE_FAST (use_p, iterator, var)
{
stmt = USE_STMT (use_p);
if (is_gimple_debug (stmt))
continue;
if (!flow_bb_inside_loop_p (loop, gimple_bb (stmt)))
continue;
if (res)
return NULL;
res = stmt;
}
return res;
}
/* Return true if E is unsupported in loop interchange, i.e, E is a complex
edge or part of irreducible loop. */
static inline bool
unsupported_edge (edge e)
{
return (e->flags & (EDGE_COMPLEX | EDGE_IRREDUCIBLE_LOOP));
}
/* Return the reduction if STMT is one of its lcssa PHI, producer or consumer
stmt. */
reduction_p
loop_cand::find_reduction_by_stmt (gimple *stmt)
{
gphi *phi = dyn_cast <gphi *> (stmt);
reduction_p re;
for (unsigned i = 0; m_reductions.iterate (i, &re); ++i)
if ((phi != NULL && phi == re->lcssa_phi)
|| (stmt == re->producer || stmt == re->consumer))
return re;
return NULL;
}
/* Return true if current loop_cand be interchanged. ILOOP is not NULL if
current loop_cand is outer loop in loop nest. */
bool
loop_cand::can_interchange_p (loop_cand *iloop)
{
/* For now we only support at most one reduction. */
unsigned allowed_reduction_num = 1;
/* Only support reduction if the loop nest to be interchanged is the
innermostin two loops. */
if ((iloop == NULL && m_loop->inner != NULL)
|| (iloop != NULL && iloop->m_loop->inner != NULL))
allowed_reduction_num = 0;
if (m_reductions.length () > allowed_reduction_num
|| (m_reductions.length () == 1
&& m_reductions[0]->type == UNKNOWN_RTYPE))
return false;
/* Only support lcssa PHI node which is for reduction. */
if (m_lcssa_nodes.length () > allowed_reduction_num)
return false;
/* Check if basic block has any unsupported operation. Note basic blocks
of inner loops are not checked here. */
for (unsigned i = 0; i < m_loop->num_nodes; i++)
{
basic_block bb = m_bbs[i];
gphi_iterator psi;
gimple_stmt_iterator gsi;
/* Skip basic blocks of inner loops. */
if (bb->loop_father != m_loop)
continue;
for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
{
gimple *stmt = gsi_stmt (gsi);
if (is_gimple_debug (stmt))
continue;
if (gimple_has_side_effects (stmt))
return false;
m_num_stmts++;
if (gcall *call = dyn_cast <gcall *> (stmt))
{
/* In basic block of outer loop, the call should be cheap since
it will be moved to inner loop. */
if (iloop != NULL
&& !gimple_inexpensive_call_p (call))
return false;
continue;
}
if (!iloop || !gimple_vuse (stmt))
continue;
/* Support stmt accessing memory in outer loop only if it is for
inner loop's reduction. */
if (iloop->find_reduction_by_stmt (stmt))
continue;
tree lhs;
/* Support loop invariant memory reference if it's only used once by
inner loop. */
/* ??? How's this checking for invariantness? */
if (gimple_assign_single_p (stmt)
&& (lhs = gimple_assign_lhs (stmt)) != NULL_TREE
&& TREE_CODE (lhs) == SSA_NAME
&& single_use_in_loop (lhs, iloop->m_loop))
continue;
return false;
}
/* Check if loop has too many stmts. */
if (m_num_stmts > MAX_NUM_STMT)
return false;
/* Allow PHI nodes in any basic block of inner loop, PHI nodes in outer
loop's header, or PHI nodes in dest bb of inner loop's exit edge. */
if (!iloop || bb == m_loop->header
|| bb == iloop->m_exit->dest)
continue;
/* Don't allow any other PHI nodes. */
for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
if (!virtual_operand_p (PHI_RESULT (psi.phi ())))
return false;
}
return true;
}
/* Programmers and optimizers (like loop store motion) may optimize code:
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
a[i] += b[j][i] * c[j][i];
into reduction:
for (int i = 0; i < N; i++)
{
// producer. Note sum can be intitialized to a constant.
int sum = a[i];
for (int j = 0; j < N; j++)
{
sum += b[j][i] * c[j][i];
}
// consumer.
a[i] = sum;
}
The result code can't be interchanged without undoing the optimization.
This function classifies this kind reduction and records information so
that we can undo the store motion during interchange. */
void
loop_cand::classify_simple_reduction (reduction_p re)
{
gimple *producer, *consumer;
/* Check init variable of reduction and how it is initialized. */
if (TREE_CODE (re->init) == SSA_NAME)
{
producer = SSA_NAME_DEF_STMT (re->init);
re->producer = producer;
basic_block bb = gimple_bb (producer);
if (!bb || bb->loop_father != m_outer)
return;
if (!gimple_assign_load_p (producer))
return;
re->init_ref = gimple_assign_rhs1 (producer);
}
else if (CONSTANT_CLASS_P (re->init))
m_const_init_reduc++;
else
return;
/* Check how reduction variable is used. */
consumer = single_use_in_loop (PHI_RESULT (re->lcssa_phi), m_outer);
if (!consumer
|| !gimple_store_p (consumer))
return;
re->fini_ref = gimple_get_lhs (consumer);
re->consumer = consumer;
/* Simple reduction with constant initializer. */
if (!re->init_ref)
{
gcc_assert (CONSTANT_CLASS_P (re->init));
re->init_ref = unshare_expr (re->fini_ref);
}
/* Require memory references in producer and consumer are the same so
that we can undo reduction during interchange. */
if (re->init_ref && !operand_equal_p (re->init_ref, re->fini_ref, 0))
return;
re->type = SIMPLE_RTYPE;
}
/* Analyze reduction variable VAR for inner loop of the loop nest to be
interchanged. Return true if analysis succeeds. */
bool
loop_cand::analyze_iloop_reduction_var (tree var)
{
gphi *phi = as_a <gphi *> (SSA_NAME_DEF_STMT (var));
gphi *lcssa_phi = NULL, *use_phi;
tree init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (m_loop));
tree next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (m_loop));
reduction_p re;
gimple *stmt, *next_def, *single_use = NULL;
use_operand_p use_p;
imm_use_iterator iterator;
if (TREE_CODE (next) != SSA_NAME)
return false;
next_def = SSA_NAME_DEF_STMT (next);
basic_block bb = gimple_bb (next_def);
if (!bb || !flow_bb_inside_loop_p (m_loop, bb))
return false;
/* In restricted reduction, the var is (and must be) used in defining
the updated var. The process can be depicted as below:
var ;; = PHI<init, next>
|
|
v
+---------------------+
| reduction operators | <-- other operands
+---------------------+
|
|
v
next
In terms loop interchange, we don't change how NEXT is computed based
on VAR and OTHER OPERANDS. In case of double reduction in loop nest
to be interchanged, we don't changed it at all. In the case of simple
reduction in inner loop, we only make change how VAR/NEXT is loaded or
stored. With these conditions, we can relax restrictions on reduction
in a way that reduction operation is seen as black box. In general,
we can ignore reassociation of reduction operator; we can handle fake
reductions in which VAR is not even used to compute NEXT. */
if (! single_imm_use (var, &use_p, &single_use)
|| ! flow_bb_inside_loop_p (m_loop, gimple_bb (single_use)))
return false;
/* Check the reduction operation. We require a left-associative operation.
For FP math we also need to be allowed to associate operations. */
if (gassign *ass = dyn_cast <gassign *> (single_use))
{
enum tree_code code = gimple_assign_rhs_code (ass);
if (! (associative_tree_code (code)
|| (code == MINUS_EXPR
&& use_p->use == gimple_assign_rhs1_ptr (ass)))
|| (FLOAT_TYPE_P (TREE_TYPE (var))
&& ! flag_associative_math))
return false;
}
else
return false;
/* Handle and verify a series of stmts feeding the reduction op. */
if (single_use != next_def
&& !check_reduction_path (dump_user_location_t (), m_loop, phi, next,
gimple_assign_rhs_code (single_use)))
return false;
/* Only support cases in which INIT is used in inner loop. */
if (TREE_CODE (init) == SSA_NAME)
FOR_EACH_IMM_USE_FAST (use_p, iterator, init)
{
stmt = USE_STMT (use_p);
if (is_gimple_debug (stmt))
continue;
if (!flow_bb_inside_loop_p (m_loop, gimple_bb (stmt)))
return false;
}
FOR_EACH_IMM_USE_FAST (use_p, iterator, next)
{
stmt = USE_STMT (use_p);
if (is_gimple_debug (stmt))
continue;
/* Or else it's used in PHI itself. */
use_phi = dyn_cast <gphi *> (stmt);
if (use_phi == phi)
continue;
if (use_phi != NULL
&& lcssa_phi == NULL
&& gimple_bb (stmt) == m_exit->dest
&& PHI_ARG_DEF_FROM_EDGE (use_phi, m_exit) == next)
lcssa_phi = use_phi;
else
return false;
}
if (!lcssa_phi)
return false;
re = XCNEW (struct reduction);
re->var = var;
re->init = init;
re->next = next;
re->phi = phi;
re->lcssa_phi = lcssa_phi;
classify_simple_reduction (re);
if (dump_file && (dump_flags & TDF_DETAILS))
dump_reduction (re);
m_reductions.safe_push (re);
return true;
}
/* Analyze reduction variable VAR for outer loop of the loop nest to be
interchanged. ILOOP is not NULL and points to inner loop. For the
moment, we only support double reduction for outer loop, like:
for (int i = 0; i < n; i++)
{
int sum = 0;
for (int j = 0; j < n; j++) // outer loop
for (int k = 0; k < n; k++) // inner loop
sum += a[i][k]*b[k][j];
s[i] = sum;
}
Note the innermost two loops are the loop nest to be interchanged.
Return true if analysis succeeds. */
bool
loop_cand::analyze_oloop_reduction_var (loop_cand *iloop, tree var)
{
gphi *phi = as_a <gphi *> (SSA_NAME_DEF_STMT (var));
gphi *lcssa_phi = NULL, *use_phi;
tree init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (m_loop));
tree next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (m_loop));
reduction_p re;
gimple *stmt, *next_def;
use_operand_p use_p;
imm_use_iterator iterator;
if (TREE_CODE (next) != SSA_NAME)
return false;
next_def = SSA_NAME_DEF_STMT (next);
basic_block bb = gimple_bb (next_def);
if (!bb || !flow_bb_inside_loop_p (m_loop, bb))
return false;
/* Find inner loop's simple reduction that uses var as initializer. */
reduction_p inner_re = NULL;
for (unsigned i = 0; iloop->m_reductions.iterate (i, &inner_re); ++i)
if (inner_re->init == var || operand_equal_p (inner_re->init, var, 0))
break;
if (inner_re == NULL
|| inner_re->type != UNKNOWN_RTYPE
|| inner_re->producer != phi)
return false;
/* In case of double reduction, outer loop's reduction should be updated
by inner loop's simple reduction. */
if (next_def != inner_re->lcssa_phi)
return false;
/* Outer loop's reduction should only be used to initialize inner loop's
simple reduction. */
if (! single_imm_use (var, &use_p, &stmt)
|| stmt != inner_re->phi)
return false;
/* Check this reduction is correctly used outside of loop via lcssa phi. */
FOR_EACH_IMM_USE_FAST (use_p, iterator, next)
{
stmt = USE_STMT (use_p);
if (is_gimple_debug (stmt))
continue;
/* Or else it's used in PHI itself. */
use_phi = dyn_cast <gphi *> (stmt);
if (use_phi == phi)
continue;
if (lcssa_phi == NULL
&& use_phi != NULL
&& gimple_bb (stmt) == m_exit->dest
&& PHI_ARG_DEF_FROM_EDGE (use_phi, m_exit) == next)
lcssa_phi = use_phi;
else
return false;
}
if (!lcssa_phi)
return false;
re = XCNEW (struct reduction);
re->var = var;
re->init = init;
re->next = next;
re->phi = phi;
re->lcssa_phi = lcssa_phi;
re->type = DOUBLE_RTYPE;
inner_re->type = DOUBLE_RTYPE;
if (dump_file && (dump_flags & TDF_DETAILS))
dump_reduction (re);
m_reductions.safe_push (re);
return true;
}
/* Return true if VAR is induction variable of current loop whose scev is
specified by CHREC. */
bool
loop_cand::analyze_induction_var (tree var, tree chrec)
{
gphi *phi = as_a <gphi *> (SSA_NAME_DEF_STMT (var));
tree init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (m_loop));
/* Var is loop invariant, though it's unlikely to happen. */
if (tree_does_not_contain_chrecs (chrec))
{
struct induction *iv = XCNEW (struct induction);
iv->var = var;
iv->init_val = init;
iv->init_expr = chrec;
iv->step = build_int_cst (TREE_TYPE (chrec), 0);
m_inductions.safe_push (iv);
return true;
}
if (TREE_CODE (chrec) != POLYNOMIAL_CHREC
|| CHREC_VARIABLE (chrec) != (unsigned) m_loop->num
|| tree_contains_chrecs (CHREC_LEFT (chrec), NULL)
|| tree_contains_chrecs (CHREC_RIGHT (chrec), NULL))
return false;
struct induction *iv = XCNEW (struct induction);
iv->var = var;
iv->init_val = init;
iv->init_expr = CHREC_LEFT (chrec);
iv->step = CHREC_RIGHT (chrec);
if (dump_file && (dump_flags & TDF_DETAILS))
dump_induction (m_loop, iv);
m_inductions.safe_push (iv);
return true;
}
/* Return true if all loop carried variables defined in loop header can
be successfully analyzed. */
bool
loop_cand::analyze_carried_vars (loop_cand *iloop)
{
edge e = loop_preheader_edge (m_outer);
gphi_iterator gsi;
if (dump_file && (dump_flags & TDF_DETAILS))
fprintf (dump_file, "\nLoop(%d) carried vars:\n", m_loop->num);
for (gsi = gsi_start_phis (m_loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
{
gphi *phi = gsi.phi ();
tree var = PHI_RESULT (phi);
if (virtual_operand_p (var))
continue;
tree chrec = analyze_scalar_evolution (m_loop, var);
chrec = instantiate_scev (e, m_loop, chrec);
/* Analyze var as reduction variable. */
if (chrec_contains_undetermined (chrec)
|| chrec_contains_symbols_defined_in_loop (chrec, m_outer->num))
{
if (iloop && !analyze_oloop_reduction_var (iloop, var))
return false;
if (!iloop && !analyze_iloop_reduction_var (var))
return false;
}
/* Analyze var as induction variable. */
else if (!analyze_induction_var (var, chrec))
return false;
}
return true;
}
/* Return TRUE if loop closed PHI nodes can be analyzed successfully. */
bool
loop_cand::analyze_lcssa_phis (void)
{
gphi_iterator gsi;
for (gsi = gsi_start_phis (m_exit->dest); !gsi_end_p (gsi); gsi_next (&gsi))
{
gphi *phi = gsi.phi ();
if (virtual_operand_p (PHI_RESULT (phi)))
continue;
/* TODO: We only support lcssa phi for reduction for now. */
if (!find_reduction_by_stmt (phi))
return false;
}
return true;
}
/* CONSUMER is a stmt in BB storing reduction result into memory object.
When the reduction is intialized from constant value, we need to add
a stmt loading from the memory object to target basic block in inner
loop during undoing the reduction. Problem is that memory reference
may use ssa variables not dominating the target basic block. This
function finds all stmts on which CONSUMER depends in basic block BB,
records and returns them via STMTS. */
static void
find_deps_in_bb_for_stmt (gimple_seq *stmts, basic_block bb, gimple *consumer)
{
auto_vec<gimple *, 4> worklist;
use_operand_p use_p;
ssa_op_iter iter;
gimple *stmt, *def_stmt;
gimple_stmt_iterator gsi;
/* First clear flag for stmts in bb. */
for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
gimple_set_plf (gsi_stmt (gsi), GF_PLF_1, false);
/* DFS search all depended stmts in bb and mark flag for these stmts. */
worklist.safe_push (consumer);
while (!worklist.is_empty ())
{
stmt = worklist.pop ();
FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
{
def_stmt = SSA_NAME_DEF_STMT (USE_FROM_PTR (use_p));
if (is_a <gphi *> (def_stmt)
|| gimple_bb (def_stmt) != bb
|| gimple_plf (def_stmt, GF_PLF_1))
continue;
worklist.safe_push (def_stmt);
}
gimple_set_plf (stmt, GF_PLF_1, true);
}
for (gsi = gsi_start_nondebug_bb (bb);
!gsi_end_p (gsi) && (stmt = gsi_stmt (gsi)) != consumer;)
{
/* Move dep stmts to sequence STMTS. */
if (gimple_plf (stmt, GF_PLF_1))
{
gsi_remove (&gsi, false);
gimple_seq_add_stmt_without_update (stmts, stmt);
}
else
gsi_next_nondebug (&gsi);
}
}
/* User can write, optimizers can generate simple reduction RE for inner
loop. In order to make interchange valid, we have to undo reduction by
moving producer and consumer stmts into the inner loop. For example,
below code:
init = MEM_REF[idx]; //producer
loop:
var = phi<init, next>
next = var op ...
reduc_sum = phi<next>
MEM_REF[idx] = reduc_sum //consumer
is transformed into:
loop:
new_var = MEM_REF[idx]; //producer after moving
next = new_var op ...
MEM_REF[idx] = next; //consumer after moving
Note if the reduction variable is initialized to constant, like:
var = phi<0.0, next>
we compute new_var as below:
loop:
tmp = MEM_REF[idx];
new_var = !first_iteration ? tmp : 0.0;
so that the initial const is used in the first iteration of loop. Also
record ssa variables for dead code elimination in DCE_SEEDS. */
void
loop_cand::undo_simple_reduction (reduction_p re, bitmap dce_seeds)
{
gimple *stmt;
gimple_stmt_iterator from, to = gsi_after_labels (m_loop->header);
gimple_seq stmts = NULL;
tree new_var;
/* Prepare the initialization stmts and insert it to inner loop. */
if (re->producer != NULL)
{
gimple_set_vuse (re->producer, NULL_TREE);
from = gsi_for_stmt (re->producer);
gsi_remove (&from, false);
gimple_seq_add_stmt_without_update (&stmts, re->producer);
new_var = re->init;
}
else
{
/* Find all stmts on which expression "MEM_REF[idx]" depends. */
find_deps_in_bb_for_stmt (&stmts, gimple_bb (re->consumer), re->consumer);
/* Because we generate new stmt loading from the MEM_REF to TMP. */
tree cond, tmp = copy_ssa_name (re->var);
stmt = gimple_build_assign (tmp, re->init_ref);
gimple_seq_add_stmt_without_update (&stmts, stmt);
/* Init new_var to MEM_REF or CONST depending on if it is the first
iteration. */
induction_p iv = m_inductions[0];
cond = fold_build2 (NE_EXPR, boolean_type_node, iv->var, iv->init_val);
new_var = copy_ssa_name (re->var);
stmt = gimple_build_assign (new_var, COND_EXPR, cond, tmp, re->init);
gimple_seq_add_stmt_without_update (&stmts, stmt);
}
gsi_insert_seq_before (&to, stmts, GSI_SAME_STMT);
/* Replace all uses of reduction var with new variable. */
use_operand_p use_p;
imm_use_iterator iterator;
FOR_EACH_IMM_USE_STMT (stmt, iterator, re->var)
{
FOR_EACH_IMM_USE_ON_STMT (use_p, iterator)
SET_USE (use_p, new_var);
update_stmt (stmt);
}
/* Move consumer stmt into inner loop, just after reduction next's def. */
unlink_stmt_vdef (re->consumer);
release_ssa_name (gimple_vdef (re->consumer));
gimple_set_vdef (re->consumer, NULL_TREE);
gimple_set_vuse (re->consumer, NULL_TREE);
gimple_assign_set_rhs1 (re->consumer, re->next);
from = gsi_for_stmt (re->consumer);
to = gsi_for_stmt (SSA_NAME_DEF_STMT (re->next));
gsi_move_after (&from, &to);
/* Mark the reduction variables for DCE. */
bitmap_set_bit (dce_seeds, SSA_NAME_VERSION (re->var));
bitmap_set_bit (dce_seeds, SSA_NAME_VERSION (PHI_RESULT (re->lcssa_phi)));
}
/* Free DATAREFS and its auxiliary memory. */
static void
free_data_refs_with_aux (vec<data_reference_p> datarefs)
{
data_reference_p dr;
for (unsigned i = 0; datarefs.iterate (i, &dr); ++i)
if (dr->aux != NULL)
{
DR_ACCESS_STRIDE (dr)->release ();
delete (vec<tree> *) dr->aux;
}
free_data_refs (datarefs);
}
/* Class for loop interchange transformation. */
class tree_loop_interchange
{
public:
tree_loop_interchange (vec<struct loop *> loop_nest)
: m_loop_nest (loop_nest), m_niters_iv_var (NULL_TREE),
m_dce_seeds (BITMAP_ALLOC (NULL)) { }
~tree_loop_interchange () { BITMAP_FREE (m_dce_seeds); }
bool interchange (vec<data_reference_p>, vec<ddr_p>);
private:
void update_data_info (unsigned, unsigned, vec<data_reference_p>, vec<ddr_p>);
bool valid_data_dependences (unsigned, unsigned, vec<ddr_p>);
void interchange_loops (loop_cand &, loop_cand &);
void map_inductions_to_loop (loop_cand &, loop_cand &);
void move_code_to_inner_loop (struct loop *, struct loop *, basic_block *);
/* The whole loop nest in which interchange is ongoing. */
vec<struct loop *> m_loop_nest;
/* We create new IV which is only used in loop's exit condition check.
In case of 3-level loop nest interchange, when we interchange the
innermost two loops, new IV created in the middle level loop does
not need to be preserved in interchanging the outermost two loops
later. We record the IV so that it can be skipped. */
tree m_niters_iv_var;
/* Bitmap of seed variables for dead code elimination after interchange. */
bitmap m_dce_seeds;
};
/* Update data refs' access stride and dependence information after loop
interchange. I_IDX/O_IDX gives indices of interchanged loops in loop
nest. DATAREFS are data references. DDRS are data dependences. */
void
tree_loop_interchange::update_data_info (unsigned i_idx, unsigned o_idx,
vec<data_reference_p> datarefs,
vec<ddr_p> ddrs)
{
struct data_reference *dr;
struct data_dependence_relation *ddr;
/* Update strides of data references. */
for (unsigned i = 0; datarefs.iterate (i, &dr); ++i)
{
vec<tree> *stride = DR_ACCESS_STRIDE (dr);
gcc_assert (stride->length () > i_idx);
std::swap ((*stride)[i_idx], (*stride)[o_idx]);
}
/* Update data dependences. */
for (unsigned i = 0; ddrs.iterate (i, &ddr); ++i)
if (DDR_ARE_DEPENDENT (ddr) != chrec_known)
{
for (unsigned j = 0; j < DDR_NUM_DIST_VECTS (ddr); ++j)
{
lambda_vector dist_vect = DDR_DIST_VECT (ddr, j);
std::swap (dist_vect[i_idx], dist_vect[o_idx]);
}