/
loopTransform.cpp
4176 lines (3790 loc) · 164 KB
/
loopTransform.cpp
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
/*
* Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "compiler/compileLog.hpp"
#include "gc/shared/barrierSet.hpp"
#include "gc/shared/c2/barrierSetC2.hpp"
#include "memory/allocation.inline.hpp"
#include "opto/addnode.hpp"
#include "opto/callnode.hpp"
#include "opto/castnode.hpp"
#include "opto/connode.hpp"
#include "opto/convertnode.hpp"
#include "opto/divnode.hpp"
#include "opto/loopnode.hpp"
#include "opto/mulnode.hpp"
#include "opto/movenode.hpp"
#include "opto/opaquenode.hpp"
#include "opto/phase.hpp"
#include "opto/predicates.hpp"
#include "opto/rootnode.hpp"
#include "opto/runtime.hpp"
#include "opto/subnode.hpp"
#include "opto/superword.hpp"
#include "opto/vectornode.hpp"
#include "runtime/globals_extension.hpp"
#include "runtime/stubRoutines.hpp"
//------------------------------is_loop_exit-----------------------------------
// Given an IfNode, return the loop-exiting projection or null if both
// arms remain in the loop.
Node *IdealLoopTree::is_loop_exit(Node *iff) const {
if (iff->outcnt() != 2) return nullptr; // Ignore partially dead tests
PhaseIdealLoop *phase = _phase;
// Test is an IfNode, has 2 projections. If BOTH are in the loop
// we need loop unswitching instead of peeling.
if (!is_member(phase->get_loop(iff->raw_out(0))))
return iff->raw_out(0);
if (!is_member(phase->get_loop(iff->raw_out(1))))
return iff->raw_out(1);
return nullptr;
}
//=============================================================================
//------------------------------record_for_igvn----------------------------
// Put loop body on igvn work list
void IdealLoopTree::record_for_igvn() {
for (uint i = 0; i < _body.size(); i++) {
Node *n = _body.at(i);
_phase->_igvn._worklist.push(n);
}
// put body of outer strip mined loop on igvn work list as well
if (_head->is_CountedLoop() && _head->as_Loop()->is_strip_mined()) {
CountedLoopNode* l = _head->as_CountedLoop();
Node* outer_loop = l->outer_loop();
assert(outer_loop != nullptr, "missing piece of strip mined loop");
_phase->_igvn._worklist.push(outer_loop);
Node* outer_loop_tail = l->outer_loop_tail();
assert(outer_loop_tail != nullptr, "missing piece of strip mined loop");
_phase->_igvn._worklist.push(outer_loop_tail);
Node* outer_loop_end = l->outer_loop_end();
assert(outer_loop_end != nullptr, "missing piece of strip mined loop");
_phase->_igvn._worklist.push(outer_loop_end);
Node* outer_safepoint = l->outer_safepoint();
assert(outer_safepoint != nullptr, "missing piece of strip mined loop");
_phase->_igvn._worklist.push(outer_safepoint);
Node* cle_out = _head->as_CountedLoop()->loopexit()->proj_out(false);
assert(cle_out != nullptr, "missing piece of strip mined loop");
_phase->_igvn._worklist.push(cle_out);
}
}
//------------------------------compute_exact_trip_count-----------------------
// Compute loop trip count if possible. Do not recalculate trip count for
// split loops (pre-main-post) which have their limits and inits behind Opaque node.
void IdealLoopTree::compute_trip_count(PhaseIdealLoop* phase) {
if (!_head->as_Loop()->is_valid_counted_loop(T_INT)) {
return;
}
CountedLoopNode* cl = _head->as_CountedLoop();
// Trip count may become nonexact for iteration split loops since
// RCE modifies limits. Note, _trip_count value is not reset since
// it is used to limit unrolling of main loop.
cl->set_nonexact_trip_count();
// Loop's test should be part of loop.
if (!phase->is_member(this, phase->get_ctrl(cl->loopexit()->in(CountedLoopEndNode::TestValue))))
return; // Infinite loop
#ifdef ASSERT
BoolTest::mask bt = cl->loopexit()->test_trip();
assert(bt == BoolTest::lt || bt == BoolTest::gt ||
bt == BoolTest::ne, "canonical test is expected");
#endif
Node* init_n = cl->init_trip();
Node* limit_n = cl->limit();
if (init_n != nullptr && limit_n != nullptr) {
// Use longs to avoid integer overflow.
int stride_con = cl->stride_con();
const TypeInt* init_type = phase->_igvn.type(init_n)->is_int();
const TypeInt* limit_type = phase->_igvn.type(limit_n)->is_int();
jlong init_con = (stride_con > 0) ? init_type->_lo : init_type->_hi;
jlong limit_con = (stride_con > 0) ? limit_type->_hi : limit_type->_lo;
int stride_m = stride_con - (stride_con > 0 ? 1 : -1);
jlong trip_count = (limit_con - init_con + stride_m)/stride_con;
// The loop body is always executed at least once even if init >= limit (for stride_con > 0) or
// init <= limit (for stride_con < 0).
trip_count = MAX2(trip_count, (jlong)1);
if (trip_count < (jlong)max_juint) {
if (init_n->is_Con() && limit_n->is_Con()) {
// Set exact trip count.
cl->set_exact_trip_count((uint)trip_count);
} else if (cl->unrolled_count() == 1) {
// Set maximum trip count before unrolling.
cl->set_trip_count((uint)trip_count);
}
}
}
}
//------------------------------compute_profile_trip_cnt----------------------------
// Compute loop trip count from profile data as
// (backedge_count + loop_exit_count) / loop_exit_count
float IdealLoopTree::compute_profile_trip_cnt_helper(Node* n) {
if (n->is_If()) {
IfNode *iff = n->as_If();
if (iff->_fcnt != COUNT_UNKNOWN && iff->_prob != PROB_UNKNOWN) {
Node *exit = is_loop_exit(iff);
if (exit) {
float exit_prob = iff->_prob;
if (exit->Opcode() == Op_IfFalse) {
exit_prob = 1.0 - exit_prob;
}
if (exit_prob > PROB_MIN) {
float exit_cnt = iff->_fcnt * exit_prob;
return exit_cnt;
}
}
}
}
if (n->is_Jump()) {
JumpNode *jmp = n->as_Jump();
if (jmp->_fcnt != COUNT_UNKNOWN) {
float* probs = jmp->_probs;
float exit_prob = 0;
PhaseIdealLoop *phase = _phase;
for (DUIterator_Fast imax, i = jmp->fast_outs(imax); i < imax; i++) {
JumpProjNode* u = jmp->fast_out(i)->as_JumpProj();
if (!is_member(_phase->get_loop(u))) {
exit_prob += probs[u->_con];
}
}
return exit_prob * jmp->_fcnt;
}
}
return 0;
}
void IdealLoopTree::compute_profile_trip_cnt(PhaseIdealLoop *phase) {
if (!_head->is_Loop()) {
return;
}
LoopNode* head = _head->as_Loop();
if (head->profile_trip_cnt() != COUNT_UNKNOWN) {
return; // Already computed
}
float trip_cnt = (float)max_jint; // default is big
Node* back = head->in(LoopNode::LoopBackControl);
while (back != head) {
if ((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
back->in(0) &&
back->in(0)->is_If() &&
back->in(0)->as_If()->_fcnt != COUNT_UNKNOWN &&
back->in(0)->as_If()->_prob != PROB_UNKNOWN &&
(back->Opcode() == Op_IfTrue ? 1-back->in(0)->as_If()->_prob : back->in(0)->as_If()->_prob) > PROB_MIN) {
break;
}
back = phase->idom(back);
}
if (back != head) {
assert((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
back->in(0), "if-projection exists");
IfNode* back_if = back->in(0)->as_If();
float loop_back_cnt = back_if->_fcnt * (back->Opcode() == Op_IfTrue ? back_if->_prob : (1 - back_if->_prob));
// Now compute a loop exit count
float loop_exit_cnt = 0.0f;
if (_child == nullptr) {
for (uint i = 0; i < _body.size(); i++) {
Node *n = _body[i];
loop_exit_cnt += compute_profile_trip_cnt_helper(n);
}
} else {
ResourceMark rm;
Unique_Node_List wq;
wq.push(back);
for (uint i = 0; i < wq.size(); i++) {
Node *n = wq.at(i);
assert(n->is_CFG(), "only control nodes");
if (n != head) {
if (n->is_Region()) {
for (uint j = 1; j < n->req(); j++) {
wq.push(n->in(j));
}
} else {
loop_exit_cnt += compute_profile_trip_cnt_helper(n);
wq.push(n->in(0));
}
}
}
}
if (loop_exit_cnt > 0.0f) {
trip_cnt = (loop_back_cnt + loop_exit_cnt) / loop_exit_cnt;
} else {
// No exit count so use
trip_cnt = loop_back_cnt;
}
} else {
head->mark_profile_trip_failed();
}
#ifndef PRODUCT
if (TraceProfileTripCount) {
tty->print_cr("compute_profile_trip_cnt lp: %d cnt: %f\n", head->_idx, trip_cnt);
}
#endif
head->set_profile_trip_cnt(trip_cnt);
}
// Return nonzero index of invariant operand for an associative
// binary operation of (nonconstant) invariant and variant values.
// Helper for reassociate_invariants.
int IdealLoopTree::find_invariant(Node* n, PhaseIdealLoop* phase) {
bool in1_invar = this->is_invariant(n->in(1));
bool in2_invar = this->is_invariant(n->in(2));
if (in1_invar && !in2_invar) return 1;
if (!in1_invar && in2_invar) return 2;
return 0;
}
// Return TRUE if "n" is an associative cmp node. A cmp node is
// associative if it is only used for equals or not-equals
// comparisons of integers or longs. We cannot reassociate
// non-equality comparisons due to possibility of overflow.
bool IdealLoopTree::is_associative_cmp(Node* n) {
if (n->Opcode() != Op_CmpI && n->Opcode() != Op_CmpL) {
return false;
}
for (DUIterator i = n->outs(); n->has_out(i); i++) {
BoolNode* bool_out = n->out(i)->isa_Bool();
if (bool_out == nullptr || !(bool_out->_test._test == BoolTest::eq ||
bool_out->_test._test == BoolTest::ne)) {
return false;
}
}
return true;
}
// Return TRUE if "n" is an associative binary node. If "base" is
// not null, "n" must be re-associative with it.
bool IdealLoopTree::is_associative(Node* n, Node* base) {
int op = n->Opcode();
if (base != nullptr) {
assert(is_associative(base), "Base node should be associative");
int base_op = base->Opcode();
if (base_op == Op_AddI || base_op == Op_SubI || base_op == Op_CmpI) {
return op == Op_AddI || op == Op_SubI;
}
if (base_op == Op_AddL || base_op == Op_SubL || base_op == Op_CmpL) {
return op == Op_AddL || op == Op_SubL;
}
return op == base_op;
} else {
// Integer "add/sub/mul/and/or/xor" operations are associative. Integer
// "cmp" operations are associative if it is an equality comparison.
return op == Op_AddI || op == Op_AddL
|| op == Op_SubI || op == Op_SubL
|| op == Op_MulI || op == Op_MulL
|| op == Op_AndI || op == Op_AndL
|| op == Op_OrI || op == Op_OrL
|| op == Op_XorI || op == Op_XorL
|| is_associative_cmp(n);
}
}
// Reassociate invariant add and subtract expressions:
//
// inv1 + (x + inv2) => ( inv1 + inv2) + x
// (x + inv2) + inv1 => ( inv1 + inv2) + x
// inv1 + (x - inv2) => ( inv1 - inv2) + x
// inv1 - (inv2 - x) => ( inv1 - inv2) + x
// (x + inv2) - inv1 => (-inv1 + inv2) + x
// (x - inv2) + inv1 => ( inv1 - inv2) + x
// (x - inv2) - inv1 => (-inv1 - inv2) + x
// inv1 + (inv2 - x) => ( inv1 + inv2) - x
// inv1 - (x - inv2) => ( inv1 + inv2) - x
// (inv2 - x) + inv1 => ( inv1 + inv2) - x
// (inv2 - x) - inv1 => (-inv1 + inv2) - x
// inv1 - (x + inv2) => ( inv1 - inv2) - x
//
// Apply the same transformations to == and !=
// inv1 == (x + inv2) => ( inv1 - inv2 ) == x
// inv1 == (x - inv2) => ( inv1 + inv2 ) == x
// inv1 == (inv2 - x) => (-inv1 + inv2 ) == x
Node* IdealLoopTree::reassociate_add_sub_cmp(Node* n1, int inv1_idx, int inv2_idx, PhaseIdealLoop* phase) {
Node* n2 = n1->in(3 - inv1_idx);
bool n1_is_sub = n1->is_Sub() && !n1->is_Cmp();
bool n1_is_cmp = n1->is_Cmp();
bool n2_is_sub = n2->is_Sub();
assert(n1->is_Add() || n1_is_sub || n1_is_cmp, "Target node should be add, subtract, or compare");
assert(n2->is_Add() || (n2_is_sub && !n2->is_Cmp()), "Child node should be add or subtract");
Node* inv1 = n1->in(inv1_idx);
Node* inv2 = n2->in(inv2_idx);
Node* x = n2->in(3 - inv2_idx);
// Determine whether x, inv1, or inv2 should be negative in the transformed
// expression
bool neg_x = n2_is_sub && inv2_idx == 1;
bool neg_inv2 = (n2_is_sub && !n1_is_cmp && inv2_idx == 2) || (n1_is_cmp && !n2_is_sub);
bool neg_inv1 = (n1_is_sub && inv1_idx == 2) || (n1_is_cmp && inv2_idx == 1 && n2_is_sub);
if (n1_is_sub && inv1_idx == 1) {
neg_x = !neg_x;
neg_inv2 = !neg_inv2;
}
bool is_int = n2->bottom_type()->isa_int() != nullptr;
Node* inv1_c = phase->get_ctrl(inv1);
Node* n_inv1;
if (neg_inv1) {
Node* zero;
if (is_int) {
zero = phase->_igvn.intcon(0);
n_inv1 = new SubINode(zero, inv1);
} else {
zero = phase->_igvn.longcon(0L);
n_inv1 = new SubLNode(zero, inv1);
}
phase->set_ctrl(zero, phase->C->root());
phase->register_new_node(n_inv1, inv1_c);
} else {
n_inv1 = inv1;
}
Node* inv;
if (is_int) {
if (neg_inv2) {
inv = new SubINode(n_inv1, inv2);
} else {
inv = new AddINode(n_inv1, inv2);
}
phase->register_new_node(inv, phase->get_early_ctrl(inv));
if (n1_is_cmp) {
return new CmpINode(x, inv);
}
if (neg_x) {
return new SubINode(inv, x);
} else {
return new AddINode(x, inv);
}
} else {
if (neg_inv2) {
inv = new SubLNode(n_inv1, inv2);
} else {
inv = new AddLNode(n_inv1, inv2);
}
phase->register_new_node(inv, phase->get_early_ctrl(inv));
if (n1_is_cmp) {
return new CmpLNode(x, inv);
}
if (neg_x) {
return new SubLNode(inv, x);
} else {
return new AddLNode(x, inv);
}
}
}
// Reassociate invariant binary expressions with add/sub/mul/
// and/or/xor/cmp operators.
// For add/sub/cmp expressions: see "reassociate_add_sub_cmp"
//
// For mul/and/or/xor expressions:
//
// inv1 op (x op inv2) => (inv1 op inv2) op x
//
Node* IdealLoopTree::reassociate(Node* n1, PhaseIdealLoop *phase) {
if (!is_associative(n1) || n1->outcnt() == 0) return nullptr;
if (is_invariant(n1)) return nullptr;
// Don't mess with add of constant (igvn moves them to expression tree root.)
if (n1->is_Add() && n1->in(2)->is_Con()) return nullptr;
int inv1_idx = find_invariant(n1, phase);
if (!inv1_idx) return nullptr;
Node* n2 = n1->in(3 - inv1_idx);
if (!is_associative(n2, n1)) return nullptr;
int inv2_idx = find_invariant(n2, phase);
if (!inv2_idx) return nullptr;
if (!phase->may_require_nodes(10, 10)) return nullptr;
Node* result = nullptr;
switch (n1->Opcode()) {
case Op_AddI:
case Op_AddL:
case Op_SubI:
case Op_SubL:
case Op_CmpI:
case Op_CmpL:
result = reassociate_add_sub_cmp(n1, inv1_idx, inv2_idx, phase);
break;
case Op_MulI:
case Op_MulL:
case Op_AndI:
case Op_AndL:
case Op_OrI:
case Op_OrL:
case Op_XorI:
case Op_XorL: {
Node* inv1 = n1->in(inv1_idx);
Node* inv2 = n2->in(inv2_idx);
Node* x = n2->in(3 - inv2_idx);
Node* inv = n2->clone_with_data_edge(inv1, inv2);
phase->register_new_node(inv, phase->get_early_ctrl(inv));
result = n1->clone_with_data_edge(x, inv);
break;
}
default:
ShouldNotReachHere();
}
assert(result != nullptr, "");
phase->register_new_node_with_ctrl_of(result, n1);
phase->_igvn.replace_node(n1, result);
assert(phase->get_loop(phase->get_ctrl(n1)) == this, "");
_body.yank(n1);
return result;
}
//---------------------reassociate_invariants-----------------------------
// Reassociate invariant expressions:
void IdealLoopTree::reassociate_invariants(PhaseIdealLoop *phase) {
for (int i = _body.size() - 1; i >= 0; i--) {
Node *n = _body.at(i);
for (int j = 0; j < 5; j++) {
Node* nn = reassociate(n, phase);
if (nn == nullptr) break;
n = nn; // again
}
}
}
//------------------------------policy_peeling---------------------------------
// Return TRUE if the loop should be peeled, otherwise return FALSE. Peeling
// is applicable if we can make a loop-invariant test (usually a null-check)
// execute before we enter the loop. When TRUE, the estimated node budget is
// also requested.
bool IdealLoopTree::policy_peeling(PhaseIdealLoop *phase) {
uint estimate = estimate_peeling(phase);
return estimate == 0 ? false : phase->may_require_nodes(estimate);
}
// Perform actual policy and size estimate for the loop peeling transform, and
// return the estimated loop size if peeling is applicable, otherwise return
// zero. No node budget is allocated.
uint IdealLoopTree::estimate_peeling(PhaseIdealLoop *phase) {
// If nodes are depleted, some transform has miscalculated its needs.
assert(!phase->exceeding_node_budget(), "sanity");
// Peeling does loop cloning which can result in O(N^2) node construction.
if (_body.size() > 255) {
return 0; // Suppress too large body size.
}
// Optimistic estimate that approximates loop body complexity via data and
// control flow fan-out (instead of using the more pessimistic: BodySize^2).
uint estimate = est_loop_clone_sz(2);
if (phase->exceeding_node_budget(estimate)) {
return 0; // Too large to safely clone.
}
// Check for vectorized loops, any peeling done was already applied.
if (_head->is_CountedLoop()) {
CountedLoopNode* cl = _head->as_CountedLoop();
if (cl->is_unroll_only() || cl->trip_count() == 1) {
return 0;
}
}
Node* test = tail();
while (test != _head) { // Scan till run off top of loop
if (test->is_If()) { // Test?
Node *ctrl = phase->get_ctrl(test->in(1));
if (ctrl->is_top()) {
return 0; // Found dead test on live IF? No peeling!
}
// Standard IF only has one input value to check for loop invariance.
assert(test->Opcode() == Op_If ||
test->Opcode() == Op_CountedLoopEnd ||
test->Opcode() == Op_LongCountedLoopEnd ||
test->Opcode() == Op_RangeCheck ||
test->Opcode() == Op_ParsePredicate,
"Check this code when new subtype is added");
// Condition is not a member of this loop?
if (!is_member(phase->get_loop(ctrl)) && is_loop_exit(test)) {
return estimate; // Found reason to peel!
}
}
// Walk up dominators to loop _head looking for test which is executed on
// every path through the loop.
test = phase->idom(test);
}
return 0;
}
//------------------------------peeled_dom_test_elim---------------------------
// If we got the effect of peeling, either by actually peeling or by making
// a pre-loop which must execute at least once, we can remove all
// loop-invariant dominated tests in the main body.
void PhaseIdealLoop::peeled_dom_test_elim(IdealLoopTree* loop, Node_List& old_new) {
bool progress = true;
while (progress) {
progress = false; // Reset for next iteration
Node* prev = loop->_head->in(LoopNode::LoopBackControl); // loop->tail();
Node* test = prev->in(0);
while (test != loop->_head) { // Scan till run off top of loop
int p_op = prev->Opcode();
assert(test != nullptr, "test cannot be null");
Node* test_cond = nullptr;
if ((p_op == Op_IfFalse || p_op == Op_IfTrue) && test->is_If()) {
test_cond = test->in(1);
}
if (test_cond != nullptr && // Test?
!test_cond->is_Con() && // And not already obvious?
// And condition is not a member of this loop?
!loop->is_member(get_loop(get_ctrl(test_cond)))) {
// Walk loop body looking for instances of this test
for (uint i = 0; i < loop->_body.size(); i++) {
Node* n = loop->_body.at(i);
// Check against cached test condition because dominated_by()
// replaces the test condition with a constant.
if (n->is_If() && n->in(1) == test_cond) {
// IfNode was dominated by version in peeled loop body
progress = true;
dominated_by(old_new[prev->_idx]->as_IfProj(), n->as_If());
}
}
}
prev = test;
test = idom(test);
} // End of scan tests in loop
} // End of while (progress)
}
//------------------------------do_peeling-------------------------------------
// Peel the first iteration of the given loop.
// Step 1: Clone the loop body. The clone becomes the peeled iteration.
// The pre-loop illegally has 2 control users (old & new loops).
// Step 2: Make the old-loop fall-in edges point to the peeled iteration.
// Do this by making the old-loop fall-in edges act as if they came
// around the loopback from the prior iteration (follow the old-loop
// backedges) and then map to the new peeled iteration. This leaves
// the pre-loop with only 1 user (the new peeled iteration), but the
// peeled-loop backedge has 2 users.
// Step 3: Cut the backedge on the clone (so its not a loop) and remove the
// extra backedge user.
//
// orig
//
// stmt1
// |
// v
// predicates
// |
// v
// loop<----+
// | |
// stmt2 |
// | |
// v |
// if ^
// / \ |
// / \ |
// v v |
// false true |
// / \ |
// / ----+
// |
// v
// exit
//
//
// after clone loop
//
// stmt1
// |
// v
// predicates
// / \
// clone / \ orig
// / \
// / \
// v v
// +---->loop clone loop<----+
// | | | |
// | stmt2 clone stmt2 |
// | | | |
// | v v |
// ^ if clone If ^
// | / \ / \ |
// | / \ / \ |
// | v v v v |
// | true false false true |
// | / \ / \ |
// +---- \ / ----+
// \ /
// 1v v2
// region
// |
// v
// exit
//
//
// after peel and predicate move
//
// stmt1
// |
// v
// predicates
// /
// /
// clone / orig
// /
// / +----------+
// / | |
// / | |
// / | |
// v v |
// TOP-->loop clone loop<----+ |
// | | | |
// stmt2 clone stmt2 | |
// | | | ^
// v v | |
// if clone If ^ |
// / \ / \ | |
// / \ / \ | |
// v v v v | |
// true false false true | |
// | \ / \ | |
// | \ / ----+ ^
// | \ / |
// | 1v v2 |
// v region |
// | | |
// | v |
// | exit |
// | |
// +--------------->-----------------+
//
//
// final graph
//
// stmt1
// |
// v
// predicates
// |
// v
// stmt2 clone
// |
// v
// if clone
// / |
// / |
// v v
// false true
// | |
// | v
// | Initialized Assertion Predicates
// | |
// | v
// | loop<----+
// | | |
// | stmt2 |
// | | |
// | v |
// v if ^
// | / \ |
// | / \ |
// | v v |
// | false true |
// | | \ |
// v v --+
// region
// |
// v
// exit
//
void PhaseIdealLoop::do_peeling(IdealLoopTree *loop, Node_List &old_new) {
C->set_major_progress();
// Peeling a 'main' loop in a pre/main/post situation obfuscates the
// 'pre' loop from the main and the 'pre' can no longer have its
// iterations adjusted. Therefore, we need to declare this loop as
// no longer a 'main' loop; it will need new pre and post loops before
// we can do further RCE.
#ifndef PRODUCT
if (TraceLoopOpts) {
tty->print("Peel ");
loop->dump_head();
}
#endif
LoopNode* head = loop->_head->as_Loop();
C->print_method(PHASE_BEFORE_LOOP_PEELING, 4, head);
bool counted_loop = head->is_CountedLoop();
if (counted_loop) {
CountedLoopNode *cl = head->as_CountedLoop();
assert(cl->trip_count() > 0, "peeling a fully unrolled loop");
cl->set_trip_count(cl->trip_count() - 1);
if (cl->is_main_loop()) {
cl->set_normal_loop();
#ifndef PRODUCT
if (PrintOpto && VerifyLoopOptimizations) {
tty->print("Peeling a 'main' loop; resetting to 'normal' ");
loop->dump_head();
}
#endif
}
}
Node* entry = head->in(LoopNode::EntryControl);
// Step 1: Clone the loop body. The clone becomes the peeled iteration.
// The pre-loop illegally has 2 control users (old & new loops).
const uint idx_before_clone = Compile::current()->unique();
LoopNode* outer_loop_head = head->skip_strip_mined();
clone_loop(loop, old_new, dom_depth(outer_loop_head), ControlAroundStripMined);
// Step 2: Make the old-loop fall-in edges point to the peeled iteration.
// Do this by making the old-loop fall-in edges act as if they came
// around the loopback from the prior iteration (follow the old-loop
// backedges) and then map to the new peeled iteration. This leaves
// the pre-loop with only 1 user (the new peeled iteration), but the
// peeled-loop backedge has 2 users.
Node* new_entry = old_new[head->in(LoopNode::LoopBackControl)->_idx];
_igvn.hash_delete(outer_loop_head);
outer_loop_head->set_req(LoopNode::EntryControl, new_entry);
for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) {
Node* old = head->fast_out(j);
if (old->in(0) == loop->_head && old->req() == 3 && old->is_Phi()) {
Node* new_exit_value = old_new[old->in(LoopNode::LoopBackControl)->_idx];
if (!new_exit_value) // Backedge value is ALSO loop invariant?
// Then loop body backedge value remains the same.
new_exit_value = old->in(LoopNode::LoopBackControl);
_igvn.hash_delete(old);
old->set_req(LoopNode::EntryControl, new_exit_value);
}
}
// Step 3: Cut the backedge on the clone (so its not a loop) and remove the
// extra backedge user.
Node* new_head = old_new[head->_idx];
_igvn.hash_delete(new_head);
new_head->set_req(LoopNode::LoopBackControl, C->top());
for (DUIterator_Fast j2max, j2 = new_head->fast_outs(j2max); j2 < j2max; j2++) {
Node* use = new_head->fast_out(j2);
if (use->in(0) == new_head && use->req() == 3 && use->is_Phi()) {
_igvn.hash_delete(use);
use->set_req(LoopNode::LoopBackControl, C->top());
}
}
// Step 4: Correct dom-depth info. Set to loop-head depth.
int dd_outer_loop_head = dom_depth(outer_loop_head);
set_idom(outer_loop_head, outer_loop_head->in(LoopNode::EntryControl), dd_outer_loop_head);
for (uint j3 = 0; j3 < loop->_body.size(); j3++) {
Node *old = loop->_body.at(j3);
Node *nnn = old_new[old->_idx];
if (!has_ctrl(nnn)) {
set_idom(nnn, idom(nnn), dd_outer_loop_head-1);
}
}
// Step 5: Assertion Predicates initialization
if (counted_loop && UseLoopPredicate) {
CountedLoopNode *cl_head = head->as_CountedLoop();
Node* init = cl_head->init_trip();
Node* stride = cl_head->stride();
IdealLoopTree* outer_loop = get_loop(outer_loop_head);
const Predicates predicates(new_head->in(LoopNode::EntryControl));
initialize_assertion_predicates_for_peeled_loop(predicates.loop_predicate_block(),
outer_loop_head, dd_outer_loop_head,
init, stride, outer_loop,
idx_before_clone, old_new);
initialize_assertion_predicates_for_peeled_loop(predicates.profiled_loop_predicate_block(),
outer_loop_head, dd_outer_loop_head,
init, stride, outer_loop,
idx_before_clone, old_new);
}
// Now force out all loop-invariant dominating tests. The optimizer
// finds some, but we _know_ they are all useless.
peeled_dom_test_elim(loop,old_new);
loop->record_for_igvn();
C->print_method(PHASE_AFTER_LOOP_PEELING, 4, new_head);
}
//------------------------------policy_maximally_unroll------------------------
// Calculate the exact loop trip-count and return TRUE if loop can be fully,
// i.e. maximally, unrolled, otherwise return FALSE. When TRUE, the estimated
// node budget is also requested.
bool IdealLoopTree::policy_maximally_unroll(PhaseIdealLoop* phase) const {
CountedLoopNode* cl = _head->as_CountedLoop();
assert(cl->is_normal_loop(), "");
if (!cl->is_valid_counted_loop(T_INT)) {
return false; // Malformed counted loop.
}
if (!cl->has_exact_trip_count()) {
return false; // Trip count is not exact.
}
uint trip_count = cl->trip_count();
// Note, max_juint is used to indicate unknown trip count.
assert(trip_count > 1, "one iteration loop should be optimized out already");
assert(trip_count < max_juint, "exact trip_count should be less than max_juint.");
// If nodes are depleted, some transform has miscalculated its needs.
assert(!phase->exceeding_node_budget(), "sanity");
// Allow the unrolled body to get larger than the standard loop size limit.
uint unroll_limit = (uint)LoopUnrollLimit * 4;
assert((intx)unroll_limit == LoopUnrollLimit * 4, "LoopUnrollLimit must fit in 32bits");
if (trip_count > unroll_limit || _body.size() > unroll_limit) {
return false;
}
uint new_body_size = est_loop_unroll_sz(trip_count);
if (new_body_size == UINT_MAX) { // Check for bad estimate (overflow).
return false;
}
// Fully unroll a loop with few iterations, regardless of other conditions,
// since the following (general) loop optimizations will split such loop in
// any case (into pre-main-post).
if (trip_count <= 3) {
return phase->may_require_nodes(new_body_size);
}
// Reject if unrolling will result in too much node construction.
if (new_body_size > unroll_limit || phase->exceeding_node_budget(new_body_size)) {
return false;
}
// Do not unroll a loop with String intrinsics code.
// String intrinsics are large and have loops.
for (uint k = 0; k < _body.size(); k++) {
Node* n = _body.at(k);
switch (n->Opcode()) {
case Op_StrComp:
case Op_StrEquals:
case Op_VectorizedHashCode:
case Op_StrIndexOf:
case Op_StrIndexOfChar:
case Op_EncodeISOArray:
case Op_AryEq:
case Op_CountPositives: {
return false;
}
#if INCLUDE_RTM_OPT
case Op_FastLock:
case Op_FastUnlock: {
// Don't unroll RTM locking code because it is large.
if (UseRTMLocking) {
return false;
}
}
#endif
} // switch
}
return phase->may_require_nodes(new_body_size);
}
//------------------------------policy_unroll----------------------------------
// Return TRUE or FALSE if the loop should be unrolled or not. Apply unroll if
// the loop is a counted loop and the loop body is small enough. When TRUE,
// the estimated node budget is also requested.
bool IdealLoopTree::policy_unroll(PhaseIdealLoop *phase) {
CountedLoopNode *cl = _head->as_CountedLoop();
assert(cl->is_normal_loop() || cl->is_main_loop(), "");
if (!cl->is_valid_counted_loop(T_INT)) {
return false; // Malformed counted loop
}
// If nodes are depleted, some transform has miscalculated its needs.
assert(!phase->exceeding_node_budget(), "sanity");
// Protect against over-unrolling.
// After split at least one iteration will be executed in pre-loop.
if (cl->trip_count() <= (cl->is_normal_loop() ? 2u : 1u)) {
return false;
}
_local_loop_unroll_limit = LoopUnrollLimit;
_local_loop_unroll_factor = 4;
int future_unroll_cnt = cl->unrolled_count() * 2;
if (!cl->is_vectorized_loop()) {
if (future_unroll_cnt > LoopMaxUnroll) return false;
} else {
// obey user constraints on vector mapped loops with additional unrolling applied
int unroll_constraint = (cl->slp_max_unroll()) ? cl->slp_max_unroll() : 1;
if ((future_unroll_cnt / unroll_constraint) > LoopMaxUnroll) return false;
}
const int stride_con = cl->stride_con();
// Check for initial stride being a small enough constant
const int initial_stride_sz = MAX2(1<<2, Matcher::max_vector_size(T_BYTE) / 2);
// Maximum stride size should protect against overflow, when doubling stride unroll_count times
const int max_stride_size = MIN2<int>(max_jint / 2 - 2, initial_stride_sz * future_unroll_cnt);
// No abs() use; abs(min_jint) = min_jint
if (stride_con < -max_stride_size || stride_con > max_stride_size) return false;
// Don't unroll if the next round of unrolling would push us
// over the expected trip count of the loop. One is subtracted
// from the expected trip count because the pre-loop normally
// executes 1 iteration.
if (UnrollLimitForProfileCheck > 0 &&
cl->profile_trip_cnt() != COUNT_UNKNOWN &&
future_unroll_cnt > UnrollLimitForProfileCheck &&
(float)future_unroll_cnt > cl->profile_trip_cnt() - 1.0) {
return false;
}
bool should_unroll = true;
// When unroll count is greater than LoopUnrollMin, don't unroll if:
// the residual iterations are more than 10% of the trip count
// and rounds of "unroll,optimize" are not making significant progress
// Progress defined as current size less than 20% larger than previous size.
if (phase->C->do_superword() &&
cl->node_count_before_unroll() > 0 &&
future_unroll_cnt > LoopUnrollMin &&
is_residual_iters_large(future_unroll_cnt, cl) &&
1.2 * cl->node_count_before_unroll() < (double)_body.size()) {
if ((cl->slp_max_unroll() == 0) && !is_residual_iters_large(cl->unrolled_count(), cl)) {
// cl->slp_max_unroll() = 0 means that the previous slp analysis never passed.
// slp analysis may fail due to the loop IR is too complicated especially during the early stage
// of loop unrolling analysis. But after several rounds of loop unrolling and other optimizations,
// it's possible that the loop IR becomes simple enough to pass the slp analysis.
// So we don't return immediately in hoping that the next slp analysis can succeed.
should_unroll = false;
future_unroll_cnt = cl->unrolled_count();
} else {
return false;
}
}
Node *init_n = cl->init_trip();
Node *limit_n = cl->limit();
if (limit_n == nullptr) return false; // We will dereference it below.
// Non-constant bounds.