-
Notifications
You must be signed in to change notification settings - Fork 747
/
Copy pathJ9EstimateCodeSize.cpp
2365 lines (2054 loc) · 102 KB
/
J9EstimateCodeSize.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 <algorithm>
#include "codegen/CodeGenerator.hpp"
#include "compile/InlineBlock.hpp"
#include "compile/Method.hpp"
#include "compile/ResolvedMethod.hpp"
#if defined(J9VM_OPT_JITSERVER)
#include "env/j9methodServer.hpp"
#endif /* defined(J9VM_OPT_JITSERVER) */
#include "env/VMJ9.h"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/ParameterSymbol.hpp"
#include "il/TreeTop.hpp"
#include "il/TreeTop_inlines.hpp"
#include "optimizer/PreExistence.hpp"
#include "optimizer/J9CallGraph.hpp"
#include "optimizer/J9EstimateCodeSize.hpp"
#include "optimizer/InterpreterEmulator.hpp"
#include "ras/LogTracer.hpp"
#include "runtime/J9Profiler.hpp"
// Empirically determined value
const float TR_J9EstimateCodeSize::STRING_COMPRESSION_ADJUSTMENT_FACTOR = 0.75f;
// There was no analysis done to determine this factor. It was chosen by intuition.
const float TR_J9EstimateCodeSize::METHOD_INVOKE_ADJUSTMENT_FACTOR = 0.20f;
// Empirically determined value
const float TR_J9EstimateCodeSize::CONST_ARG_IN_CALLEE_ADJUSTMENT_FACTOR = 0.75f;
#define DEFAULT_KNOWN_OBJ_WEIGHT 10
#define DEFAULT_FREQ_CUTOFF 40
#define DEFAULT_GRACE_INLINING_THRESHOLD 100
#define DEFAULT_ANALYZED_ALLOWANCE_FACTOR 2
/*
DEFINEs are ugly in general, but putting
if (tracer)
heuristicTrace(...)
everywhere in this class seems to be a much worse idea.
Unfortunately, C++98 doesn't have a good way to forward varargs
except for using a DEFINE
*/
#define heuristicTraceIfTracerIsNotNull(r, ...) \
if (r) { \
if ((r)->heuristicLevel()) { (r)->alwaysTraceM(__VA_ARGS__); } \
}
class NeedsPeekingHeuristic
{
public:
static const int default_distance = 25;
static const int NUM_LOADS = 4;
NeedsPeekingHeuristic(TR_CallTarget* calltarget, TR_J9ByteCodeIterator& bci, TR::ResolvedMethodSymbol* methodSymbol, TR::Compilation* comp, int d = default_distance) :
_hasArgumentsInfo(false),
_size(0),
_bci(bci),
_distance(d),
_numOfArgs(0),
_needsPeeking(false),
_tracer(0)
{
TR_PrexArgInfo* argInfo = calltarget->_ecsPrexArgInfo;
//no argInfo available for this caller
if (!argInfo)
return;
int i = 0;
int32_t numParms = methodSymbol->getParameterList().getSize();
_numOfArgs = numParms;
ListIterator<TR::ParameterSymbol> parmIt(&methodSymbol->getParameterList());
for (TR::ParameterSymbol *p = parmIt.getFirst(); p; p = parmIt.getNext(), i++)
{
int32_t len;
const char *sig = p->getTypeSignature(len);
if (i >= argInfo->getNumArgs() || //not enough slots in argInfo
(*sig != 'L') || //primitive arg
!argInfo->get(i) || //no arg at the i-th slot
!argInfo->get(i)->getClass() //no classInfo at the i-th slot
)
{
continue;
}
TR_OpaqueClassBlock *clazz = comp->fej9()->getClassFromSignature(sig, len, methodSymbol->getResolvedMethod());
if (!clazz)
{
continue;
}
TR_OpaqueClassBlock* argClass = argInfo->get(i)->getClass();
//findCallSiteTarget and validateAndPropagateArgsFromCalleeSymbol
//should take care of incompatible receivers
//this assertion only checks if the receiver is of the right type
//there's no harm in propagating other incompatible arguments
//as soon as one of those becomes a receiver this very same assertion
//should fire
TR_ASSERT(comp->fej9()->isInstanceOf(argClass, clazz, true, true, true) == TR_yes || i != 0 || !calltarget->_myCallSite->_isIndirectCall, "Incompatible receiver should have been handled by findCallSiteTarget");
// even the arg type propagated from the caller might be not more specific
// than the type got from callee signature, we should still try to
// do peeking. if we don't do peeking here, we will lose the chance to propagate
// the type info to the callsites of this calltarget.
static const bool keepBogusPeekingCondition = feGetEnv("TR_DisableBogusPeekingCondition") ? false: true;
if ( !keepBogusPeekingCondition || clazz != argClass ) //if two classes aren't equal it follows that argClass is more specific
//argsClass can either be equal to or a subclass of clazz
//see validateAndPropagateArgsFromCalleeSymbol
{
_hasArgumentsInfo = true;
_argInfo = argInfo;
}
/*
if (comp->fej9()->isInstanceOf (argClass, clazz, true, true, true) == TR_yes)
{
if (clazz != argClass)
_hasArgumentsInfo = true;
}
else
{
_hasArgumentsInfo = false;
return; // _hasArgumentsInfo will be equal to false and no propagation is going to happen
// because the incoming type information is not compatible
}
*/
}
};
void setTracer(TR_InlinerTracer *trc)
{
_tracer = trc;
heuristicTraceIfTracerIsNotNull(_tracer, "NeedsPeekingHeuristic is initialized with the following values: _hasArgumentsInfo = %d, NUM_LOADS = %d, _distance =%d, _needsPeeking = %d", _hasArgumentsInfo, NUM_LOADS, _distance, _needsPeeking);
}
void checkIfThereIsAParmLoadWithinDistance()
{
for (int i = 0; i < _size; i++)
{
if (_bci.bcIndex() - _loadIndices[i] <= _distance)
{
heuristicTraceIfTracerIsNotNull(_tracer, "there is a parm load at %d which is within %d of a call at %d", _loadIndices[i], _distance, _bci.bcIndex());
}
}
};
void setNeedsPeekingToTrue()
{
_needsPeeking = true;
}
void processByteCode()
{
if (!_hasArgumentsInfo)
return;
TR_J9ByteCode bc = _bci.current();
int slotIndex = -1;
switch (bc)
{
case J9BCaload0:
slotIndex = 0;
break;
case J9BCaload1:
slotIndex = 1;
break;
case J9BCaload2:
slotIndex = 2;
break;
case J9BCaload3:
slotIndex = 3;
break;
case J9BCaload:
slotIndex = _bci.nextByte();
TR_ASSERT(slotIndex >= 0 , "a slot shouldn't be negative");
break;
case J9BCaloadw:
slotIndex = _bci.next2Bytes();
TR_ASSERT(slotIndex >= 0 , "a slot shouldn't be negative");
break;
case J9BCinvokevirtual:
case J9BCinvokespecial:
case J9BCinvokestatic:
case J9BCinvokeinterface:
case J9BCinvokedynamic:
case J9BCinvokehandle:
case J9BCinvokehandlegeneric:
checkIfThereIsAParmLoadWithinDistance ();
default :
break;
}
if (slotIndex >=0)
{
processParameterLoad(slotIndex);
}
};
void processParameterLoad (int slotIndex)
{
//This heuristic simply checks if we indeed hit a parameter load (as opposed to an auto)
//and if we have an argInfo for this slot we would want to propagate
//Note, _hasArgumentsInfo is checked in processByteCode
//we should not even reach this code unless we have some PrexInfo
if (slotIndex < _numOfArgs && _argInfo->get(slotIndex))
{
heuristicTraceIfTracerIsNotNull(_tracer,"came across of a load of slot %d at %d", slotIndex, _bci.bcIndex());
_loadIndices[_size] = _bci.bcIndex();
_size = (_size + 1) % NUM_LOADS;
}
}
bool doPeeking () { return _needsPeeking; };
protected:
int32_t _loadIndices [NUM_LOADS];
int _size;
int _numOfArgs;
int _distance;
TR_J9ByteCodeIterator& _bci;
bool _hasArgumentsInfo;
TR_PrexArgInfo * _argInfo;
bool _needsPeeking;
TR_InlinerTracer * _tracer;
};
#undef heuristicTraceIfTracerIsNotNull
void
TR_J9EstimateCodeSize::setupNode(TR::Node *node, uint32_t bcIndex,
TR_ResolvedMethod *feMethod, TR::Compilation *comp)
{
node->getByteCodeInfo().setDoNotProfile(0);
node->setByteCodeIndex(bcIndex);
node->setInlinedSiteIndex(-10);
node->setMethod(feMethod->getPersistentIdentifier());
}
TR::Block *
TR_J9EstimateCodeSize::getBlock(TR::Compilation *comp, TR::Block * * blocks,
TR_ResolvedMethod *feMethod, int32_t i, TR::CFG & cfg)
{
if (!blocks[i])
{
TR::TreeTop *startTree = TR::TreeTop::create(comp, TR::Node::create(
NULL, TR::BBStart, 0));
TR::TreeTop *endTree = TR::TreeTop::create(comp, TR::Node::create(
NULL, TR::BBEnd, 0));
startTree->join(endTree);
blocks[i] = TR::Block::createBlock(startTree, endTree, cfg);
blocks[i]->setBlockBCIndex(i);
blocks[i]->setNumber(cfg.getNextNodeNumber());
setupNode(startTree->getNode(), i, feMethod, comp);
setupNode(endTree->getNode(), i, feMethod, comp);
cfg.addNode(blocks[i]);
}
return blocks[i];
}
static TR::ILOpCodes convertBytecodeToIL (TR_J9ByteCode bc)
{
switch (bc)
{
case J9BCifeq: return TR::ificmpeq;
case J9BCifne: return TR::ificmpne;
case J9BCiflt: return TR::ificmplt;
case J9BCifge: return TR::ificmpge;
case J9BCifgt: return TR::ificmpgt;
case J9BCifle: return TR::ificmple;
case J9BCifnull: return TR::ifacmpeq;
case J9BCifnonnull: return TR::ifacmpne;
case J9BCificmpeq: return TR::ificmpeq;
case J9BCificmpne: return TR::ificmpne;
case J9BCificmplt: return TR::ificmplt;
case J9BCificmpge: return TR::ificmpge;
case J9BCificmpgt: return TR::ificmpgt;
case J9BCificmple: return TR::ificmple;
case J9BCifacmpeq: return TR::ifacmpeq;
case J9BCifacmpne: return TR::ifacmpne;
case J9BCtableswitch: return TR::table;
case J9BClookupswitch: return TR::lookup;
case J9BCgoto:
case J9BCgotow: return TR::Goto;
case J9BCReturnC: /* fall-through */
case J9BCReturnS: /* fall-through */
case J9BCReturnB: /* fall-through */
case J9BCReturnZ: /* fall-through */
case J9BCgenericReturn: return TR::Return;
case J9BCathrow: return TR::athrow;
default:
TR_ASSERT(0,"Unsupported conversion for now.");
return TR::BadILOp;
}
return TR::BadILOp;
}
void
TR_J9EstimateCodeSize::setupLastTreeTop(TR::Block *currentBlock, TR_J9ByteCode bc,
uint32_t bcIndex, TR::Block *destinationBlock, TR_ResolvedMethod *feMethod,
TR::Compilation *comp)
{
TR::Node *node = TR::Node::createOnStack(NULL, convertBytecodeToIL(bc), 0);
TR::TreeTop *tree = TR::TreeTop::create(comp, node);
setupNode(node, bcIndex, feMethod, comp);
if (node->getOpCode().isBranch())
node->setBranchDestination(destinationBlock->getEntry());
currentBlock->append(tree);
}
//Partial Inlining
bool
TR_J9EstimateCodeSize::isInExceptionRange(TR_ResolvedMethod * feMethod,
int32_t bcIndex)
{
int32_t numExceptionRanges = feMethod->numberOfExceptionHandlers();
if (numExceptionRanges == 0)
return false;
int32_t start, end, catchtype;
for (int32_t i = 0; i < numExceptionRanges; i++)
{
feMethod->exceptionData(i, &start, &end, &catchtype);
if (bcIndex > start && bcIndex < end)
return true;
}
return false;
}
static bool cameFromArchetypeSpecimen(TR_ResolvedMethod *method)
{
if (!method)
return false; // end of recursion
else if (method->convertToMethod()->isArchetypeSpecimen())
return true; // Archetypes often call methods that are never called until the archetype is compiled
else
return cameFromArchetypeSpecimen(method->owningMethod());
}
bool
TR_J9EstimateCodeSize::adjustEstimateForStringCompression(TR_ResolvedMethod* method, int32_t& value, float factor)
{
const uint16_t classNameLength = method->classNameLength();
if ((classNameLength == 16 && !strncmp(method->classNameChars(), "java/lang/String", classNameLength)) ||
(classNameLength == 22 && !strncmp(method->classNameChars(), "java/lang/StringBuffer", classNameLength)) ||
(classNameLength == 23 && !strncmp(method->classNameChars(), "java/lang/StringBuilder", classNameLength)))
{
// A statistical analysis of the number of places certain methods got inlined yielded results which suggest that the
// following recognized methods incurr several percent worth of increase in compile-time at no benefit to throughput.
// As such we can save additional compile-time by not making adjustments to these methods.
if (method->getRecognizedMethod() != TR::java_lang_String_regionMatches &&
method->getRecognizedMethod() != TR::java_lang_String_regionMatches_bool &&
method->getRecognizedMethod() != TR::java_lang_String_equals)
{
value *= factor;
return true;
}
}
return false;
}
/** \details
* The `Method.invoke` API contains a call to `Reflect.getCallerClass()` API which when executed will trigger a
* stack walking operation. Performance wise this is quite expensive. The `Reflect.getCallerClass()` API returns
* the class of the method which called `Method.invoke`, so if we can promote inlining of `Method.invoke` we can
* eliminate the `Reflect.getCallerClass()` call with a simple load, thus avoiding the expensive stack walk.
*/
bool
TR_J9EstimateCodeSize::adjustEstimateForMethodInvoke(TR_ResolvedMethod* method, int32_t& value, float factor)
{
if (method->getRecognizedMethod() == TR::java_lang_reflect_Method_invoke)
{
static const char *factorOverrideChars = feGetEnv("TR_MethodInvokeInlinerFactor");
static const int32_t factorOverride = (factorOverrideChars != NULL) ? atoi(factorOverrideChars) : 0;
if (factorOverride != 0)
{
factor = 1.0f / static_cast<float>(factorOverride);
}
value *= factor;
return true;
}
return false;
}
bool
TR_J9EstimateCodeSize::adjustEstimateForConstArgs(TR_CallTarget * target, int32_t& value, float factor)
{
static const char * disableConstArgWeightReduction = feGetEnv("TR_disableConstArgWeightReduction");
if (disableConstArgWeightReduction || !target->_calleeSymbol)
return false;
// Weight adjustments performed for load consts or boxed primitive arg types can still be beneficial but
// may require a different adjustment factor.
static const char * enableLoadConstArgWeightAdjustment = feGetEnv("TR_enableLoadConstArgWeightAdjustment");
// Weight reduction by numArgs * 4 is done in TR_MultipleCallTargetInliner::applyArgumentHeuristics, but
// doing this adjustment this early can have a negative impact on performance in some workloads
static const char * enableArgCountWeightAdjustment = feGetEnv("TR_enableArgCountWeightAdjustment");
// This for remaining consistent with TR_MultipleCallTargetInliner::applyArgumentHeuristics
static const char * envKnownObjWeight = feGetEnv("TR_constClassWeight");
int32_t knownObjWeight = envKnownObjWeight ? atoi(envKnownObjWeight) : DEFAULT_KNOWN_OBJ_WEIGHT;
// The less aggressive adjustment factor, which is just the factor increased by 15% is
// intended to be used in cases where we can distinguish different degree of benefit
// to be had, with the original factor applied for the more beneficial cases, and the
// less aggressive factor being applied for the less beneficial cases.
float lessAggressiveAdjustmentFactor = factor * 1.15f;
int32_t originalWeight = value;
TR_LinkHead<TR_ParameterMapping> argMap;
TR_PrexArgInfo *prexArgInfo = target->_ecsPrexArgInfo;
if (((TR_J9InlinerPolicy *)_inliner->getPolicy())->validateArguments(target,argMap))
{
int32_t argIndex = 0;
for (TR_ParameterMapping* parm = argMap.getFirst(); parm; parm = parm->getNext())
{
int32_t interimWeight = value;
TR::Node * parmNode = parm->_parameterNode;
TR::ParameterSymbol * parmSym = parm->_parmSymbol;
const char * parmClassName = NULL;
int32_t parmClassNameLen = 0;
char * argClassName = NULL;
TR_PrexArgument * prexArg = NULL;
if (prexArgInfo) prexArg = prexArgInfo->get(argIndex++);
if (parmSym)
parmClassName = parmSym->getTypeSignature(parmClassNameLen);
if (prexArg && prexArg->getClass())
argClassName = TR::Compiler->cls.classSignature(comp(), prexArg->getClass(), comp()->trMemory());
if (parmNode->getOpCode().hasSymbolReference()
&& parmNode->getSymbolReference()->getSymbol()->isStatic()
&& parmNode->getSymbolReference()->getSymbol()->castToStaticSymbol()->isConstString())
{
value *= factor;
heuristicTrace(tracer(),"Setting size from %d to %d because arg is constant string.", interimWeight, value);
}
else if (argClassName
&& parmClassName
&& strncmp(argClassName, parmClassName, parmClassNameLen) != 0 // arg type needs to be more specific than declared type to benefit from weight adjustment
&& strcmp(argClassName, "Ljava/lang/String;") == 0)
{
value *= lessAggressiveAdjustmentFactor;
heuristicTrace(tracer(),"Setting size from %d to %d because arg is a string.", interimWeight, value);
}
else if (parmNode->getOpCodeValue() == TR::aload
&& parmNode->getSymbolReference()
&& parmNode->getSymbolReference()->getSymbol()->isConstObjectRef())
{
value *= factor;
heuristicTrace(tracer(),"Setting size from %d to %d because arg is const object ref.", interimWeight, value);
}
else if (parmNode->getOpCodeValue() == TR::aloadi
&& parmNode->getOpCode().hasSymbolReference()
&& parmNode->getSymbolReference() == comp()->getSymRefTab()->findJavaLangClassFromClassSymbolRef()
&& parmNode->getFirstChild()
&& parmNode->getFirstChild()->getOpCodeValue() == TR::loadaddr
&& parmNode->getFirstChild()->getSymbol()->isStatic()
&& !parmNode->getFirstChild()->getSymbolReference()->isUnresolved()
&& parmNode->getFirstChild()->getSymbol()->isClassObject())
{
value *= factor;
heuristicTrace(tracer(),"Setting size from %d to %d because arg is const class ref.", interimWeight, value);
}
else if (argClassName
&& parmClassName
&& strncmp(argClassName, parmClassName, parmClassNameLen) != 0
&& strcmp(argClassName, "Ljava/lang/Class;") == 0)
{
value *= lessAggressiveAdjustmentFactor;
heuristicTrace(tracer(),"Setting size from %d to %d because arg is a class ref.", interimWeight, value);
}
else if (enableLoadConstArgWeightAdjustment
&& parmNode->getOpCode().isLoadConst())
{
value *= factor;
heuristicTrace(tracer(),"Setting size from %d to %d because arg is load const.", interimWeight, value);
}
else if (enableLoadConstArgWeightAdjustment
&& argClassName
&& parmClassName
&& strncmp(argClassName, parmClassName, parmClassNameLen) != 0
&& (strcmp(argClassName, "Ljava/lang/Integer;") == 0
|| strcmp(argClassName, "Ljava/lang/Long;") == 0
|| strcmp(argClassName, "Ljava/lang/Byte;") == 0
|| strcmp(argClassName, "Ljava/lang/Double;") == 0
|| strcmp(argClassName, "Ljava/lang/Float;") == 0
|| strcmp(argClassName, "Ljava/lang/Short;") == 0
|| strcmp(argClassName, "Ljava/lang/Boolean;") == 0
|| strcmp(argClassName, "Ljava/lang/Character;") == 0))
{
value *= lessAggressiveAdjustmentFactor;
heuristicTrace(tracer(),"Setting size from %d to %d because arg is boxed primitive type.", interimWeight, value);
}
if (prexArg && prexArg->hasKnownObjectIndex())
{
value = knownObjWeight;
heuristicTrace(tracer(),"Setting size from %d to %d because arg is known object.", interimWeight, value);
break;
}
}
if (enableArgCountWeightAdjustment)
{
value -= (argMap.getSize() * 4);
heuristicTrace(tracer(),"Reduced size estimate to %d (subtract num args * 4)", value);
}
}
if (value < originalWeight)
return true;
else
return false;
}
bool
TR_J9EstimateCodeSize::estimateCodeSize(TR_CallTarget *calltarget, TR_CallStack *prevCallStack, bool recurseDown)
{
if (realEstimateCodeSize(calltarget, prevCallStack, recurseDown, comp()->trMemory()->currentStackRegion()))
{
if (_isLeaf && _realSize > 1)
{
heuristicTrace(tracer(),"Subtracting 1 from sizes because _isLeaf is true");
--_realSize;
--_analyzedSize;
}
return true;
}
return false;
}
TR::CFG&
TR_J9EstimateCodeSize::processBytecodeAndGenerateCFG(TR_CallTarget *calltarget, TR::Region &cfgRegion, TR_J9ByteCodeIterator& bci, NeedsPeekingHeuristic &nph, TR::Block** blocks, flags8_t * flags)
{
char nameBuffer[1024];
const char *callerName = NULL;
if (tracer()->heuristicLevel())
callerName = comp()->fej9()->sampleSignature(
calltarget->_calleeMethod->getPersistentIdentifier(), nameBuffer,
1024, comp()->trMemory());
int size = calltarget->_myCallSite->_isIndirectCall ? 5 : 0;
int32_t maxIndex = bci.maxByteCodeIndex() + 5;
int32_t *bcSizes = (int32_t *) comp()->trMemory()->allocateStackMemory(
maxIndex * sizeof(int32_t));
memset(bcSizes, 0, maxIndex * sizeof(int32_t));
bool blockStart = true;
bool thisOnStack = false;
bool hasThisCalls = false;
bool foundNewAllocation = false;
bool unresolvedSymbolsAreCold = comp()->notYetRunMeansCold();
TR_ByteCodeInfo newBCInfo;
newBCInfo.setDoNotProfile(0);
if (_mayHaveVirtualCallProfileInfo)
newBCInfo.setCallerIndex(comp()->getCurrentInlinedSiteIndex());
// PHASE 1: Bytecode Iteration
bool callExists = false;
size = calltarget->_myCallSite->_isIndirectCall ? 5 : 0;
TR_J9ByteCode bc = bci.first(), nextBC;
#if defined(J9VM_OPT_JITSERVER)
if (comp()->isOutOfProcessCompilation())
{
// JITServer optimization:
// request this resolved method to create all of its callee resolved methods
// in a single query.
//
// If the method is unresolved, return NULL for 2 requests without asking the client,
// since they are called almost immediately after this request and are unlikely to
// become resolved.
//
// NOTE: first request occurs in the for loop over bytecodes, immediately after this request,
// second request occurs in InterpreterEmulator::findAndCreateCallsitesFromBytecodes
auto calleeMethod = static_cast<TR_ResolvedJ9JITServerMethod *>(calltarget->_calleeMethod);
calleeMethod->cacheResolvedMethodsCallees(2);
}
#endif /* defined(J9VM_OPT_JITSERVER) */
for (; bc != J9BCunknown; bc = bci.next())
{
nph.processByteCode();
TR_ResolvedMethod * resolvedMethod;
int32_t cpIndex;
bool isVolatile, isPrivate, isUnresolvedInCP, resolved;
TR::DataType type = TR::NoType;
void * staticAddress;
uint32_t fieldOffset;
newBCInfo.setByteCodeIndex(bci.bcIndex());
int32_t i = bci.bcIndex();
if (blockStart) //&& calltarget->_calleeSymbol)
{
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::bbStart);
blockStart = false;
foundNewAllocation = false;
}
if (bc == J9BCgenericReturn ||
bc == J9BCReturnC ||
bc == J9BCReturnS ||
bc == J9BCReturnB ||
bc == J9BCReturnZ)
{
if (!calltarget->_calleeMethod->isSynchronized())
size += 1;
else
size += bci.estimatedCodeSize();
}
else
size += bci.estimatedCodeSize();
switch (bc)
{
case J9BCificmpeq:
case J9BCificmpne:
case J9BCificmplt:
case J9BCificmpge:
case J9BCificmpgt:
case J9BCificmple:
case J9BCifacmpeq:
case J9BCifacmpne:
case J9BCifnull:
case J9BCifnonnull:
case J9BCifeq:
case J9BCifne:
case J9BCiflt:
case J9BCifge:
case J9BCifgt:
case J9BCifle:
case J9BCgoto:
case J9BCgotow:
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isBranch);
flags[i + bci.relativeBranch()].set(InterpreterEmulator::BytecodePropertyFlag::bbStart);
blockStart = true;
break;
case J9BCReturnC:
case J9BCReturnS:
case J9BCReturnB:
case J9BCReturnZ:
case J9BCgenericReturn:
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isBranch);
blockStart = true;
break;
case J9BCnew:
case J9BCnewarray:
case J9BCanewarray:
case J9BCmultianewarray:
if (calltarget->_calleeSymbol)
foundNewAllocation = true;
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
case J9BCathrow:
_foundThrow = true;
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isBranch);
blockStart = true;
if (!_aggressivelyInlineThrows)
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isCold);
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
case J9BCtableswitch:
{
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isBranch);
int32_t index = bci.defaultTargetIndex();
flags[i + bci.nextSwitchValue(index)].set(InterpreterEmulator::BytecodePropertyFlag::bbStart);
int32_t low = bci.nextSwitchValue(index);
int32_t high = bci.nextSwitchValue(index) - low + 1;
for (int32_t j = 0; j < high; ++j)
flags[i + bci.nextSwitchValue(index)].set(InterpreterEmulator::BytecodePropertyFlag::bbStart);
blockStart = true;
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
}
case J9BClookupswitch:
{
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isBranch);
int32_t index = bci.defaultTargetIndex();
flags[i + bci.nextSwitchValue(index)].set(InterpreterEmulator::BytecodePropertyFlag::bbStart);
int32_t tableSize = bci.nextSwitchValue(index);
for (int32_t j = 0; j < tableSize; ++j)
{
index += 4; // match value
flags[i + bci.nextSwitchValue(index)].set(InterpreterEmulator::BytecodePropertyFlag::bbStart);
}
blockStart = true;
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
}
case J9BCinvokevirtual:
{
if (thisOnStack)
hasThisCalls = true;
cpIndex = bci.next2Bytes();
auto calleeMethod = (TR_ResolvedJ9Method*)calltarget->_calleeMethod;
resolvedMethod = calleeMethod->getResolvedPossiblyPrivateVirtualMethod(comp(), cpIndex, true, &isUnresolvedInCP);
if (resolvedMethod)
{
TR::RecognizedMethod rm = resolvedMethod->getRecognizedMethod();
if (rm == TR::java_util_HashMap_put ||
rm == TR::java_util_HashMap_get ||
rm == TR::java_lang_Object_hashCode)
{
nph.setNeedsPeekingToTrue();
heuristicTrace(tracer(), "Depth %d: invokevirtual call at bc index %d has Signature %s, enabled peeking for caller to propagate prex arg info from caller.", _recursionDepth, i, tracer()->traceSignature(resolvedMethod));
}
}
///if (!resolvedMethod || isUnresolvedInCP || resolvedMethod->isCold(comp(), true))
if ((isUnresolvedInCP && !resolvedMethod) || (resolvedMethod
&& resolvedMethod->isCold(comp(), true)))
{
if(tracer()->heuristicLevel())
{
if(resolvedMethod)
{
heuristicTrace(tracer(), "Depth %d: Call at bc index %d is Cold. Not searching for targets. Signature %s",_recursionDepth,i,tracer()->traceSignature(resolvedMethod));
}
else
{
TR::Method *meth = comp()->fej9()->createMethod(comp()->trMemory(), calltarget->_calleeMethod->containingClass(), cpIndex);
heuristicTrace(tracer(), "Depth %d: Call at bc index %d is Cold. Not searching for targets. Signature %s",_recursionDepth,i,tracer()->traceSignature(meth));
}
}
if (unresolvedSymbolsAreCold)
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isCold);
_isLeaf = false;
}
}
callExists = true;
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
case J9BCinvokespecial:
case J9BCinvokespecialsplit:
{
if (thisOnStack)
hasThisCalls = true;
cpIndex = bci.next2Bytes();
resolvedMethod = calltarget->_calleeMethod->getResolvedSpecialMethod(comp(), (bc == J9BCinvokespecialsplit)?cpIndex |= J9_SPECIAL_SPLIT_TABLE_INDEX_FLAG:cpIndex, &isUnresolvedInCP);
bool isIndirectCall = false;
bool isInterface = false;
TR::Method *interfaceMethod = 0;
TR::TreeTop *callNodeTreeTop = 0;
TR::Node *parent = 0;
TR::Node *callNode = 0;
TR::ResolvedMethodSymbol *resolvedSymbol = 0;
if (!resolvedMethod || isUnresolvedInCP || resolvedMethod->isCold(comp(), false))
{
if(tracer()->heuristicLevel())
{
if(resolvedMethod)
{
heuristicTrace(tracer(), "Depth %d: Call at bc index %d is Cold. Not searching for targets. Signature %s",_recursionDepth,i,tracer()->traceSignature(resolvedMethod));
}
else
{
if (bc == J9BCinvokespecialsplit)
cpIndex |= J9_SPECIAL_SPLIT_TABLE_INDEX_FLAG;
TR::Method *meth = comp()->fej9()->createMethod(comp()->trMemory(), calltarget->_calleeMethod->containingClass(), cpIndex);
heuristicTrace(tracer(), "Depth %d: Call at bc index %d is Cold. Not searching for targets. Signature %s",_recursionDepth,i,tracer()->traceSignature(meth));
}
}
if (unresolvedSymbolsAreCold)
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isCold);
_isLeaf = false;
}
}
callExists = true;
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
case J9BCinvokestatic:
case J9BCinvokestaticsplit:
{
cpIndex = bci.next2Bytes();
resolvedMethod = calltarget->_calleeMethod->getResolvedStaticMethod(comp(), (bc == J9BCinvokestaticsplit)?cpIndex |= J9_STATIC_SPLIT_TABLE_INDEX_FLAG:cpIndex, &isUnresolvedInCP);
bool isIndirectCall = false;
bool isInterface = false;
TR::Method *interfaceMethod = 0;
TR::TreeTop *callNodeTreeTop = 0;
TR::Node *parent = 0;
TR::Node *callNode = 0;
TR::ResolvedMethodSymbol *resolvedSymbol = 0;
if (resolvedMethod &&
resolvedMethod->getRecognizedMethod() == TR::java_util_HashMap_hash)
{
nph.setNeedsPeekingToTrue();
heuristicTrace(tracer(), "Depth %d: invokestatic call at bc index %d has Signature %s, enabled peeking for caller to propagate prex arg info from caller.", _recursionDepth, i, tracer()->traceSignature(resolvedMethod));
}
if (!resolvedMethod || isUnresolvedInCP || resolvedMethod->isCold(comp(), false))
{
if (unresolvedSymbolsAreCold)
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isCold);
if(tracer()->heuristicLevel())
{
if(resolvedMethod)
heuristicTrace(tracer(), "Depth %d: Call at bc index %d is Cold. Not searching for targets. Signature %s",_recursionDepth,i,tracer()->traceSignature(resolvedMethod));
else
{
if (bc == J9BCinvokestaticsplit)
cpIndex |= J9_STATIC_SPLIT_TABLE_INDEX_FLAG;
TR::Method *meth = comp()->fej9()->createMethod(comp()->trMemory(), calltarget->_calleeMethod->containingClass(), cpIndex);
heuristicTrace(tracer(), "Depth %d: Call at bc index %d is Cold. Not searching for targets. Signature %s",_recursionDepth,i,tracer()->traceSignature(meth));
}
}
}
}
callExists = true;
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
case J9BCinvokeinterface:
{
cpIndex = bci.next2Bytes();
TR::Method *meth = comp()->fej9()->createMethod(comp()->trMemory(), calltarget->_calleeMethod->containingClass(), cpIndex);
if (meth)
{
const char * sig = meth->signature(comp()->trMemory());
if (sig && (!strncmp(sig, "java/util/Map.put", 17) || !strncmp(sig, "java/util/Map.get", 17)))
{
nph.setNeedsPeekingToTrue();
heuristicTrace(tracer(), "Depth %d: invokeinterface call at bc index %d has Signature %s, enabled peeking for caller to propagate prex arg info from caller.", _recursionDepth, i, sig);
}
#if JAVA_SPEC_VERSION >= 21
else if (sig && (!strncmp(sig, "java/lang/foreign/MemorySegment.get", 35) || !strncmp(sig, "java/lang/foreign/MemorySegment.set", 35) ))
{
nph.setNeedsPeekingToTrue();
heuristicTrace(tracer(), "Depth %d: invokeinterface call at bc index %d has Signature %s, enabled peeking for caller to fold layout field load necessary for VarHandle operation inlining.", _recursionDepth, i, sig);
}
#endif // JAVA_SPEC_VERSION >= 21
}
}
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
case J9BCgetfield:
resolved = calltarget->_calleeMethod->fieldAttributes(comp(), bci.next2Bytes(), &fieldOffset, &type, &isVolatile, 0, &isPrivate, false, &isUnresolvedInCP, false);
if (!resolved || isUnresolvedInCP)
{
if (unresolvedSymbolsAreCold)
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isCold);
if (!resolved)
_isLeaf = false;
}
if (isInExceptionRange(calltarget->_calleeMethod, i))
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
case J9BCputfield:
resolved = calltarget->_calleeMethod->fieldAttributes(comp(), bci.next2Bytes(), &fieldOffset, &type, &isVolatile, 0, &isPrivate, true, &isUnresolvedInCP, false);
if (!resolved || isUnresolvedInCP)
{
if (unresolvedSymbolsAreCold)
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isCold);
if (!resolved)
_isLeaf = false;
}
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
case J9BCgetstatic:
resolved = calltarget->_calleeMethod->staticAttributes(comp(), bci.next2Bytes(), &staticAddress, &type, &isVolatile, 0, &isPrivate, false, &isUnresolvedInCP, false);
if (!resolved || isUnresolvedInCP)
{
if (unresolvedSymbolsAreCold)
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isCold);
if (!resolved)
_isLeaf = false;
}
if (isInExceptionRange(calltarget->_calleeMethod, i))
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
case J9BCputstatic:
resolved = calltarget->_calleeMethod->staticAttributes(comp(), bci.next2Bytes(), &staticAddress, &type, &isVolatile, 0, &isPrivate, true, &isUnresolvedInCP, false);
if (!resolved || isUnresolvedInCP)
{
if (unresolvedSymbolsAreCold)
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isCold);
if (!resolved)
_isLeaf = false;
}
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
case J9BCaload0:
if (calltarget->_myCallSite->_isIndirectCall)
thisOnStack = true;
break;
case J9BCiastore:
case J9BClastore:
case J9BCfastore:
case J9BCdastore:
case J9BCaastore:
case J9BCbastore:
case J9BCcastore:
case J9BCsastore: //array stores can change the global state - hence unsanitizeable
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
case J9BCiaload:
case J9BClaload:
case J9BCfaload:
case J9BCdaload:
case J9BCaaload:
case J9BCbaload:
case J9BCcaload:
case J9BCsaload:
case J9BCarraylength: //array accesses are ok as long as we don't catch exception
case J9BCidiv:
case J9BCldiv:
case J9BCfdiv:
case J9BCddiv:
case J9BCirem:
case J9BClrem:
case J9BCfrem:
case J9BCdrem:
case J9BCcheckcast:
case J9BCinstanceof:
case J9BCasyncCheck:
if (isInExceptionRange(calltarget->_calleeMethod, i))
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
case J9BCinvokedynamic:
case J9BCinvokehandle:
case J9BCinvokehandlegeneric:
// TODO:JSR292: Use getResolvedHandleMethod
case J9BCmonitorenter:
case J9BCmonitorexit:
case J9BCunknown:
flags[i].set(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable);
break;
default:
break;
}
if (flags[i].testAny(InterpreterEmulator::BytecodePropertyFlag::isUnsanitizeable))
debugTrace(tracer(),"BC at index %d is unsanitizeable.", i);
else if (flags[i].testAny(InterpreterEmulator::BytecodePropertyFlag::isCold))
debugTrace(tracer(),"BC at index %d is cold.", i);
else
debugTrace(tracer(),"BC iteration at index %d.", i); //only print this index if we are debugging
bcSizes[i] = size;
}
auto sizeBeforeAdjustment = size;
if (adjustEstimateForStringCompression(calltarget->_calleeMethod, size, STRING_COMPRESSION_ADJUSTMENT_FACTOR))
{
heuristicTrace(tracer(), "*** Depth %d: Adjusting size for %s because of string compression from %d to %d", _recursionDepth, callerName, sizeBeforeAdjustment, size);
}