-
Notifications
You must be signed in to change notification settings - Fork 391
/
OMRRegisterCandidate.cpp
3753 lines (3252 loc) · 154 KB
/
OMRRegisterCandidate.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 OMRZTPF
#define __TPF_DO_NOT_MAP_ATOE_REMOVE
#endif
#include "optimizer/RegisterCandidate.hpp"
#include <algorithm>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "codegen/CodeGenerator.hpp"
#include "env/FrontEnd.hpp"
#include "codegen/LinkageConventionsEnum.hpp"
#include "codegen/RegisterConstants.hpp"
#include "compile/Compilation.hpp"
#include "compile/SymbolReferenceTable.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "cs2/bitvectr.h"
#include "cs2/hashtab.h"
#include "cs2/sparsrbit.h"
#include "env/CompilerEnv.hpp"
#include "env/TRMemory.hpp"
#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/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/ParameterSymbol.hpp"
#include "il/RegisterMappedSymbol.hpp"
#include "il/ResolvedMethodSymbol.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/Link.hpp"
#include "infra/List.hpp"
#include "infra/Checklist.hpp"
#include "infra/CfgEdge.hpp"
#include "infra/CfgNode.hpp"
#include "optimizer/Optimizations.hpp"
#include "optimizer/Optimizer.hpp"
#include "optimizer/Structure.hpp"
#include "optimizer/GlobalRegister.hpp"
#include "optimizer/GlobalRegister_inlines.hpp"
#include "ras/Debug.hpp"
//TODO:GRA: if we are going to have two versions of GRA one with Meta Data and one without then we can do someting here
// for different compilation level then we can have two version of this, one using CPIndex and one (i.e. with MetaData)
// using getReferenceNumber
#define GET_INDEX_FOR_CANDIDATE_FOR_SYMREF(S) (S)->getReferenceNumber()
#define CANDIDATE_FOR_SYMREF_SIZE (comp()->getSymRefCount()+1)
#define OPT_DETAILS "O^O GLOBAL REGISTER ASSIGNER: "
//static TR_BitVector *blocksVisited = NULL;
// Duplicated in GlobalRegisterAllocator.cpp. TODO try and factor this out
#define keepAllStores false
OMR::GlobalSet::GlobalSet(TR::Compilation * comp, TR::Region ®ion)
:_region(region),
_blocksPerAuto((RefMapComparator()),(RefMapAllocator(region))),
_EMPTY(region),
_collected(false),
_comp(comp)
{
}
void OMR::GlobalSet::collectBlocks()
{
TR::StackMemoryRegion stackMemoryRegion(*_comp->trMemory());
TR_BitVector references(0, _comp->trMemory(), stackAlloc);
TR_BitVectorIterator bvi(references);
TR::NodeChecklist visited(_comp);
TR::TreeTop *startTree = _comp->getStartTree();
TR::TreeTop *endTree = NULL;
TR::TreeTop *treeTop;
TR::TreeTop *exitTreeTop = startTree->getExtendedBlockExitTreeTop();
// Process each block in treetop order
//
for (treeTop = startTree; (treeTop != endTree); treeTop = exitTreeTop->getNextTreeTop())
{
TR::Block *block = NULL;
exitTreeTop = treeTop->getExtendedBlockExitTreeTop();
// Collect all autos/parms used in this block
visited.remove(visited);
for (TR::TreeTop * tt = treeTop; tt && tt != exitTreeTop; tt = tt->getNextTreeTop())
{
if (tt->getNode()->getOpCodeValue() == TR::BBStart)
{
references.empty();
block = tt->getNode()->getBlock();
}
collectReferencedAutoSymRefs(tt->getNode(), references, visited);
if (tt->getNextTreeTop()->getNode()->getOpCodeValue() == TR::BBEnd)
{
// Set this block as referencing the collected autos/params
//
bvi.setBitVector(references);
while (bvi.hasMoreElements())
{
uint32_t symRefNum = bvi.getNextElement();
auto lookup = _blocksPerAuto.find(symRefNum);
if (lookup != _blocksPerAuto.end())
{
lookup->second->set(block->getNumber());
}
else
{
TR_BitVector *blocks = new (_region) TR_BitVector(_region);
blocks->set(block->getNumber());
_blocksPerAuto[symRefNum] = blocks;
}
}
}
}
}
_collected = true;
}
void OMR::GlobalSet::collectReferencedAutoSymRefs(TR::Node *node, TR_BitVector &referencedAutoSymRefs, TR::NodeChecklist &visited)
{
if (visited.contains(node))
return;
visited.add(node);
if (node->getOpCode().hasSymbolReference() && node->getSymbolReference()->getSymbol()->isAutoOrParm())
referencedAutoSymRefs.set(node->getSymbolReference()->getReferenceNumber());
for (int32_t i = 0; i < node->getNumChildren(); ++i)
collectReferencedAutoSymRefs(node->getChild(i), referencedAutoSymRefs, visited);
}
// Duplicated in GlobalRegisterAllocator.cpp. TODO try and factor this out
static bool dontAssignInColdBlocks(TR::Compilation *comp) { return comp->getMethodHotness() >= hot; }
// Duplicated in GlobalRegisterAllocator.cpp. TODO try and factor this out
// For both switch/table instructions and igoto instructions, the
// same sort of processing has to be done for each successor block.
// These classes are meant to allow that work to be independent of
// the way that the successor blocks are actually identified.
int32_t OMR::RegisterCandidates::_candidateTypeWeights[TR_NumRegisterCandidateTypes] =
{
1, // TR_InductionVariableCandidate
1 // 10 // TR_PRECandidate
};
OMR::RegisterCandidate::RegisterCandidate(TR::SymbolReference * sr, TR::Region &r)
: _symRef(sr), _splitSymRef(NULL), _restoreSymRef(NULL), _lowRegNumber(-1), _highRegNumber(-1),
_liveOnEntry(), _liveOnExit(), _originalLiveOnEntry(),
_reprioritized(0),
_blocks(r),
_loopExitBlocks(r),
_stores(r),
_loopsWithHoles(r),
_mostRecentValue(NULL),
_lastLoad(NULL)
{
}
TR::DataType
OMR::RegisterCandidate::getType()
{
return getSymbol()->getType();
}
TR::DataType
OMR::RegisterCandidate::getDataType()
{
TR::Symbol *rcSymbol = getSymbol();
TR::DataType dtype = rcSymbol->getDataType();
return dtype;
}
TR_RegisterKinds
OMR::RegisterCandidate::getRegisterKinds()
{
TR::DataType dt = getDataType();
if(dt == TR::Float
|| dt == TR::Double
)
return TR_FPR;
else if (dt.isVector())
return TR_VRF;
else
return TR_GPR;
}
void OMR::RegisterCandidate::addAllBlocksInStructure(TR_Structure *structure, TR::Compilation *comp, const char *description, vcount_t count, bool recursiveCall)
{
if (!recursiveCall)
count = comp->incVisitCount();
if (structure->asBlock() != NULL)
{
TR_BlockStructure *blockStructure = structure->asBlock();
TR::Block *block = blockStructure->getBlock();
addBlock(block, 0);
if (description)
traceMsg(comp, "\nAdded %s #%d (symRef %p) as global reg candidate in block_%d\n", description, getSymbolReference()->getReferenceNumber(), getSymbolReference(), block->getNumber());
}
else
{
TR_RegionStructure *regionStructure = structure->asRegion();
TR_StructureSubGraphNode *node;
TR_RegionStructure::Cursor si(*regionStructure);
for (node = si.getCurrent(); node != NULL; node = si.getNext())
addAllBlocksInStructure(node->getStructure(), comp, description, count, true);
}
}
OMR::RegisterCandidates::RegisterCandidates(TR::Compilation *comp)
: _compilation(comp), _trMemory(comp->trMemory()), _candidateRegion(_trMemory->heapMemoryRegion()),
_referencedAutoSymRefsInBlock(NULL)
{
_candidateForSymRefs = 0;
}
TR::RegisterCandidate *OMR::RegisterCandidates::newCandidate(TR::SymbolReference *ref) {
return new (_candidateRegion) TR::RegisterCandidate(ref, _candidateRegion);
}
TR::RegisterCandidate *
OMR::RegisterCandidates::findOrCreate(TR::SymbolReference * symRef)
{
TR::RegisterCandidate * rc;
if ((rc = find(symRef)))
{
if (_candidateForSymRefs)
{
(*_candidateForSymRefs)[GET_INDEX_FOR_CANDIDATE_FOR_SYMREF(symRef)] = rc;
}
return rc;
}
_candidates.add(rc = newCandidate(symRef));
if (_candidateForSymRefs)
(*_candidateForSymRefs)[GET_INDEX_FOR_CANDIDATE_FOR_SYMREF(symRef)] = rc;
TR_ASSERT(comp()->cg()->considerTypeForGRA(symRef),"should create a registerCandidate for symRef #%d with datatype %s\n",symRef->getReferenceNumber(),rc->getDataType().toString());
return rc;
}
TR::RegisterCandidate *
OMR::RegisterCandidates::find(TR::SymbolReference * symRef)
{
if (symRef->getSymbol()->isAutoOrParm())
{
TR::RegisterCandidate* rc= (_candidateForSymRefs) ? (*_candidateForSymRefs)[GET_INDEX_FOR_CANDIDATE_FOR_SYMREF(symRef)] : NULL;
// two symrefs can point to same symbols so it is possible that we have an rc for symref->getSymbol but not have it added to the cache
if(rc==NULL)
{
rc = find(symRef->getSymbol());
if (_candidateForSymRefs)
(*_candidateForSymRefs)[GET_INDEX_FOR_CANDIDATE_FOR_SYMREF(symRef)] = rc;
}
return rc;
}
else
return NULL;
}
TR::RegisterCandidate *
OMR::RegisterCandidates::find(TR::Symbol* sym)
{
TR::RegisterCandidate * rc;
for (rc = _candidates.getFirst(); rc; rc = rc->getNext())
if (rc->getSymbolReference()->getSymbol() == sym)
return rc;
return NULL;
}
TR::GlobalSet&
OMR::RegisterCandidates::getReferencedAutoSymRefs(TR::Region ®ion)
{
if (_referencedAutoSymRefsInBlock == NULL)
{
void *memory = region.allocate(sizeof(TR::GlobalSet));
_referencedAutoSymRefsInBlock = new (memory) TR::GlobalSet(comp(), region);
}
return *_referencedAutoSymRefsInBlock;
}
TR_BitVector *
OMR::RegisterCandidates::getBlocksReferencingSymRef(uint32_t symRefNum)
{
if (_referencedAutoSymRefsInBlock == NULL)
return NULL;
return (*_referencedAutoSymRefsInBlock)[symRefNum];
}
bool
OMR::RegisterCandidate::find(TR::Block * b)
{
return _blocks.find(b->getNumber());
}
void
OMR::RegisterCandidate::addBlock(TR::Block * block, int32_t numberOfLoadsAndStores)
{
_blocks.incNumberOfLoadsAndStores(block->getNumber(), numberOfLoadsAndStores);
}
int32_t
OMR::RegisterCandidate::removeBlock(TR::Block * block)
{
if (find(block))
{
int32_t numLoadsAndStores = _blocks.getNumberOfLoadsAndStores(block->getNumber());
_blocks.removeBlock(block->getNumber());
return numLoadsAndStores;
}
return 0;
}
void OMR::RegisterCandidate::removeLoopExitBlock(TR::Block *b)
{
_loopExitBlocks.remove(b);
}
void OMR::RegisterCandidate::addLoopExitBlock(TR::Block *b)
{
if (!_loopExitBlocks.find(b))
_loopExitBlocks.add(b);
}
bool OMR::RegisterCandidate::hasLoopExitBlock(TR::Block * b)
{
return (_loopExitBlocks.find(b) != 0);
}
int32_t
OMR::RegisterCandidate::countNumberOfLoadsAndStoresInBlocks(List<TR::Block> *blocksInLoop)
{
int32_t numLoadsAndStores = 0;
ListIterator<TR::Block> blocksIt(blocksInLoop);
TR::Block *nextBlock;
for (nextBlock = blocksIt.getCurrent(); nextBlock; nextBlock=blocksIt.getNext())
{
numLoadsAndStores += _blocks.getNumberOfLoadsAndStores(nextBlock->getNumber());
}
return numLoadsAndStores;
}
#ifdef TRIM_ASSIGNED_CANDIDATES
// The following are methods for maintaining info about number of candidate's loads
// and stores per loop (vs. per block)
OMR::RegisterCandidate::LoopInfo *
OMR::RegisterCandidate::find(TR_Structure * l)
{
for (LoopInfo * li = _loops.getFirst(); li; li = li->getNext())
if (li->_loop == l)
return li;
return 0;
}
void
OMR::RegisterCandidate::printLoopInfo(TR::Compilation *comp)
{
for (LoopInfo * li = _loops.getFirst(); li; li = li->getNext())
{
traceMsg(comp, "Candidate #%d has %d loads and stores in loop %d\n",
getSymbolReference()->getReferenceNumber(),
li->_numberOfLoadsAndStores,
li->_loop->getNumber());
}
}
void
OMR::RegisterCandidate::addLoop(TR_Structure * loop, int32_t numberOfLoadsAndStores, TR_Memory * m)
{
LoopInfo * li = find(loop);
if (li)
li->_numberOfLoadsAndStores += numberOfLoadsAndStores;
else
_loops.add(new (m->trHeapMemory()) LoopInfo(loop, numberOfLoadsAndStores));
}
// Reduce block info into loop info by counting loads and stores in loops
void
OMR::RegisterCandidate::countNumberOfLoadsAndStoresInLoops(TR_Memory * m)
{
for (BlockInfo * bi = _blocks.getFirst(); bi; bi = bi->getNext())
{
TR_BlockStructure *blockStructure = bi->_block->getStructureOf();
if (blockStructure)
{
TR_Structure *containingLoop = blockStructure->getContainingLoop();
if (containingLoop)
addLoop(containingLoop, bi->_numberOfLoadsAndStores, m);
}
}
}
int32_t
OMR::RegisterCandidate::getNumberOfLoadsAndStoresInLoop(TR_Structure *loop)
{
LoopInfo * li = find(loop);
if (li)
return li->_numberOfLoadsAndStores;
else
return 0;
}
bool isInnerLoop(TR::Compilation *comp, TR_Structure *loop)
{
List<TR::Block> blocksInLoop(comp->trMemory());
loop->getBlocks(&blocksInLoop);
ListIterator<TR::Block> blocksIt(&blocksInLoop);
TR::Block *nextBlock;
blocksIt.reset();
for (nextBlock = blocksIt.getCurrent(); nextBlock; nextBlock=blocksIt.getNext())
{
if (nextBlock->getStructureOf()->getContainingLoop() != loop)
return false;
}
return true;
}
void
OMR::RegisterCandidate::removeAssignedCandidateFromLoop(TR::Compilation *comp, TR_Structure *loop, int32_t regNum, TR_BitVector *liveOnEntryUsage, TR_BitVector *liveOnExitUsage, bool trace)
{
List<TR::Block> blocksInLoop(comp->trMemory());
loop->getBlocks(&blocksInLoop);
ListIterator<TR::Block> blocksIt(&blocksInLoop);
TR::Block *nextBlock;
blocksIt.reset();
for (nextBlock = blocksIt.getCurrent(); nextBlock; nextBlock=blocksIt.getNext())
{
int32_t blockNumber = nextBlock->getNumber();
_liveOnEntry.reset(blockNumber);
_liveOnExit.reset(blockNumber);
liveOnEntryUsage->reset(blockNumber);
liveOnExitUsage->reset(blockNumber);
if (trace)
traceMsg(comp, "Removed candidate #%d from block_%d entry and exit\n",
getSymbolReference()->getReferenceNumber(), blockNumber);
nextBlock->getGlobalRegisters(comp)[regNum].setRegisterCandidateOnEntry(NULL);
nextBlock->getGlobalRegisters(comp)[regNum].setRegisterCandidateOnExit(NULL);
// handle predecessors
for (auto pred = nextBlock->getPredecessors().begin(); pred != nextBlock->getPredecessors().end(); ++pred)
{
TR::Block *block = toBlock((*pred)->getFrom());
_liveOnExit.reset(block->getNumber());
liveOnExitUsage->reset(block->getNumber());
block->getGlobalRegisters(comp)[regNum].setRegisterCandidateOnExit(NULL);
}
// handle successors
for (auto succ = nextBlock->getSuccessors().begin(); succ != nextBlock->getSuccessors().end(); ++succ)
{
TR::Block *block = toBlock((*succ)->getTo());
_liveOnEntry.reset(block->getNumber());
liveOnEntryUsage->reset(block->getNumber());
block->getGlobalRegisters(comp)[regNum].setRegisterCandidateOnEntry(NULL);
}
}
}
#endif
bool
OMR::RegisterCandidate::symbolIsLive(TR::Block * block)
{
TR_BitVector * liveLocals = block->getLiveLocals();
if (!liveLocals)
return true; // can be a new block
if (!getSymbol()->getAutoSymbol())
{
return true;
}
if (!getSymbol()->isAutoOrParm())
{
return true;
}
TR::RegisterMappedSymbol * regSym = getSymbol()->getRegisterMappedSymbol();
return liveLocals->get(regSym->getLiveLocalIndex()) != 0;
}
static bool findStoreNearEndOfBlock(TR::Block *block, TR::SymbolReference *ref)
{
TR::Node * node = block->getLastRealTreeTop()->getNode();
if (node->getOpCode().isStore())
return (node->getSymbolReference() == ref);
else if (block->getLastRealTreeTop()->getPrevTreeTop())
{
node = block->getLastRealTreeTop()->getPrevTreeTop()->getNode();
return (node->getOpCode().isStore() && (node->getSymbolReference()) == ref);
}
return false;
}
static bool findLoad(TR::Node *node, TR::SymbolReference *ref)
{
if (node->getOpCode().isLoad() &&
node->getSymbolReference() == ref)
return true;
return false; // simplify for now to avoid timeout in SPEC
for (int i = 0; i < node->getNumChildren(); i++)
{
if (findLoad(node->getChild(i), ref))
return true;
}
return false;
}
static bool findLoadNearStartOfBlock(TR::Block *block, TR::SymbolReference *ref)
{
// vcount_t visitCount = comp->incVisitCount();
return findLoad(block->getFirstRealTreeTop()->getNode(), ref);
}
bool OMR::RegisterCandidates::aliasesPreventAllocation(TR::Compilation *comp, TR::SymbolReference *symRef)
{
if (!symRef->getSymbol()->isAutoOrParm() && !(comp->target().cpu.isZ() && comp->target().isLinux()) ) return true;
TR::SparseBitVector use_def_aliases(comp->allocator());
symRef->getUseDefAliases(false).getAliases(use_def_aliases);
if (!use_def_aliases.IsZero())
{
use_def_aliases[symRef->getReferenceNumber()] = false;
if (!use_def_aliases.IsZero())
return true;
}
return false;
}
void
OMR::RegisterCandidate::setWeight(TR::Block * * blocks, int32_t *blockStructureWeight, TR::Compilation *comp,
TR_Array<int32_t> & blockGPRCount,
TR_Array<int32_t> & blockFPRCount,
TR_Array<int32_t> & blockVRFCount,
TR_BitVector *referencedBlocks, TR_Array<TR::Block *>& startOfExtendedBBForBB,
TR_BitVector &firstBlocks,
TR_BitVector &isExtensionOfPreviousBlock)
{
LexicalTimer t("setWeight", comp->phaseTimer());
TR::CFG * cfg = comp->getFlowGraph();
int32_t numberOfBlocks = cfg->getNextNodeNumber();
_liveOnEntry.init(numberOfBlocks, comp->trMemory(), stackAlloc, growable);
_liveOnExit.init(numberOfBlocks, comp->trMemory(), stackAlloc, growable);
_originalLiveOnEntry.init(numberOfBlocks, comp->trMemory(), stackAlloc, growable);
TR::CodeGenerator * cg = comp->cg();
BlockInfo::iterator itr = _blocks.getIterator();
while (itr.hasMoreElements())
{
int32_t blockNumber = itr.getNextElement();
TR_ASSERT(blockNumber < cfg->getNextNodeNumber(), "Overflow on candidate BB numbers");
TR::Block * b = blocks[blockNumber];
if (!b) continue;
TR_ASSERT(blockNumber == b->getNumber(),"blocks[x]->getNumber() != x");
TR_ASSERT((blockNumber < cfg->getNextNodeNumber()) && (blocks[blockNumber] == b),"blockNumber is wrong");
int32_t blockWeight = _blocks.getNumberOfLoadsAndStores(blockNumber);
bool firstBlock = firstBlocks.isSet(blockNumber);
if ((firstBlock && isAllBlocks() && cg->getSupportsGlRegDepOnFirstBlock()) ||
(!firstBlock && (((blockWeight == 0) && hasLoopExitBlock(b)) || symbolIsLive(b))))
_liveOnEntry.set(blockNumber);
TR_BlockStructure * blockStructure = b->getStructureOf();
int32_t blockFreq = 1;
if (blockStructure)
{
blockFreq = blockStructureWeight[blockNumber];
}
TR_ASSERT(comp->getOptimizer()->cachedExtendedBBInfoValid(), "Incorrect value in _startOfExtendedBBForBB");
TR::Block * extendedBlock = startOfExtendedBBForBB[blockNumber];
int32_t extendedBlockFreq = 1;
TR_BlockStructure *extendedBlockStructure = extendedBlock->getStructureOf();
if (extendedBlockStructure)
{
extendedBlockFreq = blockStructureWeight[extendedBlock->getNumber()];
}
// We should not mark a candidate as being referenced in the extended block if the
// only references to it are in the portion of the extended block that is outside a loop
// This is important as we cannot recognize that a candidate is not referenced at all in a loop
// otherwise. We see a 'false' use in the extended basic block that started inside the loop because
// of the portion of the extended basic block outside the loop.
//
if (extendedBlockFreq <= blockFreq)
{
if ((uint32_t)blockWeight > _blocks.getNumberOfLoadsAndStores(extendedBlock->getNumber()))
_blocks.setNumberOfLoadsAndStores(extendedBlock->getNumber(), blockWeight);
}
}
_originalLiveOnEntry |= _liveOnEntry;
processLiveOnEntryBlocks(blocks, blockStructureWeight, comp,blockGPRCount,blockFPRCount, blockVRFCount, referencedBlocks, startOfExtendedBBForBB);
}
void
OMR::RegisterCandidate::recalculateWeight(TR::Block * * blocks, int32_t *blockStructureWeight, TR::Compilation *comp,
TR_Array<int32_t> & blockGPRCount,
TR_Array<int32_t> & blockFPRCount,
TR_Array<int32_t> & blockVRFCount,
TR_BitVector *referencedBlocks, TR_Array<TR::Block *>& startOfExtendedBBForBB)
{
getBlocksLiveOnExit().empty();
_originalLiveOnEntry = _liveOnEntry;
processLiveOnEntryBlocks(blocks, blockStructureWeight, comp,blockGPRCount,blockFPRCount, blockVRFCount, referencedBlocks, startOfExtendedBBForBB);
}
// Look at exit live count of predecessor, and return true if there is too much
// register pressue
bool
OMR::RegisterCandidate::prevBlockTooRegisterConstrained(TR::Compilation *comp, TR::Block *block,
TR_Array<int32_t> & blockGPRCount,
TR_Array<int32_t> & blockFPRCount,
TR_Array<int32_t> & blockVRFCount)
{
static char * doit = feGetEnv("TR_SkipIfPrevBlockConstrained");
int32_t blockNum = block->getNumber();
if (doit != NULL) return true;
if (_liveOnEntry.get(blockNum))
{
int32_t gprCount=0,fprCount=0,vrfCount=0;
gprCount = blockGPRCount[blockNum];
fprCount = blockFPRCount[blockNum];
vrfCount = blockVRFCount[blockNum];
//printf("block_%d: gpr:%d fpr:%d vrf:%d\n",blockNum,gprCount,fprCount,vrfCount);
for (auto e = block->getPredecessors().begin(); e != block->getPredecessors().end(); ++e)
{
TR::Block * pred = toBlock((*e)->getFrom());
if (pred == comp->getFlowGraph()->getStart())
continue;
TR::Node * node = pred->getLastRealTreeTop()->getNode();
//printf("looking at block_%d's previous node %p\n",blockNum,node);
int32_t maxGPRs= comp->cg()->getMaximumNumberOfGPRsAllowedAcrossEdge(pred);
int32_t maxFPRs= comp->cg()->getMaximumNumberOfFPRsAllowedAcrossEdge(node);
int32_t maxVRFs= comp->cg()->getMaximumNumberOfVRFsAllowedAcrossEdge(node);
//dumpOptDetails(comp, " pred %d actual gprs %d max gprs %d ", pred->getNumber(), gprCount, maxGPRs);
if (maxFPRs <= fprCount || maxGPRs <= gprCount || maxVRFs <= vrfCount) return true;
}
}
//printf(".....no constraints\n");
return false;
}
bool OMR::RegisterCandidate::rcNeeds2Regs(TR::Compilation *comp)
{
if(getType().isAggregate())
{
if ( (comp->target().is32Bit() && !comp->cg()->use64BitRegsOn32Bit() && getSymbol()->getSize() > 4) || (getSymbol()->getSize() > 8 ) )
return true;
else
return false;
}
else
return ((getType().isInt64() && comp->target().is32Bit() && !comp->cg()->use64BitRegsOn32Bit())
);
}
bool
OMR::RegisterCandidate::hasSameGlobalRegisterNumberAs(TR::Node *node, TR::Compilation *comp)
{
if (node->requiresRegisterPair(comp))
return (getLowGlobalRegisterNumber() == node->getLowGlobalRegisterNumber())
&& (getHighGlobalRegisterNumber() == node->getHighGlobalRegisterNumber());
else
return getGlobalRegisterNumber() == node->getGlobalRegisterNumber();
}
void
OMR::RegisterCandidate::processLiveOnEntryBlocks(TR::Block * * blocks, int32_t *blockStructureWeight, TR::Compilation *comp,
TR_Array<int32_t> & blockGPRCount,
TR_Array<int32_t> & blockFPRCount,
TR_Array<int32_t> & blockVRFCount,
TR_BitVector *referencedBlocks,
TR_Array<TR::Block *>& startOfExtendedBBForBB, bool callToRemoveUnusedLoops)
{
LexicalTimer t("processLiveOnEntryBlocks", comp->phaseTimer());
TR::SymbolReference *symRef = getSymbolReference();
TR::Symbol * sym = getSymbolReference()->getSymbol();
bool trace = comp->getOptions()->trace(OMR::tacticalGlobalRegisterAllocator);
bool removeUnusedLoops = callToRemoveUnusedLoops;
bool useProfilingFrequencies = comp->getUsesBlockFrequencyInGRA();
double freqRatio;
if(useProfilingFrequencies)
freqRatio = 0.7;
else
freqRatio = 1.0;
if (comp->cg()->areAssignableGPRsScarce())
removeUnusedLoops = true;
if (trace)
dumpOptDetails(comp, "\nWeighing candidate #%d\n", getSymbolReference()->getReferenceNumber());
// If the candidate is marked to be live on entry but is not live on
// entry in any of its predecessors and is not referenced in any of its
// predecessor then remove the block from the _liveOnEntry bitVector
//
referencedBlocks->empty();
vcount_t visitCount = comp->incVisitCount();
TR_BitVectorIterator bvi;
bool lookForBlocksToRemove = !isAllBlocks();
// TODO take this all out
// used for MetaData that are live on entry in blocks, just to mark that they can escape via return but there is no real loads
// so we do not want such live on entry blocks to contribute to weigh of the candidate
// TR_BitVector *ignoreLiveOnEntryBlocks = new (comp->trHeapMemory()) TR_BitVector(comp->getFlowGraph()->getNextNodeNumber(), comp->trMemory());
while (lookForBlocksToRemove)
{
lookForBlocksToRemove = false;
bvi.setBitVector(_liveOnEntry);
while (bvi.hasMoreElements())
{
int32_t blockNumber = bvi.getNextElement();
if (trace)
dumpOptDetails(comp, "Examining original live-on-entry block_%d with loads and stores = %d\n", blockNumber, _blocks.getNumberOfLoadsAndStores(blockNumber));
TR::Block * block = blocks[blockNumber];
bool referencedInPred = false;
for (auto e = block->getPredecessors().begin(); e != block->getPredecessors().end(); ++e)
{
TR_ASSERT(comp->getOptimizer()->cachedExtendedBBInfoValid(), "Incorrect value in _startOfExtendedBBForBB");
if (_liveOnEntry.get(startOfExtendedBBForBB[toBlock((*e)->getFrom())->getNumber()]->getNumber()))
//if (_liveOnEntry.get(toBlock(e->getFrom())->getNumber()))
{ referencedInPred = true; break; }
}
if (!referencedInPred)
for (auto e = block->getPredecessors().begin(); e != block->getPredecessors().end(); ++e)
//if (toBlock(e->getFrom())->startOfExtendedBlock()->findFirstReference(sym, true))
{
TR::Block *predBlock = toBlock((*e)->getFrom());
TR_ASSERT(comp->getOptimizer()->cachedExtendedBBInfoValid(), "Incorrect value in _startOfExtendedBBForBB");
TR::Block *parentPredBlock = startOfExtendedBBForBB[predBlock->getNumber()];
while (parentPredBlock)
{
if (parentPredBlock->getVisitCount() < visitCount)
{
parentPredBlock->setVisitCount(visitCount);
if (parentPredBlock->findFirstReference(sym, visitCount))
{referencedBlocks->set(parentPredBlock->getNumber()); referencedInPred = true; break;}
}
else
{
if (referencedBlocks->get(parentPredBlock->getNumber()))
{
referencedInPred = true;
break;
}
}
// Fixed by Nakaike
// if (predBlock && !predBlock->isExtensionOfPreviousBlock())
if (parentPredBlock == predBlock ||
(parentPredBlock->getNextBlock() && ( parentPredBlock->getNextBlock() == block || !parentPredBlock->getNextBlock()->isExtensionOfPreviousBlock())))
break;
parentPredBlock = parentPredBlock->getNextBlock();
}
if (referencedInPred)
break;
}
if (!referencedInPred)
{
if (trace)
dumpOptDetails(comp, "Not referenced in pred, re-setting block_%d \n", blockNumber);
_liveOnEntry.reset(blockNumber);
lookForBlocksToRemove = true;
}
}
}
lookForBlocksToRemove = true;
// If the number of loads and stores for a block is 0 and the candidate
// is not live on exit then remove the block from the _liveOnEntry bitVector
//
if (lookForBlocksToRemove && trace)
traceMsg(comp, "Trim live ranges upward:\n");
while (lookForBlocksToRemove)
{
lookForBlocksToRemove = false;
bvi.setBitVector(_liveOnEntry);
while (bvi.hasMoreElements())
{
int32_t blockNumber = bvi.getNextElement();
if (trace)
traceMsg(comp, "\tExamining live-on-entry block_%d with loads and stores = %d\n", blockNumber, _blocks.getNumberOfLoadsAndStores(blockNumber));
if (_blocks.getNumberOfLoadsAndStores(blockNumber) == 0)
{
TR::Block * block = blocks[blockNumber];
bool liveOnExit = false;
for (auto succ = block->getSuccessors().begin(); succ != block->getSuccessors().end(); ++succ)
if (_liveOnEntry.get((*succ)->getTo()->getNumber()))
{ liveOnExit = true; break; }
if (!liveOnExit && block->isCold())
{
for (auto pred = block->getPredecessors().begin(); pred != block->getPredecessors().end(); ++pred)
if (!(*pred)->getFrom()->asBlock()->isCold())
{
liveOnExit = true;
break;
}
}
if (!liveOnExit)
{
if (trace)
traceMsg(comp, "\tNot referenced and not live on exit, re-setting block %d \n", blockNumber);
_liveOnEntry.reset(blockNumber);
lookForBlocksToRemove = true;
}
}
}
}
// Calculate the max frequency of any block as per structure
// (one could use some profiling here too)
//
int32_t maxFrequency = 1;
bvi.setBitVector(_liveOnEntry);
while (bvi.hasMoreElements())
{
int32_t blockNumber = bvi.getNextElement();
if (trace)
dumpOptDetails(comp, "Examining live-on-entry block_%d with loads and stores = %d to find maxFrequency\n", blockNumber, _blocks.getNumberOfLoadsAndStores(blockNumber));
TR::Block * block = blocks[blockNumber];
TR_BlockStructure *blockStructure = block->getStructureOf();
int32_t blockWeight = 1;
if (blockStructure &&
(!dontAssignInColdBlocks(comp) || !block->isCold()))
{
blockWeight = blockStructureWeight[block->getNumber()];
// blockStructure->calculateFrequencyOfExecution(&blockWeight);
if (blockWeight > maxFrequency)
maxFrequency = blockWeight;
}
}
int32_t currMaxFrequency = maxFrequency;
if (!getLoopsWithHoles().isEmpty())
removeUnusedLoops = true; // try to remove even if weight is not negative yet
// For every loop nesting depth, figure out how many blocks
// really use the candidate; discard blocks which don't use the candidate
// iff the containing loop does not use the candidate at all. Basically
// the entire loop will be discarded from the blocks list for the
// candidate if the loop does not use the candidate.
//
TR_BitVector *resetLiveOnEntry = new (comp->trHeapMemory()) TR_BitVector(comp->getFlowGraph()->getNextNodeNumber(), comp->trMemory()); // Added by Nakaike
TR_BitVector *resetLiveOnExit = new (comp->trHeapMemory()) TR_BitVector(comp->getFlowGraph()->getNextNodeNumber(), comp->trMemory()); // Added by Nakaike
if ((maxFrequency > 1) &&
removeUnusedLoops)
{
lookForBlocksToRemove = true;
int32_t frequency = 1;
if (comp->getMethodHotness() <= warm &&
getLoopsWithHoles().isEmpty())
frequency = maxFrequency; // to save compile time
while (lookForBlocksToRemove)
{
lookForBlocksToRemove = false;
int32_t numBlocksAtThisFrequency = 0;
int32_t numUnreferencedBlocksAtThisFrequency = 0;
if (1) // to calculate numUnreferencedBlocksAtThisFrequency for setting maxFrequency later
{
// Maybe there is some value in figuring out the ratio of unutilized blocks
// before we decide to discard any; experiment more with that; in that case use the
// commented out portion below
//
bvi.setBitVector(_liveOnEntry);
while (bvi.hasMoreElements())
{
int32_t blockNumber = bvi.getNextElement();
TR::Block * block = blocks[blockNumber];
TR_BlockStructure *blockStructure = block->getStructureOf();
int32_t blockWeight = 1;
if (blockStructure)
{
// blockStructure->calculateFrequencyOfExecution(&blockWeight);
TR_ASSERT(blockNumber == block->getNumber(),"blocks[x]->getNumber() != x");
blockWeight = blockStructureWeight[blockNumber];
}
if (blockWeight == frequency)
{
if (_blocks.getNumberOfLoadsAndStores(blockNumber) == 0)
{
numUnreferencedBlocksAtThisFrequency++;
break;
}
}
}
}
if (trace)
traceMsg(comp, "At frequency %d for %d numBlocks %d numUnreferencedBlocks %d\n", frequency, getSymbolReference()->getReferenceNumber(), numBlocksAtThisFrequency, numUnreferencedBlocksAtThisFrequency);
TR_ScratchList<TR_Structure> unreferencedLoops(comp->trMemory());
TR_ScratchList<TR_Structure> referencedLoops(comp->trMemory());
if ((numUnreferencedBlocksAtThisFrequency > 0) &&
(comp->getOption(TR_EnableRangeSplittingGRA) || // move this check above ?
(comp->cg()->areAssignableGPRsScarce())))
{
bool seenBlockAtThisFrequency = false;
bvi.setBitVector(_liveOnEntry);
while (bvi.hasMoreElements())