-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathLoopReplicator.cpp
2408 lines (2199 loc) · 92 KB
/
LoopReplicator.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 IBM Corp. and others 2000
*
* 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 https://www.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] https://openjdk.org/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 OR GPL-2.0-only WITH OpenJDK-assembly-exception-1.0
*******************************************************************************/
#include "optimizer/LoopReplicator.hpp"
#include <stdio.h>
#include <string.h>
#include "env/FrontEnd.hpp"
#include "compile/Compilation.hpp"
#include "compile/SymbolReferenceTable.hpp"
#include "env/TRMemory.hpp"
#include "il/Block.hpp"
#include "il/ILOpCodes.hpp"
#include "il/ILOps.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/TreeTop.hpp"
#include "il/TreeTop_inlines.hpp"
#include "infra/Assert.hpp"
#include "infra/BitVector.hpp"
#include "infra/Cfg.hpp"
#include "infra/Stack.hpp"
#include "infra/CfgEdge.hpp"
#include "infra/CfgNode.hpp"
#include "optimizer/Optimization_inlines.hpp"
#include "optimizer/Optimizer.hpp"
#include "optimizer/Structure.hpp"
#include "ras/Debug.hpp"
#define OPT_DETAILS "O^O LOOP REPLICATOR: "
#define MIN_BLOCKS_IN_TRACE 5
#define INITIAL_BLOCK_WEIGHT -999
#define COLOR_BLACK 0
#define COLOR_WHITE 1
#define COLOR_GRAY -1
TR_LoopReplicator::TR_LoopReplicator(TR::OptimizationManager *manager)
: TR_LoopTransformer(manager),
_blocksCloned(trMemory())
{
_nodeCount = 0;
_nodesInCFG = 0;
_switchTree = NULL;
_maxNestingDepth = 0;
}
//Add static debug counter for a given replication failure
static void countReplicationFailure(const char *failureReason, int32_t regionNum)
{
TR::Compilation *comp = TR::comp();
//Assemble format string: "LoopReplicator/<failureReason>/%s/(%s)/region_%d"
TR::DebugCounter::incStaticDebugCounter(comp, TR::DebugCounter::debugCounterName(comp,
"LoopReplicator/%s/%s/(%s)/region_%d", failureReason,
comp->getHotnessName(comp->getMethodHotness()),
comp->signature(), regionNum));
}
int32_t TR_LoopReplicator::perform()
{
// mainline entry
static char *disableLR = feGetEnv("TR_NoLoopReplicate");
if (disableLR)
return 0;
if (!comp()->mayHaveLoops() ||
optimizer()->optsThatCanCreateLoopsDisabled())
return 0;
if (comp()->getProfilingMode() == JitProfiling)
return 0;
_cfg = comp()->getFlowGraph();
_rootStructure = _cfg->getStructure();
_haveProfilingInfo = true;
static char *testLR = feGetEnv("TR_LRTest");
if (!_haveProfilingInfo)
{
dumpOptDetails(comp(), "Need profiling information in order to replicate...\n");
if (trace())
traceMsg(comp(), "method is %s \n", comp()->signature());
if (!testLR)
return 0;
}
_nodesInCFG = _cfg->getNextNodeNumber();
TR_Structure *root = _rootStructure;
// From this point on, stack memory allocations will die when the function returns
TR::StackMemoryRegion stackMemoryRegion(*trMemory());
_blocksInCFG = (TR::Block **) trMemory()->allocateStackMemory(_nodesInCFG * sizeof(TR::Block *));
memset(_blocksInCFG, 0, _nodesInCFG * sizeof(TR::Block *));
_blockWeights = (int32_t *) trMemory()->allocateStackMemory(_nodesInCFG * sizeof(int32_t));
memset(_blockWeights, 0, _nodesInCFG * sizeof(int32_t));
_seenBlocks = (int32_t *) trMemory()->allocateStackMemory(_nodesInCFG * sizeof(int32_t));
memset(_seenBlocks, 0, _nodesInCFG * sizeof(int32_t));
//
_blocksVisited = new (trStackMemory()) TR_BitVector(_nodesInCFG, trMemory(), stackAlloc);
for (TR::CFGNode *n = _cfg->getFirstNode(); n; n = n->getNext())
{
if (toBlock(n) && (n->getNumber() >= 0))
_blocksInCFG[n->getNumber()] = toBlock(n);
_blockWeights[n->getNumber()] = INITIAL_BLOCK_WEIGHT;
_seenBlocks[n->getNumber()] = COLOR_WHITE;
}
// initialize the bitvectors
_blocksVisited->empty();
if (trace() && getDebug())
{
traceMsg(comp(), "structure before replication :\n");
getDebug()->print(comp()->getOutFile(), _rootStructure, 6);
}
// collect info about potential
// loops for replication
perform(root);
// now modify trees & CFG
dumpOptDetails(comp(), "analysis complete...attempting to replicate\n");
modifyLoops();
return 0;
}
int32_t TR_LoopReplicator::perform(TR_Structure *str)
{
TR_RegionStructure *region;
if (!(region = str->asRegion()))
return 0;
// replicate in post-order
TR_RegionStructure::Cursor sgnIt(*region);
for (TR_StructureSubGraphNode *n = sgnIt.getCurrent(); n; n = sgnIt.getNext())
perform(n->getStructure());
if (!region->isNaturalLoop())
{
dumpOptDetails(comp(), "region (%d) is not a natural loop\n", region->getNumber());
return 0;
}
// ignore loops known to be cold
TR::Block *entryBlock = region->getEntryBlock();
if (entryBlock->isCold())
{
countReplicationFailure("ColdLoop", region->getNumber());
dumpOptDetails(comp(), "region (%d) is a cold loop\n", region->getNumber());
return 0;
}
_blockMapper = (TR::Block **) trMemory()->allocateStackMemory(_nodesInCFG * sizeof(TR::Block *));
memset(_blockMapper, 0, _nodesInCFG * sizeof(TR::Block *));
// analyze 2 kinds of loops
// (a) do-while loops
// contain a block that has 2 edges - one edge exits the region and another edge is the
// loop back-edge
// region
// (b) while loops
// entry block (of the region) has an edge that exits the region. One of the predecessor
// edges of the entry is the loop back-edge
//
// there are 2 places where the controlling condition can be found
// (1) first treetop - (while loops)
// (2) originator of back-edge - (do-while loops)
if (trace())
traceMsg(comp(), "analyzing loop (%d)\n", region->getNumber());
// case 1
TR_StructureSubGraphNode *entryNode = region->getEntry();
TR_BlockStructure *entry = entryNode->getStructure()->asBlock();
if (entry)
{
for (auto edge = entryNode->getSuccessors().begin(); edge != entryNode->getSuccessors().end(); ++edge)
{
if (region->isExitEdge(*edge))
{
if (isWellFormedLoop(region, entry))
{
if (trace())
traceMsg(comp(), "found while loop\n");
_loopType = whileDo;
return replicateLoop(region, entryNode);
}
}
}
}
// case 2
TR_StructureSubGraphNode *branchNode = NULL;
TR_RegionStructure::Cursor snIt(*region);
for (TR_StructureSubGraphNode *sgNode = snIt.getCurrent();
sgNode && (branchNode == NULL);
sgNode = snIt.getNext())
{
bool hasBackEdge = false;
bool hasExitEdge = false;
for (auto edge = sgNode->getSuccessors().begin(); edge != sgNode->getSuccessors().end(); ++edge)
{
TR_StructureSubGraphNode *dest = toStructureSubGraphNode((*edge)->getTo());
if (region->isExitEdge(*edge))
hasExitEdge = true;
if (dest == region->getEntry())
hasBackEdge = true;
if (hasBackEdge && hasExitEdge)
{
if (isWellFormedLoop(region, sgNode->getStructure()))
branchNode = sgNode;
}
}
}
if (branchNode)
{
if (trace())
traceMsg(comp(), "found do-while loop\n");
_loopType = doWhile;
return replicateLoop(region, branchNode);
}
countReplicationFailure("UnsupportedLoopStructure", region->getNumber());
dumpOptDetails(comp(), "loop (%d) does not conform to required form & will not be replicated\n",
region->getNumber());
return false;
}
bool TR_LoopReplicator::isWellFormedLoop(TR_RegionStructure *region, TR_Structure *condBlock)
{
// FIXME:very simple checks for now
//
vcount_t visitCount = comp()->incVisitCount();
// (1)
// condition has to be in a block
if (!condBlock->asBlock())
return false;
// (2)
// iterate blocks and check for catch blocks; since they shouldnt be cloned
TR_ScratchList<TR::Block> blocksInLoop(trMemory());
region->getBlocks(&blocksInLoop);
ListIterator<TR::Block> bilIt(&blocksInLoop);
TR::Block *b = NULL;
int32_t numBlocks = 0;
for (b = bilIt.getCurrent(); b; b = bilIt.getNext(), numBlocks++)
{
if (b->hasExceptionPredecessors()) // catch
{
if (trace())
traceMsg(comp(), "block (%d) has exception predecessors - currently not supported\n", b->getNumber());
return false;
}
if (b->hasExceptionSuccessors()) // try
{
if (trace())
traceMsg(comp(), "block (%d) has exception successors\n", b->getNumber());
}
}
// (3)
// check if number of nodes in loop exceeds threshold
// FIXME: decide on a threshold; disabled for now
bilIt.reset();
for (b = bilIt.getCurrent(); b; b = bilIt.getNext())
{
TR::TreeTop *entryTT = b->getEntry();
TR::TreeTop *exitTT = b->getExit();
for (TR::TreeTop *tt = entryTT->getNextRealTreeTop();
tt != exitTT; tt = tt->getNextRealTreeTop())
{
_nodeCount += countChildren(tt->getNode(), visitCount);
}
}
int32_t currentNestingDepth = 0;
int32_t currentMaxNestingDepth = 0;
_maxNestingDepth = region->getMaxNestingDepth(¤tNestingDepth, ¤tMaxNestingDepth);
if (trace())
{
// loopproperties
traceMsg(comp(), "for loop (%d): \n", region->getNumber());
traceMsg(comp(), " number of nodes: %d\n", _nodeCount);
traceMsg(comp(), " number of blocks: %d\n", numBlocks);
traceMsg(comp(), " max nesting depth: %d\n", _maxNestingDepth);
}
if (_maxNestingDepth > MAX_REPLICATION_NESTING_DEPTH)
{
if (traceAny())
traceMsg(comp(), "for loop (%d), max nest depth thresholds exceeded\n", region->getNumber());
return false;
}
//growth factor, 33% of the loop
//
if ((numBlocks*MAX_REPLICATION_GROWTH_FACTOR) > MAX_REPLICATION_GROWTH_SIZE)
{
if (traceAny())
traceMsg(comp(), "for loop (%d), loop too big, thresholds exceeded\n", region->getNumber());
return false;
}
#if 0
if (_nodeCount > MAX_NODE_THRESHOLD_FOR_REPLICATION)
{
if (trace())
traceMsg(comp(), "no replication, node count exceeds threshold for loop (%d)\n",
region->getNumber());
return false;
}
#endif
return true;
}
// restructure loop by replication
int32_t TR_LoopReplicator::replicateLoop(TR_RegionStructure *region,
TR_StructureSubGraphNode *branchNode)
{
TR::Block *cBlock = branchNode->getStructure()->asBlock()->getBlock();
TR::TreeTop *lastTT = cBlock->getLastRealTreeTop();
if (!lastTT->getNode()->getOpCode().isBranch())
{
countReplicationFailure("NoBranchFoundInLoop", region->getNumber());
if (trace())
traceMsg(comp(), "no branch condition found in loop (%d)\n", region->getNumber());
return false;
}
dumpOptDetails(comp(), "picking trace in loop (%d)...\n", region->getNumber());
LoopInfo *lInfo = new (trStackMemory()) (LoopInfo);
lInfo->_regionNumber = region->getNumber();
lInfo->_replicated = false;
lInfo->_region = region;
_loopInfo.add(lInfo);
_curLoopInfo = lInfo;
// reset bitvector
//_blocksVisited->empty();
static char *pEnv = feGetEnv("TR_NewLRTracer");
if (pEnv)
{
///printf("computing weights for loop %d in method %s\n", region->getNumber(), comp()->signature());fflush(stdout);
calculateBlockWeights(region);
///printf("finished computing weights for loop %d in method %s\n", region->getNumber(), comp()->signature());fflush(stdout);
if (trace())
{
traceMsg(comp(), "propagated frequencies: \n");
for(int32_t i = 0; i < _nodesInCFG; i++)
traceMsg(comp(), "%d : %d\n", i, _blockWeights[i]);
}
}
static char *testLR = feGetEnv("TR_LRTest");
if (!testLR)
{
lInfo->_seedFreq = getSeedFreq(region);
// gathers the blocks in the common path
if (!heuristics(lInfo))
{
dumpOptDetails(comp(), "failed...unable to select trace inside the loop\n");
return false;
}
}
else
{
if (!heuristics(lInfo, true)) // testing mode
{
dumpOptDetails(comp(), "failed...unable to select trace inside the loop\n");
return false;
}
}
if (trace())
traceMsg(comp(), "gathered information for loop (%d)\n", lInfo->_regionNumber);
return true;
}
/////////////////////////////
// helper routines
//
//
int32_t TR_LoopReplicator::countChildren(TR::Node *node, vcount_t visitCount)
{
// counts children not yet visited
//
if (!node)
return 0;
if (node->getVisitCount() == visitCount)
return 0;
node->setVisitCount(visitCount);
int32_t nodeCount = 1;
for (int32_t i = node->getNumChildren()-1; i >= 0; i--)
{
nodeCount += countChildren(node->getChild(i), visitCount);
}
return nodeCount;
}
static void collectNonColdLoops(TR::Compilation *c, TR_RegionStructure *region, List<TR_RegionStructure> &innerLoops);
// Find non-cold loops strictly nested within region.
static void collectNonColdInnerLoops(TR::Compilation *c, TR_RegionStructure *region, List<TR_RegionStructure> &innerLoops)
{
TR_RegionStructure::Cursor it(*region);
for (TR_StructureSubGraphNode *node = it.getFirst();
node;
node = it.getNext())
{
if (node->getStructure()->asRegion())
collectNonColdLoops(c, node->getStructure()->asRegion(), innerLoops);
}
}
// Find non-cold loops within region, possibly including region itself.
static void collectNonColdLoops(TR::Compilation *c, TR_RegionStructure *region, List<TR_RegionStructure> &loops)
{
if (region->getEntryBlock()->isCold())
return;
List<TR_RegionStructure> innerLoops(c->trMemory());
collectNonColdInnerLoops(c, region, innerLoops);
if (region->isNaturalLoop() && innerLoops.isEmpty())
loops.add(region);
else
loops.add(innerLoops);
}
bool TR_LoopReplicator::checkInnerLoopFrequencies(TR_RegionStructure *region, LoopInfo *lInfo)
{
// dont bother with small traces
//
int32_t count = 0;
for (BlockEntry *be = (lInfo->_nodesCommon).getFirst(); be; be = be->getNext())
count++;
if (count < MIN_BLOCKS_IN_TRACE)
return true;
if (comp()->getFlowGraph()->getMaxFrequency() <= 0)
{
if (trace())
traceMsg(comp(), "no frequency info\n");
return true; // maybe this should actually be false...
}
if (trace())
traceMsg(comp(), "inspecting non-cold inner loops\n");
List<TR_RegionStructure> innerLoops(trMemory());
collectNonColdInnerLoops(comp(), region, innerLoops);
if (innerLoops.isEmpty())
{
if (trace())
traceMsg(comp(), "failed to find non-cold inner loops; will attempt to replicate\n");
return true;
}
logTrace(lInfo);
TR_ScratchList<TR::Block> hotInnerLoopHeaders(trMemory());
int32_t outerLoopFrequency = region->getEntryBlock()->getFrequency();
ListIterator<TR_RegionStructure> it(&innerLoops);
for (TR_RegionStructure *loop = it.getFirst(); loop; loop = it.getNext())
{
if (trace())
traceMsg(comp(), "\tlooking at inner loop %d\n", loop->getNumber());
TR::Block * const innerLoopHeader = loop->getEntryBlock();
int32_t entryBlockFrequency = innerLoopHeader->getFrequency();
float outerLoopRelativeFrequency = entryBlockFrequency / (float)outerLoopFrequency;
bool isInnerLoopHot = (outerLoopRelativeFrequency > 1.3f); // FIXME: const
if (trace())
traceMsg(comp(), "\t outerloop relative frequency = %.3g\n", outerLoopRelativeFrequency);
if (!isInnerLoopHot && outerLoopFrequency == 6)
{
isInnerLoopHot = true;
if (trace())
traceMsg(comp(), "\t considered hot because outer loop has frequency 6\n");
}
if (isInnerLoopHot)
{
if (trace())
traceMsg(comp(), "\t this is a hot inner loop\n");
hotInnerLoopHeaders.add(innerLoopHeader);
if (!searchList(innerLoopHeader, common, lInfo))
{
countReplicationFailure("HotInnerLoopNotOnTrace", loop->getNumber());
traceMsg(comp(), "not going to replicate loop because hot inner loop %d is not on the trace\n", loop->getNumber());
return false;
}
}
}
return shouldReplicateWithHotInnerLoops(region, lInfo, &hotInnerLoopHeaders);
}
bool TR_LoopReplicator::shouldReplicateWithHotInnerLoops(
TR_RegionStructure *region,
LoopInfo *lInfo,
TR_ScratchList<TR::Block> *hotInnerLoopHeaders)
{
if (comp()->getOption(TR_DisableLoopReplicatorColdSideEntryCheck))
return true;
// If there are no hot inner loops, then replicate away.
if (hotInnerLoopHeaders->isEmpty())
return true;
// When there are hot inner loops, we only want to replicate when we'll
// remove confounding paths leading into those inner loops. Right now we're
// only hoping to eliminate cold paths. Otherwise, we don't really expect
// any benefit from replicating an outer loop.
//
// Removal of cold paths is helpful because they often contain things we
// don't want to consider, such as calls, and they're often reached by
// failing guards. Splitting the tail in this case can help later analysis,
// e.g. VP may be able to fold guards within the hot inner loops.
//
// The following generates a conservative answer to whether we'll be able to
// remove any such cold paths, by requiring that the trace encounter a
// side-entry directly from a cold block before it hits either a hot inner
// loop or a branch within the trace.
//
// If it does, then we can definitely remove cold paths from consideration.
//
// Otherwise, we may miss some opportunities. For instance, the side-entry
// could occur only after a branch within the trace, or it may not come
// directly from a cold block. It's also possible that the eliminated cold
// path doesn't lead to every hot inner loop, but only most of them, for
// example. The heuristic can be extended to cover such cases later as
// necessary.
//
if (trace())
traceMsg(comp(), "Loop has hot inner loops. Looking for early cold side-entry.\n");
TR::Block * const outerLoopHeader = region->getEntryBlock();
TR::Block *tracePrefixCursor = outerLoopHeader;
for (;;)
{
// If this block has only one successor in the trace, move to that one.
// If it has multiple, stop searching.
TR::Block *tracePrefixNext = NULL;
for (auto e = tracePrefixCursor->getSuccessors().begin(); e != tracePrefixCursor->getSuccessors().end(); ++e)
{
TR::Block * const succ = toBlock((*e)->getTo());
if (succ == outerLoopHeader)
continue; // Don't follow back-edges.
if (!searchList(succ, common, lInfo))
continue; // Don't leave the trace.
if (tracePrefixNext != NULL)
{
// Stop due to branching paths within the trace.
countReplicationFailure("HotInnerLoopHitBranchWithoutColdSideEntry", region->getNumber());
if (trace())
traceMsg(comp(), "Hit a branch without finding a cold side-entry. Will not replicate.\n");
return false;
}
tracePrefixNext = succ;
}
if (tracePrefixNext == NULL)
{
// This is supposed to be impossible, since it means that we've
// iterated over the entire trace without encountering a hot inner
// loop header. But there has to be a hot inner loop header in the
// trace, since we have at least one hot inner loop, and we verified
// in checkInnerLoopFrequencies that each hot inner loop header is in
// the trace.
//
// To see why we must have iterated over the entire trace, consider
// that reaching this point means that we haven't returned due to
// finding a branch within the trace. For any block on the trace,
// there is a path to it from outerLoopHeader, and that path has to be
// a prefix of the sequence of blocks considered by this loop.
//
TR_ASSERT(false, "cold side-entry detection ran out of trace\n");
countReplicationFailure("HotInnerLoopRanOutOfTrace", region->getNumber());
// In production, just safely return false for this case.
if (trace())
traceMsg(comp(), "Ran out of trace without finding a cold side-entry. Will not replicate.\n");
return false;
}
tracePrefixCursor = tracePrefixNext;
if (trace())
traceMsg(comp(), "Checking for cold side-entries targeting block_%d\n", tracePrefixCursor->getNumber());
// If this block is the target of a side-entry from a cold block, good!
// Note that edges into outerLoopHeader are not side-entries, but we're
// not looking at outerLoopHeader here.
TR_ASSERT(tracePrefixCursor != outerLoopHeader,
"cold side-entry detection returned to outerLoopHeader\n");
for (auto e = tracePrefixCursor->getPredecessors().begin(); e != tracePrefixCursor->getPredecessors().end(); ++e)
{
TR::Block * const pred = toBlock((*e)->getFrom());
if (pred->isCold() && !searchList(pred, common, lInfo))
{
if (trace())
traceMsg(comp(), "Found a cold side-entry into block_%d from block_%d. Will replicate.\n", tracePrefixCursor->getNumber(), pred->getNumber());
return true;
}
}
// Don't search past the header of a hot inner loop.
if (hotInnerLoopHeaders->find(tracePrefixCursor))
{
countReplicationFailure("HotInnerLoopNoColdSideEntry", region->getNumber());
if (trace())
traceMsg(comp(), "Hit a hot inner loop without finding a cold side-entry. Will not replicate.\n");
return false;
}
}
}
bool TR_LoopReplicator::heuristics(LoopInfo *lInfo)
{
// pick a trace in the loop based on some heuristics [basic block frequencies]
// any algorithm can be implemented here; however it should probably have the side
// effect of populating lInfo->_nodesCommon for a given loop
//
TR_RegionStructure *region = lInfo->_region;
if (trace())
traceMsg(comp(), "analyzing region - %d (%p)\n", region->getNumber(), region);
TR::Block *seed = region->getEntryBlock();
BlockEntry *be = new (trStackMemory()) BlockEntry;
be->_block = seed;
(lInfo->_nodesCommon).append(be);
if (trace())
traceMsg(comp(), " adding loop header %d as seed\n", seed->getNumber());
_blocksVisited->set(seed->getNumber());
// select path of desirable successors
TR::Block *X = seed;
TR_Queue<TR::Block> blockq(trMemory());
blockq.enqueue(X);
do
{
X = blockq.dequeue();
if (trace())
traceMsg(comp(), "current candidate block : %d\n", X->getNumber());
X = nextCandidate(X, region, true);
if (!X || searchList(X, common, lInfo))
continue;
else
{
// add this block to the common path
BlockEntry *be = new (trStackMemory()) BlockEntry;
be->_block = X;
_blocksVisited->set(X->getNumber());
(lInfo->_nodesCommon).append(be);
}
blockq.enqueue(X);
} while (!blockq.isEmpty());
// select path of desirable predecessors
#if 0
X = seed;
blockq.enqueue(X);
do
{
X = blockq.dequeue();
if (trace())
dumpOptDetails(comp(), "candidate block - %d\n", X->getNumber());
X = nextCandidate(X, region, false);
if (!X || searchList(X, common, lInfo))
continue;
else
{
// add this block to the common path
BlockEntry *be = new (trStackMemory()) BlockEntry;
be->_block = X;
_blocksVisited->set(X->getNumber());
(lInfo->_nodesCommon).append(be);
}
blockq.enqueue(X);
} while (!blockq.isEmpty());
#endif
// select desirable successors of all blocks
_bStack = new (trStackMemory()) TR_Stack<TR::Block *>(trMemory(), 32, false, stackAlloc);
BlockEntry *bE = NULL;
for (bE = (lInfo->_nodesCommon).getFirst(); bE; bE = bE->getNext())
_bStack->push(bE->_block);
if (trace())
traceMsg(comp(), "attempting to extend trace...\n");
while(!_bStack->isEmpty())
{
X = _bStack->pop();
processBlock(X, region, lInfo);
}
bool checkSideEntrances = true;
if (_maxNestingDepth > 1)
{
checkSideEntrances = checkInnerLoopFrequencies(region, lInfo);
}
if (checkSideEntrances)
lInfo->_replicated = gatherBlocksToBeCloned(lInfo);
else
lInfo->_replicated = false;
logTrace(lInfo);
if (!lInfo->_replicated)
dumpOptDetails(comp(), "no side entrance found into trace; no replication will be performed\n");
return lInfo->_replicated;
}
void TR_LoopReplicator::logTrace(LoopInfo *lInfo)
{
if (!trace())
return;
traceMsg(comp(), "trace selected in loop :\n");
traceMsg(comp(), "{ ");
for (BlockEntry *be = (lInfo->_nodesCommon).getFirst(); be; be = be->getNext())
traceMsg(comp(), "%d -> ", (be->_block)->getNumber());
traceMsg(comp(), " }\n");
}
TR::Block * TR_LoopReplicator::nextCandidate(TR::Block *X, TR_RegionStructure *region, bool doSucc)
{
TR::CFGEdge *edge = NULL;
TR::Block *seed = region->getEntryBlock();
TR::Block *cand = NULL;
TR::Block *Y = bestSuccessor(region, X, &edge);
if (Y)
{
// could be skipping over inner loops
// in which case edge will be null
if (!edge)
{
if (trace())
traceMsg(comp(), " candidate is %d\n", Y->getNumber());
cand = Y;
}
else if (computeWeight(edge))
{
if (trace())
traceMsg(comp(), " candidate (%d) satisfied weight computation\n", Y->getNumber());
cand = Y;
}
}
return cand;
}
// analyze a block's successors to see if they can be included
void TR_LoopReplicator::processBlock(TR::Block *X, TR_RegionStructure *region, LoopInfo *lInfo)
{
TR::Block *seed = region->getEntryBlock();
for (auto e = X->getSuccessors().begin(); e != X->getSuccessors().end(); ++e)
{
TR::Block *dest = toBlock((*e)->getTo());
// a successor could either be
// 1. cold
// 2. header of inner loop
// 3. back-edge -> header
// 4. loop exit -> exit of the region
// 5. normal loop block
if (dest->isCold())
continue;
else if (isBackEdgeOrLoopExit(*e, region))
continue;
BlockEntry *bE = searchList(dest, common, lInfo);
if (bE && bE->_nonLoop)
continue;
else if (_blocksVisited->get(dest->getNumber()))
continue;
if (computeWeight(*e))
{
if (trace())
traceMsg(comp(), " candidate (%d) satisfied weight computation, extending trace\n", dest->getNumber());
// favorable block found, extend the trace
BlockEntry *bE = new (trStackMemory()) BlockEntry;
bE->_block = dest;
(lInfo->_nodesCommon).append(bE);
_blocksVisited->set(dest->getNumber());
_bStack->push(dest);
}
}
}
bool TR_LoopReplicator::isBackEdgeOrLoopExit(TR::CFGEdge *e, TR_RegionStructure *region, bool testSGraph)
{
// check if this is the loop back-edge or an exit-edge
//
TR_Structure *destStructure = NULL;
if (!testSGraph)
destStructure = toBlock(e->getTo())->getStructureOf();
else
destStructure = toStructureSubGraphNode(e->getTo())->getStructure();
bool notExitEdge = region->contains(destStructure, region->getParent());
if (!notExitEdge || destStructure == region->getEntry()->getStructure())
return true;
return false;
}
bool TR_LoopReplicator::computeWeight(TR::CFGEdge *edge)
{
TR::Block *X = toBlock(edge->getFrom());
TR::Block *Y = toBlock(edge->getTo());
int32_t Xfreq = getBlockFreq(X);
int32_t Yfreq = getBlockFreq(Y);
int32_t seedFreq = _curLoopInfo->_seedFreq;
//float w1 = ((float)(edge->getFrequency()))/(float)Xfreq;
// the criteria currently used is that the successor block
// should be at least T% of the current block and Ts% of
// the seed (seed in our case is the loop entry)
// w(x->y)/w(x) >= T && w(y)/w(s) >= Ts
// where T = block threshold
// Ts = seed threshold
// x,y = blocks and x->y is the edge from x to y
//
float w1 = ((float)Yfreq)/(float)Xfreq;
float w2 = ((float)Yfreq)/(float)seedFreq;
if (trace())
{
traceMsg(comp(), " weighing candidate : %d (Y) predeccessor : %d (X)\n", Y->getNumber(), X->getNumber());
traceMsg(comp(), " w(Y): %d w(X): %d w(seed): %d w(Y)/w(X): %.4f w(Y)/w(seed): %.4f\n", Yfreq, Xfreq,
seedFreq, w1, w2);
}
return (w1 >= BLOCK_THRESHOLD && w2 >= SEED_THRESHOLD) ? true : false;
}
// return the potential successor node in the CFG
TR::Block * TR_LoopReplicator::bestSuccessor(TR_RegionStructure *region, TR::Block *node, TR::CFGEdge **edge)
{
TR::Block *cand = NULL;
if (trace())
traceMsg(comp(), " analyzing region %d (%p)\n", region->getNumber(), region);
int16_t candFreq = -1;
for (auto e = node->getSuccessors().begin(); e != node->getSuccessors().end(); ++e)
{
TR::Block *dest = toBlock((*e)->getTo());
if (trace())
traceMsg(comp(), " analyzing successor block : %d\n", dest->getNumber());
TR_Structure *destStructure = dest->getStructureOf();
TR_Structure *parentStructure = destStructure->getParent();
if (trace())
traceMsg(comp(), " found parent %p is block a direct descendent? (%s)\n", destStructure->getParent(),
(region->contains(parentStructure, region->getParent()) ? "yes" : "no"));
//dumpOptDetails(comp(), "destStruct - %p\n", findNodeInHierarchy(region, destStructure->getNumber()));
// check for exit edges & loop backedges
bool notExitEdge = region->contains(destStructure, region->getParent());
if (!notExitEdge || destStructure == region->getEntry()->getStructure())
{
if (trace())
traceMsg(comp(), " isRegionExit? (%s) successor structure %p\n", (!notExitEdge ? "yes" : "no"),
destStructure);
continue;
}
// ignore cold successors
if (dest->isCold())
continue;
int32_t destFreq = dest->getFrequency();
static char *pEnv = feGetEnv("TR_NewLRTracer");
if (pEnv)
destFreq = _blockWeights[dest->getNumber()];
if (destFreq > candFreq)
{
candFreq = destFreq;
cand = dest;
*edge = *e;
}
}
if (cand)
{
// skip over loops already examined
nextSuccessor(region, &cand, edge);
if (trace())
traceMsg(comp(), " next candidate chosen : %d (Y)\n", cand->getNumber());
}
return cand;
}
// if the current candidate is the start of an inner loop [which would have already been
// analyzed]; this routine skips the loop, picking the inner loop exit
void TR_LoopReplicator::nextSuccessor(TR_RegionStructure *region, TR::Block **cand, TR::CFGEdge **edge)
{
TR::CFGEdge *succEdge = NULL;
TR_Structure *candStructure = (*cand)->getStructureOf();
TR_RegionStructure *parentStructure = candStructure->getParent()->asRegion();
if ((parentStructure != region) &&
(parentStructure && parentStructure->isNaturalLoop()))
{
ListIterator<TR::CFGEdge> eIt(&parentStructure->getExitEdges());
if (trace())
traceMsg(comp(), " inner loop detected : %p , exit edges are :\n", parentStructure);
TR::CFGEdge *e = NULL;
for (e = eIt.getFirst(); e; e = eIt.getNext())
{
// an exit edge could be on either the header or
// the block containing the back edge. search the exit edges
// to see if there is an exit to a block in the outer
// loop [there could be edges to say blocks which throw exceptions
// or return & these blocks will be in the parentstructure of the
// outer loop which is an acyclic region]
TR_Structure *dest = (_blocksInCFG[e->getTo()->getNumber()])->getStructureOf();
TR_Structure *source = (_blocksInCFG[e->getFrom()->getNumber()])->getStructureOf();
if (trace())
traceMsg(comp(), " %d (%p) -> %d (%p)\n", e->getFrom()->getNumber(), source,
e->getTo()->getNumber(), dest);
if (region->contains(dest, region->getParent()))
{
if (trace())
traceMsg(comp(), " found edge to %p (%d)\n", dest, _blocksInCFG[e->getTo()->getNumber()]);
succEdge = e;
break;
}
}
if (!succEdge)
{
// FIXME: this branch should not be taken
TR_ASSERT(succEdge, "loopReplicator: no exit edge found for loop!\n");
*cand = NULL;
*edge = NULL;
return;
}
//if (succEdge)
{
int32_t num = succEdge->getTo()->getNumber();
if (trace())
traceMsg(comp(), " choosing candidate : %d (%p)\n", num, _blocksInCFG[num]);
LoopInfo *lInfo = findLoopInfo(region->getNumber());
TR_ASSERT(lInfo, "no loop info for loop?\n");
// add all the blocks in the inner loop to the current trace
TR_ScratchList<TR::Block> blocksInLoop(trMemory());
parentStructure->getBlocks(&blocksInLoop);
ListIterator<TR::Block> bIt(&blocksInLoop);
for (TR::Block *b = bIt.getFirst(); b; b = bIt.getNext())
{
if (!searchList(b, common, lInfo))
{
BlockEntry *bE = new (trStackMemory()) BlockEntry;
// poison the blocks
bE->_nonLoop = true;
bE->_block = b;
(lInfo->_nodesCommon).append(bE);