-
Notifications
You must be signed in to change notification settings - Fork 397
/
Copy pathRedundantAsyncCheckRemoval.cpp
2392 lines (2064 loc) · 83.6 KB
/
RedundantAsyncCheckRemoval.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/RedundantAsyncCheckRemoval.hpp"
#include <algorithm>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include "codegen/CodeGenerator.hpp"
#include "env/FrontEnd.hpp"
#include "codegen/RecognizedMethods.hpp"
#include "compile/Compilation.hpp"
#include "compile/ResolvedMethod.hpp"
#include "compile/SymbolReferenceTable.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "control/Recompilation.hpp"
#include "env/CompilerEnv.hpp"
#include "env/StackMemoryRegion.hpp"
#include "env/jittypes.h"
#include "il/Block.hpp"
#include "il/DataTypes.hpp"
#include "il/ILOps.hpp"
#include "il/MethodSymbol.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.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/CfgEdge.hpp"
#include "infra/CfgNode.hpp"
#include "optimizer/Optimization_inlines.hpp"
#include "optimizer/Optimizer.hpp"
#include "optimizer/Structure.hpp"
#include "optimizer/TransformUtil.hpp"
#include "optimizer/VPConstraint.hpp"
#include "optimizer/AsyncCheckInsertion.hpp"
#define OPT_DETAILS "O^O REDUNDANT ASYNC CHECK REMOVAL: "
#define SHORT_RUNNING_LOOP 1
#define SHORT_RUNNING_LOOP_BOUND 20000
#define NUMBER_OF_NODES_IN_LARGE_METHOD 2000
#define NUMBER_OF_NODES_IN_LARGE_WARM_ACYCLIC_METHOD 200
// The following macro(s) works on StructureSubGraphNodes
#define GET_ASYNC_INFO(x) ((AsyncInfo*)(((x)->getStructure())->getAnalysisInfo()))
// Find a loop that this regoin is contained in
//
static TR_RegionStructure *getOuterLoop(TR_RegionStructure *region)
{
if (region->getParent() == 0)
return 0;
TR_RegionStructure *parent = region->getParent()->asRegion();
if (parent->isNaturalLoop())
return parent;
return getOuterLoop(parent);
}
static TR_RegionStructure *getOuterImproperRegion(TR_Structure *region)
{
if (region->getParent() == 0)
return 0;
TR_RegionStructure *parent = region->getParent()->asRegion();
if (parent->containsInternalCycles())
return parent;
return getOuterImproperRegion(parent);
}
static inline int32_t ceiling(int32_t numer, int32_t denom)
{
return (numer % denom == 0) ?
numer / denom :
numer / denom + 1;
}
TR_RedundantAsyncCheckRemoval::TR_RedundantAsyncCheckRemoval(TR::OptimizationManager *manager)
: TR::Optimization(manager), _ancestors(trMemory())
{}
bool TR_RedundantAsyncCheckRemoval::shouldPerform()
{
// Don't run when profiling
//
if (comp()->getProfilingMode() == JitProfiling || comp()->generateArraylets())
return false;
// It is not safe to add an asynccheck under involuntary OSR
// as a transition may have to occur at the added point and the
// required infrastructure may not exist
//
if (comp()->getOption(TR_EnableOSR) && comp()->getOSRMode() == TR::involuntaryOSR)
return false;
return true;
}
int32_t TR_RedundantAsyncCheckRemoval::perform()
{
TR::StackMemoryRegion stackMemoryRegion(*trMemory());
if (trace())
comp()->dumpMethodTrees("Before analysis:");
_asyncCheckInCurrentLoop = false;
_numAsyncChecksInserted = 0;
_foundShortRunningLoops = false;
_cfg = comp()->getFlowGraph();
// If this is a large acyclic method - add a yield point at each return from this method
// so that sampling will realize that we are actually in this method.
//
// Under (voluntary) OSR, it's safe to insert asynccheck immediately before
// return, but not necessarily elsewhere.
if (comp()->getMethodHotness() <= warm
|| !comp()->mayHaveLoops()
|| comp()->getOption(TR_EnableOSR))
{
static const char *p;
static uint32_t numNodesInLargeMethod = (p = feGetEnv("TR_LargeMethodNodes")) ? atoi(p) : NUMBER_OF_NODES_IN_LARGE_METHOD;
if (!p && 0)
{
if (comp()->getMethodHotness() <= warm &&
!comp()->mayHaveLoops())
numNodesInLargeMethod = NUMBER_OF_NODES_IN_LARGE_WARM_ACYCLIC_METHOD;
}
if ((uint32_t) comp()->getNodeCount() > numNodesInLargeMethod ||
comp()->getLoopWasVersionedWrtAsyncChecks())
{
_numAsyncChecksInserted += TR_AsyncCheckInsertion::insertReturnAsyncChecks(this,
"redundantAsyncCheckRemoval/returns");
}
return 1;
}
initialize(_cfg->getStructure());
comp()->incVisitCount();
int32_t count = perform(_cfg->getStructure());
// If all the loops are short running in the method, and we have
// resulted in the removal of all async checks - then sampling might
// be effected. Insert async checks on method exits.
//
if ((comp()->getMethodHotness() < scorching) && // make sure we don't add unnecessary checks at scorching
(comp()->getLoopWasVersionedWrtAsyncChecks() ||
(_numAsyncChecksInserted == 0 && _foundShortRunningLoops &&
comp()->getRecompilationInfo() &&
#ifdef J9_PROJECT_SPECIFIC
comp()->getRecompilationInfo()->useSampling() &&
#endif
comp()->getRecompilationInfo()->shouldBeCompiledAgain())))
{
_numAsyncChecksInserted += TR_AsyncCheckInsertion::insertReturnAsyncChecks(this,
"redundantAsyncCheckRemoval/returns");
}
if (trace())
comp()->dumpMethodTrees("After analysis:");
return count;
}
int32_t TR_RedundantAsyncCheckRemoval::perform(TR_Structure *str, bool insideImproperRegion)
{
TR_RegionStructure *region = str->asRegion();
if (region == 0)
return processBlockStructure(str->asBlock());
bool origAsyncCheckFlag = _asyncCheckInCurrentLoop;
if (region->containsInternalCycles())
{
int32_t retValue = processImproperRegion(region);
if (origAsyncCheckFlag)
_asyncCheckInCurrentLoop = true;
return retValue;
}
bool asyncCheckFlag = false;
if (region->isNaturalLoop())
_asyncCheckInCurrentLoop = false;
TR_RegionStructure::Cursor it(*region);
TR_StructureSubGraphNode *node;
for (node = it.getFirst(); node != 0; node = it.getNext())
{
perform(node->getStructure());
if (_asyncCheckInCurrentLoop)
asyncCheckFlag = true;
if (trace())
traceMsg(comp(), "sub node %d flag %d\n", node->getNumber(), asyncCheckFlag);
if (region->isNaturalLoop())
_asyncCheckInCurrentLoop = false;
}
if (region->isNaturalLoop())
{
if (trace())
traceMsg(comp(), "region %d flag %d\n", region->getNumber(), asyncCheckFlag);
_asyncCheckInCurrentLoop = asyncCheckFlag;
int32_t retValue = processNaturalLoop(region, insideImproperRegion);
if (asyncCheckFlag || origAsyncCheckFlag)
_asyncCheckInCurrentLoop = true;
else
_asyncCheckInCurrentLoop = false;
return retValue;
}
_asyncCheckInCurrentLoop = asyncCheckFlag;
int32_t retValue = processAcyclicRegion(region);
if (asyncCheckFlag || origAsyncCheckFlag)
_asyncCheckInCurrentLoop = true;
else
_asyncCheckInCurrentLoop = false;
return retValue;
}
// Initializes the AsyncInfo analysis objects for each of the structures,
// ignoring any improper regoins
//
void TR_RedundantAsyncCheckRemoval::initialize(TR_Structure *str)
{
AsyncInfo *info = new (trStackMemory()) AsyncInfo(trMemory());
info->setVisitMarker(0);
str->setAnalysisInfo(info);
TR_RegionStructure *region = str->asRegion();
if (region == 0)
return;
TR_RegionStructure::Cursor it(*region);
for (TR_StructureSubGraphNode *node = it.getFirst(); node; node = it.getNext())
initialize(node->getStructure());
}
int32_t TR_RedundantAsyncCheckRemoval::processBlockStructure(TR_BlockStructure *b)
{
// We remove all explicit async checks from the block. All calls other than INL
// calls cause a yield point as well. We must ignore unresolved calls as well
// because they might resolve to INL calls.
//
// 20020816: Return Paths as implicit yield points:
// Base Case: If the return is in "main", it is safe to omit the yield
// point on returning paths.
// Induction Step: Assume that the caller has correct yield points in it (it is safe).
// If you are returning to the caller, you need not do a yield, since you know
// that the caller will do it.
//
// By Induction, on the call depth, omitting yield points on paths that return is safe.
//
TR::Block *block = b->getBlock();
TR::TreeTop *treeTop;
TR::TreeTop *prev;
bool hasAYieldPoint = false;
bool hadAYieldPoint = false;
AsyncInfo *info = (AsyncInfo *)b->getAnalysisInfo();
TR::TreeTop *firstBlockEntry = block->startOfExtendedBlock()->getEntry();
TR::Block *curBlock = block;
TR::TreeTop *stopTree = NULL;
for (treeTop = firstBlockEntry; treeTop != block->getExit(); treeTop = treeTop->getNextTreeTop())
{
TR::Node *node = treeTop->getNode();
if (node->getOpCodeValue() == TR::BBStart)
{
stopTree = NULL;
curBlock = node->getBlock();
TR_RegionStructure *outerImproperRegion = getOuterImproperRegion(curBlock->getStructureOf());
TR_Structure * outerLoop = curBlock->getStructureOf()->getContainingLoop();
if ((node->getVisitCount() == comp()->getVisitCount()) ||
(outerImproperRegion && (!outerLoop || outerLoop->contains(outerImproperRegion))) ||
(curBlock->getStructureOf()->getContainingLoop() != b->getContainingLoop()))
{
stopTree = node->getBlock()->getExit()->getPrevTreeTop();
//continue;
}
node->setVisitCount(comp()->getVisitCount());
}
if (info->canHaveAYieldPoint() &&
containsImplicitInternalPointer(node))
{
// Mark all extendees as 'mustNotHaveAYieldPoint'
//
// Sometimes CSE creates implicit internal pointers in portions of code
// where there were no gc-points before. We cannot add a async check is such
// regions of code - since it will invalidate that optimization. Instead
// we recognize portions of extended basic blocks as "grey-areas" where its
// going to be dangerous to put a new async check.
//
markExtendees(curBlock, false);
}
if (!stopTree)
{
switch (node->getOpCodeValue())
{
case TR::asynccheck:
// Remove the async check
//
_asyncCheckInCurrentLoop = true;
if (trace())
traceMsg(comp(), "removing async check from block_%d\n", b->getNumber());
if (performTransformation(comp(), "%sremoving async check from block_%d\n", OPT_DETAILS, b->getNumber()))
{
prev = treeTop->getPrevTreeTop();
optimizer()->prepareForTreeRemoval(treeTop);
TR::TransformUtil::removeTree(comp(), treeTop);
treeTop = prev;
}
hadAYieldPoint = true;
break;
case TR::treetop:
case TR::NULLCHK:
case TR::ResolveCHK:
case TR::ResolveAndNULLCHK:
if (node->getFirstChild()->getOpCode().isCall() && !node->getFirstChild()->getSymbolReference()->isUnresolved())
{
if (callDoesAnImplicitAsyncCheck(node->getFirstChild()))
hasAYieldPoint = true;
}
break;
default:
if (node->getOpCode().isReturn())
hasAYieldPoint = true;
break;
}
}
}
// If we cannot have a yield point here because of a implicit internal pointer
// seen earlier in the extended basic block, then the internal pointer must go
// dead before the end of the block, since by definition, it cannot be live
// across a gc point. Any extendees of this block can have a asynccheck
// put into them
//
////if ((hasAYieldPoint || hadAYieldPoint) && !info->canHaveAYieldPoint())
//// markExtendees(block, true);
if (hasAYieldPoint)
info->setHardYieldPoint();
return 0;
}
bool TR_RedundantAsyncCheckRemoval::callDoesAnImplicitAsyncCheck(TR::Node *callNode)
{
TR::SymbolReference *symRef = callNode->getSymbolReference();
TR::MethodSymbol *symbol = callNode->getSymbol()->castToMethodSymbol();
TR::SymbolReferenceTable *symRefTab = comp()->getSymRefTab();
if (symbol->isVMInternalNative() || symbol->isJITInternalNative())
return false;
// This covers jitProfileValue, singlePrecisionSQRT and currentTimeMaxPrecision
if (symbol->isHelper())
return false;
#ifdef J9_PROJECT_SPECIFIC
if ((symbol->getRecognizedMethod()==TR::java_lang_Math_sqrt) ||
(symbol->getRecognizedMethod()==TR::java_lang_StrictMath_sqrt) ||
(symbol->getRecognizedMethod()==TR::java_lang_Math_max_I) ||
(symbol->getRecognizedMethod()==TR::java_lang_Math_min_I) ||
(symbol->getRecognizedMethod()==TR::java_lang_Math_max_L) ||
(symbol->getRecognizedMethod()==TR::java_lang_Math_min_L) ||
(symbol->getRecognizedMethod()==TR::java_lang_Math_abs_L) ||
(symbol->getRecognizedMethod()==TR::java_lang_Math_abs_D) ||
(symbol->getRecognizedMethod()==TR::java_lang_Math_abs_F) ||
(symbol->getRecognizedMethod()==TR::java_lang_Math_abs_I) ||
(symbol->getRecognizedMethod()==TR::java_lang_System_hiresClockImpl) ||
(symbol->getRecognizedMethod()==TR::java_lang_Integer_numberOfLeadingZeros) ||
(symbol->getRecognizedMethod()==TR::java_lang_Long_numberOfLeadingZeros) ||
(symbol->getRecognizedMethod()==TR::java_lang_Integer_numberOfTrailingZeros) ||
(symbol->getRecognizedMethod()==TR::java_lang_Long_numberOfTrailingZeros) ||
(symbol->getRecognizedMethod()==TR::java_lang_Integer_highestOneBit) ||
(symbol->getRecognizedMethod()==TR::java_lang_Long_reverseBytes) ||
(symbol->getRecognizedMethod()==TR::java_lang_Short_reverseBytes) ||
(symbol->getRecognizedMethod()==TR::java_lang_Integer_reverseBytes) ||
(symbol->getRecognizedMethod()==TR::java_lang_Long_highestOneBit) ||
(symbol->getRecognizedMethod()==TR::java_lang_Integer_rotateLeft) ||
(symbol->getRecognizedMethod()==TR::java_lang_Long_rotateLeft) ||
(symbol->getRecognizedMethod()==TR::java_lang_Integer_rotateRight) ||
(symbol->getRecognizedMethod()==TR::java_lang_Long_rotateRight)
)
return false;
// Beginning in Java9 we use the same enum values for both the
// sun.misc.Unsafe wrappers and the jdk.internal.misc.Unsafe JNI methods, so
// for these we need to do an additional test to check if they are the native
// versions or not.
if (symbol->isNative() &&
((symbol->getRecognizedMethod()==TR::sun_misc_Unsafe_compareAndSwapInt_jlObjectJII_Z) ||
(symbol->getRecognizedMethod()==TR::sun_misc_Unsafe_compareAndSwapLong_jlObjectJJJ_Z) ||
(symbol->getRecognizedMethod()==TR::sun_misc_Unsafe_compareAndSwapObject_jlObjectJjlObjectjlObject_Z))
)
return false;
if ((symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPPerformHysteresis) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPUseDFP) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPHWAvailable) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPIntConstructor) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPLongConstructor) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPLongExpConstructor) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPAdd) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPSubtract) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPMultiply) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPDivide) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPScaledAdd) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPScaledSubtract) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPScaledMultiply) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPScaledDivide) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPRound) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPSetScale) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPCompareTo) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPSignificance) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPExponent) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPBCDDigits) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPUnscaledValue) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPConvertPackedToDFP) ||
(symbol->getRecognizedMethod()==TR::java_math_BigDecimal_DFPConvertDFPToPacked)
)
return false;
if ((symbol->getRecognizedMethod()==TR::com_ibm_dataaccess_DecimalData_JITIntrinsicsEnabled) ||
(symbol->getRecognizedMethod()==TR::com_ibm_dataaccess_DecimalData_DFPFacilityAvailable) ||
(symbol->getRecognizedMethod()==TR::com_ibm_dataaccess_DecimalData_DFPUseDFP) ||
(symbol->getRecognizedMethod()==TR::com_ibm_dataaccess_DecimalData_DFPConvertPackedToDFP) ||
(symbol->getRecognizedMethod()==TR::com_ibm_dataaccess_DecimalData_DFPConvertDFPToPacked) ||
(symbol->getRecognizedMethod()==TR::com_ibm_dataaccess_DecimalData_createZeroBigDecimal) ||
(symbol->getRecognizedMethod()==TR::com_ibm_dataaccess_DecimalData_getlaside) ||
(symbol->getRecognizedMethod()==TR::com_ibm_dataaccess_DecimalData_setlaside) ||
(symbol->getRecognizedMethod()==TR::com_ibm_dataaccess_DecimalData_getflags) ||
(symbol->getRecognizedMethod()==TR::com_ibm_dataaccess_DecimalData_setflags))
return false;
#endif
return true;
}
int32_t TR_RedundantAsyncCheckRemoval::processAcyclicRegion(TR_RegionStructure *region)
{
// We do not need to look inside an acyclic region, if it is
// not inside a loop.
//
if (getOuterLoop(region) == 0)
return 0;
_ancestors.deleteAll();
comp()->incVisitCount();
computeCoverageInfo(region->getEntry(), region->getEntry());
if (GET_ASYNC_INFO(region->getEntry())->getCoverage() != FullyCovered)
{
comp()->incVisitCount();
TR_RegionStructure::Cursor it(*region);
TR_StructureSubGraphNode *node;
for (node = it.getFirst(); node; node = it.getNext())
{
AsyncInfo *info = GET_ASYNC_INFO(node);
if (info->hasYieldPoint())
markAncestors(node, region->getEntry());
}
ListIterator<TR_StructureSubGraphNode> ait(&_ancestors);
if (!_ancestors.isEmpty())
{
for (node = ait.getFirst(); node; node = ait.getNext())
{
getNearestAncestors(node, node, region->getEntry());
}
while ((node = findSmallestAncestor()) != 0)
{
insertAsyncCheckOnSubTree(node, region->getEntry());
}
}
}
AsyncInfo *info = (AsyncInfo *)region->getAnalysisInfo();
AsyncInfo *entryInfo = GET_ASYNC_INFO(region->getEntry());
// At this point, an ac region can either be not covered or
// fully covered. It may /seem/ partially covered because of
// exit successors. For such cases:
//
if (entryInfo->getCoverage() == PartiallyCovered)
entryInfo->setCoverage(FullyCovered);
info->setCoverage(entryInfo->getCoverage());
return 0;
}
// Recursively propagates coverage information about nodes in a loop or acylic region
//
void TR_RedundantAsyncCheckRemoval::computeCoverageInfo(TR_StructureSubGraphNode *node, TR_StructureSubGraphNode *entry)
{
if (node->getVisitCount() == comp()->getVisitCount())
return;
node->setVisitCount(comp()->getVisitCount());
AsyncInfo *info = GET_ASYNC_INFO(node);
if (!info->hasYieldPoint())
{
// This node is not FullyCovered, if all it's successors are covered.
// If it is covered on some paths then it is PartirallyCovered
// If it is not covered on any path, then it is NotCovered.
//
bool coveredOnSomePaths = false;
bool notCoveredOnSomePaths = false;
bool hasRealSuccessors = false;
for (auto edge = node->getSuccessors().begin(); edge != node->getSuccessors().end(); ++edge)
{
TR_StructureSubGraphNode *succ = toStructureSubGraphNode((*edge)->getTo());
// If there is an exit edge from node, we are not covered on that path
//
if (!succ->getStructure())
notCoveredOnSomePaths = true;
else
{
hasRealSuccessors = true;
if (succ == entry)
notCoveredOnSomePaths = true;
else
{
computeCoverageInfo(succ, entry);
switch (GET_ASYNC_INFO(succ)->getCoverage())
{
case NotCovered:
notCoveredOnSomePaths = true;
break;
case PartiallyCovered:
coveredOnSomePaths = true;
notCoveredOnSomePaths = true;
break;
case FullyCovered:
coveredOnSomePaths = true;
break;
}
}
}
}
if (hasRealSuccessors)
{
if (coveredOnSomePaths && notCoveredOnSomePaths)
info->setCoverage(PartiallyCovered);
else if (coveredOnSomePaths && !notCoveredOnSomePaths)
info->setCoverage(FullyCovered);
else if (!coveredOnSomePaths && notCoveredOnSomePaths)
info->setCoverage(NotCovered);
else
info->setCoverage(NotCovered);
}
else
info->setCoverage(NotCovered);
}
if (trace())
traceMsg(comp(), "for node: %d coverage: %d\n", node->getNumber(), info->getCoverage());
}
bool TR_RedundantAsyncCheckRemoval::isMaxLoopIterationGuardedLoop(TR_RegionStructure *loop)
{
// FIXME: this is much easier if dominator trees are available
TR_RegionStructure *parent = loop->getParent()->asRegion();
TR_StructureSubGraphNode *node = parent->findSubNodeInRegion(loop->getNumber());
if (!(node->getPredecessors().size() == 1))
return false;
TR_StructureSubGraphNode *pred = node->getPredecessors().front()->getFrom()
->asStructureSubGraphNode();
// If parent is an improper region, give up
//
if (parent->containsInternalCycles())
return false;
// The following is a rather intricate structure walk, and requires some explanation
// we start at the node representing the loop in the parent region. What we want to do
// is to find a dominating if-block that contains the max-loop-iteration guard for this
// loop. Traditionally, the guard is not the parent region, but infact there are several
// other versioning guards intervening between the loop and the iter guard. Each of
// these guards forms its own acyclic region, nesting the inner guards.
//
// We start the search in the parent region, walking the predecessors of the loop region.
// By definition there must exist an acyclic path between the loop and the guard. Ignore
// backedges and just walk the preds. There cannot be a region structure en route
// since that would imply that there was some control flow not typical of guarded versioned
// loops. If we hit the entry of the parent region, we start the same process in the
// parent of the parent region, until we hit the start-node, which implies failure.
//
// Each node en route must have exactly one predecessor, otherwise we have control flow
// not typical of a versioned loop.
//
// The walk below uses a queue for traversal just to look like a canonical backwards
// reverse post order walk, however there is never more than one element in the queue.
// NOTE: there is no use of visit counts in this loop, a node can never be visited twice
// in the following walk
//
TR_Queue<TR_StructureSubGraphNode> q(trMemory());
q.enqueue(pred);
while (!q.isEmpty())
{
TR_StructureSubGraphNode *cursor = q.dequeue();
// cannot have a region between the guard and the actual loop
//
if (cursor->getStructure()->asRegion())
return false;
// Check the cursor block
//
TR::Block *block = cursor->getStructure()->asBlock()->getBlock();
if (block == _cfg->getStart()->asBlock())
return false;
TR::TreeTop *tt = block->getLastRealTreeTop();
if (tt->getNode()->isMaxLoopIterationGuard())
return true;
// if we have hit the entry of the parent, we need to start looking in the
// parent's parent
//
TR_RegionStructure *cursorParent = cursor->getStructure()->getParent()->asRegion();
if (cursor == cursorParent->getEntry())
{
// if the parent was a loop, we know already that the guard was not found
// (cannot be improper, otherwise we would never have enqueued it)
//
if (cursorParent->isNaturalLoop())
return false;
// if we hit the start of the cfg, we have failed
//
if (!cursorParent->getParent())
return false;
cursorParent = cursorParent->getParent()->asRegion();
// If the parent is improper, give up
//
if (cursorParent->containsInternalCycles())
return false;
cursor = cursorParent->findSubNodeInRegion(cursor->getNumber());
}
// Enqueue the predecessors of the cursor
// there must be one unique predecessor
//
if (!(cursor->getPredecessors().size() == 1))
return false;
TR_StructureSubGraphNode *pred = cursor->getPredecessors().front()->getFrom()
->asStructureSubGraphNode();
q.enqueue(pred);
}
return false;
}
bool
TR_RedundantAsyncCheckRemoval::containsImplicitInternalPointer(TR::Node *node)
{
if (node->getVisitCount() == comp()->getVisitCount())
return false;
node->setVisitCount(comp()->getVisitCount());
bool result = false;
if (node->getOpCode().isArrayRef() && node->getReferenceCount() > 1 &&
(!comp()->cg()->supportsInternalPointers() || !node->isInternalPointer() || !node->getPinningArrayPointer()))
{
result = true;
}
else
{
for (int32_t c = node->getNumChildren()-1; c >= 0; --c)
{
if (containsImplicitInternalPointer(node->getChild(c)))
{
result = true;
break;
}
}
}
if (trace())
traceMsg(comp(), " containsImplicitInternalPointer(%p) = %s\n", node, result?"true":"false");
return result;
}
void
TR_RedundantAsyncCheckRemoval::markExtendees(TR::Block *block, bool canHaveAYieldPoint)
{
for (TR::Block *cursor = block->getNextBlock();
cursor && cursor->isExtensionOfPreviousBlock();
cursor = cursor->getNextBlock())
{
TR_BlockStructure *s = cursor->getStructureOf();
AsyncInfo *ai = ((AsyncInfo*)s->getAnalysisInfo());
if (trace())
{
traceMsg(comp(), " block_%d canHaveAYieldPoint %s -> %s\n",
cursor->getNumber(),
ai->canHaveAYieldPoint()? "true":"false",
canHaveAYieldPoint? "true":"false");
}
ai->setCanHaveAYieldPoint(canHaveAYieldPoint);
}
}
#define FIND_LOOP_ITERATIONS(Type,Name,NAME) \
bool Killme_CantBeginMacroWith_HASH_HASH; \
Type incr = incrVal->getLow##Name(); \
Type in, out, iters, diff; \
if (incr == 0) continue; \
if (entryVal && exitVal && entryVal->as##Name##Const() && exitVal->as##Name##Const()) \
{ \
in = entryVal->getLow##Name(); \
out = exitVal->getLow##Name(); \
} \
else if (entryVal && entryVal->as##Name##Const()) \
{ \
Type lo, hi; \
if (exitVal) \
{ \
lo = exitVal->getLow##Name(); \
hi = exitVal->getHigh##Name(); \
} \
else \
{ \
lo = TR::getMinSigned<NAME>(); \
hi = TR::getMaxSigned<NAME>(); \
} \
in = entryVal->getLow##Name(); \
if (incr > 0 && in < lo) \
out = lo; \
else if (incr < 0 && in > hi) \
out = hi; \
else \
continue; \
} \
else \
continue; \
diff = in-out; \
if (diff == TR::getMinSigned<NAME>()) \
continue; \
iters = (diff < 0) ? -diff/incr : diff/-incr;
int32_t TR_RedundantAsyncCheckRemoval::estimateLoopIterations(TR_RegionStructure *loop)
{
int32_t estimate = INT_MAX;
TR_InductionVariable *indVar;
for (indVar = loop->getFirstInductionVariable();
indVar != 0;
indVar = indVar->getNext())
{
TR::VPConstraint *entryVal = indVar->getEntry();
TR::VPConstraint *exitVal = indVar->getExit();
TR::VPConstraint *incrVal = indVar->getIncr();
if (incrVal->asLongConst() || (entryVal && entryVal->asLongConst()) || (exitVal && exitVal->asLongConst()))
{
FIND_LOOP_ITERATIONS(int64_t,Long,TR::Int64);
if (iters < estimate)
estimate = (int32_t) iters;
}
else
{
FIND_LOOP_ITERATIONS(int32_t,Int,TR::Int32);
if (iters < estimate)
estimate = iters;
}
}
if (isMaxLoopIterationGuardedLoop(loop))
{
return SHORT_RUNNING_LOOP;
}
if (loop->getFirstInductionVariable() == 0)
{
TR_LoopEstimator est(comp()->getFlowGraph(), loop, trace());
estimate = est.estimateLoopIterationsUpperBound();
}
return estimate;
}
int32_t TR_RedundantAsyncCheckRemoval::findShallowestCommonCaller(int32_t callSiteIndex1, int32_t callSiteIndex2)
{
while ((callSiteIndex1 != -1) && (callSiteIndex1 != -1) && (callSiteIndex1 != callSiteIndex2))
{
if (callSiteIndex1 > callSiteIndex2)
callSiteIndex1 = comp()->getInlinedCallSite(callSiteIndex1)._byteCodeInfo.getCallerIndex();
else
callSiteIndex2 = comp()->getInlinedCallSite(callSiteIndex2)._byteCodeInfo.getCallerIndex();
}
if (callSiteIndex1 == callSiteIndex2)
return callSiteIndex1;
else
return -1;
}
bool TR_RedundantAsyncCheckRemoval::originatesFromShortRunningMethod(TR_RegionStructure* region)
{
// Loops originating from java/lang/String methods are assumed to be short running unless
// they contain loops that are inlined from methods outsides the above classes.
// The following is an algorithm to detect such loops. In the algorithm, we assume that if all branches of all basic blocks of a loop
// have the same owning method, then that loop originates from that method.
//First build a list of branches in all basic blocks of the loop (region)
TR_ScratchList<TR::Block> blocksInRegion(trMemory());
region->getBlocks(&blocksInRegion);
ListIterator<TR::Block> blocksIt(&blocksInRegion);
TR_ScratchList<TR::Node> branches(trMemory());
for (TR::Block * block = blocksIt.getCurrent(); block; block=blocksIt.getNext())
{
TR::TreeTop* lastTreeTop = block->getLastRealTreeTop();
if (lastTreeTop != block->getEntry() && lastTreeTop->getNode()->getOpCode().isBranch())
branches.add(lastTreeTop->getNode());
}
TR_ASSERT(!branches.isEmpty(), "there are no branches in this loop!\n");
if (branches.isEmpty())
return false;
ListIterator<TR::Node> branchNodeIt(&branches);
int32_t commonCaller = branchNodeIt.getFirst()->getByteCodeInfo().getCallerIndex();
for (TR::Node* branchNode = branchNodeIt.getNext(); branchNode; branchNode = branchNodeIt.getNext())
{
commonCaller = findShallowestCommonCaller(commonCaller,
branchNode->getByteCodeInfo().getCallerIndex());
}
while ((commonCaller != -1) && !comp()->isShortRunningMethod(commonCaller))
commonCaller = comp()->getInlinedCallSite(commonCaller)._byteCodeInfo.getCallerIndex();
if (commonCaller == -1)
return false;
//Check all the branches. Either their origin must be the
//same as the common ancestor, or they must be called by the
//same origin through short-running or loopless methods.
for (TR::Node* branchNode = branchNodeIt.getFirst(); branchNode; branchNode = branchNodeIt.getNext())
{
int32_t callerIndex = branchNode->getByteCodeInfo().getCallerIndex();
bool callerMatch = false;
while (callerIndex != -1)
{
if (callerIndex == commonCaller)
{
callerMatch = true;
break;
}
TR_InlinedCallSite &ics = comp()->getInlinedCallSite(callerIndex);
if (!comp()->isShortRunningMethod(callerIndex) &&
TR::Compiler->mtd.hasBackwardBranches(ics._methodInfo))
break;
//set callerIndex to its caller
callerIndex = comp()->getInlinedCallSite(callerIndex)._byteCodeInfo.getCallerIndex();
}
if (!callerMatch)
return false;
}
return true;
}
bool TR_RedundantAsyncCheckRemoval::hasEarlyExit(TR_RegionStructure *region)
{
ListIterator<TR::CFGEdge> eit2(®ion->getExitEdges());
for (TR::CFGEdge *edge2 = eit2.getCurrent(); edge2 != 0; edge2 = eit2.getNext())
{
TR_StructureSubGraphNode *pred2 = edge2->getFrom()->asStructureSubGraphNode();
bool earlyExit = true;
for (auto edge = region->getEntry()->getPredecessors().begin(); edge != region->getEntry()->getPredecessors().end();
++edge)
{
if (pred2 == (*edge)->getFrom())
{
if (trace())
{
traceMsg(comp(), "pred2 = %d\n", pred2 ? pred2->getNumber() : -1);
traceMsg(comp(), "edge->getFrom = %d\n", (*edge)->getFrom() ? (*edge)->getFrom()->getNumber() : -1);
}
earlyExit = false;
break;
}
}
if (earlyExit)
{
if (trace())
traceMsg(comp(), "found earlyExit in region %d \n", region->getNumber());
return true;
}
}
return false;
}
int32_t TR_RedundantAsyncCheckRemoval::processNaturalLoop(TR_RegionStructure *region, bool isInsideImproperRegion)
{
if (trace())
traceMsg(comp(), "==> Forward Processing natural loop %d\n", region->getNumber());
bool isShortRunning = false;
bool needsForwardAnalysis = true;
if (!isInsideImproperRegion)
{
// There is no need to put async checks in loops created by tail recursion
// elimination. The reasoning is that if the loop were long-running, we
// would have resulted in a stack overflow to begin with.
//
TR::Block *entryBlock = region->getEntryBlock();
for (auto edge = entryBlock->getPredecessors().begin(); (edge != entryBlock->getPredecessors().end())&& !isShortRunning; ++edge)
{
if ((*edge)->getCreatedByTailRecursionElimination())
{
isShortRunning = true;
if (trace())
traceMsg(comp(), "Loop %d was created by TailRecursionElim. Skipping\n", region->getNumber());
}
}
if ((comp()->getMethodHotness() == scorching) && originatesFromShortRunningMethod(region))
{
isShortRunning = true;
if (trace())
traceMsg(comp(), "Loop %d originates from a trusted method, and therefore, is tagged as short running. Skipping\n", region->getNumber());
}
// Async check did not exist in this loop at beginning of RACR
// This implies that loop versioning eliminated the asynccheck
// from the loop based on short running guard.
//
if (!_asyncCheckInCurrentLoop)
{
isShortRunning = true;
if (trace())
traceMsg(comp(), "Loop %d is a Short running loop. Skipping\n", region->getNumber());
}
// Spill Loops generated by the General Loop Unroller do not need any async checks
// either since they are guaranteed to be short running
//
if (entryBlock->getStructureOf()->isEntryOfShortRunningLoop())
{
isShortRunning = true;
if (trace())
traceMsg(comp(), "Loop %d is a Short running loop. Skipping\n", region->getNumber());
}