-
Notifications
You must be signed in to change notification settings - Fork 397
/
Copy pathLoopCanonicalizer.cpp
4606 lines (3962 loc) · 177 KB
/
LoopCanonicalizer.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, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#include "optimizer/LoopCanonicalizer.hpp"
#include <limits.h>
#include <stdint.h>
#include <stdlib.h>
#include "codegen/CodeGenerator.hpp"
#include "env/FrontEnd.hpp"
#include "compile/Compilation.hpp"
#include "compile/SymbolReferenceTable.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "cs2/bitvectr.h"
#include "cs2/sparsrbit.h"
#include "env/StackMemoryRegion.hpp"
#include "env/TRMemory.hpp"
#include "il/AliasSetInterface.hpp"
#include "il/Block.hpp"
#include "il/DataTypes.hpp"
#include "il/ILOpCodes.hpp"
#include "il/ILOps.hpp"
#include "il/LabelSymbol.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/ResolvedMethodSymbol.hpp"
#include "il/Symbol.hpp"
#include "il/SymbolReference.hpp"
#include "il/TreeTop.hpp"
#include "il/TreeTop_inlines.hpp"
#include "infra/Assert.hpp"
#include "infra/BitVector.hpp"
#include "infra/Cfg.hpp"
#include "infra/ILWalk.hpp"
#include "infra/List.hpp"
#include "infra/CfgEdge.hpp"
#include "infra/CfgNode.hpp"
#include "infra/Checklist.hpp"
#include "optimizer/InductionVariable.hpp"
#include "optimizer/Optimization_inlines.hpp"
#include "optimizer/Optimizations.hpp"
#include "optimizer/Optimizer.hpp"
#include "optimizer/Structure.hpp"
#include "optimizer/UseDefInfo.hpp"
#include "optimizer/VPConstraint.hpp"
#include "ras/Debug.hpp"
namespace TR { class RegisterMappedSymbol; }
#define OPT_DETAILS "O^O LOOP TRANSFORMATION: "
/**
* Canonicalize While structures and convert them into If guarded
* Do While structures. We also add some empty blocks to split critical
* edges in the CFG for helping PRE (which is really the main optimization
* that benefits from canonicalization of loops). Note that the general
* critical edge splitter runs before structural analysis (so that it can
* avoid the problems associated with complex structure repair and because it
* does not really need structure for anything). There are some new CFG edges,
* structures, and trees (actually cloned) that are created in this pass, and
* for the part of the CFG that has changed now (the original While) we split
* critical edges in a specific manner.
*/
TR_LoopCanonicalizer::TR_LoopCanonicalizer(TR::OptimizationManager *manager)
: TR_LoopTransformer(manager)
{}
int32_t TR_LoopCanonicalizer::perform()
{
if (!comp()->mayHaveLoops())
return 0;
if (comp()->hasLargeNumberOfLoops())
{
return 0;
}
_loopTestBlock = NULL;
_storeTrees = NULL;
_currTree = NULL;
_insertionTreeTop = NULL;
_loopTestTree = NULL;
_asyncCheckTree = NULL;
_cannotBeEliminated = NULL;
_neverRead = NULL;
_neverWritten = NULL;
_writtenExactlyOnce.Clear();
_readExactlyOnce.Clear();
_allKilledSymRefs.Clear();
_allSymRefs.Clear();
_numberOfIterations = NULL;
_constNode = NULL;
_loadUsedInLoopIncrement = NULL;
_startOfHeader = NULL;
_cfg = NULL;
_rootStructure = NULL;
_hasPredictableExits = NULL;
_invariantBlocks.deleteAll();
_blocksToBeCleansed.deleteAll();
_analysisStack.clear();
_whileIndex = 0;
_visitCount = 0;
_topDfNum = 0;
_counter = 0;
_loopDrivingInductionVar = 0;
_nextExpression = 0;
_startExpressionForThisInductionVariable = 0;
_numberOfTreesInLoop = 0;
_isAddition = false;
_requiresAdditionalCheckForIncrement = false;
_doingVersioning = false;
{
TR::StackMemoryRegion stackMemoryRegion(*trMemory());
optimizer()->changeContinueLoopsToNestedLoops();
TR_ScratchList<TR::CFGNode> newEmptyBlocks(trMemory());
TR_ScratchList<TR::CFGNode> newEmptyExceptionBlocks(trMemory());
_cfg = comp()->getFlowGraph();
_rootStructure = _cfg->getStructure();
if (trace())
{
traceMsg(comp(), "Starting LoopCanonicalizer\n");
traceMsg(comp(), "\nCFG before loop canonicalization:\n");
getDebug()->print(comp()->getOutFile(), _cfg);
}
// printTrees();
// Recursive call through the structure tree that would
// collect all the While Structures (if any) in the method.
// Note that only while loops with a single block as its
// header will be detected here.
//
TR_ScratchList<TR_Structure> whileLoops(trMemory());
ListAppender<TR_Structure> whileLoopsInnerFirst(&whileLoops);
TR_ScratchList<TR_Structure> doWhileLoops(trMemory());
ListAppender<TR_Structure> doWhileLoopsInnerFirst(&doWhileLoops);
_nodesInCycle = new (trStackMemory()) TR_BitVector(_cfg->getNextNodeNumber(), trMemory(), stackAlloc);
//comp()->incVisitCount();
detectWhileLoops(whileLoopsInnerFirst, whileLoops, doWhileLoopsInnerFirst, doWhileLoops, _rootStructure, true);
if (whileLoops.isEmpty() && doWhileLoops.isEmpty())
{
return false;
}
if (trace())
traceMsg(comp(), "Number of WhileLoops = %d\n", whileLoops.getSize());
// _startOfHeader originally points to the last tree in the method;
// this variable is used as a placeholder to keep track of where
// trees can be moved (sometimes required for efficiency purposes
// to minimize gotos in the critical 'hot' path between the loop body
// and the new duplicate header that drives the new Do While loop.
//
_startOfHeader = comp()->getMethodSymbol()->getLastTreeTop();
_whileIndex = 0;
_counter = 0;
ListIterator<TR_Structure> whileLoopsIt(&whileLoops);
TR_Structure *nextWhileLoop;
for (nextWhileLoop = whileLoopsIt.getFirst(); nextWhileLoop != NULL; nextWhileLoop = whileLoopsIt.getNext())
{
// Can be used for debugging; to stop a particular loop from being
// and see if the problem persists or not.
//
// if (_counter == 1)
// break;
// else
// _counter++;
TR_RegionStructure *naturalLoop = nextWhileLoop->asRegion();
TR_ASSERT(naturalLoop && naturalLoop->isNaturalLoop(),"Loop canonicalizer, expecting natural loop");
if (naturalLoop->getEntryBlock()->isCold())
continue;
canonicalizeNaturalLoop(naturalLoop);
}
///comp()->dumpMethodTrees("Trees now\n");
if (trace())
traceMsg(comp(), "Number of cleansed blocks : %d\n", _blocksToBeCleansed.getSize());
//
// Move the trees around in this method so that the blocks that are currently
// violating the CFG constraints (only 1 branch in a block) are cleansed
//
ListIterator<TR::Block> cleansedBlocksIt(&_blocksToBeCleansed);
TR::Block *nextCleansedBlock = NULL;
for (nextCleansedBlock = cleansedBlocksIt.getCurrent(); nextCleansedBlock; nextCleansedBlock = cleansedBlocksIt.getNext())
{
cleanseTrees(nextCleansedBlock);
}
// Move the trees around in this method so that the invariant blocks
// fall through into the loop where possible
//
ListIterator<TR::Block> invariantBlocksIt(&_invariantBlocks);
TR::Block *nextInvariantBlock = NULL;
for (nextInvariantBlock = invariantBlocksIt.getCurrent(); nextInvariantBlock; nextInvariantBlock = invariantBlocksIt.getNext())
{
makeInvariantBlockFallThroughIfPossible(nextInvariantBlock);
}
if (trace())
traceMsg(comp(), "Number of DoWhileLoops = %d\n", doWhileLoops.getSize());
ListIterator<TR_Structure> doWhileLoopsIt(&doWhileLoops);
TR_Structure *nextDoWhileLoop;
for (nextDoWhileLoop = doWhileLoopsIt.getFirst(); nextDoWhileLoop != NULL; nextDoWhileLoop = doWhileLoopsIt.getNext())
{
// Can be used for debugging; to stop a particular loop from being
// and see if the problem persists or not.
//
// if (_counter == 1)
// break;
// else
// _counter++;
TR_RegionStructure *naturalLoop = nextDoWhileLoop->asRegion();
TR_ASSERT(naturalLoop && naturalLoop->isNaturalLoop(),"Loop canonicalizer, expecting natural loop");
if (naturalLoop->getEntryBlock()->isCold())
continue;
canonicalizeDoWhileLoop(naturalLoop);
}
/*
for (nextWhileLoop = whileLoopsIt.getFirst(); nextWhileLoop != NULL; nextWhileLoop = whileLoopsIt.getNext())
{
TR_RegionStructure *naturalLoop = nextWhileLoop->asRegion();
TR_ASSERT(naturalLoop && naturalLoop->isNaturalLoop(),"Loop canonicalizer, expecting natural loop");
if (naturalLoop->getEntryBlock()->isCold())
continue;
eliminateRedundantInductionVariablesFromLoop(naturalLoop);
}
for (nextDoWhileLoop = doWhileLoopsIt.getFirst(); nextDoWhileLoop != NULL; nextDoWhileLoop = doWhileLoopsIt.getNext())
{
TR_RegionStructure *naturalLoop = nextDoWhileLoop->asRegion();
TR_ASSERT(naturalLoop && naturalLoop->isNaturalLoop(),"Loop canonicalizer, expecting natural loop");
if (naturalLoop->getEntryBlock()->isCold())
continue;
eliminateRedundantInductionVariablesFromLoop(naturalLoop);
}
*/
// Use/def info and value number info are now bad.
//
optimizer()->setUseDefInfo(NULL);
optimizer()->setValueNumberInfo(NULL);
//requestOpt(loopVersioner);
requestOpt(OMR::loopVersionerGroup);
if (trace())
{
traceMsg(comp(), "\nCFG after loop canonicalization:\n");
getDebug()->print(comp()->getOutFile(), _cfg);
traceMsg(comp(), "Ending LoopCanonicalizer\n");
}
} // scope of the stack memory region
//if (trace())
{
if (trace())
comp()->dumpMethodTrees("Trees after canonicalization\n");
}
return 1; // actual cost
}
void TR_LoopTransformer::detectWhileLoopsInSubnodesInOrder(ListAppender<TR_Structure> &whileLoopsInnerFirst, List<TR_Structure> &whileLoops, ListAppender<TR_Structure> &doWhileLoopsInnerFirst, List<TR_Structure> &doWhileLoops, TR_Structure *root, TR_StructureSubGraphNode *rootNode, TR_RegionStructure *region, vcount_t visitCount, TR_BitVector *pendingList, bool innerFirst)
{
if (trace())
traceMsg(comp(), "Begin looking for canonicalizable loops in node %p numbered %d\n", root, root->getNumber());
bool alreadyVisitedNode = false;
//if (rootNode->getVisitCount() == visitCount)
if (_nodesInCycle->get(rootNode->getNumber()))
alreadyVisitedNode = true;
//rootNode->setVisitCount(visitCount);
_nodesInCycle->set(rootNode->getNumber());
for (auto pred = rootNode->getPredecessors().begin(); pred != rootNode->getPredecessors().end(); ++pred)
{
TR_StructureSubGraphNode *predNode = (TR_StructureSubGraphNode *) (*pred)->getFrom();
TR_Structure *predStructure = predNode->getStructure();
if (pendingList->get(predStructure->getNumber()) && (!alreadyVisitedNode))
{
detectWhileLoopsInSubnodesInOrder(whileLoopsInnerFirst, whileLoops, doWhileLoopsInnerFirst, doWhileLoops, predStructure, predNode, region, visitCount, pendingList, innerFirst);
return;
}
}
for (auto pred = rootNode->getExceptionPredecessors().begin(); pred != rootNode->getExceptionPredecessors().end(); ++pred)
{
TR_StructureSubGraphNode *predNode = (TR_StructureSubGraphNode *) (*pred)->getFrom();
TR_Structure *predStructure = predNode->getStructure();
if (pendingList->get(predStructure->getNumber()) && (!alreadyVisitedNode))
{
detectWhileLoopsInSubnodesInOrder(whileLoopsInnerFirst, whileLoops, doWhileLoopsInnerFirst, doWhileLoops, predStructure, predNode, region, visitCount, pendingList, innerFirst);
return;
}
}
_nodesInCycle->empty();
detectWhileLoops(whileLoopsInnerFirst, whileLoops, doWhileLoopsInnerFirst, doWhileLoops, root, innerFirst);
pendingList->reset(root->getNumber());
for (auto succ = rootNode->getSuccessors().begin(); succ != rootNode->getSuccessors().end(); ++succ)
{
TR_StructureSubGraphNode *succNode = (TR_StructureSubGraphNode *) (*succ)->getTo();
TR_Structure *succStructure = succNode->getStructure();
bool isExitEdge = false;
ListIterator<TR::CFGEdge> ei(®ion->getExitEdges());
TR::CFGEdge *edge;
for (edge = ei.getCurrent(); edge != NULL; edge = ei.getNext())
{
if (edge == *succ)
{
isExitEdge = true;
break;
}
}
if ((!isExitEdge) && pendingList->get(succStructure->getNumber()))
{
//comp()->incVisitCount();
_nodesInCycle->empty();
detectWhileLoopsInSubnodesInOrder(whileLoopsInnerFirst, whileLoops, doWhileLoopsInnerFirst, doWhileLoops, succStructure, succNode, region, visitCount, pendingList, innerFirst);
}
}
for (auto succ = rootNode->getExceptionSuccessors().begin(); succ != rootNode->getExceptionSuccessors().end(); ++succ)
{
TR_StructureSubGraphNode *succNode = (TR_StructureSubGraphNode *) (*succ)->getTo();
TR_Structure *succStructure = succNode->getStructure();
bool isExitEdge = false;
ListIterator<TR::CFGEdge> ei(®ion->getExitEdges());
TR::CFGEdge *edge;
for (edge = ei.getCurrent(); edge != NULL; edge = ei.getNext())
{
if (edge == *succ)
{
isExitEdge = true;
break;
}
}
if ((!isExitEdge) && pendingList->get(succStructure->getNumber()))
{
//comp()->incVisitCount();
_nodesInCycle->empty();
detectWhileLoopsInSubnodesInOrder(whileLoopsInnerFirst, whileLoops, doWhileLoopsInnerFirst, doWhileLoops, succStructure, succNode, region, visitCount, pendingList, innerFirst);
}
}
}
void TR_LoopTransformer::detectWhileLoopsInSubnodesInOrder(ListAppender<TR_Structure> &whileLoopsInnerFirst, List<TR_Structure> &whileLoops, ListAppender<TR_Structure> &doWhileLoopsInnerFirst, List<TR_Structure> &doWhileLoops, TR_RegionStructure *region, vcount_t visitCount, TR_BitVector *pendingList, bool innerFirst)
{
while (!_analysisStack.isEmpty() &&
_analysisStack.top()->getStructure() != region)
{
TR_StructureSubGraphNode *rootNode = _analysisStack.top();
TR_Structure *root = rootNode->getStructure();
if (!pendingList->get(root->getNumber()))
{
_analysisStack.pop();
continue;
}
if (trace())
traceMsg(comp(), "Begin looking for canonicalizable loops in node %p numbered %d\n", root, root->getNumber());
if (!_nodesInCycle->get(rootNode->getNumber()))
{
_nodesInCycle->set(rootNode->getNumber());
bool stopAnalyzingThisNode = false;
TR_PredecessorIterator precedingEdges(rootNode);
for (auto precedingEdge = precedingEdges.getFirst(); precedingEdge; precedingEdge = precedingEdges.getNext())
{
TR_StructureSubGraphNode *predNode = (TR_StructureSubGraphNode *) precedingEdge->getFrom();
TR_Structure *predStructure = predNode->getStructure();
if (pendingList->get(predStructure->getNumber()))
{
_analysisStack.pop();
_analysisStack.push(predNode);
stopAnalyzingThisNode = true;
break;
}
}
if (stopAnalyzingThisNode)
continue;
}
_nodesInCycle->empty();
detectWhileLoops(whileLoopsInnerFirst, whileLoops, doWhileLoopsInnerFirst, doWhileLoops, root, innerFirst);
pendingList->reset(root->getNumber());
_analysisStack.pop();
TR_SuccessorIterator succeedingEdges(rootNode);
for (auto succeedingEdge = succeedingEdges.getFirst(); succeedingEdge; succeedingEdge = succeedingEdges.getNext())
{
TR_StructureSubGraphNode *succNode = (TR_StructureSubGraphNode *) succeedingEdge->getTo();
TR_Structure *succStructure = succNode->getStructure();
bool isExitEdge = false;
ListIterator<TR::CFGEdge> ei(®ion->getExitEdges());
TR::CFGEdge *edge;
for (edge = ei.getCurrent(); edge != NULL; edge = ei.getNext())
{
if (edge == succeedingEdge)
{
isExitEdge = true;
break;
}
}
if ((!isExitEdge) && pendingList->get(succStructure->getNumber()))
{
_nodesInCycle->empty();
_analysisStack.push(succNode);
}
}
}
}
void TR_LoopTransformer::createWhileLoopsList(TR_ScratchList<TR_Structure>* whileLoops)
{
TR_ScratchList<TR::CFGNode> newEmptyBlocks(trMemory());
TR_ScratchList<TR::CFGNode> newEmptyExceptionBlocks(trMemory());
// printTrees();
// Recursive call through the structure tree that would
// collect all the While Structures (if any) in the method.
// Note that only while loops with a single block as its
// header will be detected here.
//
ListAppender<TR_Structure> whileLoopsInnerFirst(whileLoops);
TR_ScratchList<TR_Structure> doWhileLoops(trMemory());
ListAppender<TR_Structure> doWhileLoopsInnerFirst(&doWhileLoops);
//comp()->incVisitCount();
_cfg = comp()->getFlowGraph();
_rootStructure = _cfg->getStructure();
_nodesInCycle = new (trStackMemory()) TR_BitVector(_cfg->getNextNodeNumber(), trMemory(), stackAlloc);
if (asLoopVersioner())
detectWhileLoops(whileLoopsInnerFirst, *whileLoops, doWhileLoopsInnerFirst, doWhileLoops, _rootStructure, false);
else
detectWhileLoops(whileLoopsInnerFirst, *whileLoops, doWhileLoopsInnerFirst, doWhileLoops, _rootStructure, true);
/*
ListIterator<TR_Structure> whileLoopsIt(whileLoops);
TR_Structure *nextWhileLoop;
for (nextWhileLoop = whileLoopsIt.getFirst(); nextWhileLoop != NULL; nextWhileLoop = whileLoopsIt.getNext())
{
dumpOptDetails(comp(), "Loop is %d\n", nextWhileLoop->getNumber());
}
ListIterator<TR_Structure> doWhileLoopsIt(&doWhileLoops);
TR_Structure *nextDoWhileLoop;
for (nextDoWhileLoop = doWhileLoopsIt.getFirst(); nextDoWhileLoop != NULL; nextDoWhileLoop = doWhileLoopsIt.getNext())
{
dumpOptDetails(comp(), "Do While Loop is %d\n", nextDoWhileLoop->getNumber());
}
*/
// _startOfHeader originally points to the last tree in the method;
// this variable is used as a placeholder to keep track of where
// trees can be moved (sometimes required for efficiency purposes
// to minimize gotos in the critical 'hot' path between the loop body
// and the new duplicate header that drives the new Do While loop.
//
_startOfHeader = comp()->getMethodSymbol()->getLastTreeTop();
_whileIndex = 0;
_counter = 0;
}
/**
* Detect while loops in the structure control tree
*/
void TR_LoopTransformer::detectWhileLoops(ListAppender<TR_Structure> &whileLoopsInnerFirst, List<TR_Structure> &whileLoops, ListAppender<TR_Structure> &doWhileLoopsInnerFirst, List<TR_Structure> &doWhileLoops, TR_Structure *root, bool innerFirst)
{
TR_RegionStructure *region = root->asRegion();
if (!region)
return;
// Detect while loops in the subnodes
//
TR_StructureSubGraphNode *node;
int32_t numSubNodes = 0;
int32_t numberOfNodes = comp()->getFlowGraph()->getNextNodeNumber();
TR_BitVector *pendingList = new (trStackMemory()) TR_BitVector(numberOfNodes, trMemory(), stackAlloc);
pendingList->setAll(numberOfNodes);
vcount_t visitCount = comp()->getVisitCount();
//if (debug("nonRecursiveBVA"))
{
_analysisStack.push(region->getEntry());
detectWhileLoopsInSubnodesInOrder(whileLoopsInnerFirst, whileLoops, doWhileLoopsInnerFirst, doWhileLoops, region, visitCount, pendingList, innerFirst);
}
/*
else
detectWhileLoopsInSubnodesInOrder(whileLoopsInnerFirst, whileLoops, doWhileLoopsInnerFirst, doWhileLoops, region->getEntry()->getStructure(), region->getEntry(), region, visitCount, pendingList, innerFirst);
*/
TR_RegionStructure::Cursor si(*region);
for (node = si.getCurrent(); node; node = si.getNext())
numSubNodes++;
if (!region->isNaturalLoop())
return;
/*
// The loop must not have exception successors
//
if (region->getEntry()->hasExceptionOutEdges())
return;
*/
// The header of the loop must be a block.
//
TR_StructureSubGraphNode *entryNode = region->getEntry();
TR_BlockStructure *loopHeader = entryNode->getStructure()->asBlock();
bool isDoWhileLoop = false;
bool isWhileLoop = false;
if (asLoopCanonicalizer())
{
// There must be more than one subnode in the loop
//
/////if (numSubNodes <= 1)
///// return;
/////
if ((loopHeader && loopHeader->getBlock()->getNextBlock() && loopHeader->getBlock()->getNextBlock()->isExtensionOfPreviousBlock()) ||
(loopHeader && loopHeader->getBlock()->getLastRealTreeTop()->getNode()->getOpCode().isJumpWithMultipleTargets()) ||
(loopHeader && loopHeader->getBlock()->getLastRealTreeTop()->getNode()->getOpCode().isCompBranchOnly()))
{
isDoWhileLoop = true;
}
if (!isDoWhileLoop && loopHeader && (numSubNodes > 1))
{
// There must be no exception edges into or out of the header block.
//
TR::Block *hdrBlock = loopHeader->getBlock();
if ((hdrBlock->hasExceptionPredecessors() == false) &&
(hdrBlock->hasExceptionSuccessors() == false))
{
// There must be two edges out of the header, one internal and one external.
//
if (entryNode->getSuccessors().size() == 2)
{
auto it = entryNode->getSuccessors().begin();
TR::CFGEdge* succ1 = *it;
++it;
TR::CFGEdge* succ2 = *it;
bool succ1Internal = region->contains(toStructureSubGraphNode(succ1->getTo())->getStructure(), region->getParent());
bool succ2Internal = region->contains(toStructureSubGraphNode(succ2->getTo())->getStructure(), region->getParent());
if (succ1Internal ^ succ2Internal)
{
TR::TreeTop *firstTree = hdrBlock->getFirstRealTreeTop();
static const bool skipTt = feGetEnv("TR_canonicalizerStopAtTreetop") == NULL;
static const bool skipCRAnchor = feGetEnv("TR_canonicalizerStopAtCompressedRefsAnchor") == NULL;
while ((firstTree &&
(firstTree->getNode()->getOpCodeValue() == TR::asynccheck ||
(skipTt && firstTree->getNode()->getOpCodeValue() == TR::treetop) ||
(skipCRAnchor && firstTree->getNode()->getOpCodeValue() == TR::compressedRefs) ||
firstTree->getNode()->getOpCode().isCheck())))
firstTree = firstTree->getNextTreeTop();
if (firstTree == hdrBlock->getLastRealTreeTop() ||
firstTree->getNextTreeTop() == hdrBlock->getLastRealTreeTop())
{
TR_ScratchList<TR::Block> exitBlocks(trMemory());
region->collectExitBlocks(&exitBlocks);
bool doNotConsiderAsWhile = false;
if (!exitBlocks.isSingleton())
{
TR::TreeTop *hdrBlockLoopTestTree = hdrBlock->getLastRealTreeTop();
bool foundInductionVariable =
findMatchingIVInRegion(hdrBlockLoopTestTree, region);
if (!foundInductionVariable)
{
ListIterator<TR::Block> blocksIt(&exitBlocks);
TR::Block *exitBlock;
for (exitBlock = blocksIt.getCurrent(); exitBlock; exitBlock = blocksIt.getNext())
{
if (exitBlock != hdrBlock)
{
if (exitBlock->getSuccessors().size() == 2)
{
auto it = exitBlock->getSuccessors().begin();
TR::CFGEdge* exitSucc1 = *it;
++it;
TR::CFGEdge* exitSucc2 = *it;
bool successor1Internal = region->contains(toBlock(exitSucc1->getTo())->getStructureOf(), region->getParent());
bool successor2Internal = region->contains(toBlock(exitSucc2->getTo())->getStructureOf(), region->getParent());
if (successor1Internal ^ successor2Internal)
{
TR::TreeTop *exitBlockLoopTestTree = exitBlock->getLastRealTreeTop();
if (exitBlockLoopTestTree->getNode()->getOpCode().isCompBranchOnly() ||
exitBlockLoopTestTree->getNode()->getOpCode().isJumpWithMultipleTargets()) continue;
foundInductionVariable =
findMatchingIVInRegion(exitBlockLoopTestTree, region);
}
}
}
if (foundInductionVariable)
{
doNotConsiderAsWhile = true;
break;
}
}
}
}
if (!doNotConsiderAsWhile)
isWhileLoop = true;
else
{
//printf("Found a fake while loop in %s\n", comp()->signature());
//fflush(stdout);
}
}
}
}
}
}
if (!isWhileLoop)
{
TR_StructureSubGraphNode *blockNode = entryNode;
while (!blockNode->getStructure()->asBlock())
blockNode = blockNode->getStructure()->asRegion()->getEntry();
/*
// There must be no exception edges into or out of the header block.
//
TR::Block *hdrBlock = blockNode->getStructure()->asBlock()->getBlock();
if (!(hdrBlock->getExceptionPredecessors().empty() &&
hdrBlock->getExceptionSuccessors().empty()))
return;
*/
isDoWhileLoop = true;
}
}
else if (asLoopVersioner())
{
if ((loopHeader && loopHeader->getBlock()->getLastRealTreeTop()->getNode()->getOpCode().isJumpWithMultipleTargets()) ||
(loopHeader && loopHeader->getBlock()->getLastRealTreeTop()->getNode()->getOpCode().isCompBranchOnly()))
return;
TR_RegionStructure *parentStructure = region->getParent()->asRegion();
if (parentStructure)
{
TR_RegionStructure::Cursor si(*parentStructure);
TR_StructureSubGraphNode *subNode;
for (subNode = si.getCurrent(); subNode != NULL; subNode = si.getNext())
{
TR_Structure *subStruct = subNode->getStructure();
if (subStruct == region)
{
/*
if (!(subNode->getExceptionPredecessors().empty() &&
subNode->getExceptionSuccessors().empty()))
return;
*/
if (subNode->getPredecessors().empty())
return;
TR_BlockStructure *pred = toStructureSubGraphNode(subNode->getPredecessors().front()->getFrom())->getStructure()->asBlock();
if (!pred ||
!pred->isLoopInvariantBlock())
return;
// This condition is required as we cannot create new catch blocks easily;
// a catch block normally has some specific info (handler info etc.) that are
// created by IL generator and if we try to create new catch blocks, then
// there was a crash when generating exception table entries.
//
TR_ScratchList<TR::Block> blocksInRegion(trMemory());
region->getBlocks(&blocksInRegion);
ListIterator<TR::Block> blocksIt(&blocksInRegion);
TR::Block *nextBlock;
for (nextBlock = blocksIt.getCurrent(); nextBlock; nextBlock=blocksIt.getNext())
if (!nextBlock->getExceptionPredecessors().empty())
return;
break;
}
}
}
//
//ListIterator<TR::CFGEdge> preds(&entryNode->getPredecessors());
//TR::CFGEdge *pred1 = preds.getCurrent();
//TR::CFGEdge *pred2 = preds.getNext();
//if (!pred1 || !pred2 || preds.getNext())
// return;
//bool pred1Internal = region->contains(toStructureSubGraphNode(pred1->getFrom())->getStructure(), region->getParent());
//bool pred2Internal = region->contains(toStructureSubGraphNode(pred2->getFrom())->getStructure(), region->getParent());
//if (!(pred1Internal ^ pred2Internal))
// return;
}
// This has satisfied all the criteria for a while loop that can be
// transformed.
//
if (isDoWhileLoop)
{
if (trace())
traceMsg(comp(), "Adding structure %d(%p) as a doWhile loop\n", region->getNumber(), region);
if (innerFirst)
doWhileLoopsInnerFirst.add(region);
else
doWhileLoops.add(region);
}
else
{
if (trace())
traceMsg(comp(), "Adding structure %d(%p) as a While loop\n", region->getNumber(), region);
if (innerFirst)
whileLoopsInnerFirst.add(region);
else
whileLoops.add(region);
}
}
bool TR_LoopTransformer::findMatchingIVInRegion(TR::TreeTop* loopTestTree, TR_RegionStructure* region)
{
TR::Node *firstChild = loopTestTree->getNode()->getFirstChild();
TR::SymbolReference *firstChildSymRef = NULL;
if (firstChild->getOpCode().hasSymbolReference())
firstChildSymRef = firstChild->getSymbolReference();
else
{
if ((firstChild->getOpCode().isAdd() || firstChild->getOpCode().isSub()) &&
(firstChild->getReferenceCount() > 1) &&
firstChild->getSecondChild()->getOpCode().isLoadConst())
{
firstChild = firstChild->getFirstChild();
}
if (firstChild &&
firstChild->getOpCode().hasSymbolReference())
firstChildSymRef = firstChild->getSymbolReference();
}
if (!firstChildSymRef)
return false;
if (region->findMatchingIV(firstChildSymRef))
return true;
TR_PrimaryInductionVariable *piv = region->getPrimaryInductionVariable();
if (piv && piv->getSymRef()->getSymbol() == firstChildSymRef->getSymbol())
return true;
ListIterator<TR_BasicInductionVariable> it(®ion->getBasicInductionVariables());
for (TR_BasicInductionVariable *biv = it.getFirst(); biv; biv = it.getNext())
if (biv->getSymRef()->getSymbol() == firstChildSymRef->getSymbol())
return true;
return false;
}
/**
* @verbatim
* The loop is changed from this: to this:
* | |
* | |
* --->| |
* | | |
* | ----- ----- ----- -----
* | | H |---->| E | | H |---->| S1 |------
* | ----- ----- ----- ----- |
* | | | |
* | | ----- |
* | ----- | S2 | |
* | | B | ----- |
* | ----- ---->| |
* | | | ----- |
* ---- | | B | |
* | ----- |
* | | V
* | ----- ----- -----
* | | H1 |---->| G |-->| E |
* | ----- ----- -----
* | |
* -----
* @endverbatim
* The new block H1 is a clone of the original header H
* The new blocks S1 and S2 are empty critical-edge-splitting blocks
* The new block G is optional, it may be necessary to contain an extra
* goto.
*/
void TR_LoopCanonicalizer::canonicalizeNaturalLoop(TR_RegionStructure *whileLoop)
{
rewritePostToPreIncrementTestInRegion(whileLoop);
if (!performTransformation(comp(), "%sCanonicalizing natural loop %d\n", OPT_DETAILS, whileLoop->getNumber()))
return;
if (trace())
comp()->dumpMethodTrees("Trees at this stage");
TR_StructureSubGraphNode *entryGraphNode = whileLoop->getEntry();
TR_ASSERT(entryGraphNode->getStructure()->asBlock(), "Loop canonicalizer, header is not a block");
// Find the basic blocks that represent the loop header and the
// first block in the loop body.
//
TR::Block *loopHeader = entryGraphNode->getStructure()->asBlock()->getBlock();
TR::Block *loopBody = NULL;
for (auto nextSucc = loopHeader->getSuccessors().begin(); nextSucc != loopHeader->getSuccessors().end(); ++nextSucc)
{
TR::Block *dest = toBlock((*nextSucc)->getTo());
if (whileLoop->contains(dest->getStructureOf(), whileLoop->getParent()))
{
loopBody = dest;
break;
}
}
TR_ScratchList<TR::Block> newBlocks(trMemory());
TR_ScratchList<TR::CFGEdge> removedEdges(trMemory());
TR::TreeTop *entryTree = loopHeader->getEntry();
TR::TreeTop *exitTree = loopHeader->getExit();
TR::Node *entryNode = entryTree->getNode();
TR::Block *fallThroughBlock;
if (!_blocksToBeCleansed.find(loopHeader))
fallThroughBlock = exitTree->getNextTreeTop()->getNode()->getBlock();
else
{
TR_ASSERT(loopHeader->getLastRealTreeTop()->getNode()->getOpCodeValue() == TR::Goto, "Unexpected opcode instead of TR::Goto\n");
fallThroughBlock = loopHeader->getLastRealTreeTop()->getNode()->getBranchDestination()->getNode()->getBlock();
}
// Create a new empty block to hold the cloned header H1.
// It will be filled out with duplicate trees soon .
//
TR::Block *clonedHeader = TR::Block::createEmptyBlock(entryNode, comp(), loopHeader->getFrequency(), loopHeader);
bool needToSetFlag = false;
if (loopHeader->getStructureOf()->isEntryOfShortRunningLoop())
needToSetFlag = true;
newBlocks.add(clonedHeader);
TR::TreeTop *newEntryTree = clonedHeader->getEntry();
TR::TreeTop *newExitTree = clonedHeader->getExit();
TR::TreeTop *prevTree = entryTree->getPrevTreeTop();
// Since we will be explicitly doing structure repair later, remove the
// structure so that repair is not attempted as we modify the CFG.
//
_cfg->setStructure(NULL);
// Start fixing up the predecessors of the original loop
// header; i.e. make all of the back edges now point to the
// new duplicate header block; but maintain the incoming edges to the
// original header as the new If guarded structure must still be entered
// through the If guard (which is where the original loop header
// is present after canonicalization).
//
int32_t sumPredFreq = 0;
TR::Block *adjPred = NULL;
for (auto edge = loopHeader->getPredecessors().begin(); edge != loopHeader->getPredecessors().end(); ++edge)
{
TR::Block *pred = toBlock((*edge)->getFrom());
if ((*edge)->getCreatedByTailRecursionElimination())
needToSetFlag = true;
if (!whileLoop->contains(pred->getStructureOf(), whileLoop->getParent()))
{
sumPredFreq = sumPredFreq + (*edge)->getFrequency();
//
// This is NOT a back edge as the predecessor is not part of the loop.
// The operations here are to insert gotos at the end of this
// predecessor block as its not certain what the optimal
// positioning of the trees in the original header would be
// right now. Since this control flow path is guaranteed to be
// less 'hot' than the actual loop, we are trying to remove
// any constraints that might keep us from moving the trees
// in the original loop header; we might want to move trees
// in this original header in order to specifically take advantage
// of falling through in the 'hot' path between the loop body
// and the new duplicate header.
//
if (pred->getExit())
loopHeader->getEntry()->getNode()->copyByteCodeInfo(pred->getExit()->getNode());
//dumpOptDetails(comp(), "Block loopHeader %d gets info from pred %d\n", loopHeader->getNumber(), pred->getNumber());
if (!(pred == _cfg->getStart()))
{
TR::TreeTop *lastNonFenceTree = pred->getLastRealTreeTop();
if (_blocksToBeCleansed.find(pred))
lastNonFenceTree = lastNonFenceTree->getPrevRealTreeTop();
TR::Node * lastNonFenceNode = lastNonFenceTree->getNode();
if (lastNonFenceTree->getNode()->getOpCode().isBranch())
{
// If the predecessor had a branch but was still falling
// through rather than branching explicitly to the original
// header. Note that a switch always has explicit branches;
// so it cannot be falling through to the original header.
//
if (lastNonFenceTree->getNode()->getBranchDestination() != entryTree)
{
// We add a goto at the end of a block already having
// a branch; so we MUST fix this up by moving trees
// at the end. The reasoning here is that in general in
// a nested while loop we might have the headers
// falling through to each other and the body falling
// through to the innermost header. In such cases we
// want our canonicalized nested do whiles to also
// utilize maximum fall through like originally but
// with the new duplicate headers now. So two or more
// original header blocks (their trees) would need to be
// moved out of the 'hot' path first and then at the end,
// we patch up the trees properly and get rid of this
// goto we have inserted that breaks CFG constraints
// temporarily.
//
TR::TreeTop *gotoTreeTop = TR::TreeTop::create(comp(), TR::Node::create(entryNode, TR::Goto, 0, entryTree));
TR::TreeTop *treeTop = lastNonFenceTree->getNextTreeTop();
lastNonFenceTree->join(gotoTreeTop);
gotoTreeTop->join(treeTop);
_blocksToBeCleansed.add(pred);
}
}
else if (!lastNonFenceTree->getNode()->getOpCode().isJumpWithMultipleTargets() &&
!lastNonFenceTree->getNode()->getOpCode().isCompBranchOnly())
{
if (adjPred)
{
// If the predecessor used to fall through into the
// original header (no branch or switch)
//
TR::TreeTop *gotoTreeTop = TR::TreeTop::create(comp(), TR::Node::create(entryNode, TR::Goto, 0, entryTree));
TR::TreeTop *treeTop = lastNonFenceTree->getNextTreeTop();
lastNonFenceTree->join(gotoTreeTop);
gotoTreeTop->join(treeTop);
}
else
{
adjPred = pred;