-
Notifications
You must be signed in to change notification settings - Fork 392
/
OrderBlocks.cpp
2440 lines (2081 loc) · 97.3 KB
/
OrderBlocks.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, 2021 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/OrderBlocks.hpp"
#include <algorithm>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "env/FrontEnd.hpp"
#include "compile/Compilation.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "cs2/bitvectr.h"
#include "env/IO.hpp"
#include "env/StackMemoryRegion.hpp"
#include "env/TRMemory.hpp"
#include "il/Block.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/TreeTop.hpp"
#include "il/TreeTop_inlines.hpp"
#include "infra/Assert.hpp"
#include "infra/Cfg.hpp"
#include "infra/List.hpp"
#include "infra/CfgEdge.hpp"
#include "infra/CfgNode.hpp"
#include "optimizer/Optimization_inlines.hpp"
#include "optimizer/OptimizationManager.hpp"
#include "optimizer/Optimizations.hpp"
#include "optimizer/Optimizer.hpp"
#include "optimizer/Structure.hpp"
#include "optimizer/OMRSimplifierHelpers.hpp"
#define OPT_DETAILS "O^O ORDER BLOCKS: "
// statistics collectors
static unsigned numberOfReorderings = 0;
static unsigned numberOfCompiles = 0;
static unsigned numberMethodReplicationCandidates = 0;
static unsigned numberReplicationCandidates = 0;
static unsigned numberHazardCandidates = 0;
void printReorderingStatistics(void)
{
if (numberOfCompiles++)
{
printf("Fall-through successor changed %d times\n", numberOfReorderings);
printf("Compiled %d times\n", numberOfCompiles);
printf("Average reorderings = %f\n", (float)numberOfReorderings/(float)numberOfCompiles);
printf("\nReplication candidates: %d\n", numberReplicationCandidates);
printf("\nCandidates chosen on hazards: %d\n", numberHazardCandidates);
}
}
void checkOrderingConsistency(TR::Compilation *comp);
TR_OrderBlocks::TR_OrderBlocks(TR::OptimizationManager *manager, bool beforeExtension)
: TR_BlockOrderingOptimization(manager), _hotPathList(manager->trMemory()), _coldPathList(manager->trMemory())
{
setTrace(comp()->getOptions()->trace(OMR::basicBlockOrdering));
_doPeepHoleOptimizationsBefore = true;
_doPeepHoleOptimizationsAfter = true;
_donePeepholeGotoToLoopHeader = false;
_changeBlockOrderBasedOnHWProfile = false;
_superColdBlockOnly = false;
_extendBlocks = false;
_needInvalidateStructure = false;
_reorderBlocks = true;
}
// returns TRUE if no need to find a better candidate for block
bool TR_OrderBlocks::needBetterChoice(TR::CFG *cfg, TR::CFGNode *block, TR::CFGNode *bestSucc)
{
// True by default if not _superColdBlockOnly
// True if the following is meet:
// 1. bestSucc is not block 2
// 2. bestSucc is super cold but block is not
// 3. bestSucc is safe to move away
if (!_superColdBlockOnly) return true;
// If hot list is empty, we have to choose the cold ones
// bestSucc is NULL, then block could be 1
if (_hotPathList.isEmpty() || bestSucc == NULL) return false;
//if (trace()) traceMsg(comp(), "\t\tneedBetterChoice: block_%d:sec_%d: bestSucc_%d:sec_%d\n",block->getNumber(), block->asBlock()->getSectionNumber(), bestSucc->getNumber(), bestSucc->asBlock()->getSectionNumber());
// Choose a better one if a cold block follows a hot block
if (bestSucc != comp()->getStartBlock() && bestSucc->asBlock()->isSuperCold() &&
!block->asBlock()->isSuperCold())
{
if (trace()) traceMsg(comp(), "\t\tneedBetterChoice: hot block_%d:cold_%d: follows a cold block bestSucc_%d:cold_%d\n",block->getNumber(), block->asBlock()->isSuperCold(), bestSucc->getNumber(), block->asBlock()->isSuperCold());
return true;
}
return false;
}
// returns TRUE if block absolutely cannot follow prevBlock in any legal ordering
bool TR_OrderBlocks::cannotFollowBlock(TR::Block *block, TR::Block *prevBlock)
{
TR::TreeTop *nextTT = NULL;
// if block extends its predecessor and that's not prevBlock, then we cannot choose block
if (block->isExtensionOfPreviousBlock())
{
if (block->getEntry()->getPrevTreeTop() != prevBlock->getExit())
{
if (trace()) traceMsg(comp(), "\t\textends some other block, can't follow\n");
return true;
}
}
return false;
}
// returns TRUE if block absolutely must follow prevBlock in any legal ordering
bool TR_OrderBlocks::mustFollowBlock(TR::Block *block, TR::Block *prevBlock)
{
// if block is prevBlock's fall-through successor then we're stuck, we have to choose it
if (block->isExtensionOfPreviousBlock())
{
if (block->getEntry()->getPrevTreeTop() == prevBlock->getExit())
{
if (trace()) traceMsg(comp(), "\t\textends previous block, must follow\n");
return true;
}
}
return false;
}
//Return the first valid block in the list. If HW Profile info exists return the first valid block only if there are no
//valid hot blocks.
TR::CFGNode *TR_OrderBlocks::findSuitablePathInList(List<TR::CFGNode> & list, TR::CFGNode *prevBlock)
{
ListElement<TR::CFGNode> *prev=NULL;
ListElement<TR::CFGNode> *ptr=list.getListHead();
TR::CFGNode *block=NULL;
ListElement<TR::CFGNode> *firstValidBlock = NULL;
ListElement<TR::CFGNode> *prevFirstValidBlock = NULL;
TR::CFGNode *validBlock=NULL;
while (ptr != NULL)
{
block = ptr->getData();
if (trace()) traceMsg(comp(), "\t\tconsidering block_%d freq: %d\n", block->getNumber(), block->getFrequency());
ListElement<TR::CFGNode> *next = ptr->getNextElement();
if (block->getVisitCount() == _visitCount)
{
// need to pop this guy off the list...no sense continuing to look at him
if (prev != NULL)
prev->setNextElement(next);
else
list.setListHead(next);
if (trace()) traceMsg(comp(), "\t\t block %d is visited\n", block->getNumber());
}
else
{
if (trace()) traceMsg(comp(), "\t\t block %d is valid\n", block->getNumber());
if (prevBlock == NULL || !cannotFollowBlock(block->asBlock(), prevBlock->asBlock()))
{
if (!_changeBlockOrderBasedOnHWProfile)
// valid to choose this block, so break out of the loop
break;
if (!firstValidBlock)
{
// valid to choose this block if hot block does not exist
firstValidBlock = ptr;
prevFirstValidBlock = prev;
validBlock = block;
}
if ((_numUnschedHotBlocks == 0) || block->getFrequency() > 0)
{
// valid to choose this block, so break out of the loop
break;
}
}
prev = ptr;
}
block = NULL;
ptr = next;
}
if (_changeBlockOrderBasedOnHWProfile && ptr == NULL)
{
ptr = firstValidBlock;
prev = prevFirstValidBlock;
block = validBlock;
}
if (ptr != NULL)
{
if (trace()) traceMsg(comp(), "\t\tRemoving block_%d from list\n", block->getNumber());
if (prev != NULL)
prev->setNextElement(ptr->getNextElement());
else
list.setListHead(ptr->getNextElement());
}
return block;
}
//Return true if a valid block that can follow prevBlock exists in the list. Otherwise return false.
bool TR_OrderBlocks::hasValidCandidate(List<TR::CFGNode> & list, TR::CFGNode *prevBlock)
{
ListElement<TR::CFGNode> *prev=NULL;
ListElement<TR::CFGNode> *ptr=list.getListHead();
TR::CFGNode *block=NULL;
while (ptr != NULL)
{
block = ptr->getData();
if (trace()) traceMsg(comp(), "\t\tconsidering block_%d\n", block->getNumber());
ListElement<TR::CFGNode> *next = ptr->getNextElement();
if (block->getVisitCount() == _visitCount)
{
// need to pop this guy off the list...no sense continuing to look at him
if (prev != NULL)
prev->setNextElement(next);
else
list.setListHead(next);
if (trace()) traceMsg(comp(), "\t\t block %d is visited\n", block->getNumber());
}
else
{
if (trace()) traceMsg(comp(), "\t\t block %d is valid\n", block->getNumber());
if (prevBlock == NULL || !cannotFollowBlock(block->asBlock(), prevBlock->asBlock()))
// valid to choose this block, so break out of the loop
return true;
prev = ptr;
}
block = NULL;
ptr = next;
}
return false;
}
// simplest implementation for now: later, look at frequencies, nesting depth, maybe even distance from predecessors
TR::CFGNode *TR_OrderBlocks::findBestPath(TR::CFGNode *prevBlock)
{
TR::CFGNode *nextBlock = findSuitablePathInList(_hotPathList, prevBlock);
if (nextBlock == NULL)
{
if (!_changeBlockOrderBasedOnHWProfile)
TR_ASSERT(_hotPathList.isEmpty(), "available hot blocks");
nextBlock = findSuitablePathInList(_coldPathList, prevBlock);
}
return nextBlock;
}
bool TR_OrderBlocks::endPathAtBlock(TR::CFGNode *block, TR::CFGNode *bestSucc, TR::CFG *cfg)
{
if (block == NULL || bestSucc == NULL)
return true;
if( block->asBlock()->getExit())
{
TR::Block *nb=block->asBlock()->getNextBlock();
if (nb && nb->isExtensionOfPreviousBlock())
return false;
}
if (_superColdBlockOnly )
{
if (block->asBlock()->isSuperCold() != bestSucc->asBlock()->isSuperCold() &&
block->asBlock()->getExit() && block->asBlock()->getExit()->getNextTreeTop())
{
// end path if coldness changes
if (trace()) traceMsg(comp(), "\t\tEnd path because coldness changed from block_%d to block_%d block->asBlock()->getExit()=%p block->asBlock()->getExit()->getNextTreeTop()=%p\n", block->asBlock()->getNumber(),bestSucc->asBlock()->getNumber(), block->asBlock()->getExit(), block->asBlock()->getExit()->getNextTreeTop());
return true;
}
}
//????: I think that's wrong
//if (!block->asBlock()->isCold() && bestSucc->asBlock()->isCold())
if (!_changeBlockOrderBasedOnHWProfile
&& block->asBlock()->isCold() != bestSucc->asBlock()->isCold())
{
if (trace()) traceMsg(comp(), "\t\tEnd path because coldness changed from block_%d to block_%d \n", block->asBlock()->getNumber(),bestSucc->asBlock()->getNumber());
return true;
}
if (block->asBlock()->getExit())
{
TR::TreeTop *lastTT = block->asBlock()->getLastRealTreeTop();
if (lastTT != NULL)
{
TR::Node *maybeBranchNode = lastTT->getNode();
if (maybeBranchNode->getOpCode().isJumpWithMultipleTargets())
return false;
}
}
if (block->getSuccessors().size() == 1)
return false;
TR_BlockStructure *bestSuccStructure = bestSucc->asBlock()->getStructureOf();
TR_BlockStructure *blockStructure = block->asBlock()->getStructureOf();
if (bestSuccStructure == NULL || blockStructure == NULL)
{
if (trace()) traceMsg(comp(), "\t\tEnd path because structure is NULL block_%d=%p to block_%d=%p \n", block->asBlock()->getNumber(),blockStructure, bestSucc->asBlock()->getNumber(),bestSuccStructure);
return true;
}
if (bestSuccStructure->getContainingLoop() != blockStructure->getContainingLoop())
{
int32_t bestSuccNum = bestSuccStructure->getNumber();
TR_Structure *bestSuccLoop = bestSuccStructure->getContainingLoop();
TR_Structure *blockLoop = blockStructure->getContainingLoop();
while (bestSuccLoop &&
(bestSuccLoop->getNumber() == bestSuccNum))
{
bestSuccLoop = bestSuccLoop->getContainingLoop();
}
return (bestSuccLoop != blockLoop);
if (bestSuccLoop != blockLoop)
{
if (trace()) traceMsg(comp(), "\t\tEnd path because different loop block_%d=%p to block_%d=%p \n", block->asBlock()->getNumber(),blockLoop, bestSucc->asBlock()->getNumber(),bestSuccLoop);
return true;
}
else return false;
}
else return false;
///return (bestSuccStructure->getContainingLoop() != blockStructure->getContainingLoop());
}
bool TR_OrderBlocks::analyseForHazards(TR::CFGNode *block)
{
TR::TreeTop *tt = block->asBlock()->getEntry();
if (tt)
{
for ( ; tt != block->asBlock()->getExit(); tt = tt->getNextTreeTop())
{
TR::Node *node = tt->getNode();
if (node != NULL)
{
if (node->getOpCode().isCall())
return true;
if (node->getOpCode().isReturn())
return true;
if (node->getOpCodeValue() == TR::athrow)
return true;
}
}
}
return false;
}
bool TR_OrderBlocks::isCandidateReallyBetter(TR::CFGEdge *candEdge, TR::Compilation *comp)
{
TR::CFGEdgeList & predecessors = candEdge->getTo()->getPredecessors();
//traceMsg(comp, "iCRB cand block_%d\n", candEdge->getTo()->getNumber());
for (auto predEdge = predecessors.begin(); predEdge != predecessors.end(); ++predEdge)
{
TR::CFGEdgeList & predSuccessors = (*predEdge)->getFrom()->getSuccessors();
float numFactor = 1.5;
for (auto predSuccEdge = predSuccessors.begin(); predSuccEdge != predSuccessors.end(); ++predSuccEdge)
{
if (_changeBlockOrderBasedOnHWProfile && ((*predSuccEdge)->getFrom()->getVisitCount() == _visitCount))
continue;
//traceMsg(comp, "comparing pred edge %d -> %d freq %d\n", predSuccEdge->getFrom()->getNumber(), predSuccEdge->getTo()->getNumber(), predSuccEdge->getFrequency());
//traceMsg(comp, "cand edge %d -> %d freq %d\n", candEdge->getFrom()->getNumber(), candEdge->getTo()->getNumber(), candEdge->getFrequency());
if (((*predSuccEdge) != candEdge) &&
((float)(*predSuccEdge)->getFrequency() > (float)(numFactor * (float)candEdge->getFrequency())))
//return predSuccEdge->getFrom();
{
//traceMsg(comp, "rejecting cand block_%d\n", candEdge->getTo()->getNumber());
return false;
}
}
}
///return candEdge->getFrom();
return true;
}
static int32_t numTransforms = 0;
static bool isCandidateTheHottestSuccessor(TR::CFGEdge *candEdge, TR::Compilation *comp)
{
///return true;
static char *pEnv = feGetEnv("TR_pNum");
int32_t count = 0;
if (pEnv) count = atoi(pEnv);
if (!comp->getFlowGraph()->getStructure()) // we cannot trust below checks if someone invalidated structure earlier in this opt
return true;
TR::CFGEdgeList & predecessors = candEdge->getTo()->getPredecessors();
TR_BlockStructure *candBlock = candEdge->getTo()->asBlock()->getStructureOf();
if (candBlock && candBlock->getContainingLoop() &&
candBlock->getContainingLoop()->getNumber() == candBlock->getNumber())
return true;
if (candBlock)
///if (1)
{
for (TR_Structure *s = candBlock->getParent(); s; s = s->getParent())
{
TR_RegionStructure *region = s->asRegion();
if (region && region->containsInternalCycles())
{
return true;
}
}
}
//traceMsg(comp, "iCHS cand block_%d\n", candEdge->getTo()->getNumber());
for (auto predEdge = predecessors.begin(); predEdge != predecessors.end(); ++predEdge)
{
if (((*predEdge)->getFrequency() > candEdge->getFrequency()) &&
((*predEdge)->getFrom() != candEdge->getTo()))
{
///numTransforms++;
//traceMsg(comp, "iCHS rejecting cand block_%d numTransforms %d\n", candEdge->getTo()->getNumber(), numTransforms);
///if (numTransforms < count)
{
//traceMsg(comp, "really iCHS rejecting cand block_%d numTransforms %d\n", candEdge->getTo()->getNumber(), numTransforms);
return false;
}
}
}
return true;
}
bool TR_OrderBlocks::candidateIsBetterSuccessorThanBest(TR::CFGEdge *candidateEdge, TR::CFGEdge *currentBestEdge)
{
TR::CFGNode *candidate = candidateEdge->getTo();
TR::CFGNode *currentBest = currentBestEdge->getTo();
TR::CFGNode *prevBlock = candidateEdge->getFrom();
TR_ASSERT(prevBlock == currentBestEdge->getFrom(), "edges are from different blocks");
// is succBlock a better choice than current best?
if (trace())
traceMsg(comp(), "\tComparing candidate %d(%d) to current best %d(%d) as successor for %d(%d)\n", candidate->getNumber(), candidate->getFrequency(), currentBest->getNumber(), currentBest->getFrequency(), prevBlock->getNumber(), prevBlock->getFrequency());
//if (!_superColdBlockOnly)
// {
if (!comp()->getOption(TR_DisableInterpreterProfiling))
{
if (candidateEdge->getFrequency() >= 0)
{
if (candidateEdge->getFrequency() == currentBestEdge->getFrequency())
{
OMR::TreeTop *lexicalSuccessorEntry = candidateEdge->getFrom()->asBlock()->getExit()->getNextTreeTop();
if (lexicalSuccessorEntry != NULL && lexicalSuccessorEntry->getNode()->getBlock() == candidateEdge->getTo())
{
if (trace()) traceMsg(comp(), "\t\tis equally hot, but is currently the lexical successor, making it my best choice\n");
return true;
}
}
if (candidateEdge->getFrequency() > currentBestEdge->getFrequency())
{
if (trace()) traceMsg(comp(), "\t\thas hotter edge, making it my best choice\n");
return true;
}
else if (candidateEdge->getFrequency() < currentBestEdge->getFrequency())
{
if (trace()) traceMsg(comp(), "\t\thas colder edge than my best choice, so discarding\n");
return false;
}
}
}
if (candidate->hasSuccessor(currentBest))
{
if (candidate->getFrequency() > (prevBlock->getFrequency() - candidate->getFrequency()))
{
if (trace()) traceMsg(comp(), "\t\thas has current best succ as a succ, detecting an if-then structure and making the if block my best choice\n");
return true;
}
}
if (candidate->getFrequency() >= 0)
{
// candidate is better if it's hotter than bestSuccessor
if (candidate->getFrequency() > currentBest->getFrequency())
{
if (trace()) traceMsg(comp(), "\t\tis hotter, making it my best choice\n");
return true;
}
else if (candidate->getFrequency() < currentBest->getFrequency())
{
if (trace()) traceMsg(comp(), "\t\tis colder than my best choice, so discarding\n");
return false;
}
}
if (!_changeBlockOrderBasedOnHWProfile)
{
// candidate is not cold, currentBest is cold
if (!candidate->asBlock()->isCold() && currentBest->asBlock()->isCold())
{
if (trace()) traceMsg(comp(), "\t\tcurrent best choice is cold but this one isn't, making it my best choice\n");
return true;
}
else if (candidate->asBlock()->isCold() && !currentBest->asBlock()->isCold())
{
if (trace()) traceMsg(comp(), "\t\tis cold while current best choice isn't cold, so discarding\n");
return false;
}
}
//}
// candidate is better if it's more deeply nested than currentBest
if (candidate->asBlock()->getNestingDepth() > currentBest->asBlock()->getNestingDepth())
{
if (trace()) traceMsg(comp(), "\t\thas deeper nesting level, making it my best choice\n");
return true;
}
else if (candidate->asBlock()->getNestingDepth() < currentBest->asBlock()->getNestingDepth())
{
if (trace()) traceMsg(comp(), "\t\thas lower nesting level than my best choice, so discarding\n");
return false;
}
// ok, we're left to static heuristics now
//TR::Node *branchNode = prevBlock->asBlock()->getLastRealTreeTop()->getNode();
bool bestHasHazards = analyseForHazards(currentBest);
bool candHasHazards = analyseForHazards(candidate);
if (bestHasHazards && !candHasHazards)
{
if (trace()) traceMsg(comp(), "\t\tbest choice has hazards but candidate doesn't, making it my best choice\n");
//numberHazardCandidates++;
return true;
}
// we've exhausted good ideas for choosing, so now try to choose simply based on extension opportunity
if (!(currentBest->getPredecessors().size() == 1) && (candidate->getPredecessors().size() == 1))
{
if (trace()) traceMsg(comp(), "\t\tbetter candidate for extension, making it my best choice\n");
return true;
}
return false;
}
TR::CFGNode *TR_OrderBlocks::chooseBestFallThroughSuccessor(TR::CFG *cfg, TR::CFGNode *block, int32_t & numCandidates)
{
static char *reallyNewReordering=feGetEnv("TR_reallyNewReordering");
List<TR::CFGEdge> candidateEdges(trMemory());
//int32_t numCandidates = 0;
TR::CFGEdge *bestSuccessorEdge = NULL;
if (block == NULL)
return NULL;
if (trace()) traceMsg(comp(), "Block %d: looking for best successor\n", block->getNumber());
// first, build up a list of potential choices: unvisited successors
TR::CFGEdgeList & successors = block->getSuccessors();
for (auto succEdge = successors.begin(); succEdge != successors.end(); ++succEdge)
{
TR::Block *succBlock = (*succEdge)->getTo()->asBlock();
if (trace()) traceMsg(comp(), "\t\texamining successor %d\n", succBlock->getNumber());
if (reallyNewReordering == NULL && succBlock->getVisitCount() == _visitCount)
{
if (trace()) traceMsg(comp(), "\t\tblock already visited\n");
continue;
}
if (reallyNewReordering != NULL && succBlock->getVisitCount() != _visitCount)
{
if (trace()) traceMsg(comp(), "\t\tblock not yet visited\n");
continue;
}
if (cannotFollowBlock(succBlock, block->asBlock()))
{
if (trace()) traceMsg(comp(), "\t\tcannot follow block, so we can't choose it\n");
continue;
}
if (mustFollowBlock(succBlock, block->asBlock()))
{
if (trace()) traceMsg(comp(), "\t\tmust follow block, so we have to choose it\n");
numCandidates = 1;
return succBlock;
}
if (block->hasExceptionSuccessor(succBlock))
{
if (trace()) traceMsg(comp(), "\t\texceptional successor: not a candidate\n");
continue;
}
if (block->asBlock()->getExit() && block->asBlock()->getExit()->getNextTreeTop() &&
succBlock == block->asBlock()->getExit()->getNextTreeTop()->getNode()->getBlock())
{
bestSuccessorEdge = *succEdge;
if (trace()) traceMsg(comp(), "\t\tfound original fall-through successor %d: making it initial best successor\n", succBlock->getNumber());
}
if (trace()) traceMsg(comp(), "\t\trecording as a candidate\n");
candidateEdges.add(*succEdge);
numCandidates++;
}
// no-brainer if there's only one to choose from!
if (numCandidates == 1)
{
TR::CFGNode *theCandidate = candidateEdges.popHead()->getTo();
TR::Block *candBlock = theCandidate->asBlock();
TR::Block *headBlock = NULL;
if (trace()) traceMsg(comp(), "\tOnly one candidate %d\n", theCandidate->getNumber());
if (!_changeBlockOrderBasedOnHWProfile)
{
// Bail if it is cold and we still have hot block to chose from
if (candBlock->isSuperCold())
{
if (!_hotPathList.isEmpty())
{
if (trace()) traceMsg(comp(), "\tcandidate %d is cold, discard because there are still hot choices \n", theCandidate->getNumber());
return NULL;
}
else if (!_coldPathList.isEmpty() && !_coldPathList.getHeadData()->asBlock()->isSuperCold())
{
if (trace()) traceMsg(comp(), "\tcandidate %d is super cold, discard because there are still choices which are not so cold \n", theCandidate->getNumber());
return NULL;
}
}
}
else
{
// If HW Profile info exists take the block frequency into account
if (candBlock->getFrequency() == 0 && hasValidCandidate(_hotPathList, block))
{
if (trace())
traceMsg(comp(), "HW Profile: candidate %d has freq zero, discard because there are still hot choices \n", candBlock->getNumber());
return NULL;
}
}
static const char *envp = feGetEnv("TR_NEARLYEXIT");
// if candBlock is a loop exit but the loop has multiple exits, choose the hottest exit instead of candBlock
if (!envp && cfg->getStructure())
//Make sure we still have structure info
{
TR_Structure *innerLoop = block->asBlock()->getStructureOf()->getContainingLoop();
// the block is contained in the inner loop
while (innerLoop)
{
TR_Structure *outerLoop = candBlock->getStructureOf()->getContainingLoop() ;
//outer loop does not exist or contains the inner loop
if (!outerLoop || ((innerLoop!=outerLoop) && outerLoop->contains(innerLoop)))
{
TR::CFGEdgeList& successors = block->asBlock()->getSuccessors();
if (successors.size() !=2 )
break;
//get exit edge frequency
int16_t exitFrequency=0;
for (auto succEdge = successors.begin(); succEdge != successors.end(); ++succEdge)
{
if ((*succEdge)->getTo()->asBlock()->getNumber()==theCandidate->getNumber())
{
exitFrequency=(*succEdge)->getFrequency();
if (trace())
traceMsg(comp(), "\t -> block_%d\tfrequency %4d\n", (*succEdge)->getTo()->getNumber(), (*succEdge)->getFrequency());
}
}
if (!exitFrequency)
break;
//get all exit edges including early exit
if (trace())
{
traceMsg(comp(), "\tThis is the loop exit: %d -> %d\n", block->getNumber(), theCandidate->getNumber());
traceMsg(comp(), "\t\tInner loop %d\n", innerLoop->getNumber());
traceMsg(comp(), "\t\tOuter loop %d\n", outerLoop?outerLoop->getNumber():-1);
}
List<TR::CFGEdge>& exitEdges= innerLoop->asRegion()->getExitEdges();
if (exitEdges.getSize()>1)
{
List<TR::CFGEdge> rEdges(trMemory());
List<TR::Block> rBlocks(trMemory());
innerLoop->asRegion()->collectExitBlocks(&rBlocks, &rEdges);
if (trace()) traceMsg(comp(), "\t rEdges.getSize()=%d\n", rEdges.getSize());
ListIterator<TR::CFGEdge> exitIt(&rEdges);
for (TR::CFGEdge *edge = exitIt.getFirst(); edge; edge = exitIt.getNext())
{
if (edge->getTo()->asBlock()->getVisitCount() != _visitCount)
{
if (trace())
traceMsg(comp(), "\t -> block_%d\tfrequency %4d, current exit frequency %4d\n",edge->getTo()->getNumber(), edge->getFrequency(), exitFrequency);
if (edge->getFrequency() > exitFrequency)
{
theCandidate = edge->getTo();
candBlock = theCandidate->asBlock();
exitFrequency=edge->getFrequency();
if (trace())
traceMsg(comp(), "\t Loop %d has multiple exits, consider hotter exit %d\n", innerLoop->getNumber(), theCandidate->getNumber() );
}
}
}
}
}
// end of the while
break;
}
}
return theCandidate;
}
if (numCandidates == 0)
{
if (trace()) traceMsg(comp(), "\tNo candidates\n");
return NULL;
}
if (trace()) traceMsg(comp(), "\tMultiple candidates, have to choose:\n");
// we now know there are multiple candidates, so we have to choose the best one
ListIterator<TR::CFGEdge> succCandEdgeIt(&candidateEdges);
if (bestSuccessorEdge == NULL)
{
for (TR::CFGEdge* succEdge = succCandEdgeIt.getFirst() ; succEdge; succEdge = succCandEdgeIt.getNext())
{
if (isCandidateReallyBetter(succEdge, comp()))
{
bestSuccessorEdge = succEdge;
break;
}
}
if (trace())
traceMsg(comp(), "iCRB initial best %p\n", bestSuccessorEdge);
if (!bestSuccessorEdge) return NULL;
if (trace())
traceMsg(comp(), "iCRB initial best %d\n", bestSuccessorEdge->getTo()->getNumber());
}
if (trace()) traceMsg(comp(), "\tInitial best candidate is %d(%d)\n", bestSuccessorEdge->getTo()->getNumber(), bestSuccessorEdge->getTo()->getFrequency());
candidateEdges.remove(bestSuccessorEdge);
succCandEdgeIt.reset();
for (TR::CFGEdge* succEdge = succCandEdgeIt.getFirst() ; succEdge; succEdge = succCandEdgeIt.getNext())
{
if (succEdge == bestSuccessorEdge)
continue;
if (trace()) traceMsg(comp(), "\tExamining candidate %d(%d)\n", succEdge->getTo()->getNumber(), succEdge->getTo()->getFrequency());
if (candidateIsBetterSuccessorThanBest(succEdge, bestSuccessorEdge) &&
isCandidateReallyBetter(succEdge, comp()))
{
bestSuccessorEdge = succEdge;
}
else
{
if (trace()) traceMsg(comp(), "\t\tworse than my current best choice\n");
}
}
if (trace()) traceMsg(comp(), "\tBest successor is %d\n", bestSuccessorEdge->getTo()->getNumber());
TR::CFGEdgeList & predecessors = bestSuccessorEdge->getTo()->getPredecessors();
for (auto predEdge = predecessors.begin(); predEdge != predecessors.end(); ++predEdge)
{
TR::CFGNode *pred = (*predEdge)->getFrom();
if (pred != block)
{
auto predSuccEdge = successors.begin();
for (; predSuccEdge != successors.end(); ++predSuccEdge)
{
TR::CFGNode *predSucc = (*predSuccEdge)->getTo();
if (predSucc != bestSuccessorEdge->getTo() && predSucc->getFrequency() > bestSuccessorEdge->getTo()->getFrequency())
break; // predecessor's hottest fall-through isn't bestSuccessor
}
if (predSuccEdge == successors.end())
{
if (trace()) traceMsg(comp(), "\t\tbut it has another predecessor %d for which it is the hottest successor\n", pred->getNumber());
if (trace()) traceMsg(comp(), "\t\tcounting this block as a candidate for replication\n", pred->getNumber());
numberMethodReplicationCandidates++;
}
}
}
if (_changeBlockOrderBasedOnHWProfile)
{
TR::Block *candBlock = bestSuccessorEdge->getTo()->asBlock();
//If HW Profile info exists take it into account
if (candBlock->getFrequency() == 0 && hasValidCandidate(_hotPathList, block))
{
if (trace())
traceMsg(comp(), "HW Profile: candidate %d has freq zero, discard because there are still hot choices \n", candBlock->getNumber());
return NULL;
}
}
return bestSuccessorEdge->getTo();
}
void TR_OrderBlocks::removeFromOrderedBlockLists(TR::CFGNode *block)
{
_coldPathList.remove(block);
_hotPathList.remove(block);
if (_changeBlockOrderBasedOnHWProfile && block->getFrequency() > 0)
{
_numUnschedHotBlocks--;
if (trace()) traceMsg(comp(), "\t_numUnschedHotBlocks remove %d (blockNum:%d) \n",
_numUnschedHotBlocks, block->getNumber());
}
}
void TR_OrderBlocks::addToOrderedBlockList(TR::CFGNode *block, TR_BlockList & list, bool useNumber)
{
TR_BlockListIterator iter(&list);
TR_BlockListElement *prevBlockElement=NULL;
TR::CFGNode *listBlock;
for (listBlock=iter.getFirst(); listBlock != NULL; prevBlockElement=iter.getCurrentElement(),listBlock=iter.getNext() )
{
TR::Block *cBlock = block->asBlock();
TR::Block *lBlock = listBlock->asBlock();
// if it's already on the list, don't bother adding it again
if (block->getNumber() == listBlock->getNumber())
return;
// guard NestingDepth and Number are important for performance of RELBench
if (!_superColdBlockOnly)
{
if (cBlock->isCold() && !cBlock->isSuperCold() &&
lBlock->isSuperCold())
break;
else if (cBlock->isSuperCold() &&
lBlock->isCold() && !lBlock->isSuperCold())
continue;
if (block->getFrequency() > listBlock->getFrequency())
break;
else if (block->getFrequency() < listBlock->getFrequency())
continue;
if (cBlock->getNestingDepth() > lBlock->getNestingDepth())
break;
else if (cBlock->getNestingDepth() < lBlock->getNestingDepth())
continue;
if (useNumber && block->getNumber() < listBlock->getNumber())
break;
}
}
if (prevBlockElement)
list.addAfter(block, prevBlockElement);
else
list.add(block);
}
void TR_OrderBlocks::addRemainingSuccessorsToList(TR::CFGNode *block, TR::CFGNode *excludeBlock)
{
// everything is already on the list at the beginning
if (_superColdBlockOnly) return;
if (trace()) traceMsg(comp(), "\tadding remaining successors of block_%d to queue\n", block->getNumber());
TR::CFGEdgeList & successors = block->getSuccessors();
for (auto succEdge = successors.begin(); succEdge != successors.end(); ++succEdge)
{
TR::CFGNode *succBlock = (*succEdge)->getTo();
// If the edge is created by BE, don't add block 1 to list for now
if (succBlock != excludeBlock && succBlock->getVisitCount() != _visitCount &&
isCandidateTheHottestSuccessor(*succEdge, comp()))
{
if (succBlock->asBlock()->isCold())
{
if (trace()) traceMsg(comp(), "\t\tAdding unvisited cold successor %d\n", succBlock->getNumber());
addToOrderedBlockList(succBlock, _coldPathList, true);
}
else
{
if (trace()) traceMsg(comp(), "\t\tAdding unvisited non-cold successor %d\n", succBlock->getNumber());
addToOrderedBlockList(succBlock, _hotPathList, false);
}
}
}
TR::CFGEdgeList & excSuccessors = block->getExceptionSuccessors();
for (auto excSuccEdge = excSuccessors.begin(); excSuccEdge != excSuccessors.end(); ++excSuccEdge)
{
TR::CFGNode *succBlock = (*excSuccEdge)->getTo();
if (succBlock->getVisitCount() != _visitCount)
{
if (succBlock->asBlock()->isCold() && succBlock->asBlock()->getFrequency() <= 0)
{
if (trace()) traceMsg(comp(), "\t\tAdding unvisited cold exception successor %d\n", succBlock->getNumber());
addToOrderedBlockList(succBlock, _coldPathList, true);
}
else
{
if (trace()) traceMsg(comp(), "\t\tAdding unvisited non-cold exception successor %d\n", succBlock->getNumber());
addToOrderedBlockList(succBlock, _hotPathList, false);
}
}
}
}
//Take the successor's frequencies when considering which successor to add to the hot list
void TR_OrderBlocks::addRemainingSuccessorsToListHWProfile(TR::CFGNode *block, TR::CFGNode *excludeBlock)
{
if (trace()) traceMsg(comp(), "\tadding remaining successors of block_%d to queue\n", block->getNumber());
TR::CFGEdgeList & successors = block->getSuccessors();
for (auto succEdge = successors.begin(); succEdge != successors.end(); ++succEdge)
{
TR::CFGNode *succBlock = (*succEdge)->getTo();
// If the edge is created by BE, don't add block 1 to list for now
if (succBlock != excludeBlock && succBlock->getVisitCount() != _visitCount &&
succBlock->getFrequency() > 0)
{
if (trace()) traceMsg(comp(), "\t\tAdding unvisited non-cold successor %d\n", succBlock->getNumber());
addToOrderedBlockList(succBlock, _hotPathList, false);
}
}
TR::CFGEdgeList & excSuccessors = block->getExceptionSuccessors();
for (auto excSuccEdge = excSuccessors.begin(); excSuccEdge != excSuccessors.end(); ++excSuccEdge)
{
TR::CFGNode *succBlock = (*excSuccEdge)->getTo();
if (succBlock->getVisitCount() != _visitCount && succBlock->getFrequency() > 0)
{
addToOrderedBlockList(succBlock, _hotPathList, false);
}
}
}