-
Notifications
You must be signed in to change notification settings - Fork 392
/
PartialRedundancy.cpp
6417 lines (5608 loc) · 257 KB
/
PartialRedundancy.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, 2021 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 "optimizer/PartialRedundancy.hpp"
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "codegen/CodeGenerator.hpp"
#include "env/FrontEnd.hpp"
#include "compile/Compilation.hpp"
#include "compile/SymbolReferenceTable.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "control/Recompilation.hpp"
#include "cs2/bitvectr.h"
#include "cs2/sparsrbit.h"
#include "env/CompilerEnv.hpp"
#include "env/TRMemory.hpp"
#include "env/jittypes.h"
#include "il/AliasSetInterface.hpp"
#include "il/Block.hpp"
#include "il/DataTypes.hpp"
#include "il/ILOps.hpp"
#include "il/MethodSymbol.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/Symbol.hpp"
#include "il/SymbolReference.hpp"
#include "il/TreeTop.hpp"
#include "il/TreeTop_inlines.hpp"
#include "infra/Assert.hpp"
#include "infra/BitVector.hpp"
#include "infra/Cfg.hpp"
#include "infra/Link.hpp"
#include "infra/List.hpp"
#include "infra/CfgEdge.hpp"
#include "infra/CfgNode.hpp"
#include "optimizer/DataFlowAnalysis.hpp"
#include "optimizer/InductionVariable.hpp"
#include "optimizer/LocalAnalysis.hpp"
#include "optimizer/Optimization.hpp"
#include "optimizer/Optimization_inlines.hpp"
#include "optimizer/OptimizationManager.hpp"
#include "optimizer/Optimizations.hpp"
#include "optimizer/Optimizer.hpp"
#include "optimizer/Structure.hpp"
#include "optimizer/TransformUtil.hpp"
#include "ras/Debug.hpp"
#ifdef J9_PROJECT_SPECIFIC
#include "runtime/J9Profiler.hpp"
#endif
class TR_RegisterCandidate;
static int32_t numIterations = 0;
#define OPT_DETAILS "O^O PARTIAL REDUNDANCY ELIMINATION: "
#define BOTH_SAME 0
#define FIRST_LARGER 1
#define SECOND_LARGER 2
#define BOTH_UNRELATED 3
#define NUMBER_OF_NODES_PER_PROFILING_EXPANSION 20
#define NUM_ITERATIONS 2
// The list of supported opcodes MUST be the same as that supported by local
// analyses, so use their method.
//
inline bool TR_PartialRedundancy::isSupportedOpCode(TR::Node *node, TR::Node *parent)
{
return (TR_LocalAnalysis::isSupportedNode(node, comp(), parent));
}
static void resetChildrensVisitCounts(TR::Node *node, vcount_t count)
{
for (int32_t i = node->getNumChildren()-1; i >= 0; i--)
{
TR::Node *child = node->getChild(i);
resetChildrensVisitCounts(child, count);
child->setVisitCount(count);
}
}
#ifdef J9_PROJECT_SPECIFIC
static void correctDecimalPrecision(TR::Node *store, TR::Node *child, TR::Compilation *comp)
{
if (child->getType().isBCD() &&
child->getDecimalPrecision() != store->getDecimalPrecision())
{
TR::ILOpCodes modPrecOp = TR::ILOpCode::modifyPrecisionOpCode(child->getDataType());
TR_ASSERT(modPrecOp != TR::BadILOp,"no bcd modify precision opcode found\n");
TR::Node *modPrecNode = TR::Node::create(child, modPrecOp, 1);
bool isTruncation = store->getDecimalPrecision() < child->getDecimalPrecision();
if (comp->cg()->traceBCDCodeGen())
traceMsg(comp,"%screating %s (%p) to correctDecimalPrecision (%d->%d : isTruncation=%s) on node %s (%p)\n", OPT_DETAILS,
modPrecNode->getOpCode().getName(),modPrecNode,
child->getDecimalPrecision(),store->getDecimalPrecision(),
isTruncation ? "yes":"no",
child->getOpCode().getName(),child);
modPrecNode->setChild(0, child);
modPrecNode->setDecimalPrecision(store->getDecimalPrecision());
modPrecNode->transferSignState(child, isTruncation);
store->setAndIncValueChild(modPrecNode);
}
}
#endif
static bool shouldAllowOptimalSubNodeReplacement(TR::Compilation *comp)
{
if ((comp->getOptions()->getLastOptTransformationIndex() < comp->getOptions()->getMaxLastOptTransformationIndex()) ||
(comp->getOptions()->getFirstOptTransformationIndex() > comp->getOptions()->getMinFirstOptTransformationIndex()))
{
if (!comp->getOption(TR_TracePREForOptimalSubNodeReplacement))
return false;
}
return true;
}
static bool shouldAllowLimitingOfOptimalPlacement(TR::Compilation *comp)
{
if (shouldAllowOptimalSubNodeReplacement(comp))
{
if ((comp->getOptions()->getLastOptTransformationIndex() < comp->getOptions()->getMaxLastOptTransformationIndex()) ||
(comp->getOptions()->getFirstOptTransformationIndex() > comp->getOptions()->getMinFirstOptTransformationIndex()))
return false;
}
return true;
}
TR_PartialRedundancy::TR_PartialRedundancy(TR::OptimizationManager *manager)
: TR::Optimization(manager)
{
static const char *e = feGetEnv("TR_loadaddrPRE");
_loadaddrPRE = e ? (atoi(e) != 0) : false;
_ignoreLoadaddrOfLitPool = false;
if (_loadaddrPRE && _ignoreLoadaddrOfLitPool)
_loadaddrPRE = false; // need to check each loadaddr and cannot ignore them outright
}
TR_PartialRedundancy::ContainerType *TR_PartialRedundancy::allocateContainer(int32_t size)
{
return new (trStackMemory())TR_BitVector(size, trMemory(), stackAlloc);
}
static bool ignoreValueOfMultipleReturnNode(TR::Node *node, TR::SparseBitVector &seenNodes)
{
auto npIdx = node->getGlobalIndex();
if (seenNodes[npIdx])
return false;
seenNodes[npIdx] = 1;
for (int32_t i = 0; i < node->getNumChildren(); ++i)
if (ignoreValueOfMultipleReturnNode(node->getChild(i), seenNodes))
return true;
return false;
}
bool TR_PartialRedundancy::ignoreNode (TR::Node *node)
{
TR::ILOpCodes op = node->getOpCodeValue();
TR::CodeGenerator *cg = comp()->cg();
TR::SymbolReference *symRef = node->getOpCode().hasSymbolReference()?node->getSymbolReference():NULL;
TR::SparseBitVector seenNodes(comp()->allocator());
if (ignoreValueOfMultipleReturnNode(node, seenNodes)) return true;
if (op == TR::loadaddr)
{
if (_loadaddrPRE)
return false; // loadaddrs of any symRefs are always allowed
if (_ignoreLoadaddrOfLitPool)
{
{
return false; // and allow all other symRefs
}
}
return symRef != NULL;
}
return false;
}
int32_t TR_PartialRedundancy::perform()
{
// Calculate the number of expressions commoned by PRE that are allowed
// to be profiled. This is to keep the value profiling related code expansion
// within some limits
//
_numProfilingsAllowed = (((USHRT_MAX/2 - 1000) - comp()->getNodeCount())/NUMBER_OF_NODES_PER_PROFILING_EXPANSION);
if (_numProfilingsAllowed < 0)
_numProfilingsAllowed = 0;
// PRE is too expensive when profiling with HCR on, due to the number
// of blocks and temps this configuration creates. Disabling it
// won't affect performance if there are no profilings allowed.
if (comp()->getProfilingMode() == JitProfiling && comp()->getHCRMode() != TR::none && _numProfilingsAllowed == 0)
return 0;
// Need to confirm places calling opCodeFor* APIs are doing the right
// thing for readbar and wrtbar. All the transformations applied to normal
// load/store s should be applied to rd/wrtbar s. However, we need to be
// careful about the difference in the shape of the trees and the
// mapping relationship between different loads and stores.
if (comp()->incompleteOptimizerSupportForReadWriteBarriers())
return 0;
TR::StackMemoryRegion stackMemoryRegion(*trMemory());
// setAlteredCode(false);
TR::CFG *cfg = comp()->getFlowGraph();
TR_Structure *rootStructure = cfg->getStructure();
// for particularly big methods, see also comments in LocalAnalysis.cpp
//comp()->resetVisitCounts(0);
if (trace())
{
comp()->incOrResetVisitCount();
TR::TreeTop *currentTree = comp()->getStartTree();
while (!(currentTree == NULL))
{
getDebug()->print(comp()->getOutFile(), currentTree);
currentTree = currentTree->getNextTreeTop();
}
}
// Call to constructor of Isolatedness results in successive calls
// down the call chain to constructors of analyses that are prereqs.
// Thus PartialRedundancy would be done after Isolatedness which would
// be done after Latestness and so on
//
_isolatedness = new (comp()->allocator()) TR_Isolatedness(comp(), optimizer(), rootStructure, trace());
// Obtain local anticipatable info; used in redundant set calculation
//
TR_LocalAnticipatability &localAnticipatability = _isolatedness->_latestness->_delayedness->_earliestness->_globalAnticipatability->_localAnticipatability;
if (trace())
traceMsg(comp(), "Starting PartialRedundancy\n");
_numNodes = cfg->getNextNodeNumber();
TR_ASSERT(_numNodes > 0, "Partial Redundancy, node numbers not assigned");
if (trace())
comp()->dumpMethodTrees("Trees after PRE node numbering\n");
int i;
_numberOfBits = _isolatedness->_latestness->_numberOfBits;
_optSetInfo = (ContainerType **)trMemory()->allocateStackMemory(_numNodes*sizeof(ContainerType *));
memset(_optSetInfo, 0, _numNodes*sizeof(ContainerType *));
_rednSetInfo = (ContainerType **)trMemory()->allocateStackMemory(_numNodes*sizeof(ContainerType *));
memset(_rednSetInfo, 0, _numNodes*sizeof(ContainerType *));
_unavailableSetInfo = (ContainerType **)trMemory()->allocateStackMemory(_numNodes*sizeof(ContainerType *));
memset(_unavailableSetInfo, 0, _numNodes*sizeof(ContainerType *));
_origOptSetInfo = (ContainerType **)trMemory()->allocateStackMemory(_numNodes*sizeof(ContainerType *));
memset(_origOptSetInfo, 0, _numNodes*sizeof(ContainerType *));
_globalRegisterWeights = (int32_t *)trMemory()->allocateStackMemory(_numNodes*sizeof(int32_t));
memset(_globalRegisterWeights, 0, _numNodes*sizeof(int32_t));
// These bit vectors are for storing some summary information
// over all the blocks; e.g. is an expression repeated or redundant
// in any block whatsoever or not. This information is useful to know
// whether we really need to introduce a new temp for this expression
// in global transformations (PRE) or would local CSE common some of these
// case without introducing any temps
//
ContainerType *redundants = allocateContainer(_numberOfBits);
ContainerType *optimals = allocateContainer(_numberOfBits);
ContainerType *temp = allocateContainer(_numberOfBits);
TR::CFGNode *nextNode;
for (nextNode = cfg->getFirstNode(); nextNode; nextNode = nextNode->getNext())
{
TR_Structure *blockStructure = (toBlock(nextNode))->getStructureOf();
if (blockStructure == NULL)
continue;
i = blockStructure->getNumber();
_optSetInfo[i] = allocateContainer(_numberOfBits);
_origOptSetInfo[i] = allocateContainer(_numberOfBits);
_rednSetInfo[i] = allocateContainer(_numberOfBits);
_unavailableSetInfo[i] = allocateContainer(_numberOfBits);
_unavailableSetInfo[i]->setAll(_numberOfBits);
}
// Nodes (expressions) that require a symbol to be created
//
_symOptimalNodes = allocateContainer(_numberOfBits);
_temp = allocateContainer(_numberOfBits);
TR::Node **supportedNodesAsArray = _isolatedness->_supportedNodesAsArray;
// These data structures keeps track of new temps created by PRE
//
_newSymbols = (TR::Symbol **)trMemory()->allocateStackMemory(_numberOfBits*sizeof(TR::Symbol *));
_newSymbolReferences = (TR::SymbolReference **)trMemory()->allocateStackMemory(_numberOfBits*sizeof(TR::SymbolReference *));
_newSymbolsMap = (int32_t*) trMemory()->allocateStackMemory(_numberOfBits*sizeof(int32_t));
_registerCandidates = (TR_RegisterCandidate **)trMemory()->allocateStackMemory(_numberOfBits*sizeof(TR_RegisterCandidate *));
memset(_newSymbols, 0, _numberOfBits*sizeof(TR::Symbol *));
memset(_newSymbolReferences, 0, _numberOfBits*sizeof(TR::SymbolReference *));
memset(_registerCandidates, 0, _numberOfBits*sizeof(TR_RegisterCandidate *));
// Initialize the map to -1 values
//
memset(_newSymbolsMap, 0xFF, _numberOfBits*sizeof(int32_t));
_useAliasSetsNotGuaranteedToBeCorrect = false;
ContainerType *negation = allocateContainer(_numberOfBits);
//
// Now computing optimality and redundancy information
// based on the analysis results
//
for (nextNode = cfg->getFirstNode(); nextNode; nextNode = nextNode->getNext())
{
TR::Block *block = toBlock(nextNode);
TR_Structure *blockStructure = block->getStructureOf();
if (blockStructure == NULL)
continue;
i = blockStructure->getNumber();
//negation.setAll(_numberOfBits);
// Note : Modification to use latestness info rather than isolatedness which
// we don't perform
//
///////negation -= *(_isolatedness->_outSetInfo[i]);
_isolatedness->copyFromInto(_isolatedness->_latestness->_inSetInfo[i], _optSetInfo[i]);
//*(_optSetInfo[i]) &= negation;
negation->setAll(_numberOfBits);
_isolatedness->copyFromInto(_isolatedness->_latestness->_inSetInfo[i], temp);
///////temp |= *(_isolatedness->_outSetInfo[i]);
*negation -= *temp;
// _isolatedness->copyFromInto(localAnticipatability.getAnalysisInfo(blockStructure->asBlock()->getBlock()->getNumber()), _rednSetInfo[i]);
*_rednSetInfo[i] = *localAnticipatability.getDownwardExposedAnalysisInfo(blockStructure->asBlock()->getBlock()->getNumber());
//if (!block->isCold())
*(_rednSetInfo[i]) &= *negation;
//else
// _rednSetInfo[i]->empty();
*redundants |= *(_rednSetInfo[i]);
if (trace())
{
traceMsg(comp(), "\nOptimality info for block : %d \n", i);
(*(_optSetInfo+i))->print(comp());
traceMsg(comp(), "\nRedundancy info for block : %d \n", i);
(*(_rednSetInfo+i))->print(comp());
}
}
// Compute the selective optimality and redundancy information
// (which is the original optimality and redundancy information but
// filtered with the information whether an computation really needs
// to placed (using a temp) or whether it can be handled by local CSE).
// We basically only introduce a temp if the value is redundant outside
// of the block where the computation is placed optimally; else we trust
// local CSE to do the required commoning.
//
for (nextNode = cfg->getFirstNode(); nextNode; nextNode = nextNode->getNext())
{
TR_Structure *blockStructure = (toBlock(nextNode))->getStructureOf();
if (blockStructure == NULL)
continue;
i = blockStructure->getNumber();
*(_origOptSetInfo[i]) = *(_optSetInfo[i]);
(*(_optSetInfo[i])) &= *redundants;
*optimals |= *(_optSetInfo[i]);
if (trace())
{
traceMsg(comp(), "\nSelective Optimality info for block : %d \n", i);
(*(_optSetInfo+i))->print(comp());
traceMsg(comp(), "\nSelective Redundancy info for block : %d \n", i);
(*(_rednSetInfo+i))->print(comp());
}
}
// Collect info about which expressions need a symbol
//
_symOptimalNodes->setAll(_numberOfBits);
ContainerType::Cursor bvi(*optimals);
for (bvi.SetToFirstOne(); bvi.Valid(); bvi.SetToNextOne())
{
int32_t nextOptimalComputation = bvi;
if (nextOptimalComputation != 0)
{
TR::Node *nextOptimalNode = supportedNodesAsArray[nextOptimalComputation];
if (nextOptimalNode->getOpCode().isCheck())
_symOptimalNodes->reset(nextOptimalComputation);
}
}
// Perform expression dominance and redundant expression adjustment
// to obtain 'real' solution for checks. Solution till this point is
// optimistic in that it ignores exception-ordering constraints in Java.
// This step figures out if code motion for checks can in fact be done.
//
_exceptionCheckMotion = NULL;
if (!optimals->isEmpty())
{
_exceptionCheckMotion = new (comp()->allocator()) TR_ExceptionCheckMotion(comp(), optimizer(), this);
_exceptionCheckMotion->perform();
_optSetInfo = _exceptionCheckMotion->getActualOptSetInfo();
_rednSetInfo = _exceptionCheckMotion->getActualRednSetInfo();
_orderedOptNumbersList = _exceptionCheckMotion->getOrderedOptNumbersList();
}
redundants->empty();
for (nextNode = cfg->getFirstNode(); nextNode; nextNode = nextNode->getNext())
{
TR_Structure *blockStructure = (toBlock(nextNode))->getStructureOf();
if (blockStructure == NULL)
continue;
i = blockStructure->getNumber();
*redundants |= *(_rednSetInfo[i]);
}
optimals->empty();
for (nextNode = cfg->getFirstNode(); nextNode; nextNode = nextNode->getNext())
{
TR_Structure *blockStructure = (toBlock(nextNode))->getStructureOf();
if (blockStructure == NULL)
continue;
i = blockStructure->getNumber();
(*(_optSetInfo[i])) &= *redundants;
*optimals |= *(_optSetInfo[i]);
_globalRegisterWeights[i] = 1;
calculateGlobalRegisterWeightsBasedOnStructure(blockStructure, (_globalRegisterWeights+i));
if (trace())
{
traceMsg(comp(), "\nFinal Selective Optimality info for block : %d \n", i);
(*(_optSetInfo+i))->print(comp());
traceMsg(comp(), "\nFinal Selective Redundancy info for block : %d \n", i);
(*(_rednSetInfo+i))->print(comp());
traceMsg(comp(), "\nFinal Unavailable info for block : %d \n", i);
(*(_unavailableSetInfo+i))->print(comp());
traceMsg(comp(), "\nGlobal Register weight for block : %d is %d\n", i, _globalRegisterWeights[i]);
}
}
// Duplicate the nodes so that expressions don't change while being
// moved around and placed optimally/eliminated.
//
ContainerType::Cursor bvi1(*redundants);
for (bvi1.SetToFirstOne(); bvi1.Valid(); bvi1.SetToNextOne())
{
int32_t nextRedundantComputation = bvi1;
if (nextRedundantComputation != 0)
{
supportedNodesAsArray[nextRedundantComputation] = supportedNodesAsArray[nextRedundantComputation]->duplicateTreeWithCommoning(comp()->allocator());
supportedNodesAsArray[nextRedundantComputation]->resetFlagsAndPropertiesForCodeMotion();
}
}
// If temps were created, we may want to do GCP later
// as field privatization helped subsequent GCP.
//
bool createdTemp = false;
// Create all the temps that are going to be used right at the
// outset. This is in fact required as we could have a subtree (smaller expr)
// being placed as optimal in some block B and a tree (larger expr)
// containing the subtree being placed optimally in some block that follows
// the block B in the cfg. In this case we need to replace the subtree
// by the temp in the tree (larger expression) before we place it optimally
// so as to use the value of the subtree that is guaranteed to be available
// in a temp rather than recompute the subtree.
//
//
ContainerType::Cursor bvi2(*optimals);
for (bvi2.SetToFirstOne(); bvi2.Valid(); bvi2.SetToNextOne())
{
int32_t nextOptimalComputation = bvi2;
if (nextOptimalComputation != 0)
{
TR::Node *nextOptimalNode = supportedNodesAsArray[nextOptimalComputation];
if ((_newSymbolsMap[nextOptimalComputation] < 0) &&
!nextOptimalNode->getOpCode().isCheck() &&
!nextOptimalNode->getOpCode().isAnchor() &&
!(nextOptimalNode->getOpCodeValue() == TR::treetop))
{
if (nextOptimalNode->getOpCode().isLoadVarDirect() &&
!nextOptimalNode->getSymbol()->isStatic() &&
!nextOptimalNode->getSymbol()->isMethodMetaData())
{
TR::SymbolReference *optimalSymRef = nextOptimalNode->getSymbolReference();
_newSymbols[nextOptimalComputation] = optimalSymRef->getSymbol();
_newSymbolsMap[nextOptimalComputation] = optimalSymRef->getReferenceNumber();
_newSymbolReferences[nextOptimalComputation] = optimalSymRef;
}
else if ((nextOptimalNode->getOpCode().isLoadVarDirect() &&
(nextOptimalNode->getSymbol()->isStatic() || nextOptimalNode->getSymbol()->isMethodMetaData())) ||
!isNodeAnImplicitNoOp(nextOptimalNode))
{
if (trace())
{
traceMsg(comp(), "Creating new symbol for optimal expr number %d node %p\n", nextOptimalComputation, nextOptimalNode);
}
TR::DataType dataType = nextOptimalNode->getDataType();
// set the datatype of the temporary created below to
// be at least OMR::Int ; otherwise the opcode used to create
// the store (to initialize) and the datatype on the symbol
// are inconsistent
//
if (fe()->dataTypeForLoadOrStore(nextOptimalNode->getDataType()) != nextOptimalNode->getDataType() && // only do it for Java where we use istore for small intergral types
nextOptimalNode->getSize() < 4)
dataType = TR::Int32;
size_t size = 0;
//if (nextOptimalNode->getType().isBCD())
size = nextOptimalNode->getSize();
TR::SymbolReference *newSymbolReference = comp()->getSymRefTab()->createTemporary(comp()->getMethodSymbol(), dataType, false, size);
TR::Symbol *newAutoSym = newSymbolReference->getSymbol();
comp()->AddCopyPropagationRematerializationCandidate(newSymbolReference);
if (nextOptimalNode->getOpCode().hasSymbolReference() && nextOptimalNode->getSymbolReference()->getSymbol()->isNotCollected())
newAutoSym->setNotCollected();
_newSymbols[nextOptimalComputation] = newAutoSym;
_newSymbolsMap[nextOptimalComputation] = newSymbolReference->getReferenceNumber();
_newSymbolReferences[nextOptimalComputation] = newSymbolReference;
createdTemp = true;
}
}
}
}
// Avoid creating a store inside a loop for a computation
// outside a loop if it is'nt likely that it will be placed in
// global register. Check for likelihood of obtaining a global register
// using above test (similar to test done in LocalAnalysis.cpp)
//
ContainerType::Cursor bvi3(*optimals);
for (bvi3.SetToFirstOne(); bvi3.Valid(); bvi3.SetToNextOne())
{
int32_t nextOptimalComputation = bvi3;
int32_t cost = 0;
int32_t benefit = 0;
TR::Node *nextOptimalNode = supportedNodesAsArray[nextOptimalComputation];
if (nextOptimalNode->getOpCode().isCheck() ||
(comp()->requiresSpineChecks() && nextOptimalNode->getOpCode().hasSymbolReference() && nextOptimalNode->getSymbol()->isArrayShadowSymbol()))
continue;
TR::CFGNode *nextNode;
for (nextNode = cfg->getFirstNode(); nextNode; nextNode = nextNode->getNext())
{
if (!nextNode->asBlock()->isCold())
{
if (_rednSetInfo[nextNode->getNumber()]->get(nextOptimalComputation))
{
TR_Structure *containingLoop = NULL;
int32_t weight = 1;
nextNode->asBlock()->getStructureOf()->calculateFrequencyOfExecution(&weight);
if (nextNode->getFrequency() >= 0)
weight = weight * nextNode->getFrequency();
if (trace())
traceMsg(comp(), "Benefit block_%d benefit %d\n", nextNode->getNumber(), weight);
benefit = benefit + weight;
}
if (_optSetInfo[nextNode->getNumber()]->get(nextOptimalComputation))
{
int32_t weight = 1;
nextNode->asBlock()->getStructureOf()->calculateFrequencyOfExecution(&weight);
if (nextNode->getFrequency() >= 0)
weight = weight * nextNode->getFrequency();
if (trace())
traceMsg(comp(), "Cost block_%d cost %d\n", nextNode->getNumber(), weight);
cost = cost + weight;
}
}
if (((_rednSetInfo[nextNode->getNumber()]->get(nextOptimalComputation)) ||
(_optSetInfo[nextNode->getNumber()]->get(nextOptimalComputation))) &&
(
false ))
{
invalidateOptimalComputation(nextOptimalComputation);
}
}
if (cost > benefit)
{
if (trace())
traceMsg(comp(), "Cost-benefit analysis (cost %d > benefit %d) said ignore expression #%d\n", cost, benefit, nextOptimalComputation);
invalidateOptimalComputation(nextOptimalComputation);
}
}
int32_t preIndex = 1000000;
static char *c1 = feGetEnv("TR_PreIndex");
if (c1)
preIndex = atoi(c1);
_counter = 0;
// Go through the blocks and place computations optimally and
// then replace occurrences of the expression by the temp in the optimal
// block (if there are any).
//
bool methodContainsCatchBlocks = false;
for (nextNode = cfg->getFirstNode(); nextNode; nextNode = nextNode->getNext())
{
TR::Block *block = toBlock(nextNode);
if (!block->getExceptionPredecessors().empty())
methodContainsCatchBlocks = true;
if (block->getEntry() != NULL)
{
// Use for debugging
//
if (_counter > preIndex)
break;
_counter++;
placeComputationsOptimally(block, &supportedNodesAsArray);
}
}
//
// Go through the blocks and place computations optimally and
// remove redundant computations in the block (or replace by load
// of a temp).
//
_visitCount = comp()->incOrResetVisitCount();
TR::Block *block;
for (block = comp()->getStartBlock(); block!=NULL; block = block->getNextBlock())
{
// Do not eliminate redundancy from cold blocks as this may result
// in a store remaining in a non-cold block simply for this solitary
// load. Note we still have to process the cold block because it MAY
// be executed if the cold block is actually reached somehow; in that case
// a privatization store would still need to be inserted along the cold
// path. We never allow loads of PRE temps in cold blocks though. So we
// still avoid inserting a store in a non-cold block simply for a load in a cold block.
//
if ((block->getEntry() != NULL) /* &&
!block->isCold() */)
{
// Use for debugging
//
if (_counter > preIndex)
break;
_counter++;
eliminateRedundantComputations(block, supportedNodesAsArray, _rednSetInfo, block->getEntry());
}
}
if (trace())
{
traceMsg(comp(), "\nEnding PartialRedundancy\n");
printTrees();
comp()->dumpMethodTrees("Trees after PRE done\n");
}
if (manager()->getAlteredCode())
{
optimizer()->enableAllLocalOpts();
if (createdTemp)
optimizer()->setRequestOptimization(OMR::globalValuePropagation, true);
optimizer()->setUseDefInfo(NULL);
optimizer()->setValueNumberInfo(NULL);
optimizer()->setRequestOptimization(OMR::globalDeadStoreElimination, true);
}
if (_useAliasSetsNotGuaranteedToBeCorrect && methodContainsCatchBlocks)
optimizer()->setAliasSetsAreValid(false);
return 10; // actual cost
}
void TR_PartialRedundancy::invalidateOptimalComputation(int32_t nextOptimalComputation)
{
TR::CFGNode *nextNode;
TR::CFG * cfg = comp()->getFlowGraph();
for (nextNode = cfg->getFirstNode(); nextNode; nextNode = nextNode->getNext())
{
_rednSetInfo[nextNode->getNumber()]->reset(nextOptimalComputation);
_optSetInfo[nextNode->getNumber()]->reset(nextOptimalComputation);
}
_newSymbols[nextOptimalComputation] = NULL;
_newSymbolsMap[nextOptimalComputation] = -1;
_newSymbolReferences[nextOptimalComputation] = NULL;
}
// Routine used in duplicating nodes for optimal placement; dulpicates respecting
// visitCounts. Unlike TR::Node::duplicateTree()
//
TR::Node *TR_PartialRedundancy::duplicateExact(TR::Node *node, List<TR::Node> *seenNodes, List<TR::Node> *duplicateNodes, vcount_t visitCount)
{
node->setVisitCount(visitCount);
TR::Node *newRoot = TR::Node::copy(node);
if (node->getOpCode().hasSymbolReference())
newRoot->setSymbolReference(node->getSymbolReference());
seenNodes->add(node);
duplicateNodes->add(newRoot);
newRoot->setReferenceCount(1);
int32_t i;
for (i = 0; i < node->getNumChildren(); i++)
{
if (node->getChild(i)->getVisitCount() != visitCount)
newRoot->setChild(i, duplicateExact(node->getChild(i), seenNodes, duplicateNodes, visitCount));
else
{
// We've seen this node before - find its duplicate
//
ListIterator<TR::Node> seenNodesIt(seenNodes);
ListIterator<TR::Node> duplicateNodesIt(duplicateNodes);
TR::Node *nextDuplicateNode = duplicateNodesIt.getFirst();
TR::Node *nextNode;
for (nextNode = seenNodesIt.getFirst(); nextNode != NULL; nextNode = seenNodesIt.getNext())
{
if (nextNode == node->getChild(i))
{
nextDuplicateNode->incReferenceCount();
newRoot->setChild(i, nextDuplicateNode);
}
nextDuplicateNode = duplicateNodesIt.getNext();
}
}
}
return newRoot;
}
void TR_PartialRedundancy::calculateGlobalRegisterWeightsBasedOnStructure(TR_Structure *structure, int32_t *currentWeight)
{
structure->calculateFrequencyOfExecution(currentWeight);
}
bool TR_PartialRedundancy::isNodeAnImplicitNoOp(TR::Node *node)
{
// The following allows strider to introduce fewer induction variables
// Applies to WCode only since address expressions are not commoned in Java
if (node->getOpCode().isArrayRef() &&
node->getSecondChild()->getOpCode().isLoadConst() &&
!comp()->cg()->isMaterialized(node->getSecondChild()))
return true;
if (ignoreNode(node))
return true;
if (TR::ILOpCode::isOpCodeAnImplicitNoOp(node->getOpCode())) //FIXME: disables 190546!!!
return true;
if (node->getType().isAggregate() && node->getSize() > 8)
{
// if (trace())
// traceMsg(comp(),"skipping placing aggr %s (%p)\n",node->getOpCode().getName(),node);
return true;
}
if (TR::TransformUtil::isNoopConversion(comp(), node))
return true;
#ifdef J9_PROJECT_SPECIFIC
if (!TR::Compiler->cls.romClassObjectsMayBeCollected() &&
node->getOpCode().hasSymbolReference() &&
((node->getSymbolReference() == comp()->getSymRefTab()->findArrayClassRomPtrSymbolRef()) ||
(node->getSymbolReference() == comp()->getSymRefTab()->findClassRomPtrSymbolRef())))
return true;
#endif
return false;
}
// Some opcodes don't really generate any code; for these kinds of
// expressions it is wasteful to introduce a temp.
//
bool TR_PartialRedundancy::isOpCodeAnImplicitNoOp(TR::ILOpCode &opCode)
{
return comp()->cg()->opCodeIsNoOp(opCode);
}
// Sign state does not have to be tracked on BCD nodes. This can lead to a BCD node with a particular
// sign setting to be stored to a temp and then the load of this temp will lose this sign info and
// subsequent generated code may clobber an unsigned sign code (0xf -> 0xc for example)
// pdSetSignA sign=?
// x
// ...
// pdSetSignB
// x
// After PRE:
// pdstore <temp1>
// pdSetSignA sign=?
// ...
// pdload <temp1> sign=?
//
// To prevent this mark the pdload (reused from the original pdSetSignB) as containing some sign state info
// so the code generator will conservatively not alter this sign code.
void TR_PartialRedundancy::processReusedNode(TR::Node *node, TR::ILOpCodes newOpCode, TR::SymbolReference *newSymRef,
int newNumChildren)
{
#ifdef J9_PROJECT_SPECIFIC
bool wasBCDNonLoad = node->getType().isBCD() && !node->getOpCode().isLoad();
#endif
if (comp()->cg()->traceBCDCodeGen())
traceMsg(comp(),"reusing %s (%p) as op ",node->getOpCode().getName(),node);
node->setNumChildren(newNumChildren);
if (newSymRef)
node = TR::Node::recreateWithSymRef(node, newOpCode, newSymRef);
else
node = TR::Node::recreate(node, newOpCode);
if(node->getOpCode().isLoadVarDirect()) node->setIsNodeCreatedByPRE();
if (comp()->cg()->traceBCDCodeGen()) traceMsg(comp(),"%s",node->getOpCode().getName());
#ifdef J9_PROJECT_SPECIFIC
if (wasBCDNonLoad && node->getOpCode().isBCDLoad())
{
node->setHasSignStateOnLoad(true);
if (comp()->cg()->traceBCDCodeGen()) traceMsg(comp()," and setting hasSignState flag to true\n");
}
else
{
if (comp()->cg()->traceBCDCodeGen()) traceMsg(comp(),"\n");
}
#endif
}
TR::TreeTop *TR_PartialRedundancy::placeComputationsOptimally(TR::Block *block, TR::Node ***supportedNodesAsArray)
{
if (_optSetInfo[block->getStructureOf()->getNumber()]->isEmpty())
return NULL;
TR::TreeTop *placeToInsertOptimalComputations = block->getEntry();
TR::TreeTop *placeToInsertUnanticipatableOptimalComputations = NULL;
if (trace())
traceMsg(comp(), "Placing computations optimally in block number %d\n", block->getStructureOf()->getNumber());
ContainerType *anticipatabilityInfo = _isolatedness->_latestness->_delayedness->_earliestness->_globalAnticipatability->_localAnticipatability.getDownwardExposedAnalysisInfo(block->getNumber());
int32_t numOptimalElements =_optSetInfo[block->getNumber()]->elementCount();
int32_t seenOptimalElements = 0;
int32_t currOptimalElement = 0;
int32_t *orderedOptNumbersList = _orderedOptNumbersList[block->getNumber()];
_prevTree = NULL;
int32_t nextOptimalComputation;
bool seenFirstOptimalCheck = false;
for (nextOptimalComputation = orderedOptNumbersList[currOptimalElement]; seenOptimalElements < numOptimalElements; currOptimalElement++)
{
nextOptimalComputation = orderedOptNumbersList[currOptimalElement];
if (trace())
traceMsg(comp(), "Optimal computation %d in block number %d insert after %p\n", nextOptimalComputation, block->getStructureOf()->getNumber(), placeToInsertOptimalComputations->getNode());
if (_optSetInfo[block->getNumber()]->get(nextOptimalComputation))
{
seenOptimalElements++;
// Bit 0 is just a dummy placeholder
//
if (nextOptimalComputation == 0)
continue;
}
else
continue;
// Its a local variable/parm load, in which case nothing to do
//
TR::Node *nextOptimalNode = (*supportedNodesAsArray)[nextOptimalComputation];
if (
(nextOptimalNode->getOpCode().isLoadVarDirect() &&
!nextOptimalNode->getSymbol()->isStatic() &&
!nextOptimalNode->getSymbol()->isMethodMetaData())
||
(ignoreNode(nextOptimalNode))
)
continue;
if (nextOptimalNode->getOpCode().isCheck())
{
if (!seenFirstOptimalCheck)
placeToInsertOptimalComputations = block->getEntry();
seenFirstOptimalCheck = true;
}
bool changeUnanticipatableOptimalComputations = false;
// If this expression is anticipatable in this block
// i.e. it is evaluated in this block in original program,
// then find the evaluation point
//
if (anticipatabilityInfo->get(nextOptimalComputation))
{
if (!nextOptimalNode->getOpCode().isCheck())
comp()->incOrResetVisitCount();
TR::TreeTop *lastInsertionMade = NULL, *notLastInsertionInBlock = NULL;
bool lastInsertionCanBeRemoved = false;
TR::TreeTop *exitTree = block->getExit();
//if (placeToInsertOptimalComputations == block->getExit())
placeToInsertOptimalComputations = block->getEntry();
TR::TreeTop *startingPoint = placeToInsertOptimalComputations;
while (placeToInsertOptimalComputations != exitTree)
{
if (nextOptimalNode->getOpCode().isCheck())
{
TR::Node *nextNode = placeToInsertOptimalComputations->getNode();
if (nextNode->getOpCode().isCheck())
{
if (nextNode->getLocalIndex() == nextOptimalComputation)
{
if (nextNode->getOpCode().isNullCheck())
{
if (nextNode->getFirstChild()->exceptionsRaised() != 0)
{
TR::TreeTop *prevTreeTop = placeToInsertOptimalComputations->getPrevTreeTop();
//vcount_t visitCount1 = comp()->incVisitCount();
//List<TR::Node> seenNodes, duplicateNodes;
//TR::Node *duplicateOptimalNode = duplicateExact(nextOptimalNode->getNullCheckReference(), &seenNodes, &duplicateNodes, visitCount1);
//duplicateOptimalNode->setReferenceCount(0);
TR::SymbolReference *newSymRef = nextOptimalNode->getSymbolReference();
TR::Node *passThroughNode = TR::Node::create(TR::PassThrough, 1, nextNode->getNullCheckReference());
TR::Node *nodeInTreeTop = TR::Node::createWithSymRef(TR::NULLCHK, 1, 1, passThroughNode, newSymRef);
TR::TreeTop *duplicateOptimalTree = TR::TreeTop::create(comp(), nodeInTreeTop);