-
Notifications
You must be signed in to change notification settings - Fork 392
/
OSRData.cpp
1542 lines (1413 loc) · 60.5 KB
/
OSRData.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, 2020 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 "compile/OSRData.hpp"
#include <algorithm>
#include <stdint.h>
#include <stdio.h>
#include "codegen/CodeGenerator.hpp"
#include "env/FrontEnd.hpp"
#include "codegen/Instruction.hpp"
#include "compile/Compilation.hpp"
#include "compile/ResolvedMethod.hpp"
#include "compile/SymbolReferenceTable.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "env/ObjectModel.hpp"
#include "env/StackMemoryRegion.hpp"
#include "env/jittypes.h"
#include "env/CompilerEnv.hpp"
#include "env/VerboseLog.hpp"
#include "il/Block.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/ResolvedMethodSymbol.hpp"
#include "il/Symbol.hpp"
#include "il/SymbolReference.hpp"
#include "il/TreeTop.hpp"
#include "infra/Assert.hpp"
#include "infra/Cfg.hpp"
#include "infra/List.hpp"
TR::Compilation& operator<< (TR::Compilation& out, const TR_OSRSlotSharingInfo* osrSlotSharingInfo);
TR_OSRCompilationData::TR_OSRCompilationData(TR::Compilation* _comp) :
instruction2SharedSlotMap(_comp->trMemory()->heapMemoryRegion()),
comp(_comp),
_classPreventingInducedOSRSeen(false),
osrMethodDataArray(_comp->trMemory()),
symRefOrderMap(_comp->allocator()),
numOfSymsThatShareSlot(0), maxScratchBufferSize(0)
{};
/**
This is top-level method that is called by the OSR def analysis
Each call to this method means that the symbol with symref number of "symRefNum" is live
at the location given by bcinfo.
That symref is in slot "slot", has symRefOrder "symRefOrder", its size is "symSize" and
it takes two slots if "takesTwoSlots" is true.
*/
void
TR_OSRCompilationData::addSlotSharingInfo(const TR_ByteCodeInfo& bcinfo,
int32_t slot, int32_t symRefNum, int32_t symRefOrder, int32_t symSize, bool takesTwoSlots)
{
//we'll add the symref to the inlined method that corresponds to the location given by bcinfo.
getOSRMethodDataArray()[bcinfo.getCallerIndex()+1]->
addSlotSharingInfo(bcinfo.getByteCodeIndex(), slot, symRefNum, symRefOrder, symSize, takesTwoSlots);
}
TR_OSRSlotSharingInfo *
TR_OSRCompilationData::getSlotsInfo(const TR_ByteCodeInfo& bcinfo)
{
return getOSRMethodDataArray()[bcinfo.getCallerIndex()+1]->getSlotsInfo(bcinfo.getByteCodeIndex());
}
void
TR_OSRCompilationData::ensureSlotSharingInfoAt(const TR_ByteCodeInfo& bcinfo)
{
TR_OSRMethodData* osrMethodData = getOSRMethodDataArray()[bcinfo.getCallerIndex()+1];
if (osrMethodData && osrMethodData->getOSRCodeBlock())
osrMethodData->ensureSlotSharingInfoAt(bcinfo.getByteCodeIndex());
}
/**
* This is the top-level method that is called by the codegen to populate
* the maps that are eventually written to meta data.
*
* In voluntary OSR, only induce OSR calls must be added to the
* OSR table, as these are the only points that will transition.
* However, under involuntary OSR, all points must support
* transitions.
*/
void
TR_OSRCompilationData::addInstruction(TR::Instruction* instr)
{
TR::Node *node = instr->getNode();
if (comp->getOSRMode() == TR::voluntaryOSR
&& !(node
&& node->getOpCode().hasSymbolReference()
&& node->getSymbolReference()->isOSRInductionHelper()))
return;
int32_t instructionPC = static_cast<int32_t>(instr->getBinaryEncoding() - instr->cg()->getCodeStart());
TR_ByteCodeInfo& bcInfo = instr->getNode()->getByteCodeInfo();
addInstruction(instructionPC, bcInfo);
}
void
TR_OSRCompilationData::addInstruction(int32_t instructionPC, TR_ByteCodeInfo bcInfo)
{
bool trace = comp->getOption(TR_TraceOSR);
if (trace)
traceMsg(comp, "instructionPC %x callerIndex %d bcidx %d ", instructionPC,
bcInfo.getCallerIndex(), bcInfo.getByteCodeIndex());
if (instructionPC < 0)
{
if (trace)
traceMsg(comp, " rejected: instructionPC %d < 0\n", instructionPC);
return;
}
// Algorithm:
// 1) p = callsite/bytecode point that correspond to the instruction
// 2) Find the live shared slots at p (by calling osrMethodData->addInstruction(...) below)
// 3) if p is at the root method exit.
// 4) p = caller point of p
// 5) goto 2
while (1)
{
if (unsigned(bcInfo.getCallerIndex()+1) >= getOSRMethodDataArray().size())
{
if (trace)
traceMsg(comp, " rejected: caller index %d +1 >= %d\n", bcInfo.getCallerIndex(), getOSRMethodDataArray().size());
break;
}
TR_OSRMethodData* osrMethodData = getOSRMethodDataArray()[bcInfo.getCallerIndex()+1];
if (!osrMethodData || !osrMethodData->getOSRCodeBlock())
{
if (trace)
traceMsg(comp, " rejected: no osrMethodData\n");
break;
}
TR_ASSERT(getNumOfSymsThatShareSlot() >= 0, "number of symbols that share slots must be non-negative; actually %d", getNumOfSymsThatShareSlot());
if (getNumOfSymsThatShareSlot() == 0)
{
if (trace)
traceMsg(comp, " rejected: no slot-sharing symbols in CompilationData\n");
break;
}
osrMethodData->addInstruction(instructionPC, bcInfo.getByteCodeIndex());
if (bcInfo.getCallerIndex() == -1)
break;
bcInfo = comp->getInlinedCallSite(bcInfo.getCallerIndex())._byteCodeInfo;
if (trace)
traceMsg(comp, " callerIndex %d bcidx %d ", bcInfo.getCallerIndex(), bcInfo.getByteCodeIndex());
}
}
TR_OSRMethodData *
TR_OSRCompilationData::findOSRMethodData(int32_t inlinedSiteIndex, TR::ResolvedMethodSymbol *methodSymbol)
{
int32_t index = inlinedSiteIndex + 1;
TR_OSRMethodData *osrMethodData = osrMethodDataArray.isEmpty() ? NULL : osrMethodDataArray[index];
if (osrMethodData &&
osrMethodData->getInlinedSiteIndex() == inlinedSiteIndex &&
osrMethodData->getMethodSymbol() == methodSymbol)
return osrMethodData;
return NULL;
}
// TODO: there is currently an implicit assumption that we are calling findOrCrete from within
// the inliner where the current compilation is at the correct depth to generate the
// inlinedSiteIndex - we should factor inlinedSiteIndex into the API to avoid accidental
// calls from other locations unaware of the implicit assumption here in
TR_OSRMethodData *
TR_OSRCompilationData::findOrCreateOSRMethodData(int32_t inlinedSiteIndex, TR::ResolvedMethodSymbol *methodSymbol)
{
TR_OSRMethodData *osrMethodData = findOSRMethodData(inlinedSiteIndex, methodSymbol);
if (osrMethodData)
return osrMethodData;
int32_t index = inlinedSiteIndex + 1;
osrMethodData = new (comp->trHeapMemory()) TR_OSRMethodData(inlinedSiteIndex, methodSymbol, this);
if (comp->getOption(TR_TraceOSR))
traceMsg(comp, "osrMethodData index %d created\n", index); // TODO: Print methodSymbol
osrMethodDataArray[index] = osrMethodData;
return osrMethodData;
}
TR_OSRMethodData *
TR_OSRCompilationData::findCallerOSRMethodData(TR_OSRMethodData *callee)
{
TR_InlinedCallSite &ics = comp->getInlinedCallSite(callee->getInlinedSiteIndex());
int32_t callerIndex = ics._byteCodeInfo.getCallerIndex();
TR_OSRMethodData *osrMethodData = osrMethodDataArray[callerIndex+1];
return osrMethodData;
}
void
TR_OSRCompilationData::addInstruction2SharedSlotMapEntry(
int32_t instructionPC,
const TR_ScratchBufferInfos& infos)
{
auto cur = instruction2SharedSlotMap.begin(), end = instruction2SharedSlotMap.end();
while (cur != end)
{
if (instructionPC <= (*cur).instructionPC)
break;
++cur;
}
if (cur != end && instructionPC == (*cur).instructionPC)
(*cur).scratchBufferInfos.append(infos);
else
instruction2SharedSlotMap.insert(cur, TR_Instruction2SharedSlotMapEntry(instructionPC, infos));
}
/*
Reduces the size of the instruction2SharedSlot map by merging consecutive equal elements.
*/
void
TR_OSRCompilationData::compressInstruction2SharedSlotMap()
{
auto cur = instruction2SharedSlotMap.begin();
while (cur != instruction2SharedSlotMap.end())
{
auto next = cur + 1;
for (; next != instruction2SharedSlotMap.end(); ++next)
{
const TR_ScratchBufferInfos& curInfo = (*cur).scratchBufferInfos;
const TR_ScratchBufferInfos& nextInfo = (*next).scratchBufferInfos;
if (curInfo.size() != nextInfo.size())
break;
size_t j;
for (j = 0; j < curInfo.size(); j++)
if (!(curInfo[static_cast<uint32_t>(j)] == nextInfo[static_cast<uint32_t>(j)]))
break;
if (j != curInfo.size())
break;
}
if (cur + 1 != next)
cur = instruction2SharedSlotMap.erase(cur + 1, next);
else
++cur;
}
}
/*
During inlining, osrMethodDataArray array is grown during genIL of methods that the inliner
intends to inline. However, at some point after genIL is finished, the inliner may decide not to inline
that method. In that case, we need to remove the elements of osrMethodDataArray that were created
for that method (and any method it inlines).
*/
void
TR_OSRCompilationData::setOSRMethodDataArraySize(int newSize)
{
osrMethodDataArray.setSize(newSize);
}
//computes the size of the meta data
uint32_t
TR_OSRCompilationData::getSizeOfMetaData() const
{
uint32_t size = 0;
//section 0
if (comp->getOption(TR_DisableOSRSharedSlots))
{
size += sizeof(uint32_t);
}
else
{
size += getSizeOfInstruction2SharedSlotMap();
}
//section 1
size += getSizeOfCallerIndex2OSRCatchBlockMap();
return size;
}
//computes size of section 0
uint32_t
TR_OSRCompilationData::getSizeOfInstruction2SharedSlotMap() const
{
int size = 0;
size += sizeof(uint32_t); //number of bytes used to store the whole section
size += sizeof(uint32_t); //maximum size of scratch buffer
size += sizeof(int32_t); //number of mappings
for (auto itr = instruction2SharedSlotMap.begin(), end = instruction2SharedSlotMap.end(); itr != end; ++itr)
{
size += sizeof(int32_t); //instructionPC
//storing the number of elements of the array (which is represented as the data of the hash table
size += sizeof(int32_t);
size += sizeof(TR_ScratchBufferInfo) * (*itr).scratchBufferInfos.size(); //data
}
return size;
}
//computes size of section 1
uint32_t
TR_OSRCompilationData::getSizeOfCallerIndex2OSRCatchBlockMap() const
{
int size = 0;
size += sizeof(uint32_t); //number of bytes for the rest of this section
size += sizeof(int32_t); //number of mappings
size += sizeof(uint32_t) //osrCatchBlockAddress
* getOSRMethodDataArray().size();
return size;
}
/*
This is the top-level method that writes OSR-specific meta data.
The meta data has two sections:
0) a mapping from instruction PC offsets to a list of shared slots that are live at that offset.
1) a mapping from from the call site index to OSR catch block
The first 4 bytes of each section is the size of the section in bytes (including the size field itself)
*/
uint32_t
TR_OSRCompilationData::writeMetaData(uint8_t* buffer) const
{
uint32_t numberOfBytesWritten = 0;
TR_ASSERT(comp->getOption(TR_EnableOSR), "OSR must be enabled for TR_OSRCompilationData::writeMetaData");
//section 0
if (comp->getOption(TR_DisableOSRSharedSlots))
{
//write an empty section so that we always have two sections regardless of whether
//osr def analysis is enabled or not
uint32_t sectionSize = sizeof(uint32_t);
*((uint32_t*)(buffer+numberOfBytesWritten)) = sectionSize;
numberOfBytesWritten += sizeof(uint32_t);
}
else
{
numberOfBytesWritten += writeInstruction2SharedSlotMap(buffer + numberOfBytesWritten);
}
//section 1
numberOfBytesWritten += writeCallerIndex2OSRCatchBlockMap(buffer + numberOfBytesWritten);
/*
traceMsg(comp, "%%%%%%%%%%%%%%%%%%% OSR MetaData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n");
for (int i = 0; i < numberOfBytesWritten; i+=4)
{
traceMsg(comp, "%010x ", *(uint32_t*)(buffer + i));
if ((i % 16) == 12) traceMsg(comp, "\n");
}
traceMsg(comp, "\n");
*/
return numberOfBytesWritten;
}
/*
This function writes section 0 of the meta data. This section has the following fields:
- size of section 0
- maximum size of the scratch buffer
- number of mappings in the instruction->(list of live shared slots) map
- for each mapping
- instruction PC offset
- for i = 1 to (size of list of live shared slots)
- callsite index that the shared slot belongs to
- offset in the osr buffer that the shared slot corresponds to. This is the slot that needs to be
written to by the jit helper
- offset in the scratch buffer that the live shared slot corresponds to. This is the slot that
needs to be read by the jit helper
- symSize: size of the symbol that the shared slot corresponds to.
The function returns the number of bytes written.
*/
uint32_t
TR_OSRCompilationData::writeInstruction2SharedSlotMap(uint8_t* buffer) const
{
uint8_t* initialBuffer = buffer;
uint32_t sectionSize = getSizeOfInstruction2SharedSlotMap();
*((uint32_t*)buffer) = sectionSize; buffer += sizeof(uint32_t);
*((uint32_t*)buffer) = getMaxScratchBufferSize(); buffer += sizeof(uint32_t);
int32_t numberOfMappings = static_cast<int32_t>(instruction2SharedSlotMap.size());
*((int32_t*)buffer) = numberOfMappings; buffer += sizeof(int32_t);
for (auto itr = instruction2SharedSlotMap.begin(), end = instruction2SharedSlotMap.end(); itr != end; ++itr)
{
*((int32_t*)buffer) = (*itr).instructionPC; buffer += sizeof(int32_t);
*((int32_t*)buffer) = (*itr).scratchBufferInfos.size(); buffer += sizeof(int32_t);
for (auto j = 0U; j < (*itr).scratchBufferInfos.size(); j++)
{
const TR_ScratchBufferInfo info = (*itr).scratchBufferInfos[j];
buffer += info.writeToBuffer(buffer);
}
}
uint32_t numberOfBytesWritten = static_cast<uint32_t>(buffer - initialBuffer);
TR_ASSERT(numberOfBytesWritten == sectionSize, "numberOfBytesWritten (%d) must match sectionSize (%d)", numberOfBytesWritten, sectionSize);
return numberOfBytesWritten;
}
/*
This function writes section 1 of the meta data. This section has the following fields:
- size of section 1
- number of mappings in the (callsite index)->(OSR catch block) map
- for each mapping
- instruction PC of the OSR catch block. Note that the call site index is implicit (starting from -1).
The function returns the number of bytes written.
*/
uint32_t
TR_OSRCompilationData::writeCallerIndex2OSRCatchBlockMap(uint8_t* buffer) const
{
uint8_t* initialBuffer = buffer;
uint32_t sectionSize = getSizeOfCallerIndex2OSRCatchBlockMap();
*((uint32_t*)buffer) = sectionSize; buffer += sizeof(uint32_t);
int32_t numberOfMappings = getOSRMethodDataArray().size();
*((int32_t*)buffer) = numberOfMappings; buffer += sizeof(int32_t);
for (int i = 0; i < numberOfMappings; i++)
{
TR_OSRMethodData* osrMethodData = getOSRMethodDataArray()[i];
if (osrMethodData == NULL || osrMethodData->getOSRCodeBlock() == NULL)
*((int32_t*)buffer) = 0;
else
*((int32_t*)buffer) = osrMethodData->getOSRCatchBlock()->getInstructionBoundaries()._startPC; buffer += sizeof(int32_t);
}
uint32_t numberOfBytesWritten = static_cast<uint32_t>(buffer - initialBuffer);
TR_ASSERT(numberOfBytesWritten == sectionSize, "numberOfBytesWritten (%d) must match sectionSize (%d)", numberOfBytesWritten, sectionSize);
return numberOfBytesWritten;
}
/// This method computes the sizes of all of the various OSR parameters and requests the VM to accomodate the JIT
/// if the VM replies that it cannot accommodate the compile we are doing we abort the compile. It is NEVER safe
/// to toggle our OSR state during a compile so this method will either return on success or call outofmemory on failure
///
void TR_OSRCompilationData::checkOSRLimits()
{
uint32_t maxFrameSize = 0;
uint32_t maxStackFrameSize = 0;
int32_t numOfInlinedCalls = comp->getNumInlinedCallSites();
{
TR::StackMemoryRegion stackMemoryRegion(*comp->trMemory());
uint32_t *frameSizes = (uint32_t *) comp->trMemory()->allocateStackMemory(numOfInlinedCalls * sizeof(uint32_t));
uint32_t *stackFrameSizes = (uint32_t *) comp->trMemory()->allocateStackMemory(numOfInlinedCalls * sizeof(uint32_t));
uint32_t rootFrameSize = static_cast<uint32_t>(TR::Compiler->vm.OSRFrameSizeInBytes(comp, comp->getCurrentMethod()->getPersistentIdentifier()));
uint32_t rootStackFrameSize = getOSRStackFrameSize(0);
for (int i = 0; i < numOfInlinedCalls; ++i)
{
frameSizes[i] = 0;
stackFrameSizes[i] = 0;
}
for (int i = 0; i < numOfInlinedCalls; ++i)
{
TR_InlinedCallSite &callSite = comp->getInlinedCallSite(i);
TR_ByteCodeInfo &bcInfo = callSite._byteCodeInfo;
frameSizes[i] = static_cast<uint32_t>(TR::Compiler->vm.OSRFrameSizeInBytes(comp, callSite._methodInfo));
frameSizes[i] += (bcInfo.getCallerIndex() == -1) ? rootFrameSize : frameSizes[bcInfo.getCallerIndex()];
stackFrameSizes[i] = getOSRStackFrameSize(i + 1);
stackFrameSizes[i] = (bcInfo.getCallerIndex() == -1) ? rootStackFrameSize : stackFrameSizes[bcInfo.getCallerIndex()];
}
maxFrameSize = rootFrameSize;
maxStackFrameSize = rootStackFrameSize;
for (int i = 0; i < numOfInlinedCalls; ++i)
{
maxFrameSize = std::max(maxFrameSize, frameSizes[i]);
maxStackFrameSize = std::max(maxStackFrameSize, stackFrameSizes[i]);
}
//getFrameSizeInBytes() is what is determined only after code generation and that's probably why
//we perform this check against the threshold after code generation.
maxStackFrameSize += comp->cg()->getFrameSizeInBytes();
} // scope of the stack memory region
if (!TR::Compiler->vm.ensureOSRBufferSize(comp, maxFrameSize, getMaxScratchBufferSize(), maxStackFrameSize))
{
if (comp->getOptions()->getAnyOption(TR_TraceAll) || comp->getOption(TR_TraceOSR))
traceMsg(comp, "OSR COMPILE ABORT: frame size %d, scratch size %d, stack size %d were not accommodated by the VM\n",
maxFrameSize, getMaxScratchBufferSize(), maxStackFrameSize);
if (comp->getOptions()->isAnyVerboseOptionSet(TR_VerboseOSR, TR_VerboseOSRDetails))
TR_VerboseLog::writeLineLocked(TR_Vlog_OSR, "OSR COMPILE ABORT in %s: frame size %d, scratch size %d, stack size %d were not accommodated by the VM\n",
comp->signature(), maxFrameSize, getMaxScratchBufferSize(), maxStackFrameSize);
comp->failCompilation<TR::CompilationException>("OSR buffers could not be enlarged to accomodate compiled method");
}
}
void
TR_OSRCompilationData::setMaxScratchBufferSize(uint32_t newSize)
{
maxScratchBufferSize = std::max(maxScratchBufferSize, newSize);
}
/**
* Computes the size of the stack frame needed for OSR operations for a single method
*
*/
uint32_t TR_OSRCompilationData::getOSRStackFrameSize(uint32_t methodIndex)
{
//when methodIndex corresponds, for example, to a JNI method, the corresponding element
//in OSRMethodDataArray doesn't exist or is NULL.
if (methodIndex < getOSRMethodDataArray().size())
{
TR_OSRMethodData* osrMethodData = getOSRMethodDataArray()[methodIndex];
if (osrMethodData != NULL)
return (1 + osrMethodData->getMethodSymbol()->getNumParameterSlots())
* static_cast<uint32_t>(TR::Compiler->om.sizeofReferenceAddress());
else
return 0;
}
else
return 0;
}
void TR_OSRCompilationData::printMap(DefiningMap *map)
{
if (map)
{
for (auto it = map->begin(); it != map->end(); ++it)
{
traceMsg(comp, "# %d:", it->first);
it->second->print(comp);
traceMsg(comp, "\n");
}
}
else
{
traceMsg(comp, "Empty map\n");
}
}
/*
* \brief This is the top level function to start building defining maps for the symbol references
* under prepareForOSRCall for each method
*
* DefiningMap maps each symRef to the set of symRefs that define it in one block or several
* contiguous blocks.
*
* There are 4 DefiningMaps for each methods and their ranges are different:
* - osrCatchBlock: starts from the osrCatchBlock and stops before the osrCodeBlock of THIS caller
* - osrCodeBlock: starts from the osrCodeBlock and stops before the osrCodeBlock of the NEXT caller
* - prepareForOSR: starts from the osrCodeBlock and stops at prepareForOSR call
* - FinalMap: this one maps all the symbol references under each prepareForOSR call from the current
* caller up until the top most caller and the is the only map published to the OSRMethodMetaData
*
* Combining the FinalMap with liveness info from OSRLiveRangeAnalysis, we are able to find which
* symbols should be kept alive at each osrPoints.
*
* \param region A \ref TR::Region memory region in which the final DefiningMaps
* will be allocated. The caller is responsible for releasing
* the memory in which the DefiningMaps are allocated
*/
void TR_OSRCompilationData::buildDefiningMap(TR::Region ®ion)
{
const TR_Array<TR_OSRMethodData *>& methodDataArray = getOSRMethodDataArray();
int numOfMethods = methodDataArray.size();
TR::StackMemoryRegion stackMemoryRegion(*comp->trMemory());
DefiningMaps definingMapAtOSRCatchBlocks(numOfMethods, static_cast<DefiningMap*>(NULL), comp->trMemory()->currentStackRegion());
DefiningMaps definingMapAtOSRCodeBlocks(numOfMethods, static_cast<DefiningMap*>(NULL), comp->trMemory()->currentStackRegion());
DefiningMaps definingMapAtPrepareForOSRCalls(numOfMethods, static_cast<DefiningMap*>(NULL), comp->trMemory()->currentStackRegion());
for (auto i = 0U; i < methodDataArray.size(); ++i)
{
TR_OSRMethodData *osrMethodData = methodDataArray[i];
if (!osrMethodData)
continue;
//Those 2 bool variables are necessary for identifying the cases where the OSRCode/CatchBlock is already
//removed by the optimizer but osrMethodData still points to the block that's no longer in the CFG
bool osrCatchBlockRemoved = false;
bool osrCodeBlockRemoved = false;
TR::Block *osrCatchBlock = osrMethodData->getOSRCatchBlock();
if (osrCatchBlock && osrCatchBlock->getExceptionPredecessors().size() > 0)
{
definingMapAtOSRCatchBlocks[i] = new (comp->trMemory()->currentStackRegion()) DefiningMap(DefiningMapComparator(), DefiningMapAllocator(comp->trMemory()->currentStackRegion()));
osrMethodData->buildDefiningMapForBlock(osrCatchBlock, definingMapAtOSRCatchBlocks[i]);
}
else osrCatchBlockRemoved = true;
TR::Block *osrCodeBlock = osrMethodData->getOSRCodeBlock();
if (osrCodeBlock && osrCodeBlock->getPredecessors().size() > 0)
{
definingMapAtOSRCodeBlocks[i] = new (comp->trMemory()->currentStackRegion()) DefiningMap(DefiningMapComparator(), DefiningMapAllocator(comp->trMemory()->currentStackRegion()));
definingMapAtPrepareForOSRCalls[i] = new (comp->trMemory()->currentStackRegion()) DefiningMap(DefiningMapComparator(), DefiningMapAllocator(comp->trMemory()->currentStackRegion()));
osrMethodData->buildDefiningMapForOSRCodeBlockAndPrepareForOSRCall(osrCodeBlock, definingMapAtOSRCodeBlocks[i], definingMapAtPrepareForOSRCalls[i]);
}
else osrCodeBlockRemoved = true;
if (!osrCatchBlockRemoved && !osrCodeBlockRemoved )
{
DefiningMap *finalMap = new (region) DefiningMap(DefiningMapComparator(), DefiningMapAllocator(region));
buildFinalMap(static_cast<int32_t>(i-1), finalMap, definingMapAtOSRCatchBlocks[i], definingMapAtOSRCodeBlocks, definingMapAtPrepareForOSRCalls);
osrMethodData->setDefiningMap(finalMap);
}
}
if (comp->getOption(TR_TraceOSR))
{
for (auto i = 0U; i < methodDataArray.size(); ++i)
{
TR_OSRMethodData *osrMethodData = methodDataArray[i];
if (!osrMethodData)
continue;
DefiningMap *definingMap = osrMethodData->getDefiningMap();
if (osrMethodData->getOSRCatchBlock())
{
traceMsg(comp, "final map for OSRCatchBlock(block_%d): \n", osrMethodData->getOSRCatchBlock()->getNumber());
printMap(definingMap);
}
}
}
}
void TR_OSRCompilationData::clearDefiningMap()
{
const TR_Array<TR_OSRMethodData *>& methodDataArray = getOSRMethodDataArray();
for (auto i = 0U; i < methodDataArray.size(); ++i)
{
TR_OSRMethodData *osrMethodData = methodDataArray[i];
if (osrMethodData)
{
osrMethodData->setDefiningMap(NULL);
}
}
}
/*
* \brief This function replace the symbols in \p subTreeSymRefs with the symbols defining them according to the \p DefiningMap
*
* @param subTreeSymRefs original symbols
* @param DefiningMap maps each symbol to the group of symbols it depends on
* @param resultSymRefs updated symbols with original symbols replaced with its defining symbols
*/
static void updateDefiningSymRefs(TR_BitVector *subTreeSymRefs, DefiningMap *definingMap, TR_BitVector *resultSymRefs)
{
TR_BitVectorIterator cursor(*subTreeSymRefs);
while (cursor.hasMoreElements())
{
int32_t j = cursor.getNextElement();
if ( definingMap->find(j) == definingMap->end() ||
(*definingMap)[j]->isEmpty())
resultSymRefs->set(j);
else
*resultSymRefs |= *(*definingMap)[j];
}
}
/*
* \brief merge the 2 DefiningMaps
*
* This is a helper function that update the defs in the `firstMap` with the defs in the `secondMap`.
* For each entry in the `secondMap`, there are 2 steps:
* step 1: overwrite the entry with the same key in the `firstMap`
* setp 2: update the defining symbols of that entry according to the `firstMap`
* Here is an example:
* firstMap:
* ------------------
* | a0 -> {a1} |
* | a2 -> {a3, a4} |
* ------------------
* secondMap:
* ------------------
* | a2 -> {a0} |
* ------------------
*
* after step 1, the firstMap looks like:
* ------------------
* | a0 -> {a1} |
* | a2 -> {a0} |
* ------------------
* after step 2, the firstMap looks like:
* ------------------
* | a0 -> {a1} |
* | a2 -> {a1} |
* ------------------
*/
static void mergeDefiningMaps(DefiningMap *firstMap, DefiningMap *secondMap, TR::Compilation *comp)
{
if (comp->getOption(TR_TraceOSR))
{
traceMsg(comp, "mergeDefiningMaps: firstMap before\n");
comp->getOSRCompilationData()->printMap(firstMap);
traceMsg(comp, "mergeDefiningMaps: secondMap before\n");
comp->getOSRCompilationData()->printMap(secondMap);
}
for (auto it = secondMap->begin(); it != secondMap->end(); ++it)
{
int32_t symRefNumber = it->first;
TR_BitVector *definingSymRefs = NULL;
if (firstMap->find(symRefNumber) == firstMap->end())
definingSymRefs = new (comp->trStackMemory()) TR_BitVector(comp->trMemory()->currentStackRegion());
else
{
definingSymRefs = (*firstMap)[symRefNumber];
definingSymRefs->empty();
}
updateDefiningSymRefs(it->second, firstMap, definingSymRefs);
(*firstMap)[symRefNumber] = definingSymRefs;
}
if (comp->getOption(TR_TraceOSR))
{
traceMsg(comp, "mergeDefiningMaps: firstMap after\n");
comp->getOSRCompilationData()->printMap(firstMap);
}
}
/*
* \brief Solve and publish the final defining map which maps all the symbols under the prepareForOSR calls
* to their defining symbols
*
* @param finalMap the map that will be published to OSRMethodMetaData
* @param workingCatchBlockMap this map maintains all the defining relationsships while iterates through all the blocks
* @param definingMapAtOSRCodeBlocks the OSRCodeBlock map for each method which needed in building the maps for all the callees
* @param definingMapAtPrepareForOSRCalls the prepareForOSRCall map needed in building maps for all the callees
*
* This function does the following 2 things:
* - put the symbols under current prepareForOSRCall into the finalMap
* - merge the workingCatchBlockMap with the OSRCodeBlockMap
*
* This is a recursive function walking up the call chain and stops at the top most method. The walking path is the same as
* the execution path of an OSR transition.
*/
void
TR_OSRCompilationData::buildFinalMap (int32_t callerIndex,
DefiningMap *finalMap,
DefiningMap *workingCatchBlockMap,
DefiningMaps &definingMapAtOSRCodeBlocks,
DefiningMaps &definingMapAtPrepareForOSRCalls
)
{
if (comp->getOption(TR_TraceOSR))
traceMsg(comp, "buildFinalMap callerIndex %d\n", callerIndex);
TR_OSRMethodData *osrMethodData = getOSRMethodDataArray()[callerIndex+1];
DefiningMap *codeBlockMap = definingMapAtOSRCodeBlocks[callerIndex+1];
DefiningMap *prepareForOSRCallMap = definingMapAtPrepareForOSRCalls[callerIndex+1];
for (auto entry = prepareForOSRCallMap->begin(); entry != prepareForOSRCallMap->end(); ++entry )
{
int32_t symRefNum = entry->first;
TR_BitVector *definingSymbols = entry->second;
TR_BitVector *result = new (comp->trHeapMemory()) TR_BitVector(0, comp->trMemory(), heapAlloc);
updateDefiningSymRefs(definingSymbols, workingCatchBlockMap, result);
TR_ASSERT(finalMap->find(symRefNum) == finalMap->end(), "same symbol reference shouldn't be written twice under different prepareForOSRCall");
if (comp->getOption(TR_TraceOSR))
{
traceMsg(comp, "adding symRef #%d and its defining symbols to finalMap\n", symRefNum);
result->print(comp);
traceMsg(comp, "\n");
}
(*finalMap)[symRefNum] = result;
}
if (callerIndex == -1)
return;
mergeDefiningMaps(workingCatchBlockMap, codeBlockMap, comp);
TR::Block *osrCodeBlock = osrMethodData->getOSRCodeBlock();
TR::Block *nextBlock = toBlock(osrCodeBlock->getSuccessors().front()->getTo());
while (!nextBlock->isOSRCodeBlock())
{
TR_ASSERT(nextBlock->getSuccessors().size() == 1, "blocks between osrCodeBlock can only have one successor (block_%d)", nextBlock->getNumber());
nextBlock = toBlock(nextBlock->getSuccessors().front()->getTo());
}
int32_t nextCallerIndex = nextBlock->getEntry()->getNode()->getByteCodeInfo().getCallerIndex();
buildFinalMap (nextCallerIndex, finalMap, workingCatchBlockMap, definingMapAtOSRCodeBlocks, definingMapAtPrepareForOSRCalls);
}
/*
* This function build the OSRCodeBlock map and the prepareForOSRCall map
*/
void
TR_OSRMethodData::buildDefiningMapForOSRCodeBlockAndPrepareForOSRCall(TR::Block *block, DefiningMap *osrCodeBlockMap, DefiningMap *prepareForOSRCallMap)
{
TR_ASSERT(block->getSuccessors().size() == 1, "OSRCodeBlock should have one successor but block_%d has %d", block->getNumber(), block->getSuccessors().size());
if (comp()->getOption(TR_TraceOSR))
traceMsg(comp(), "buildDefiningMapForOSRCodeBlockAndPrepareForOSRCall block_%d\n", block->getNumber());
buildDefiningMap(block, osrCodeBlockMap, prepareForOSRCallMap);
if (block->getEntry()->getNode()->getByteCodeInfo().getCallerIndex() == -1)
return;
TR::Block *nextBlock = toBlock(block->getSuccessors().front()->getTo());
// Keep processing all blocks one after another until reaching the next OSRCodeBlock
if (!nextBlock->isOSRCodeBlock())
buildDefiningMapForBlock(nextBlock, osrCodeBlockMap);
}
/*
* \brief This function builds the defining map for the given block and all the blocks after
* until reaching the `next OSRCodeBlock`.
*
* If called from `buildDefiningMapForOSRCodeBlockAndPrepareForOSRCall`, the map is for
* an OSRCodeBlock and `next OSRCodeBlock` belongs to the next caller in the call chain of this
* method. Note that it's possible that the immediate next caller doesn't have an OSRCodeBlock
* and the `next OSRCodeBlock` would belong to the caller's caller.
*
* If called from `buildDefiningMap`, the map is for the OSRCatchBlock, and the `next OSRCodeBlock`
* belongs to the same method as the OSRCatchBlock.
*/
void
TR_OSRMethodData::buildDefiningMapForBlock(TR::Block *block, DefiningMap *blockMap)
{
TR_ASSERT(block->getSuccessors().size() == 1, "OSRCatchBlock should have one successor but block_%d has %d", block->getNumber(), block->getSuccessors().size());
if (comp()->getOption(TR_TraceOSR))
traceMsg(comp(), "buildDefiningMapForBlock block_%d\n", block->getNumber());
buildDefiningMap(block, blockMap);
TR::Block *nextBlock = toBlock(block->getSuccessors().front()->getTo());
if (!nextBlock->isOSRCodeBlock())
buildDefiningMapForBlock(nextBlock, blockMap);
}
/*
* \brief This is the most basic function iterating through all store nodes and add entries to the DefiningMap to
* map each symbol to the group of symbols defining it
*/
void
TR_OSRMethodData::buildDefiningMap(TR::Block *block, DefiningMap *blockMap, DefiningMap *prepareForOSRCallMap)
{
for (TR::TreeTop *tt = block->getEntry(); tt != block->getExit(); tt = tt->getNextRealTreeTop())
{
TR::SymbolReference * symRef = NULL;
TR::Node *node = tt->getNode();
if (comp()->getOption(TR_TraceOSR))
traceMsg(comp(), "buildDefiningMap node n%dn\n", node->getGlobalIndex());
if (node->getOpCode().isStoreDirect())
symRef = node->getSymbolReference();
else if (node->getOpCode().isStoreReg())
symRef = node->getRegLoadStoreSymbolReference();
if (symRef)
{
if (symRef->getSymbol()->isAutoOrParm())
{
TR_BitVector subTreeSymRefs(comp()->trMemory()->currentStackRegion());
TR::NodeChecklist checklist(comp());
collectSubTreeSymRefs(node->getFirstChild(), &subTreeSymRefs, checklist);
if (comp()->getOption(TR_TraceOSR))
{
traceMsg(comp(), "buildDefiningMap: node n%dn: defining symbol #%d: ", node->getGlobalIndex(), symRef->getReferenceNumber());
subTreeSymRefs.print(comp());
traceMsg(comp(), "\n");
}
TR_BitVector *symRefs = NULL;
if (blockMap->find(symRef->getReferenceNumber()) != blockMap->end())
{
symRefs = (*blockMap)[symRef->getReferenceNumber()];
symRefs->empty(); // the current store kills previous defs
}
if (!subTreeSymRefs.isEmpty())
{
if (!symRefs)
{
symRefs = new (comp()->trStackMemory()) TR_BitVector(comp()->trMemory()->currentStackRegion());
(*blockMap)[symRef->getReferenceNumber()] = symRefs;
}
updateDefiningSymRefs(&subTreeSymRefs, blockMap, symRefs);
}
}
}
else if (node->getNumChildren() > 0 &&
node->getFirstChild() &&
node->getFirstChild()->getOpCode().isCall() &&
node->getFirstChild()->getSymbolReference()->getReferenceNumber() == TR_prepareForOSR)
{
TR::Node *callNode = node->getFirstChild();
const int firstSymChildIndex = 2;
for (int32_t child = firstSymChildIndex; child+2 < callNode->getNumChildren(); child += 3)
{
TR::Node* loadNode = callNode->getChild(child);
int32_t symRefNumber = callNode->getChild(child+1)->getInt();
TR::SymbolReference* symRef = comp()->getSymRefTab()->getSymRef(symRefNumber);
//GC map for Monitored object temps are handled specially by lmmd
if (symRef->getSymbol()->holdsMonitoredObject()
|| symRef->getSymbol()->isThisTempForObjectCtor())
continue;
TR_BitVector subTreeSymRefs(comp()->trMemory()->currentStackRegion());
TR::NodeChecklist checklist(comp());
collectSubTreeSymRefs(loadNode, &subTreeSymRefs, checklist);
if (comp()->getOption(TR_TraceOSR))
{
traceMsg(comp(), "collect subTreeSymRefs of loadNode n%dn for original symRef #%d\n", loadNode->getGlobalIndex(), symRefNumber);
subTreeSymRefs.print(comp());
traceMsg(comp(), "\n");
}
if (!subTreeSymRefs.isEmpty())
{
TR_BitVector *symRefs = new (comp()->trStackMemory()) TR_BitVector(comp()->trMemory()->currentStackRegion());
updateDefiningSymRefs(&subTreeSymRefs, blockMap, symRefs);
(*prepareForOSRCallMap)[symRefNumber] = symRefs;
}
}
}
}
}
/*
* find all the symbols on the right hand side of the store node
*/
void
TR_OSRMethodData::collectSubTreeSymRefs(TR::Node *node, TR_BitVector *subTreeSymRefs, TR::NodeChecklist &checklist)
{
if (checklist.contains(node))
return;
else checklist.add(node);
if (node->getOpCode().hasSymbolReference() && node->getSymbolReference()->getSymbol()->isAutoOrParm())
{
subTreeSymRefs->set(node->getSymbolReference()->getReferenceNumber());
}
else if (node->getOpCode().isStoreReg() || node->getOpCode().isLoadReg())
{
subTreeSymRefs->set(node->getRegLoadStoreSymbolReference()->getReferenceNumber());
}
if (node->getNumChildren() > 0)
{
for (int i=0; i < node->getNumChildren(); i++)
collectSubTreeSymRefs(node->getChild(i), subTreeSymRefs, checklist);
}
}
void TR_OSRCompilationData::buildSymRefOrderMap()
{
for (auto i = 0U; i < getOSRMethodDataArray().size(); i++)
{
TR_OSRMethodData* osrMethodData = getOSRMethodDataArray()[i];
if (osrMethodData == NULL ||
osrMethodData->getOSRCodeBlock() == NULL)
continue;
TR::ResolvedMethodSymbol *methSym = osrMethodData->getMethodSymbol();
buildSymRefOrderMapAux(methSym->getPendingPushSymRefs());
buildSymRefOrderMapAux(methSym->getAutoSymRefs());
}
}
void TR_OSRCompilationData::buildSymRefOrderMapAux( TR_Array<List<TR::SymbolReference> >* symListArray)
{
if (symListArray == NULL)
return;
for (auto j = 0U; j < symListArray->size(); j++)
{
List<TR::SymbolReference>& symList = (*symListArray)[j];
bool sharedSlot = symList.getSize() > 1;
if (!sharedSlot) continue;
int32_t symRefOrder = 0;
ListIterator<TR::SymbolReference> symIt(&symList);
for (TR::SymbolReference* symRef = symIt.getFirst(); symRef; symRef = symIt.getNext(), symRefOrder++)
{
symRefOrderMap.Add(symRef->getReferenceNumber(), symRefOrder);
}
}
}
int32_t TR_OSRCompilationData::getSymRefOrder(int32_t symRefNumber)
{
CS2::HashIndex hashIndex;
if (symRefOrderMap.Locate(symRefNumber, hashIndex))
return symRefOrderMap.DataAt(hashIndex);
else
return -1;
}
TR::Compilation& operator<< (TR::Compilation& out, const TR_OSRCompilationData& osrCompilationData)
{
out << "{";
bool first = true;
for (auto i = 0U; i < osrCompilationData.getOSRMethodDataArray().size(); i++)
{
TR_OSRMethodData* osrMethodData = osrCompilationData.getOSRMethodDataArray()[i];
if (osrMethodData == NULL || osrMethodData->getOSRCodeBlock() == NULL || osrMethodData->isEmpty()) continue;
if (first)
out << "osrMethodDataArray: [\n";
else
out << ",\n";
out << "callerIdx:" << i-1 << " -> " << *osrMethodData ;
first = false;
}
if (!first)
out << "]\n";
const TR_OSRCompilationData::TR_Instruction2SharedSlotMap& array1 = osrCompilationData.instruction2SharedSlotMap;
if (array1.size() != 0)
{