-
Notifications
You must be signed in to change notification settings - Fork 747
/
Copy pathEscapeAnalysis.cpp
9974 lines (8811 loc) · 407 KB
/
EscapeAnalysis.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
*******************************************************************************/
#ifdef J9ZTPF
#define __TPF_DO_NOT_MAP_ATOE_REMOVE
#endif
#include "optimizer/EscapeAnalysis.hpp"
#include "optimizer/EscapeAnalysisTools.hpp"
#include <algorithm>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "codegen/CodeGenerator.hpp"
#include "env/FrontEnd.hpp"
#include "codegen/RecognizedMethods.hpp"
#include "compile/Compilation.hpp"
#include "compile/CompilationTypes.hpp"
#include "compile/Method.hpp"
#include "compile/ResolvedMethod.hpp"
#include "compile/SymbolReferenceTable.hpp"
#include "compile/VirtualGuard.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "control/Recompilation.hpp"
#include "control/RecompilationInfo.hpp"
#include "env/CompilerEnv.hpp"
#include "env/ObjectModel.hpp"
#include "env/TRMemory.hpp"
#include "env/jittypes.h"
#include "env/TypeLayout.hpp"
#include "env/VMAccessCriticalSection.hpp"
#include "env/VMJ9.h"
#include "il/AliasSetInterface.hpp"
#include "il/AutomaticSymbol.hpp"
#include "il/Block.hpp"
#include "il/DataTypes.hpp"
#include "il/ILOpCodes.hpp"
#include "il/ILOps.hpp"
#include "il/MethodSymbol.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/ParameterSymbol.hpp"
#include "il/ResolvedMethodSymbol.hpp"
#include "il/StaticSymbol.hpp"
#include "il/Symbol.hpp"
#include "il/SymbolReference.hpp"
#include "il/TreeTop.hpp"
#include "il/TreeTop_inlines.hpp"
#include "infra/Array.hpp"
#include "infra/Assert.hpp"
#include "infra/BitVector.hpp"
#include "infra/Cfg.hpp"
#include "infra/Checklist.hpp"
#include "infra/Link.hpp"
#include "infra/List.hpp"
#include "infra/SimpleRegex.hpp"
#include "infra/String.hpp"
#include "infra/TRCfgEdge.hpp"
#include "infra/TRCfgNode.hpp"
#include "optimizer/Inliner.hpp"
#include "optimizer/Optimization.hpp"
#include "optimizer/OptimizationManager.hpp"
#include "optimizer/Optimizations.hpp"
#include "optimizer/Optimizer.hpp"
#include "optimizer/Structure.hpp"
#include "optimizer/TransformUtil.hpp"
#include "optimizer/DataFlowAnalysis.hpp"
#include "optimizer/UseDefInfo.hpp"
#include "optimizer/ValueNumberInfo.hpp"
#include "optimizer/LocalOpts.hpp"
#include "optimizer/MonitorElimination.hpp"
#include "ras/Debug.hpp"
#include "runtime/J9Profiler.hpp"
#include "runtime/J9Runtime.hpp"
#define OPT_DETAILS "O^O ESCAPE ANALYSIS: "
#define MAX_SIZE_FOR_ONE_CONTIGUOUS_OBJECT 2416 // Increased from 72
#define MAX_SIZE_FOR_ALL_OBJECTS 3000 // Increased from 500
#define MAX_SNIFF_BYTECODE_SIZE 1600
#define LOCAL_OBJECTS_COLLECTABLE 1
static bool blockIsInLoop(TR::Block *block)
{
for (TR_Structure *s = block->getStructureOf()->getParent(); s; s = s->getParent())
{
TR_RegionStructure *region = s->asRegion();
if (region->isNaturalLoop() || region->containsInternalCycles())
return true;
}
return false;
}
TR_EscapeAnalysis::TR_EscapeAnalysis(TR::OptimizationManager *manager)
: TR::Optimization(manager),
_newObjectNoZeroInitSymRef(NULL),
_newValueSymRef(NULL),
_newArrayNoZeroInitSymRef(NULL),
_dependentAllocations(manager->comp()->trMemory()),
_inlineCallSites(manager->comp()->trMemory()),
_dememoizedAllocs(manager->comp()->trMemory()),
_devirtualizedCallSites(manager->comp()->trMemory()),
_initializedHeapifiedTemps(NULL),
_aNewArrayNoZeroInitSymRef(NULL)
{
static char *disableValueTypeEASupport = feGetEnv("TR_DisableValueTypeEA");
_disableValueTypeStackAllocation = (disableValueTypeEASupport != NULL);
_newObjectNoZeroInitSymRef = comp()->getSymRefTab()->findOrCreateNewObjectNoZeroInitSymbolRef(0);
_newValueSymRef = comp()->getSymRefTab()->findOrCreateNewValueSymbolRef(0);
_newArrayNoZeroInitSymRef = comp()->getSymRefTab()->findOrCreateNewArrayNoZeroInitSymbolRef(0);
_aNewArrayNoZeroInitSymRef = comp()->getSymRefTab()->findOrCreateANewArrayNoZeroInitSymbolRef(0);
_maxPassNumber = 0;
_dememoizationSymRef = NULL;
_createStackAllocations = true;
_createLocalObjects = cg()->supportsStackAllocations();
_desynchronizeCalls = true;
#if CHECK_MONITORS
/* monitors */
_removeMonitors = true;
#endif
}
char *TR_EscapeAnalysis::getClassName(TR::Node *classNode)
{
char *className = NULL;
if (classNode->getOpCodeValue() == TR::loadaddr)
{
TR::SymbolReference *symRef = classNode->getSymbolReference();
if (symRef->getSymbol()->isClassObject())
{
int32_t classNameLength;
char *classNameChars = TR::Compiler->cls.classNameChars(comp(), symRef, classNameLength);
if (NULL != classNameChars)
{
className = (char *)trMemory()->allocateStackMemory(classNameLength+1, TR_Memory::EscapeAnalysis);
memcpy(className, classNameChars, classNameLength);
className[classNameLength] = 0;
}
}
}
return className;
}
bool TR_EscapeAnalysis::isImmutableObject(TR::Node *node)
{
// For debugging issues with the special handling of immutable objects
// that allows them to be discontiguously allocated even if they escape
static char *disableImmutableObjectHandling = feGetEnv("TR_disableEAImmutableObjectHandling");
if (disableImmutableObjectHandling)
{
return false;
}
if (node->getOpCodeValue() == TR::newvalue)
{
return true;
}
if (node->getOpCodeValue() != TR::New)
{
return false;
}
TR::Node *classNode = node->getFirstChild();
TR_OpaqueClassBlock *clazz = (TR_OpaqueClassBlock *)classNode->getSymbol()->getStaticSymbol()->getStaticAddress();
if (TR::Compiler->cls.isValueTypeClass(clazz))
{
return true;
}
char *className = getClassName(classNode);
if (NULL != className &&
!strncmp("java/lang/", className, 10) &&
(!strcmp("Integer", &className[10]) ||
!strcmp("Long", &className[10]) ||
!strcmp("Short", &className[10]) ||
!strcmp("Byte", &className[10]) ||
!strcmp("Boolean", &className[10]) ||
!strcmp("Character", &className[10]) ||
!strcmp("Double", &className[10]) ||
!strcmp("Float", &className[10])))
{
return true;
}
return false;
}
bool TR_EscapeAnalysis::isImmutableObject(Candidate *candidate)
{
if (candidate->_isImmutable)
return true;
bool b = isImmutableObject(candidate->_node);
candidate->_isImmutable = b;
return b;
}
int32_t TR_EscapeAnalysis::perform()
{
if (comp()->isOptServer() && (comp()->getMethodHotness() <= warm))
return 0;
// EA generates direct stores/loads to instance field which is different
// from a normal instance field read/write. Field watch would need special handling
// for stores/loads generated by EA.
if (comp()->incompleteOptimizerSupportForReadWriteBarriers())
return 0;
static char *doESCNonQuiet = feGetEnv("TR_ESCAPENONQUIET");
if (doESCNonQuiet && comp()->getOutFile() == NULL)
return 0;
int32_t nodeCount = 0;
vcount_t visitCount = comp()->incVisitCount(); //@TODO: needs a change to TR_Node's
//countNumberOfNodesInSubtree
//we should probably leave it as is
//for the next iteration
TR::TreeTop *tt = comp()->getStartTree();
for (; tt; tt = tt->getNextTreeTop())
nodeCount += tt->getNode()->countNumberOfNodesInSubtree(visitCount);
// Set thresholds depending on the method's hotness
//
TR_Hotness methodHotness = comp()->getMethodHotness();
if (methodHotness > hot)
{
_maxPassNumber = 6;
_maxSniffDepth = 8;
_maxInlinedBytecodeSize = 5000 - nodeCount;
}
else
{
_maxPassNumber = 3;
//_maxPassNumber = (methodHotness < hot) ? 2 : 3;
_maxSniffDepth = 4;
_maxInlinedBytecodeSize = 4000 - nodeCount;
}
// under HCR we can protect the top level sniff with an HCR guard
// nested sniffs are not currently supported
if (comp()->getHCRMode() != TR::none)
_maxSniffDepth = 1;
TR_ASSERT_FATAL(_maxSniffDepth < 16, "The argToCall and nonThisArgToCall flags are 16 bits - a depth limit greater than 16 will not fit in these flags");
if (getLastRun())
_maxPassNumber = 0; // Notwithstanding our heuristics, if this is the last run, our max "pass number" is zero (which is the first pass)
_maxPeekedBytecodeSize = comp()->getMaxPeekedBytecodeSize();
// Escape analysis is organized so that it may decide another pass of
// the analysis is required immediately after the current one. It leaves
// it up to the optimization strategy to re-invoke the analysis, but we
// keep track here of the number of passes through the analysis so we
// can restrict the number of passes. Each time we end the local loop of
// passes the current pass number is reset to zero in case escape analysis
// is called again later in the optimization strategy.
//
if (manager()->numPassesCompleted() == 0)
{
//
void *data = manager()->getOptData();
TR_BitVector *peekableCalls = NULL;
if (data != NULL)
{
peekableCalls = ((TR_EscapeAnalysis::PersistentData *)data)->_peekableCalls;
delete ((TR_EscapeAnalysis::PersistentData *) data) ;
manager()->setOptData(NULL);
}
manager()->setOptData(new (comp()->allocator()) TR_EscapeAnalysis::PersistentData(comp()));
if (peekableCalls != NULL)
((TR_EscapeAnalysis::PersistentData *)manager()->getOptData())->_peekableCalls = peekableCalls;
}
else
{
if (trace())
{
/////printf("secs Performing pass %d of Escape Analysis for %s\n", _currentPass, comp()->signature());
}
}
int32_t cost = 0;
{
TR::StackMemoryRegion stackMemoryRegion(*trMemory());
_callsToProtect = new (trStackMemory()) CallLoadMap(CallLoadMapComparator(), comp()->trMemory()->currentStackRegion());
#if CHECK_MONITORS
/* monitors */
TR_MonitorStructureChecker inspector;
if (inspector.checkMonitorStructure(comp()->getFlowGraph()))
{
_removeMonitors = false;
if (trace())
traceMsg(comp(), "Disallowing monitor-removal because of strange monitor structure\n");
}
#endif
cost = performAnalysisOnce();
if (!_callsToProtect->empty() && manager()->numPassesCompleted() < _maxPassNumber)
{
TR::CFG *cfg = comp()->getFlowGraph();
TR::Block *block = NULL;
TR::TreeTop *lastTree = comp()->findLastTree();
TR_EscapeAnalysisTools tools(comp());
RemainingUseCountMap *remainingUseCount = new (comp()->trStackMemory()) RemainingUseCountMap(RemainingUseCountMapComparator(), comp()->trMemory()->currentStackRegion());
for (TR::TreeTop *tt = comp()->findLastTree(); tt != NULL; tt = tt->getPrevTreeTop())
{
TR::Node *node = tt->getNode();
if (node->getOpCodeValue() == TR::BBEnd)
block = node->getBlock();
else if (node->getStoreNode() && node->getStoreNode()->getOpCode().isStoreDirect())
node = node->getStoreNode()->getFirstChild();
else if (node->getOpCode().isCheck() || node->getOpCode().isAnchor() || node->getOpCodeValue() == TR::treetop)
node = node->getFirstChild();
auto nodeLookup = _callsToProtect->find(node);
if (nodeLookup == _callsToProtect->end()
|| TR_EscapeAnalysisTools::isFakeEscape(node)
|| node->getSymbol() == NULL
|| node->getSymbol()->getResolvedMethodSymbol() == NULL
|| node->getSymbol()->getResolvedMethodSymbol()->getResolvedMethod() == NULL)
continue;
if (node->getReferenceCount() > 1)
{
auto useCount = remainingUseCount->find(node);
if (useCount == remainingUseCount->end())
{
(*remainingUseCount)[node] = node->getReferenceCount() - 1;
continue;
}
if (useCount->second > 1)
{
useCount->second -= 1;
continue;
}
}
if (!performTransformation(comp(), "%sHCR CALL PEEKING: Protecting call [%p] n%dn with an HCR guard and escape helper\n", OPT_DETAILS, node, node->getGlobalIndex()))
continue;
((TR_EscapeAnalysis::PersistentData*)manager()->getOptData())->_processedCalls->set(node->getGlobalIndex());
_repeatAnalysis = true;
optimizer()->setValueNumberInfo(NULL);
cfg->invalidateStructure();
TR::TreeTop *prevTT = tt->getPrevTreeTop();
TR::Block *callBlock = block->split(tt, comp()->getFlowGraph(), true, true);
// check uncommoned nodes for stores of the candidate - if so we need to add the new temp to the
// list of loads
for (TR::TreeTop *itr = block->getExit(); itr != prevTT; itr = itr->getPrevTreeTop())
{
TR::Node *storeNode = itr->getNode()->getStoreNode();
if (storeNode
&& storeNode->getOpCodeValue() == TR::astore
&& nodeLookup->second.first->get(storeNode->getFirstChild()->getGlobalIndex()))
{
nodeLookup->second.second->set(storeNode->getSymbolReference()->getReferenceNumber());
}
}
TR::Node *guard = TR_VirtualGuard::createHCRGuard(comp(),
node->getByteCodeInfo().getCallerIndex(),
node,
NULL,
node->getSymbol()->getResolvedMethodSymbol(),
node->getSymbol()->getResolvedMethodSymbol()->getResolvedMethod()->classOfMethod());
block->getExit()->insertBefore(TR::TreeTop::create(comp(), guard));
TR::Block *heapificationBlock = TR::Block::createEmptyBlock(node, comp(), MAX_COLD_BLOCK_COUNT);
heapificationBlock->getExit()->join(lastTree->getNextTreeTop());
lastTree->join(heapificationBlock->getEntry());
lastTree = heapificationBlock->getExit();
heapificationBlock->setIsCold();
guard->setBranchDestination(heapificationBlock->getEntry());
cfg->addNode(heapificationBlock);
cfg->addEdge(block, heapificationBlock);
cfg->addEdge(heapificationBlock, callBlock);
heapificationBlock->getExit()->insertBefore(TR::TreeTop::create(comp(), TR::Node::create(node, TR::Goto, 0, callBlock->getEntry())));
tools.insertFakeEscapeForLoads(heapificationBlock, node, *nodeLookup->second.second);
traceMsg(comp(), "Created heapification block_%d\n", heapificationBlock->getNumber());
((TR_EscapeAnalysis::PersistentData*)manager()->getOptData())->_peekableCalls->set(node->getGlobalIndex());
_callsToProtect->erase(nodeLookup);
tt = prevTT->getNextTreeTop();
}
}
} // scope of the stack memory region
if (_repeatAnalysis && manager()->numPassesCompleted() < _maxPassNumber)
{
// Ask the optimizer to repeat this analysis
//
requestOpt(OMR::eachEscapeAnalysisPassGroup);
manager()->incNumPassesCompleted();
}
else
{
// Don't repeat this analysis, reset the pass count for next time
//
manager()->setNumPassesCompleted(0);
}
return cost;
}
const char *
TR_EscapeAnalysis::optDetailString() const throw()
{
return "O^O ESCAPE ANALYSIS: ";
}
void TR_EscapeAnalysis::rememoize(Candidate *candidate, bool mayDememoizeNextTime)
{
if (!candidate->_dememoizedConstructorCall)
return;
TR_ASSERT(candidate->_treeTop->getEnclosingBlock() == candidate->_dememoizedConstructorCall->getEnclosingBlock(),
"Dememoized constructor call %p must be in the same block as allocation %p", candidate->_treeTop->getNode(), candidate->_dememoizedConstructorCall->getNode());
if (trace())
traceMsg(comp(), " Rememoizing%s [%p] using constructor call [%p]\n", mayDememoizeNextTime?"":" and inlining", candidate->_node, candidate->_dememoizedConstructorCall->getNode()->getFirstChild());
// Change trees back
//
candidate->_node->getFirstChild()->recursivelyDecReferenceCount(); // remove loadaddr of class
candidate->_node->setAndIncChild(0, candidate->_dememoizedConstructorCall->getNode()->getFirstChild()->getSecondChild()); // original call argument
TR::Node::recreate(candidate->_node, TR::acall);
candidate->_node->setSymbolReference(candidate->_dememoizedMethodSymRef);
candidate->_dememoizedConstructorCall->unlink(true);
// Only rememoize once
//
_inlineCallSites.remove(candidate->_dememoizedConstructorCall);
candidate->_dememoizedConstructorCall = NULL;
candidate->_dememoizedMethodSymRef = NULL;
if (!mayDememoizeNextTime)
{
// Inline the memoization method so we can apply EA to it even though dememoization failed.
// This also prevents us from re-trying dememoization when it's hopeless.
//
_inlineCallSites.add(candidate->_treeTop);
}
}
static const char *ynmString(TR_YesNoMaybe arg)
{
switch (arg)
{
case TR_yes:
return "yes";
case TR_no:
return "no";
case TR_maybe:
return "maybe";
}
return "";
}
static TR_YesNoMaybe ynmOr(TR_YesNoMaybe left, TR_YesNoMaybe right)
{
switch (left)
{
case TR_yes:
return TR_yes;
case TR_no:
return right;
case TR_maybe:
return (right == TR_yes)? TR_yes : TR_maybe;
}
return TR_maybe;
}
static TR_YesNoMaybe candidateHasField(Candidate *candidate, TR::Node *fieldNode, int32_t fieldOffset, TR_EscapeAnalysis *ea)
{
TR::Compilation *comp = ea->comp();
TR::SymbolReference *fieldSymRef = fieldNode->getSymbolReference();
int32_t fieldSize = fieldNode->getSize();
int32_t minHeaderSize, maxHeaderSize;
if (candidate->_origKind == TR::New || candidate->_origKind == TR::newvalue)
{
minHeaderSize = maxHeaderSize = comp->fej9()->getObjectHeaderSizeInBytes();
}
else
{
minHeaderSize = std::min(TR::Compiler->om.contiguousArrayHeaderSizeInBytes(), TR::Compiler->om.discontiguousArrayHeaderSizeInBytes());
maxHeaderSize = std::max(TR::Compiler->om.contiguousArrayHeaderSizeInBytes(), TR::Compiler->om.discontiguousArrayHeaderSizeInBytes());
}
TR_YesNoMaybe withinObjectBound = TR_maybe;
TR_YesNoMaybe withinObjectHeader = TR_maybe;
TR_YesNoMaybe belongsToAllocatedClass = TR_maybe;
TR_YesNoMaybe result = TR_maybe;
if (fieldOffset + fieldSize <= candidate->_size)
withinObjectBound = TR_yes;
else
withinObjectBound = TR_no;
if (fieldOffset + fieldSize <= minHeaderSize)
withinObjectHeader = TR_yes;
else if (fieldOffset > maxHeaderSize)
withinObjectHeader = TR_no;
else
withinObjectHeader = TR_maybe;
// Test a few conditions to try to avoid calling getDeclaringClassFromFieldOrStatic
// because that requires VM access.
//
static char *debugEAFieldValidityCheck = feGetEnv("TR_debugEAFieldValidityCheck");
if (withinObjectHeader == TR_yes)
{
result = TR_yes;
}
else
{
TR_OpaqueClassBlock *fieldClassInCP = fieldSymRef->getOwningMethod(comp)->getClassFromFieldOrStatic(comp, fieldSymRef->getCPIndex());
if ( fieldClassInCP
&& TR_yes == comp->fej9()->isInstanceOf((TR_OpaqueClassBlock*)candidate->_class, fieldClassInCP, true))
{
// Short cut: There's no need to look up the declaring class of the
// field because we already know the candidate's class contains the
// field since it inherits the class we're using to access the field
// in the constant pool.
//
if (!debugEAFieldValidityCheck
|| performTransformation(comp, "%sQuick Using candidateHasField=yes (withinObjectBound=%s) for candidate [%p] field access [%p]\n",
OPT_DETAILS, ynmString(withinObjectBound), candidate->_node, fieldNode))
{
belongsToAllocatedClass = TR_yes;
result = TR_yes;
}
}
}
// If we're still not sure, go ahead and try getDeclaringClassFromFieldOrStatic
//
if (result == TR_maybe)
{
TR::VMAccessCriticalSection candidateHasFieldCriticalSection(comp->fej9(),
TR::VMAccessCriticalSection::tryToAcquireVMAccess,
comp);
if (candidateHasFieldCriticalSection.hasVMAccess())
{
TR_OpaqueClassBlock *fieldDeclaringClass = fieldSymRef->getOwningMethod(comp)->getDeclaringClassFromFieldOrStatic(comp, fieldSymRef->getCPIndex());
if (fieldDeclaringClass)
belongsToAllocatedClass = comp->fej9()->isInstanceOf((TR_OpaqueClassBlock*)candidate->_class, fieldDeclaringClass, true);
result = ynmOr(withinObjectHeader, belongsToAllocatedClass);
if (debugEAFieldValidityCheck)
{
if (!performTransformation(comp, "%sUsing candidateHasField=%s (withinObjectBound=%s) for candidate [%p] field access [%p]\n",
OPT_DETAILS, ynmString(result), ynmString(withinObjectBound), candidate->_node, fieldNode))
{
// Conservatively return TR_no.
// We do the performTransformation even if result is already TR_no
// just to support countOptTransformations.
//
result = TR_no;
}
}
}
else if (ea->trace())
{
traceMsg(comp, " Unable to acquire vm access; conservatively assume field [%p] does not belong to candidate [%p]\n", fieldNode, candidate->_node);
}
}
if (debugEAFieldValidityCheck)
{
if ( (withinObjectBound != result)
&& !performTransformation(comp, "%sSubstituting candidateHasField=%s (withinObjectBound=%s) for candidate [%p] field access [%p]\n",
OPT_DETAILS, ynmString(result), ynmString(withinObjectBound), candidate->_node, fieldNode))
{
// Use old logic for debugging purposes
// Note: This is not necessarily correct, hence the env var guard.
// Once we have confidence in the newer logic, this withinObjectBound
// logic can eventually be deleted.
//
result = withinObjectBound;
}
}
if (ea->trace())
traceMsg(comp, " Candidate [%p] field access [%p] candidateHasField=%s (withinObjectBound=%s withinObjectHeader=%s belongsToAllocatedClass=%s)\n",
candidate->_node, fieldNode,
ynmString(result),
ynmString(withinObjectBound),
ynmString(withinObjectHeader),
ynmString(belongsToAllocatedClass));
return result;
}
//
// Hack markers
//
// PR 78801: Currently, BCD shadows don't have reliable size information, and
// BCD temps require size information. This makes it hard to create BCD temps
// from shadows.
//
#define CANT_CREATE_BCD_TEMPS (1)
int32_t TR_EscapeAnalysis::performAnalysisOnce()
{
int32_t cost = 0;
Candidate *candidate, *next;
if (trace())
{
traceMsg(comp(), "Starting Escape Analysis pass %d\n", manager()->numPassesCompleted());
comp()->dumpMethodTrees("Trees before Escape Analysis");
}
_useDefInfo = NULL; // Build these only if required
_invalidateUseDefInfo = false;
_valueNumberInfo = NULL;
_otherDefsForLoopAllocation = NULL;
_methodSymbol = NULL;
_nodeUsesThroughAselect = NULL;
_repeatAnalysis = false;
_somethingChanged = false;
_inBigDecimalAdd = false;
_candidates.setFirst(NULL);
_inlineCallSites.deleteAll();
_dependentAllocations.deleteAll();
_fixedVirtualCallSites.setFirst(NULL);
_parms = NULL;
_ignorableUses = NULL;
_nonColdLocalObjectsValueNumbers = NULL;
_allLocalObjectsValueNumbers = NULL;
_visitedNodes = NULL;
_aliasesOfAllocNode = NULL;
_aliasesOfOtherAllocNode = NULL;
_notOptimizableLocalObjectsValueNumbers = NULL;
_notOptimizableLocalStringObjectsValueNumbers = NULL;
_initializedHeapifiedTemps = NULL;
// Walk the trees and find the "new" nodes.
// Any that are candidates for local allocation or desynchronization are
// added to the list of candidates.
//
findCandidates();
cost++;
if (!_candidates.isEmpty())
{
_useDefInfo = optimizer()->getUseDefInfo();
_blocksWithFlushOnEntry = new (trStackMemory()) TR_BitVector(comp()->getFlowGraph()->getNextNodeNumber(), trMemory(), stackAlloc);
_visitedNodes = new (trStackMemory()) TR_BitVector(comp()->getNodeCount(), trMemory(), stackAlloc, growable);
_aliasesOfAllocNode = new (trStackMemory()) TR_BitVector(0, trMemory(), stackAlloc, growable);
_aliasesOfOtherAllocNode = new (trStackMemory()) TR_BitVector(0, trMemory(), stackAlloc, growable);
if (!_useDefInfo)
{
if (trace())
traceMsg(comp(), "Can't do Escape Analysis, no use/def information\n");
_candidates.setFirst(NULL);
}
_valueNumberInfo = optimizer()->getValueNumberInfo();
if (!_valueNumberInfo)
{
if (trace())
traceMsg(comp(), "Can't do Escape Analysis, no value number information\n");
_candidates.setFirst(NULL);
}
else
{
_ignorableUses = new (trStackMemory()) TR_BitVector(0, trMemory(), stackAlloc);
_nonColdLocalObjectsValueNumbers = new (trStackMemory()) TR_BitVector(_valueNumberInfo->getNumberOfValues(), trMemory(), stackAlloc);
_allLocalObjectsValueNumbers = new (trStackMemory()) TR_BitVector(_valueNumberInfo->getNumberOfValues(), trMemory(), stackAlloc);
_notOptimizableLocalObjectsValueNumbers = new (trStackMemory()) TR_BitVector(_valueNumberInfo->getNumberOfValues(), trMemory(), stackAlloc);
_notOptimizableLocalStringObjectsValueNumbers = new (trStackMemory()) TR_BitVector(_valueNumberInfo->getNumberOfValues(), trMemory(), stackAlloc);
}
}
if ( !_candidates.isEmpty())
{
findLocalObjectsValueNumbers();
findIgnorableUses();
}
// Complete the candidate info by finding all uses and defs that are reached
// from each candidate.
//
if (!_candidates.isEmpty())
{
checkDefsAndUses();
cost++;
}
if (trace())
printCandidates("Initial candidates");
// Look through the trees to see which candidates escape the method. This
// may involve sniffing into called methods.
//
_sniffDepth = 0;
_parms = NULL;
if (!_candidates.isEmpty())
{
//if (comp()->getMethodSymbol()->mayContainMonitors())
if (cg()->getEnforceStoreOrder())
{
TR_FlowSensitiveEscapeAnalysis flowSensitiveAnalysis(comp(), optimizer(), comp()->getFlowGraph()->getStructure(), this);
}
bool ignoreRecursion = false;
checkEscape(comp()->getStartTree(), false, ignoreRecursion);
cost++;
}
//fixup those who have virtual calls
for (candidate = _candidates.getFirst(); candidate; candidate = next)
{
next = candidate->getNext();
if (!candidate->isLocalAllocation())
continue;
if (!candidate->hasVirtualCallsToBeFixed())
continue;
dumpOptDetails(comp(), "Fixup indirect calls sniffed for candidate =%p\n",candidate->_node);
TR::TreeTop *callSite, *callSiteNext = NULL;
ListIterator<TR::TreeTop> it(candidate->getVirtualCallSitesToBeFixed());
for (callSite = it.getFirst(); callSite; callSite = callSiteNext)
{
//TR::TreeTop *directCallTree = findCallSiteFixed(callSite);
bool found = findCallSiteFixed(callSite);
callSiteNext = it.getNext();
if (!found)
{
if (!_devirtualizedCallSites.find(callSite))
_devirtualizedCallSites.add(callSite);
_fixedVirtualCallSites.add(new (trStackMemory()) TR_EscapeAnalysis::TR_CallSitesFixedMapper(callSite, NULL));
dumpOptDetails(comp(), "adding Map:vCall = %p direct = %p\n",callSite, NULL);
_repeatAnalysis = true;
_somethingChanged = true;
candidate->getCallSites()->remove(callSite);
//candidate->getCallSites()->add(directCallTree);
}
else
{
dumpOptDetails(comp(), "found MAp for %p\n",callSite);
//fixup the callSite list
candidate->getCallSites()->remove(callSite);
//candidate->getCallSites()->add(directCallTree);
}
}
candidate->setLocalAllocation(false);
if (trace())
traceMsg(comp(), " Make [%p] non-local because we'll try it again in another pass\n", candidate->_node);
}
//fixup those callSite which were devirtualize
//fixup the coldBlockInfo too
for (candidate = _candidates.getFirst(); candidate; candidate = next)
{
next = candidate->getNext();
if (!candidate->isLocalAllocation())
continue;
TR::TreeTop *callSite, *callSiteNext = NULL;
ListIterator<TR::TreeTop> it(candidate->getCallSites());
for (callSite = it.getFirst(); callSite; callSite = callSiteNext)
{
callSiteNext = it.getNext();
//TR::TreeTop *directCallTree = findCallSiteFixed(callSite);
bool found = findCallSiteFixed(callSite);
if (found)
{
if (trace())
traceMsg(comp(), "replacing callsite %p for candidate %p with it's direct call\n",callSite,candidate->_node);
candidate->getCallSites()->remove(callSite);
candidate->setLocalAllocation(false);
//candidate->getCallSites()->add(directCallTree);
}
}
ListIterator<TR_ColdBlockEscapeInfo> coldBlockInfoIt(candidate->getColdBlockEscapeInfo());
for (TR_ColdBlockEscapeInfo *info = coldBlockInfoIt.getFirst(); info != NULL; info = coldBlockInfoIt.getNext())
{
ListIterator<TR::TreeTop> treesIt(info->getTrees());
for (TR::TreeTop *escapeTree = treesIt.getFirst(); escapeTree != NULL; escapeTree = treesIt.getNext())
{
if (findCallSiteFixed(escapeTree))
{
candidate->setLocalAllocation(false);
break;
}
}
if (!candidate->isLocalAllocation())
break;
}
}
// Check whether tentative dememoization can proceed
//
bool shouldRepeatDueToDememoization = false;
for (candidate = _candidates.getFirst(); candidate; candidate = next)
{
next = candidate->getNext();
if (candidate->_dememoizedConstructorCall)
{
if ( candidate->isLocalAllocation()
&& !candidate->mustBeContiguousAllocation()
&& candidate->getCallSites()->isSingleton()
&& candidate->getCallSites()->find(candidate->_dememoizedConstructorCall)
&& performTransformation(comp(), "%sDememoizing [%p]\n", OPT_DETAILS, candidate->_node))
{
// Dememoization worked!
// Inline the constructor and catch this candidate on the next pass
candidate->setLocalAllocation(false);
if (trace())
traceMsg(comp(), "2 setting local alloc %p to false\n", candidate->_node);
_inlineCallSites.add(candidate->_dememoizedConstructorCall);
_repeatAnalysis = true;
}
else
{
// Dememoization failed on this pass; must re-memoize instead
bool mayDememoizeNextTime = true;
// allow the call to be inlined at least in the last pass
// and prevent from dememoizing the call again
//
if (candidate->isLocalAllocation())
_repeatAnalysis = true;
if (_repeatAnalysis)
{
if (manager()->numPassesCompleted() == _maxPassNumber-1)
mayDememoizeNextTime = false;
else
shouldRepeatDueToDememoization = true;
}
else
mayDememoizeNextTime = false;
if (trace())
{
traceMsg(comp(), " Fail [%p] because dememoization failed; will%s attempt again on next EA pass\n", candidate->_node, mayDememoizeNextTime? "":" NOT");
traceMsg(comp(), " Fail [%p] because dememoization failed; will%s attempt dememoization again on next EA pass\n", candidate->_node, mayDememoizeNextTime? "":" NOT");
traceMsg(comp(), " 4 booleans are %d %d %d %d\n", candidate->isLocalAllocation(), candidate->mustBeContiguousAllocation(), candidate->getCallSites()->isSingleton(), candidate->getCallSites()->find(candidate->_dememoizedConstructorCall));
}
// if mayDememoizeNextTime is false, then the following call to
// rememoize will add valueOf to the list of calls to be inlined
//
rememoize(candidate, mayDememoizeNextTime);
if (trace())
traceMsg(comp(), "8 removing cand %p to false\n", candidate->_node);
}
_candidates.remove(candidate);
}
}
// Decide whether or not another pass of escape analysis is appropriate.
// If we are allowed to do another pass and there are candidates which are
// contiguous only because they are arguments to calls and those calls can
// be inlined, then inline the calls and mark the candidates so that they
// are not replaced in this pass.
// This should result in the candidates being found to be non-contiguous
// candidates in a later pass.
//
if (manager()->numPassesCompleted() < _maxPassNumber)
{
for (candidate = _candidates.getFirst(); candidate; candidate = next)
{
next = candidate->getNext();
if (!candidate->isLocalAllocation())
continue;
if (trace())
traceMsg(comp(), " 0 Look at [%p] must be %d\n", candidate->_node, candidate->mustBeContiguousAllocation());
if (candidate->mustBeContiguousAllocation() || !candidate->hasCallSites() ||
(candidate->_stringCopyNode && (candidate->_stringCopyNode != candidate->_node) &&
!candidate->escapesInColdBlocks() &&
!candidate->isLockedObject() &&
!candidate->_seenSelfStore &&
!candidate->_seenStoreToLocalObject))
continue;
if (trace())
traceMsg(comp(), " 0.5 Look at [%p]\n", candidate->_node);
// If any of the call sites for this parm is a guarded virtual call - there would be nothing
// gained by inlining any of them - we will still end up with a call and will have to make
// it contiguous
//
TR::TreeTop *callSite;
bool seenGuardedCall = false;
ListIterator<TR::TreeTop> it(candidate->getCallSites());
for (callSite = it.getFirst(); callSite; callSite = it.getNext())
{
TR::Node *callNode = callSite->getNode();
if (callNode->isTheVirtualCallNodeForAGuardedInlinedCall())
{
seenGuardedCall = true;
break;
}
}
if (trace())
traceMsg(comp(), " 1 Look at [%p]\n", candidate->_node);
// If any of the calls is a guarded virtual call or
// If the depth of inlining required is greater than the number of
// passes left, or if the number of bytecodes needed to be inlined
// will exceed the maximum, enough inlining can't be done.
// In this case force the candidate to be contiguous.
//
if (seenGuardedCall ||
candidate->_maxInlineDepth >= (_maxPassNumber-manager()->numPassesCompleted()) ||
candidate->_inlineBytecodeSize > (_maxInlinedBytecodeSize-getOptData()->_totalInlinedBytecodeSize))
{
candidate->setMustBeContiguousAllocation();
if (trace())
traceMsg(comp(), " Make [%p] contiguous because we can't inline enough\n", candidate->_node);
continue;
}
// Take each call site that needs to be inlined and add it to the
// list of inlined call sites
//
while ((callSite = candidate->getCallSites()->popHead()))
{
TR::Node *node = callSite->getNode();
if (node->getOpCode().isTreeTop())
node = node->getFirstChild();
//traceMsg(comp(), "For alloc node %p call site %p\n", candidate->_node, node);
//if (node->isTheVirtualCallNodeForAGuardedInlinedCall())
if (!_inlineCallSites.find(callSite))
{
if (comp()->getMethodHotness() <= warm)
{
// Up to warm, inlining at this point can interfere with existing
// profiling and compilation heuristics, causing us to miss even