-
Notifications
You must be signed in to change notification settings - Fork 746
/
Copy pathIlGenerator.cpp
3363 lines (2944 loc) · 140 KB
/
IlGenerator.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 "codegen/CodeGenerator.hpp"
#include "compile/InlineBlock.hpp"
#include "compile/Method.hpp"
#include "compile/ResolvedMethod.hpp"
#include "control/Recompilation.hpp"
#include "control/RecompilationInfo.hpp"
#include "env/PersistentCHTable.hpp"
#include "env/CompilerEnv.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/ParameterSymbol.hpp"
#include "il/TreeTop.hpp"
#include "il/TreeTop_inlines.hpp"
#include "ilgen/IlGeneratorMethodDetails_inlines.hpp"
#include "infra/Cfg.hpp"
#include "infra/Checklist.hpp"
#include "infra/String.hpp"
#include "env/VMJ9.h"
#include "ilgen/J9ByteCodeIlGenerator.hpp"
#include "optimizer/BoolArrayStoreTransformer.hpp"
#include "ras/DebugCounter.hpp"
#include "optimizer/TransformUtil.hpp"
#include "env/JSR292Methods.h"
#define OPT_DETAILS "O^O ILGEN: "
TR_J9ByteCodeIlGenerator::TR_J9ByteCodeIlGenerator(
TR::IlGeneratorMethodDetails & methodDetails, TR::ResolvedMethodSymbol * methodSymbol, TR_J9VMBase * fe, TR::Compilation * comp,
TR::SymbolReferenceTable * symRefTab, bool forceClassLookahead, TR_InlineBlocks *blocksToInline, int32_t argPlaceholderSlot) //TR_ScratchList<TR_InlineBlock> *blocksToInline)
: TR_J9ByteCodeIteratorWithState(methodSymbol, fe, comp),
_methodDetails(methodDetails),
_symRefTab(symRefTab),
_classLookaheadSymRefTab(NULL),
_blockAddedVisitCount(comp->incVisitCount()),
_generateWriteBarriersForGC(TR::Compiler->om.writeBarrierType() != gc_modron_wrtbar_none),
_generateWriteBarriersForFieldWatch(comp->getOption(TR_EnableFieldWatch)),
_generateReadBarriersForFieldWatch(comp->getOption(TR_EnableFieldWatch)),
_suppressSpineChecks(false),
_implicitMonitorExits(comp->trMemory()),
_finalizeCallsBeforeReturns(comp->trMemory()),
_classInfo(0),
_blocksToInline(blocksToInline),
_argPlaceholderSlot(argPlaceholderSlot),
_intrinsicErrorHandling(0),
_invokeSpecialInterface(NULL),
_invokeSpecialInterfaceCalls(NULL),
_invokeSpecialSeen(false),
_couldOSRAtNextBC(false),
_processedOSRNodes(NULL),
_invokeHandleCalls(NULL),
_invokeHandleGenericCalls(NULL),
_invokeDynamicCalls(NULL),
_ilGenMacroInvokeExactCalls(NULL),
_methodHandleInvokeCalls(NULL),
_requiredConsts(
(
comp->currentILGenCallTarget() == NULL
|| comp->currentILGenCallTarget()->_requiredConsts.empty()
)
? NULL
: &comp->currentILGenCallTarget()->_requiredConsts),
_foldedRequiredConsts(NULL)
{
static const char *noLookahead = feGetEnv("TR_noLookahead");
_noLookahead = (noLookahead || comp->getOption(TR_DisableLookahead)) ? true : false;
_thisChanged = false;
if (
(forceClassLookahead ||
(comp->getNeedsClassLookahead() && !_noLookahead &&
((comp->getMethodHotness() >= scorching) ||
(comp->couldBeRecompiled() && (comp->getMethodHotness() >= hot ))))))
{
bool allowForAOT = comp->getOption(TR_UseSymbolValidationManager);
_classInfo = comp->getPersistentInfo()->getPersistentCHTable()->findClassInfoAfterLocking(method()->containingClass(), comp, allowForAOT);
}
else
{
if (!comp->getOption(TR_PerformLookaheadAtWarmCold))
_noLookahead = true;
}
if (argPlaceholderSlot == -1)
{
_argPlaceholderSignatureOffset = 0xdead1127;
}
else
{
// Compute _argPlaceholderSignatureOffset
//
char *signatureChars = _methodSymbol->getResolvedMethod()->signatureChars();
TR_ASSERT(*signatureChars = '(', "assertion failure");
char *curArg = signatureChars+1;
int32_t argSlotsSkipped = methodSymbol->isStatic()? 0 : 1; // receiver doesn't appear in the signature
while (argSlotsSkipped < argPlaceholderSlot)
{
switch (*curArg)
{
case 'D':
case 'J':
argSlotsSkipped += 2;
break;
default:
argSlotsSkipped += 1;
break;
}
curArg = nextSignatureArgument(curArg);
}
_argPlaceholderSignatureOffset = curArg - signatureChars;
}
for( int i=0 ; i < _numDecFormatRenames ; i++ )
{
_decFormatRenamesDstSymRef[i] = NULL;
}
if (comp->getOption(TR_EnableOSR)
&& !comp->isPeekingMethod()
&& comp->isOSRTransitionTarget(TR::postExecutionOSR)
&& !_cannotAttemptOSR)
_processedOSRNodes = new (trStackMemory()) TR::NodeChecklist(comp);
}
bool
TR_J9ByteCodeIlGenerator::genIL()
{
if (comp()->isOutermostMethod())
comp()->reportILGeneratorPhase();
TR::StackMemoryRegion stackMemoryRegion(*trMemory());
if (_requiredConsts != NULL)
{
_foldedRequiredConsts =
new (stackMemoryRegion) TR::set<int32_t>(stackMemoryRegion);
}
comp()->setCurrentIlGenerator(this);
bool success = internalGenIL();
if (success && _requiredConsts != NULL)
assertFoldedAllRequiredConsts();
if (success && !comp()->isPeekingMethod())
{
TR_SharedCache *sc = fej9()->sharedCache();
if (sc)
{
/*
* if DelayRelocationForAOT don't persist iprofiler info now.
* instead, persist iprofiler info when loading the aot compilation
*/
if (comp()->getOption(TR_DisableDelayRelocationForAOTCompilations) || !fej9()->shouldDelayAotLoad())
{
sc->persistIprofileInfo(_methodSymbol->getResolvedMethodSymbol(), comp());
}
}
}
/*
* If we're generating IL for DecimalformatHelper.formatAsDouble(Float), replace
* the necessary fields, statics, and methods appropriately. This is part of
* the optimization that replaces df.format(bd.doubleValue()) and
* df.format(bd.floatValue()) with, respectively,
* DecimalFormatHelper.formatAsDouble(df, bd) and
* DecimalFormatHelper.formatAsFloat(df, bd) in which bd is a BigDecimal object
* and df is DecimalFormat object. The latter pair of calls are much faster than
* the former ones because it avoids many of the conversions that the former
* performs.
*/
if (success)
{
const char* methodName = _methodSymbol->signature(comp()->trMemory());
if (!strcmp(methodName, "com/ibm/jit/DecimalFormatHelper.formatAsDouble(Ljava/text/DecimalFormat;Ljava/math/BigDecimal;)Ljava/lang/String;") ||
!strcmp(methodName, "com/ibm/jit/DecimalFormatHelper.formatAsFloat(Ljava/text/DecimalFormat;Ljava/math/BigDecimal;)Ljava/lang/String;"))
success = success && replaceMembersOfFormat();
}
if (success && !comp()->isPeekingMethod())
{
_methodSymbol->clearProfilingOffsetInfo();
for (TR::Block *block = _methodSymbol->getFirstTreeTop()->getEnclosingBlock(); block; block = block->getNextBlock())
_methodSymbol->addProfilingOffsetInfo(block->getEntry()->getNode()->getByteCodeIndex(), block->getExit()->getNode()->getByteCodeIndex());
}
comp()->setCurrentIlGenerator(0);
return success;
}
void TR_J9ByteCodeIlGenerator::assertFoldedAllRequiredConsts()
{
// The elements of _foldedRequiredConsts should be identical to the
// keys of _requiredConsts corresponding to bytecode indices for which IL
// was generated.
bool ok = true;
// Iteration should produce the same sequence (after ignoring ungenerated
// bytecode) because both containers are maintained in sorted order.
auto itF = _foldedRequiredConsts->begin();
auto endF = _foldedRequiredConsts->end();
auto itR = _requiredConsts->begin();
auto endR = _requiredConsts->end();
while (itF != endF && itR != endR)
{
if (!isGenerated(itR->first))
{
itR++;
continue;
}
if (*itF != itR->first)
{
ok = false;
break;
}
itF++;
itR++;
}
while (itR != endR && !isGenerated(itR->first))
itR++;
if (ok && itF == endF && itR == endR)
return; // all good
// mismatch
TR::StringBuf msg(comp()->trMemory()->currentStackRegion());
msg.appendf("Required constants bytecode index set mismatch:\n");
msg.appendf("Expected: ");
bool first = true;
for (itR = _requiredConsts->begin(); itR != endR; itR++)
{
if (!isGenerated(itR->first))
continue;
msg.appendf("%s%d", first ? "" : ", ", itR->first);
}
msg.appendf("\nFolded : ");
if (_foldedRequiredConsts->empty())
{
msg.appendf("(none)");
}
else
{
first = true;
for (itF = _foldedRequiredConsts->begin(); itF != endF; itF++)
msg.appendf("%s%d", first ? "" : ", ", *itF);
}
msg.appendf("\ninline call stack:");
char sigBuf[256];
int32_t atBcIndex = -1;
int32_t siteIndex = comp()->getCurrentInlinedSiteIndex();
while (siteIndex >= 0)
{
TR_InlinedCallSite &ics = comp()->getInlinedCallSite(siteIndex);
TR_ByteCodeInfo bci = ics._byteCodeInfo;
msg.appendf("\n");
if (atBcIndex >= 0)
msg.appendf("at %d ", atBcIndex);
const char *sig = fe()->sampleSignature(
ics._methodInfo, sigBuf, sizeof(sigBuf), comp()->trMemory());
msg.appendf("in %s", sig);
atBcIndex = ics._byteCodeInfo.getByteCodeIndex();
siteIndex = ics._byteCodeInfo.getCallerIndex();
}
msg.appendf("\nat %d in %s", atBcIndex, comp()->signature());
TR_ASSERT_FATAL(false, "%s", msg.text());
}
bool TR_J9ByteCodeIlGenerator::internalGenIL()
{
_stack = new (trStackMemory()) TR_Stack<TR::Node *>(trMemory(), 20, false, stackAlloc);
bool success = false;
if ((method()->isNewInstanceImplThunk() || debug("testGenNewInstanceImplThunk")))
{
success = genNewInstanceImplThunk();
if (!success) // must jit the body (throw instantiation exception)
success = genILFromByteCodes();
else if (comp()->getOption(TR_EnableOSR) && !comp()->isPeekingMethod() && !comp()->getOption(TR_FullSpeedDebug))
_methodSymbol->setCannotAttemptOSR(0);
return success;
}
TR::RecognizedMethod recognizedMethod = _methodSymbol->getRecognizedMethod();
if (recognizedMethod != TR::unknownMethod)
{
if (recognizedMethod == TR::com_ibm_jit_JITHelpers_supportsIntrinsicCaseConversion && !TR::Compiler->om.canGenerateArraylets())
{
if (performTransformation(comp(), "O^O IlGenerator: Generate com/ibm/jit/JITHelpers.supportsIntrinsicCaseConversion\n"))
{
genHWOptimizedStrProcessingAvailable();
return true;
}
}
if (recognizedMethod == TR::com_ibm_dataaccess_DecimalData_JITIntrinsicsEnabled)
{
if (performTransformation(comp(), "O^O IlGenerator: Generate com/ibm/dataaccess/DecimalData.JITIntrinsicsEnabled\n"))
{
genJITIntrinsicsEnabled();
return true;
}
}
if (recognizedMethod == TR::com_ibm_rmi_io_FastPathForCollocated_isVMDeepCopySupported)
{
if (performTransformation(comp(), "O^O IlGenerator: Generate com/ibm/rmi/io/FastPathForCollocated/isVMDeepCopySupported\n"))
{
genIsORBDeepCopyAvailable();
return true;
}
}
if (!comp()->getOption(TR_DisableInliningOfNatives))
{
// If we're inlining then there are some stack walking routines that can be made faster
// by avoiding the stack walk.
//
TR_ResolvedMethod * caller1 = method()->owningMethod();
TR_ResolvedMethod * caller = caller1 ? caller1->owningMethod() : 0;
if( caller && caller1)
{
TR_OpaqueClassBlock *callerClass = caller ? caller->classOfMethod() : 0;
TR_OpaqueClassBlock *callerClass1 = caller1 ? caller1->classOfMethod() : 0;
bool doIt = !(fej9()->stackWalkerMaySkipFrames(caller->getPersistentIdentifier(),callerClass) ||
fej9()->stackWalkerMaySkipFrames(caller1->getPersistentIdentifier(),callerClass1));
if (doIt && !comp()->compileRelocatableCode())
{
if (recognizedMethod == TR::java_lang_ClassLoader_callerClassLoader)
{
createGeneratedFirstBlock();
// check for bootstrap classloader, if so
// return null (see semantics of ClassLoader.callerClassLoader())
//
if (fej9()->isClassLoadedBySystemClassLoader(caller->classOfMethod()))
{
loadConstant(TR::aconst, (void *)0);
}
else
{
loadSymbol(TR::aload, symRefTab()->findOrCreateClassLoaderSymbolRef(caller));
}
genTreeTop(TR::Node::create(method()->returnOpCode(), 1, pop()));
return true;
}
if (recognizedMethod == TR::com_ibm_oti_vm_VM_callerClass)
{
createGeneratedFirstBlock();
loadConstant(TR::aconst, caller->classOfMethod());
genTreeTop(TR::Node::create(method()->returnOpCode(), 1, pop()));
return true;
}
}
}
}
}
if (method()->isJNINative())
return genJNIIL();
return genILFromByteCodes();
}
bool
TR_J9ByteCodeIlGenerator::genILFromByteCodes()
{
// first passthrough of the byte code to see if this pointer has been changed
if (isThisChanged())
_thisChanged = true;
initialize();
// don't go peeking into massive methods
if (comp()->isPeekingMethod() && _maxByteCodeIndex >= USHRT_MAX/8)
return false;
// FSD sync object support
//
// Ideally, I'd like the sync object in FSD to work exactly as it does in the interpreter.
// This means that the sync object (receiver for instance methods, declaring class for
// static methods) is always stored in synthetic local N+1 after the stack frame is built,
// and is re-read from memory before use in the method monitor exit. If it's a lot of trouble
// to place it at N+1, the decompiler can read it from somewhere else as long as you can point me there
// via the metadata. Whatever slot is used, it must be marked as a GC reference even when it is a class.
// If we eventually support hot code replace which does not flush the JIT code caches, we'll
// need to do some more work for static methods, since the class sync object in static sync frames must always be the "current" class.
//
if (_methodSymbol->isSynchronised())
{
if (comp()->getOption(TR_FullSpeedDebug) || !comp()->getOption(TR_DisableLiveMonitorMetadata))
{
TR::SymbolReference * symRef;
if (comp()->getOption(TR_FullSpeedDebug))
symRef = symRefTab()->findOrCreateAutoSymbol(_methodSymbol, _methodSymbol->getSyncObjectTempIndex(), TR::Address);
else
symRef = symRefTab()->createTemporary(_methodSymbol, TR::Address);
_methodSymbol->setSyncObjectTemp(symRef);
if (!comp()->getOption(TR_DisableLiveMonitorMetadata))
{
symRef->setHoldsMonitoredObjectForSyncMethod();
comp()->addAsMonitorAuto(symRef, true);
}
}
}
if (_methodSymbol->getResolvedMethod()->isNonEmptyObjectConstructor())
{
if (comp()->getOption(TR_FullSpeedDebug))
{
TR::SymbolReference *symRef = symRefTab()->findOrCreateAutoSymbol(_methodSymbol, _methodSymbol->getThisTempForObjectCtorIndex(), TR::Address);
_methodSymbol->setThisTempForObjectCtor(symRef);
symRef->getSymbol()->setThisTempForObjectCtor();
}
}
// Allocate zero-length bit vectors before walker so that the bit vectors can grow on the right
// stack memory region
//
_methodHandleInvokeCalls = new (trStackMemory()) TR_BitVector(0, trMemory(), stackAlloc, growable);
_invokeHandleCalls = new (trStackMemory()) TR_BitVector(0, trMemory(), stackAlloc, growable);
_invokeHandleGenericCalls = new (trStackMemory()) TR_BitVector(0, trMemory(), stackAlloc, growable);
_invokeDynamicCalls = new (trStackMemory()) TR_BitVector(0, trMemory(), stackAlloc, growable);
_ilGenMacroInvokeExactCalls = new (trStackMemory()) TR_BitVector(0, trMemory(), stackAlloc, growable);
TR::Block * lastBlock = walker(0);
if (hasExceptionHandlers())
{
_methodSymbol->setHasExceptionHandlers();
lastBlock = genExceptionHandlers(lastBlock);
}
_bcIndex = 0;
_methodSymbol->setFirstTreeTop(blocks(0)->getEntry());
if (inliningCheckIfFinalizeObjectIsBeneficial())
{
inlineJitCheckIfFinalizeObject(blocks(0));
}
prependEntryCode(blocks(0));
if (!comp()->getOption(TR_DisableGuardedCountingRecompilations) &&
comp()->getRecompilationInfo() && comp()->getRecompilationInfo()->shouldBeCompiledAgain() &&
!comp()->getRecompilationInfo()->isRecompilation() && // only do it for first time compilations
(!comp()->getPersistentInfo()->_countForRecompile || comp()->getOption(TR_EnableMultipleGCRPeriods)) &&
comp()->isOutermostMethod() &&
comp()->getOptions()->getInsertGCRTrees() &&
!comp()->isDLT() && !method()->isJNINative())
{
// GCR filtering: Do not insert GCR trees for methods that are small and have no calls
// This code is better suited for CompilationThread.cpp
// but we need support from VM to tell us that a method has calls
if (_methodSymbol->mayHaveInlineableCall() ||
// Possible tweak: increase the threshold for methods that do not have loops
_maxByteCodeIndex > TR::Options::_smallMethodBytecodeSizeThresholdForCold ||
_methodSymbol->mayHaveLoops())
{
prependGuardedCountForRecompilation(comp()->getStartTree()->getNode()->getBlock());
comp()->getOptimizationPlan()->resetAddToUpgradeQueue(); // do not add to upgrade queue methods for which we used GCR
// stats
comp()->getPersistentInfo()->incNumGCRBodies();
}
else
{
//TR_VerboseLog::writeLineLocked(TR_Vlog_PERF,"Saved a GCR gen body nmayHaveInlineableCall=%d mayHaveLoops=%d _maxByteCodeIndex=%d", _methodSymbol->mayHaveInlineableCall(), _methodSymbol->mayHaveLoops(), _maxByteCodeIndex);
// stats
comp()->getPersistentInfo()->incNumGCRSaves();
}
}
// Logic related to SamplingJProfiling
//
if (comp()->isOutermostMethod() && // Only do it once for the method to be compiled
!comp()->getOptions()->isDisabled(OMR::samplingJProfiling)) // If heuristic enabled samplingJProfiling for this body
{
// Verify that the GCR logic above actually inserted GCR trees
// or that this is a DLT body
// Also verify that method has bytecodes we want to profile (invokes/checkcasts/branches)
//
if ((comp()->isDLT() || (comp()->getRecompilationInfo() &&
comp()->getRecompilationInfo()->getJittedBodyInfo()->getUsesGCR()))
&& (_methodSymbol->mayHaveInlineableCall()
|| _methodSymbol->hasCheckcastsOrInstanceOfs()
|| _methodSymbol->hasBranches())
)
{
// Disable inlining to compile fast and avoid the bug with not profiling on the fast path
comp()->getOptions()->setDisabled(OMR::inlining, true);
}
else // Canot profile or there is nothing to profile; take corrective actions
{
// Disable the samplingJProfiling opt
comp()->getOptions()->setDisabled(OMR::samplingJProfiling, true);
// If the opt level was reduced to cold solely because we wanted
// to do samplingJProfiling then we must move the opt level back to warm
if (comp()->getOptimizationPlan()->isDowngradedDueToSamplingJProfiling())
{
comp()->changeOptLevel(warm);
comp()->getOptimizationPlan()->setDowngradedDueToSamplingJProfiling(false);
comp()->getOptimizationPlan()->setOptLevelDowngraded(false);
}
}
}
// Code pertaining to the secondary/upgrade compilation queue
// If the method is small, doesn't have loops or calls, then do not try to upgrade it
if (comp()->isOutermostMethod() && comp()->getOptimizationPlan()->shouldAddToUpgradeQueue())
{
if (!_methodSymbol->mayHaveInlineableCall() && !_methodSymbol->mayHaveLoops() &&
_maxByteCodeIndex <= TR::Options::_smallMethodBytecodeSizeThresholdForCold)
comp()->getOptimizationPlan()->resetAddToUpgradeQueue();
}
// the optimizer assumes that the ilGenerator doesn't gen code for
// unreachable blocks. An exception handler may be unreachable.
//
if (hasExceptionHandlers())
cfg()->removeUnreachableBlocks();
int32_t fpIndex = hasFPU() ? -1 : findFloatingPointInstruction();
if (fpIndex != -1) _unimplementedOpcode = _code[fpIndex];
if (_unimplementedOpcode)
{
_methodSymbol->setUnimplementedOpcode(_unimplementedOpcode);
if (debug("traceInfo"))
{
if (_unimplementedOpcode == 255)
diagnostic("\nUnimplemented opcodes found\n");
else
diagnostic("\nUnimplemented opcode found: %s(%d)\n",
((TR_J9VM *)fej9())->getByteCodeName(_unimplementedOpcode), _unimplementedOpcode);
}
if (!debug("continueWithUnimplementedOpCode"))
return false;
}
//if (!_thisChanged)
//setThisNonNullProperty(_methodSymbol->getFirstTreeTop(), comp());
bool needMonitor = _methodSymbol->isSynchronised() && !comp()->getOption(TR_DisableLiveMonitorMetadata);
int32_t numMonents = 0;
int32_t numMonexits = 0;
bool primitive = true;
TR::TreeTop *monentStore = NULL;
TR::TreeTop *monexitStore = NULL;
TR::Node *monentTree = NULL;
TR::Node *monexitTree = NULL;
TR::TreeTop *currTree = _methodSymbol->getFirstTreeTop()->getNextTreeTop();
List<TR::SymbolReference> autoOrParmSymRefList(comp()->trMemory());
TR_ScratchList<TR::TreeTop> unresolvedCheckcastTopsNeedingNullGuard(comp()->trMemory());
TR_ScratchList<TR::TreeTop> unresolvedInstanceofTops(comp()->trMemory());
TR_ScratchList<TR::TreeTop> invokeSpecialInterfaceTops(comp()->trMemory());
TR::NodeChecklist evaluatedInvokeSpecialCalls(comp());
TR::NodeChecklist evaluatedMethodHandleInvokeCalls(comp());
TR_BoolArrayStoreTransformer::NodeSet bstoreiUnknownArrayTypeNodes(std::less<TR::Node *>(), comp()->trMemory()->currentStackRegion());
TR_BoolArrayStoreTransformer::NodeSet bstoreiBoolArrayTypeNodes(std::less<TR::Node *>(), comp()->trMemory()->currentStackRegion());
TR_BoolArrayStoreTransformer boolArrayStoreTransformer(&bstoreiUnknownArrayTypeNodes, &bstoreiBoolArrayTypeNodes);
for (; currTree != NULL; currTree = currTree->getNextTreeTop())
{
TR::Node *currNode = currTree->getNode();
TR::ILOpCode opcode = currNode->getOpCode();
if (currNode->getNumChildren() >= 1
&& currNode->getFirstChild()->getOpCode().isCall()
&& !currNode->getFirstChild()->getSymbol()->castToMethodSymbol()->isHelper()
&& _methodHandleInvokeCalls->isSet(currNode->getFirstChild()->getByteCodeIndex())
&& !evaluatedMethodHandleInvokeCalls.contains(currNode->getFirstChild()))
{
expandMethodHandleInvokeCall(currTree);
evaluatedMethodHandleInvokeCalls.add(currNode->getFirstChild());
continue;
}
if ((opcode.isStoreDirect() && opcode.hasSymbolReference() && currNode->getSymbolReference()->getSymbol()->isAutoOrParm()) ||
opcode.isCheckCast())
{
TR::SymbolReference *symRef = currNode->getSymbolReference();
TR::Node *typeNode = NULL;
if (opcode.isStoreDirect())
typeNode = currNode->getFirstChild(); // store auto
else typeNode = currNode->getSecondChild(); // checkcast
if (boolArrayStoreTransformer.isAnyDimensionBoolArrayNode(typeNode))
boolArrayStoreTransformer.setHasBoolArrayAutoOrCheckCast();
else if (boolArrayStoreTransformer.isAnyDimensionByteArrayNode(typeNode))
boolArrayStoreTransformer.setHasByteArrayAutoOrCheckCast();
if (opcode.isStoreDirect() && symRef->getSymbol()->isParm() && currNode->getDataType() == TR::Address)
{
int lhsLength;
int rhsLength;
const char *lhsSig = currNode->getTypeSignature(lhsLength, stackAlloc, false /* parmAsAuto */);
const char *rhsSig = typeNode->getTypeSignature(rhsLength, stackAlloc, true /* parmAsAuto */);
if (!lhsSig || !rhsSig || lhsLength != rhsLength || strncmp(lhsSig, rhsSig, lhsLength))
boolArrayStoreTransformer.setHasVariantArgs();
}
}
else if (opcode.getOpCodeValue() == TR::bstorei && currNode->getSymbolReference()->getCPIndex() == -1
&& currNode->getFirstChild()->isInternalPointer())
{
TR::Node *arrayBase = currNode->getFirstChild()->getFirstChild();
if (arrayBase->getOpCode().hasSymbolReference())
{
if (boolArrayStoreTransformer.isBoolArrayNode(arrayBase))
{
if (comp()->getOption(TR_TraceILGen))
traceMsg(comp(), "bstorei node n%dn is bool array store\n", currNode->getGlobalIndex());
bstoreiBoolArrayTypeNodes.insert(currNode);
}
else if (!boolArrayStoreTransformer.isByteArrayNode(arrayBase))
bstoreiUnknownArrayTypeNodes.insert(currNode);
}
else
bstoreiUnknownArrayTypeNodes.insert(currNode);
}
if (currNode->getOpCodeValue() == TR::checkcast
&& currNode->getSecondChild()->getOpCodeValue() == TR::loadaddr
&& currNode->getSecondChild()->getSymbolReference()->isUnresolved())
{
unresolvedCheckcastTopsNeedingNullGuard.add(currTree);
}
else if (currNode->getOpCodeValue() == TR::treetop
&& currNode->getFirstChild()->getOpCodeValue() == TR::instanceof
&& currNode->getFirstChild()->getSecondChild()->getOpCodeValue() == TR::loadaddr
&& currNode->getFirstChild()->getSecondChild()->getSymbolReference()->isUnresolved())
{
unresolvedInstanceofTops.add(currTree);
}
else if (_invokeSpecialInterfaceCalls != NULL
&& currNode->getNumChildren() >= 1
&& currNode->getFirstChild()->getOpCode().isCallDirect()
&& !currNode->getFirstChild()->isPotentialOSRPointHelperCall()
&& _invokeSpecialInterfaceCalls->isSet(
currNode->getFirstChild()->getByteCodeIndex())
&& !evaluatedInvokeSpecialCalls.contains(currNode->getFirstChild()))
{
evaluatedInvokeSpecialCalls.add(currNode->getFirstChild());
invokeSpecialInterfaceTops.add(currTree);
}
// modify the vftChild
// If the receiver pointer is a simple load of an auto or parm, then clone
// it rather than incrementing its reference count. This can prevent the
// inliner from creating unnecessary temporaries. The special case is when
// there is a store to the auto or parm between the load of receiver pointer
//and the virtual function call
//keep track of the symbol references of auto or parm changed by stores
if(opcode.isStoreDirect() && opcode.hasSymbolReference())
{
TR::SymbolReference *symRef = currNode->getSymbolReference();
if (symRef && symRef->getSymbol()->isAutoOrParm())
autoOrParmSymRefList.add(symRef);
}
if(opcode.isResolveOrNullCheck())
{
TR::Node *firstChild = currNode->getFirstChild();
opcode = firstChild->getOpCode(); // the first child is indirect call to method
if (opcode.isCallIndirect()
&& !firstChild->getSymbol()->castToMethodSymbol()->isComputed())
{
TR::Node *receiver;
TR::Node *firstGrandChild = firstChild->getFirstChild(); // firstGrandChild is the vft child
receiver = firstGrandChild->getFirstChild();
TR::ILOpCode receiverOpcode = receiver->getOpCode();
TR::SymbolReference *symRef = NULL;
if(receiverOpcode.hasSymbolReference() && receiverOpcode.isLoadVarDirect())
symRef = receiver->getSymbolReference();
bool canCopyReceiver =symRef && symRef->getSymbol()->isAutoOrParm() && !autoOrParmSymRefList.find(symRef);
if (canCopyReceiver)
{
TR::Node *newReceiver = TR::Node::copy(receiver);
newReceiver->setReferenceCount(1);
firstGrandChild->setChild(0, newReceiver);
receiver->decReferenceCount();
}
}
}
if (needMonitor && primitive)
{
if ((currNode->getOpCode().isStore() &&
currNode->getSymbol()->holdsMonitoredObject() &&
!currNode->isLiveMonitorInitStore()) || currNode->getOpCode().getOpCodeValue() == TR::monexitfence)
{
bool isMonent = currNode->getOpCode().getOpCodeValue() != TR::monexitfence;
if (isMonent)
monentStore = currTree;
else
monexitStore = currTree;
}
if ((currNode->getOpCodeValue() == TR::monexit) || (currNode->getOpCodeValue() == TR::monent))
{
if (currNode->getOpCodeValue() == TR::monexit)
{
if (numMonexits > 0)
{
primitive = false;
continue;
}
monexitTree = currNode;
numMonexits++;
}
else if (currNode->getOpCodeValue() == TR::monent)
{
if (numMonents > 0)
{
primitive = false;
continue;
}
monentTree = currNode;
numMonents++;
}
}
else if (currNode->getNumChildren() > 0 &&
currNode->getFirstChild()->getNumChildren() > 0 &&
((currNode->getFirstChild()->getOpCodeValue() == TR::monexit) || (currNode->getFirstChild()->getOpCodeValue() == TR::monent)))
{
if (currNode->getFirstChild()->getOpCodeValue() == TR::monexit)
{
if (numMonexits > 0)
{
primitive = false;
continue;
}
monexitTree = currNode->getFirstChild();
numMonexits++;
}
else if (currNode->getFirstChild()->getOpCodeValue() == TR::monent)
{
if (numMonents > 0)
{
primitive = false;
continue;
}
monentTree = currNode->getFirstChild();
numMonents++;
}
}
else if (currNode->exceptionsRaised() != 0 ||
currNode->canCauseGC())
{
primitive = false;
continue;
}
}
}
if( needMonitor)
{
if (primitive &&
monentTree &&
monexitTree &&
monentStore &&
monexitStore)
{
TR::SymbolReference *replaceSymRef = NULL;
if (monentStore->getNode()->getFirstChild()->getSymbolReference()->getSymbol()->isAutoOrParm())
replaceSymRef = monentStore->getNode()->getFirstChild()->getSymbolReference();
if (replaceSymRef)
{
if (monentTree->getFirstChild()->getSymbolReference()->getSymbol()->isAutoOrParm())
{
monentTree->getFirstChild()->setSymbolReference(replaceSymRef);
}
if (monexitTree->getFirstChild()->getSymbolReference()->getSymbol()->isAutoOrParm())
{
monexitTree->getFirstChild()->setSymbolReference(replaceSymRef);
}
TR::TreeTop *prev = monentStore->getPrevTreeTop();
TR::TreeTop *next = monentStore->getNextTreeTop();
monentStore->getNode()->recursivelyDecReferenceCount();
prev->join(next);
prev = monexitStore->getPrevTreeTop();
next = monexitStore->getNextTreeTop();
monexitStore->getNode()->recursivelyDecReferenceCount();
prev->join(next);
_methodSymbol->setSyncObjectTemp(NULL);
}
}
}
{
ListIterator<TR::TreeTop> it(&unresolvedCheckcastTopsNeedingNullGuard);
for (TR::TreeTop *tree = it.getCurrent(); tree != NULL; tree = it.getNext())
expandUnresolvedClassCheckcast(tree);
}
{
ListIterator<TR::TreeTop> it(&unresolvedInstanceofTops);
for (TR::TreeTop *tree = it.getCurrent(); tree != NULL; tree = it.getNext())
expandUnresolvedClassInstanceof(tree);
}
{
ListIterator<TR::TreeTop> it(&invokeSpecialInterfaceTops);
for (TR::TreeTop *tree = it.getCurrent(); tree != NULL; tree = it.getNext())
expandInvokeSpecialInterface(tree);
}
if (!bstoreiUnknownArrayTypeNodes.empty() || !bstoreiBoolArrayTypeNodes.empty())
boolArrayStoreTransformer.perform();
return true;
}
TR::Block *
TR_J9ByteCodeIlGenerator::cloneHandler(TryCatchInfo * handlerInfo, TR::Block * firstBlock, TR::Block *lastBlock, TR::Block *lastBlockInMethod, List<TR::Block> *clonedCatchBlocks)
{
TR_BlockCloner cloner(cfg());
handlerInfo->_firstBlock = cloner.cloneBlocks(firstBlock, lastBlock);
lastBlockInMethod->getExit()->join(handlerInfo->_firstBlock->getEntry());
handlerInfo->_lastBlock = lastBlockInMethod = cloner.getLastClonedBlock();
handlerInfo->_catchBlock = cloner.getToBlock(firstBlock);
TR::Block *cursorBlock = firstBlock;
while (cursorBlock != lastBlockInMethod)
{
clonedCatchBlocks->add(cursorBlock);
cursorBlock = cursorBlock->getNextBlock();
}
clonedCatchBlocks->add(cursorBlock);
cfg()->addSuccessorEdges(lastBlockInMethod);
return lastBlockInMethod;
}
TR::Block *
TR_J9ByteCodeIlGenerator::genExceptionHandlers(TR::Block * lastBlock)
{
bool trace = comp()->getOption(TR_TraceILGen);
_inExceptionHandler = true;
TR::SymbolReference * catchObjectSymRef = symRefTab()->findOrCreateExcpSymbolRef();
uint16_t i;
List<TR::Block> clonedCatchBlocks(comp()->trMemory());
for (auto handlerInfoIter = _tryCatchInfo.begin(); handlerInfoIter != _tryCatchInfo.end(); ++handlerInfoIter)
{
TryCatchInfo & handlerInfo = *handlerInfoIter;
int32_t firstIndex = handlerInfo._handlerIndex;
// Two exception data entries can have ranges pointing at the same handler.
// If the types are different then we have to clone the handler.
//
//Partial Inlining - Deal with exception Handlers
//
if(_blocksToInline && !_blocksToInline->isInExceptionList(firstIndex)) //Case 1: item is not in exception list, therefore no ilgen to be done on it
{
continue; // nothing to be done for this handler!
}
else if (
_blocksToInline
&& _blocksToInline->isInExceptionList(firstIndex)
&& !_blocksToInline->isInList(firstIndex)
&& !isGenerated(firstIndex)) //Case 2: item is in exception list, but not in list of blocks to be ilgen'd
{
_blocksToInline->hasGeneratedRestartTree() ? genGotoPartialInliningCallBack(firstIndex,_blocksToInline->getGeneratedRestartTree()) :
_blocksToInline->setGeneratedRestartTree(genPartialInliningCallBack(firstIndex,_blocksToInline->getCallNodeTreeTop()));
handlerInfo._lastBlock = blocks(firstIndex);
handlerInfo._firstBlock = blocks(firstIndex);
handlerInfo._catchBlock = blocks(firstIndex);
blocks(firstIndex)->setIsAdded();
if(blocks(firstIndex) != _blocksToInline->getGeneratedRestartTree()->getEnclosingBlock())
{
lastBlock->getExit()->join(blocks(firstIndex)->getEntry());
cfg()->addNode(blocks(firstIndex));
cfg()->addEdge(blocks(firstIndex),_blocksToInline->getGeneratedRestartTree()->getEnclosingBlock());
}
else
{
lastBlock->getExit()->join(blocks(firstIndex)->getEntry());
cfg()->insertBefore(blocks(firstIndex),cfg()->getEnd()->asBlock());
}
lastBlock=handlerInfo._lastBlock;
//ok what I'm trying here is saying that my first block, last block and catchblock in my catcher are all the same (the one block)
handlerInfo._catchBlock->setHandlerInfo(handlerInfo._catchType, (uint8_t)comp()->getInlineDepth(), handlerInfoIter - _tryCatchInfo.begin(), method(), comp());
continue;
}
bool generateNewBlock = true;
TR::Block * handlerBlockFromNonExceptionControlFlow = 0;
if (isGenerated(firstIndex))
{
generateNewBlock = false;
TryCatchInfo * dupHandler = 0;
for (int32_t j = 0; j < (handlerInfoIter - _tryCatchInfo.begin()); ++j)
{
TryCatchInfo & h = _tryCatchInfo[j];
if (h._handlerIndex == firstIndex)
{
if (!dupHandler)
dupHandler = &h;
if (h._catchType == handlerInfo._catchType)
{
dupHandler = &h;
break;
}
}
}
if (!dupHandler)
{
handlerBlockFromNonExceptionControlFlow = _blocks[firstIndex];
generateNewBlock = true;
// this handler must also be reachable from the mainline code....we don't
// know how to handle this yet
// todo: figure out how to handle this.
//
// TR_ASSERT(dupHandler, "can't figure out why the handler is already generated");
// comp()->failCompilation<TR::CompilationException>("can't figure out why the handler is already generated");
}
if (!generateNewBlock)
{
if (handlerInfo._catchType != dupHandler->_catchType)
{
lastBlock = cloneHandler(&handlerInfo, dupHandler->_firstBlock, dupHandler->_lastBlock, lastBlock, &clonedCatchBlocks);
/*
TR_BlockCloner cloner(cfg());
handlerInfo->_firstBlock = cloner.cloneBlocks(dupHandler->_firstBlock, dupHandler->_lastBlock);
lastBlock->getExit()->join(handlerInfo->_firstBlock->getEntry());
handlerInfo->_lastBlock = lastBlock = cloner.getLastClonedBlock();
handlerInfo->_catchBlock = cloner.getToBlock(blocks(firstIndex));
cfg()->addSuccessorEdges(lastBlock);
*/
}
else
handlerInfo._catchBlock = dupHandler->_catchBlock;
}
}
if (generateNewBlock)
{
setupBBStartContext(firstIndex);
TR::SymbolReference *exceptionLoadSymRef = NULL;
if (handlerBlockFromNonExceptionControlFlow &&
_stack->topIndex() == 0)