forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredundantbranchopts.cpp
2364 lines (2098 loc) · 84 KB
/
redundantbranchopts.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "jitpch.h"
//------------------------------------------------------------------------
// optRedundantBranches: try and optimize redundant branches in the method
//
// Returns:
// PhaseStatus indicating if anything changed.
//
PhaseStatus Compiler::optRedundantBranches()
{
#if DEBUG
if (verbose)
{
fgDispBasicBlocks(verboseTrees);
}
#endif // DEBUG
class OptRedundantBranchesDomTreeVisitor : public DomTreeVisitor<OptRedundantBranchesDomTreeVisitor>
{
public:
bool madeChanges;
OptRedundantBranchesDomTreeVisitor(Compiler* compiler) : DomTreeVisitor(compiler), madeChanges(false)
{
}
void PreOrderVisit(BasicBlock* block)
{
}
void PostOrderVisit(BasicBlock* block)
{
// Skip over any removed blocks.
//
if (block->HasFlag(BBF_REMOVED))
{
return;
}
// We currently can optimize some BBJ_CONDs.
//
if (block->KindIs(BBJ_COND))
{
bool madeChangesThisBlock = m_compiler->optRedundantRelop(block);
BasicBlock* const bbNext = block->GetFalseTarget();
BasicBlock* const bbJump = block->GetTrueTarget();
madeChangesThisBlock |= m_compiler->optRedundantBranch(block);
// If we modified some flow out of block but it's still
// a BBJ_COND, retry; perhaps one of the later optimizations
// we can do has enabled one of the earlier optimizations.
//
if (madeChangesThisBlock && block->KindIs(BBJ_COND))
{
JITDUMP("Will retry RBO in " FMT_BB " after partial optimization\n", block->bbNum);
madeChangesThisBlock |= m_compiler->optRedundantBranch(block);
}
// It's possible that the changed flow into bbNext or bbJump may unblock
// further optimizations there.
//
// Note this misses cascading retries, consider reworking the overall
// strategy here to iterate until closure.
//
if (madeChangesThisBlock && (bbNext->countOfInEdges() == 0))
{
for (BasicBlock* succ : bbNext->Succs())
{
JITDUMP("Will retry RBO in " FMT_BB "; pred " FMT_BB " now unreachable\n", succ->bbNum,
bbNext->bbNum);
m_compiler->optRedundantBranch(succ);
}
}
if (madeChangesThisBlock && (bbJump->countOfInEdges() == 0))
{
for (BasicBlock* succ : bbJump->Succs())
{
JITDUMP("Will retry RBO in " FMT_BB "; pred " FMT_BB " now unreachable\n", succ->bbNum,
bbNext->bbNum);
m_compiler->optRedundantBranch(succ);
}
}
madeChanges |= madeChangesThisBlock;
}
}
};
optReachableBitVecTraits = nullptr;
OptRedundantBranchesDomTreeVisitor visitor(this);
visitor.WalkTree(m_domTree);
#if DEBUG
if (verbose && visitor.madeChanges)
{
fgDispBasicBlocks(verboseTrees);
}
#endif // DEBUG
// DFS tree is always considered invalid after RBO.
fgInvalidateDfsTree();
return visitor.madeChanges ? PhaseStatus::MODIFIED_EVERYTHING : PhaseStatus::MODIFIED_NOTHING;
}
static const ValueNumStore::VN_RELATION_KIND s_vnRelations[] = {ValueNumStore::VN_RELATION_KIND::VRK_Same,
ValueNumStore::VN_RELATION_KIND::VRK_Reverse,
ValueNumStore::VN_RELATION_KIND::VRK_Swap,
ValueNumStore::VN_RELATION_KIND::VRK_SwapReverse};
//------------------------------------------------------------------------
// RelopImplicationInfo
//
// Describes information needed to check for and describe the
// inferences between two relops.
//
struct RelopImplicationInfo
{
// Dominating relop, whose value may be determined by control flow
ValueNum domCmpNormVN = ValueNumStore::NoVN;
// Dominated relop, whose value we would like to determine
ValueNum treeNormVN = ValueNumStore::NoVN;
// Relationship between the two relops, if any
ValueNumStore::VN_RELATION_KIND vnRelation = ValueNumStore::VN_RELATION_KIND::VRK_Same;
// Can we draw an inference?
bool canInfer = false;
// If canInfer and dominating relop is true, can we infer value of dominated relop?
bool canInferFromTrue = true;
// If canInfer and dominating relop is false, can we infer value of dominated relop?
bool canInferFromFalse = true;
// Reverse the sense of the inference
bool reverseSense = false;
};
//------------------------------------------------------------------------
// RelopImplicationRule
//
// A rule allowing inference between two otherwise unrelated relops.
// Related relops are handled via s_vnRelations above.
//
struct RelopImplicationRule
{
VNFunc domRelop;
bool canInferFromTrue;
bool canInferFromFalse;
VNFunc treeRelop;
bool reverse;
};
enum RelopResult
{
Unknown,
AlwaysFalse,
AlwaysTrue
};
//------------------------------------------------------------------------
// IsCmp2ImpliedByCmp1: given two constant range checks:
//
// if (X oper1 bound1)
// {
// if (X oper2 bound2)
// {
//
// determine if the second range check is implied by the dominating first one.
//
// Arguments:
// oper1 - the first comparison operator
// bound1 - the first constant bound
// oper2 - the second comparison operator
// bound2 - the second constant bound
//
// Returns:
// Unknown - the second check is not implied by the first one
// AlwaysFalse - the second check is implied by the first one and is always false
// AlwaysTrue - the second check is implied by the first one and is always true
//
RelopResult IsCmp2ImpliedByCmp1(genTreeOps oper1, target_ssize_t bound1, genTreeOps oper2, target_ssize_t bound2)
{
struct IntegralRange
{
target_ssize_t startIncl; // inclusive
target_ssize_t endIncl; // inclusive
bool Intersects(const IntegralRange other) const
{
return (startIncl <= other.endIncl) && (other.startIncl <= endIncl);
}
bool Contains(const IntegralRange other) const
{
return (startIncl <= other.startIncl) && (other.endIncl <= endIncl);
}
};
constexpr target_ssize_t minValue = TARGET_POINTER_SIZE == 4 ? INT32_MIN : INT64_MIN;
constexpr target_ssize_t maxValue = TARGET_POINTER_SIZE == 4 ? INT32_MAX : INT64_MAX;
// Start with the widest possible ranges
IntegralRange range1 = {minValue, maxValue};
IntegralRange range2 = {minValue, maxValue};
// Update ranges based on inputs
auto setRange = [](genTreeOps oper, target_ssize_t bound, IntegralRange* range) -> bool {
switch (oper)
{
case GT_LT:
// x < cns -> [minValue, cns - 1]
if (bound == minValue)
{
// overflows
return false;
}
range->endIncl = bound - 1;
return true;
case GT_LE:
// x <= cns -> [minValue, cns]
range->endIncl = bound;
return true;
case GT_GT:
// x > cns -> [cns + 1, maxValue]
if (bound == maxValue)
{
// overflows
return false;
}
range->startIncl = bound + 1;
return true;
case GT_GE:
// x >= cns -> [cns, maxValue]
range->startIncl = bound;
return true;
case GT_EQ:
case GT_NE:
// x == cns -> [cns, cns]
// NE is special-cased below
range->startIncl = bound;
range->endIncl = bound;
return true;
default:
// unsupported operator
return false;
}
};
if (setRange(oper1, bound1, &range1) && setRange(oper2, bound2, &range2))
{
// Special handling of GT_NE:
if ((oper1 == GT_NE) || (oper2 == GT_NE))
{
// if (x != 100)
// if (x != 100) // always true
if (oper1 == oper2)
{
return bound1 == bound2 ? RelopResult::AlwaysTrue : RelopResult::Unknown;
}
// if (x == 100)
// if (x != 100) // always false
//
// if (x == 100)
// if (x != 101) // always true
if (oper1 == GT_EQ)
{
return bound1 == bound2 ? RelopResult::AlwaysFalse : RelopResult::AlwaysTrue;
}
// if (x > 100)
// if (x != 10) // always true
if ((oper2 == GT_NE) && !range1.Intersects(range2))
{
return AlwaysTrue;
}
return RelopResult::Unknown;
}
// If ranges never intersect, then the 2nd range is never "true"
if (!range1.Intersects(range2))
{
// E.g.:
//
// range1: [100 .. SSIZE_T_MAX]
// range2: [SSIZE_T_MIN .. 10]
//
// or in other words:
//
// if (x >= 100)
// if (x <= 10) // always false
//
return RelopResult::AlwaysFalse;
}
// If range1 is a subset of range2, then the 2nd range is always "true"
if (range2.Contains(range1))
{
// E.g.:
//
// range1: [100 .. SSIZE_T_MAX]
// range2: [10 .. SSIZE_T_MAX]
//
// or in other words:
//
// if (x >= 100)
// if (x >= 10) // always true
//
return RelopResult::AlwaysTrue;
}
}
return RelopResult::Unknown;
}
//------------------------------------------------------------------------
// s_implicationRules: rule table for unrelated relops
//
// clang-format off
//
#define V(x) (VNFunc)GT_ ## x
#define U(x) VNF_ ## x ## _UN
static const RelopImplicationRule s_implicationRules[] =
{
// EQ
{V(EQ), true, false, V(GE), false},
{V(EQ), true, false, V(LE), false},
{V(EQ), true, false, V(GT), true},
{V(EQ), true, false, U(GT), true},
{V(EQ), true, false, V(LT), true},
{V(EQ), true, false, U(LT), true},
// NE
{V(NE), false, true, V(GE), true},
{V(NE), false, true, V(LE), true},
{V(NE), false, true, V(GT), false},
{V(NE), false, true, U(GT), false},
{V(NE), false, true, V(LT), false},
{V(NE), false, true, U(LT), false},
// LE
{V(LE), false, true, V(EQ), false},
{V(LE), false, true, V(NE), true},
{V(LE), false, true, V(GE), true},
{V(LE), false, true, V(LT), false},
// LE_UN
{U(LE), false, true, V(EQ), false},
{U(LE), false, true, V(NE), true},
{U(LE), false, true, U(GE), true},
{U(LE), false, true, U(LT), false},
// GT
{V(GT), true, false, V(EQ), true},
{V(GT), true, false, V(NE), false},
{V(GT), true, false, V(GE), false},
{V(GT), true, false, V(LT), true},
// GT_UN
{U(GT), true, false, V(EQ), true},
{U(GT), true, false, V(NE), false},
{U(GT), true, false, U(GE), false},
{U(GT), true, false, U(LT), true},
// GE
{V(GE), false, true, V(EQ), false},
{V(GE), false, true, V(NE), true},
{V(GE), false, true, V(LE), true},
{V(GE), false, true, V(GT), false},
// GE_UN
{U(GE), false, true, V(EQ), false},
{U(GE), false, true, V(NE), true},
{U(GE), false, true, U(LE), true},
{U(GE), false, true, U(GT), false},
// LT
{V(LT), true, false, V(EQ), true},
{V(LT), true, false, V(NE), false},
{V(LT), true, false, V(LE), false},
{V(LT), true, false, V(GT), true},
// LT_UN
{U(LT), true, false, V(EQ), true},
{U(LT), true, false, V(NE), false},
{U(LT), true, false, U(LE), false},
{U(LT), true, false, U(GT), true},
};
// clang-format on
//------------------------------------------------------------------------
// optRedundantBranch: try and optimize a possibly redundant branch
//
// Arguments:
// rii - struct with relop implication information
//
// Returns:
// No return value.
// Sets rii->canInfer and other fields, if inference is possible.
//
// Notes:
//
// First looks for exact or similar relations.
//
// If that fails, then looks for cases where the user or optOptimizeBools
// has combined two distinct predicates with a boolean AND, OR, or has wrapped
// a predicate in NOT.
//
// This will be expressed as {NE/EQ}({AND/OR/NOT}(...), 0).
// If the operator is EQ then a true {AND/OR} result implies
// a false taken branch, so we need to invert the sense of our
// inferences.
//
// We can also partially infer the tree relop's value from other
// dominating relops, for example, (x >= 0) dominating (x > 0).
//
// We don't get all the cases here we could. Still to do:
// * two unsigned compares, same operands
// * mixture of signed/unsigned compares, same operands
//
void Compiler::optRelopImpliesRelop(RelopImplicationInfo* rii)
{
assert(!rii->canInfer);
// Look for related VNs
//
for (auto vnRelation : s_vnRelations)
{
const ValueNum relatedVN = vnStore->GetRelatedRelop(rii->domCmpNormVN, vnRelation);
if ((relatedVN != ValueNumStore::NoVN) && (relatedVN == rii->treeNormVN))
{
rii->canInfer = true;
rii->vnRelation = vnRelation;
return;
}
}
// VNs are not directly related. See if dominating
// compare encompasses a related VN.
//
VNFuncApp domApp;
if (!vnStore->GetVNFunc(rii->domCmpNormVN, &domApp))
{
return;
}
// Exclude floating point relops.
//
if (varTypeIsFloating(vnStore->TypeOfVN(domApp.m_args[0])))
{
return;
}
#ifdef DEBUG
static ConfigMethodRange JitEnableRboRange;
JitEnableRboRange.EnsureInit(JitConfig.JitEnableRboRange());
const unsigned hash = impInlineRoot()->info.compMethodHash();
const bool inRange = JitEnableRboRange.Contains(hash);
#else
const bool inRange = true;
#endif
// If the dominating compare has the form R(x,y), see if tree compare has the
// form R*(x,y) or R*(y,x) where we can infer R* from R.
//
VNFunc const domFunc = domApp.m_func;
VNFuncApp treeApp;
if (inRange && ValueNumStore::VNFuncIsComparison(domFunc) && vnStore->GetVNFunc(rii->treeNormVN, &treeApp))
{
if (((treeApp.m_args[0] == domApp.m_args[0]) && (treeApp.m_args[1] == domApp.m_args[1])) ||
((treeApp.m_args[0] == domApp.m_args[1]) && (treeApp.m_args[1] == domApp.m_args[0])))
{
const bool swapped = (treeApp.m_args[0] == domApp.m_args[1]);
VNFunc const treeFunc = treeApp.m_func;
VNFunc domFunc1 = domFunc;
if (swapped)
{
domFunc1 = ValueNumStore::SwapRelop(domFunc);
}
for (const RelopImplicationRule& rule : s_implicationRules)
{
if ((rule.domRelop == domFunc1) && (rule.treeRelop == treeFunc))
{
rii->canInfer = true;
rii->vnRelation = ValueNumStore::VN_RELATION_KIND::VRK_Inferred;
rii->canInferFromTrue = rule.canInferFromTrue;
rii->canInferFromFalse = rule.canInferFromFalse;
rii->reverseSense = rule.reverse;
JITDUMP("Can infer %s from [%s] dominating %s\n", ValueNumStore::VNFuncName(treeFunc),
rii->canInferFromTrue ? "true" : "false", ValueNumStore::VNFuncName(domFunc));
return;
}
}
}
// Given R(x, cns1) and R*(x, cns2) see if we can infer R* from R.
// We assume cns1 and cns2 are always on the RHS of the compare.
if ((treeApp.m_args[0] == domApp.m_args[0]) && vnStore->IsVNConstant(treeApp.m_args[1]) &&
vnStore->IsVNConstant(domApp.m_args[1]) && varTypeIsIntOrI(vnStore->TypeOfVN(treeApp.m_args[1])) &&
vnStore->TypeOfVN(domApp.m_args[0]) == vnStore->TypeOfVN(treeApp.m_args[1]) &&
vnStore->TypeOfVN(domApp.m_args[1]) == vnStore->TypeOfVN(treeApp.m_args[1]))
{
// We currently don't handle VNF_relop_UN funcs here
if (ValueNumStore::VNFuncIsSignedComparison(domApp.m_func) &&
ValueNumStore::VNFuncIsSignedComparison(treeApp.m_func))
{
// Dominating "X relop CNS"
const genTreeOps domOper = static_cast<genTreeOps>(domApp.m_func);
const target_ssize_t domCns = vnStore->CoercedConstantValue<target_ssize_t>(domApp.m_args[1]);
// Dominated "X relop CNS"
const genTreeOps treeOper = static_cast<genTreeOps>(treeApp.m_func);
const target_ssize_t treeCns = vnStore->CoercedConstantValue<target_ssize_t>(treeApp.m_args[1]);
// Example:
//
// void Test(int x)
// {
// if (x > 100)
// if (x > 10)
// Console.WriteLine("Taken!");
// }
//
// Corresponding BB layout:
//
// BB1:
// if (x <= 100)
// goto BB4
//
// BB2:
// // x is known to be > 100 here
// if (x <= 10) // never true
// goto BB4
//
// BB3:
// Console.WriteLine("Taken!");
//
// BB4:
// return;
// Check whether the dominating compare being "false" implies the dominated compare is known
// to be either "true" or "false".
RelopResult treeOperStatus =
IsCmp2ImpliedByCmp1(GenTree::ReverseRelop(domOper), domCns, treeOper, treeCns);
if (treeOperStatus != RelopResult::Unknown)
{
rii->canInfer = true;
rii->vnRelation = ValueNumStore::VN_RELATION_KIND::VRK_Inferred;
rii->canInferFromTrue = false;
rii->canInferFromFalse = true;
rii->reverseSense = treeOperStatus == RelopResult::AlwaysTrue;
return;
}
}
}
}
// See if dominating compare is a compound comparison that might
// tell us the value of the tree compare.
//
// Look for {EQ,NE}({AND,OR,NOT}, 0)
//
genTreeOps const oper = genTreeOps(domFunc);
if (!GenTree::StaticOperIs(oper, GT_EQ, GT_NE))
{
return;
}
if (domApp.m_args[1] != vnStore->VNZeroForType(TYP_INT))
{
return;
}
const ValueNum predVN = domApp.m_args[0];
VNFuncApp predFuncApp;
if (!vnStore->GetVNFunc(predVN, &predFuncApp))
{
return;
}
genTreeOps const predOper = genTreeOps(predFuncApp.m_func);
if (!GenTree::StaticOperIs(predOper, GT_AND, GT_OR, GT_NOT))
{
return;
}
// Dominating compare is {EQ,NE}({AND,OR,NOT}, 0).
//
// See if one of {AND,OR,NOT} operands is related.
//
for (unsigned int i = 0; (i < predFuncApp.m_arity) && !rii->canInfer; i++)
{
ValueNum pVN = predFuncApp.m_args[i];
for (auto vnRelation : s_vnRelations)
{
const ValueNum relatedVN = vnStore->GetRelatedRelop(pVN, vnRelation);
if ((relatedVN != ValueNumStore::NoVN) && (relatedVN == rii->treeNormVN))
{
rii->vnRelation = vnRelation;
rii->canInfer = true;
// If dom predicate is wrapped in EQ(*,0) then a true dom
// predicate implies a false branch outcome, and vice versa.
//
// And if the dom predicate is GT_NOT we reverse yet again.
//
rii->reverseSense = (oper == GT_EQ) ^ (predOper == GT_NOT);
// We only get partial knowledge in these cases.
//
// AND(p1,p2) = true ==> both p1 and p2 must be true
// AND(p1,p2) = false ==> don't know p1 or p2
// OR(p1,p2) = true ==> don't know p1 or p2
// OR(p1,p2) = false ==> both p1 and p2 must be false
//
if (predOper != GT_NOT)
{
rii->canInferFromFalse = rii->reverseSense ^ (predOper == GT_OR);
rii->canInferFromTrue = rii->reverseSense ^ (predOper == GT_AND);
}
JITDUMP("Inferring predicate value from %s\n", GenTree::OpName(predOper));
return;
}
}
}
}
//------------------------------------------------------------------------
// optRedundantBranch: try and optimize a possibly redundant branch
//
// Arguments:
// block - block with branch to optimize
//
// Returns:
// True if the branch was optimized.
//
bool Compiler::optRedundantBranch(BasicBlock* const block)
{
JITDUMP("\n--- Trying RBO in " FMT_BB " ---\n", block->bbNum);
Statement* const stmt = block->lastStmt();
if (stmt == nullptr)
{
return false;
}
GenTree* const jumpTree = stmt->GetRootNode();
if (!jumpTree->OperIs(GT_JTRUE))
{
return false;
}
GenTree* const tree = jumpTree->AsOp()->gtOp1;
if (!tree->OperIsCompare())
{
return false;
}
// Walk up the dom tree and see if any dominating block has branched on
// exactly this tree's VN...
//
BasicBlock* prevBlock = block;
BasicBlock* domBlock = block->bbIDom;
int relopValue = -1;
ValueNum treeExcVN = ValueNumStore::NoVN;
ValueNum domCmpExcVN = ValueNumStore::NoVN;
unsigned matchCount = 0;
const unsigned matchLimit = 4;
// Unpack the tree's VN
//
ValueNum treeNormVN;
vnStore->VNUnpackExc(tree->GetVN(VNK_Liberal), &treeNormVN, &treeExcVN);
// If the treeVN is a constant, we optimize directly.
//
// Note the inferencing we do below is not valid for constant VNs,
// so handling/avoiding this case up front is a correctness requirement.
//
if (vnStore->IsVNConstant(treeNormVN))
{
relopValue = (treeNormVN == vnStore->VNZeroForType(TYP_INT)) ? 0 : 1;
JITDUMP("Relop [%06u] " FMT_BB " has known value %s\n ", dspTreeID(tree), block->bbNum,
relopValue == 0 ? "false" : "true");
}
else
{
if (domBlock == nullptr)
{
return false;
}
JITDUMP("Relop [%06u] " FMT_BB " value unknown, trying inference\n", dspTreeID(tree), block->bbNum);
}
bool trySpeculativeDom = false;
while ((relopValue == -1) && !trySpeculativeDom)
{
if (domBlock == nullptr)
{
// It's possible that bbIDom is not up to date at this point due to recent BB modifications
// so let's try to quickly calculate new one
domBlock = fgGetDomSpeculatively(block);
if (domBlock == block->bbIDom)
{
// We already checked this one
break;
}
trySpeculativeDom = true;
}
if (domBlock == nullptr)
{
break;
}
// Check the current dominator
//
if (domBlock->KindIs(BBJ_COND))
{
Statement* const domJumpStmt = domBlock->lastStmt();
GenTree* const domJumpTree = domJumpStmt->GetRootNode();
assert(domJumpTree->OperIs(GT_JTRUE));
GenTree* const domCmpTree = domJumpTree->AsOp()->gtGetOp1();
if (domCmpTree->OperIsCompare())
{
// We can use liberal VNs here, as bounds checks are not yet
// manifest explicitly as relops.
//
RelopImplicationInfo rii;
rii.treeNormVN = treeNormVN;
vnStore->VNUnpackExc(domCmpTree->GetVN(VNK_Liberal), &rii.domCmpNormVN, &domCmpExcVN);
// See if knowing the value of domCmpNormVN implies knowing the value of treeNormVN.
//
optRelopImpliesRelop(&rii);
if (rii.canInfer)
{
// If we have a long skinny dominator tree we may scale poorly,
// and in particular reachability (below) is costly. Give up if
// we've matched a few times and failed to optimize.
//
if (++matchCount > matchLimit)
{
JITDUMP("Bailing out; %d matches found w/o optimizing\n", matchCount);
break;
}
// Was this an inference from an unrelated relop (GE => GT, say)?
//
const bool domIsInferredRelop = (rii.vnRelation == ValueNumStore::VN_RELATION_KIND::VRK_Inferred);
// The compare in "tree" is redundant.
// Is there a unique path from the dominating compare?
//
if (domIsInferredRelop)
{
// This inference should be one-sided
//
assert(rii.canInferFromTrue ^ rii.canInferFromFalse);
JITDUMP("\nDominator " FMT_BB " of " FMT_BB " has same VN operands but different relop\n",
domBlock->bbNum, block->bbNum);
}
else
{
JITDUMP("\nDominator " FMT_BB " of " FMT_BB " has relop with %s liberal VN\n", domBlock->bbNum,
block->bbNum, ValueNumStore::VNRelationString(rii.vnRelation));
}
DISPTREE(domCmpTree);
JITDUMP(" Redundant compare; current relop:\n");
DISPTREE(tree);
const bool domIsSameRelop = (rii.vnRelation == ValueNumStore::VN_RELATION_KIND::VRK_Same) ||
(rii.vnRelation == ValueNumStore::VN_RELATION_KIND::VRK_Swap);
BasicBlock* const trueSuccessor = domBlock->GetTrueTarget();
BasicBlock* const falseSuccessor = domBlock->GetFalseTarget();
// If we can trace the flow from the dominating relop, we can infer its value.
//
const bool trueReaches = optReachable(trueSuccessor, block, domBlock);
const bool falseReaches = optReachable(falseSuccessor, block, domBlock);
if (trueReaches && falseReaches && rii.canInferFromTrue && rii.canInferFromFalse)
{
// JIT-TP: it didn't produce diffs so let's skip it
if (trySpeculativeDom)
{
break;
}
// Both dominating compare outcomes reach the current block so we can't infer the
// value of the relop.
//
// However we may be able to update the flow from block's predecessors so they
// bypass block and instead transfer control to jump's successors (aka jump threading).
//
const bool wasThreaded = optJumpThreadDom(block, domBlock, domIsSameRelop);
if (wasThreaded)
{
return true;
}
}
else if (trueReaches && !falseReaches && rii.canInferFromTrue)
{
// Taken jump in dominator reaches, fall through doesn't; relop must be true/false.
//
const bool relopIsTrue = rii.reverseSense ^ (domIsSameRelop | domIsInferredRelop);
JITDUMP("Jump successor " FMT_BB " of " FMT_BB " reaches, relop [%06u] must be %s\n",
domBlock->GetTrueTarget()->bbNum, domBlock->bbNum, dspTreeID(tree),
relopIsTrue ? "true" : "false");
relopValue = relopIsTrue ? 1 : 0;
break;
}
else if (falseReaches && !trueReaches && rii.canInferFromFalse)
{
// Fall through from dominator reaches, taken jump doesn't; relop must be false/true.
//
const bool relopIsFalse = rii.reverseSense ^ (domIsSameRelop | domIsInferredRelop);
JITDUMP("Fall through successor " FMT_BB " of " FMT_BB " reaches, relop [%06u] must be %s\n",
domBlock->GetFalseTarget()->bbNum, domBlock->bbNum, dspTreeID(tree),
relopIsFalse ? "false" : "true");
relopValue = relopIsFalse ? 0 : 1;
break;
}
else if (!falseReaches && !trueReaches)
{
// No apparent path from the dominating BB.
//
// We should rarely see this given that optReachable is returning
// up to date results, but as we optimize we create unreachable blocks,
// and that can lead to cases where we can't find paths. That means we may be
// optimizing code that is now unreachable, but attempts to fix or avoid
// doing that lead to more complications, and it isn't that common.
// So we just tolerate it.
//
// No point in looking further up the tree.
//
JITDUMP("inference failed -- no apparent path, will stop looking\n");
break;
}
else
{
// Keep looking up the dom tree
//
JITDUMP("inference failed -- will keep looking higher\n");
}
}
}
}
// Keep looking higher up in the tree
//
prevBlock = domBlock;
domBlock = domBlock->bbIDom;
}
// Did we determine the relop value via dominance checks? If so, optimize.
//
if (relopValue == -1)
{
// We were unable to determine the relop value via dominance checks.
// See if we can jump thread via phi disambiguation.
//
return optJumpThreadPhi(block, tree, treeNormVN);
}
// Be conservative if there is an exception effect and we're in an EH region
// as we might not model the full extent of EH flow.
//
if (((tree->gtFlags & GTF_EXCEPT) != 0) && block->hasTryIndex())
{
JITDUMP("Current relop has exception side effect and is in a try, so we won't optimize\n");
return false;
}
// Handle the side effects: for exceptions we can know whether we can drop them using the exception sets.
// Other side effects we always leave around (the unused tree will be appropriately transformed by morph).
//
bool keepTreeForSideEffects = false;
if ((tree->gtFlags & GTF_SIDE_EFFECT) != 0)
{
keepTreeForSideEffects = true;
if (((tree->gtFlags & GTF_SIDE_EFFECT) == GTF_EXCEPT) && vnStore->VNExcIsSubset(domCmpExcVN, treeExcVN))
{
keepTreeForSideEffects = false;
}
}
if (keepTreeForSideEffects)
{
JITDUMP("Current relop has side effects, keeping it, unused\n");
GenTree* relopComma = gtNewOperNode(GT_COMMA, TYP_INT, tree, gtNewIconNode(relopValue));
jumpTree->AsUnOp()->gtOp1 = relopComma;
}
else
{
tree->BashToConst(relopValue);
}
JITDUMP("\nRedundant branch opt in " FMT_BB ":\n", block->bbNum);
fgMorphBlockStmt(block, stmt DEBUGARG(__FUNCTION__));
return true;
}
//------------------------------------------------------------------------
// JumpThreadInfo
//
// Describes the relationship between a block-ending predicate value and the
// block's predecessors.
//
struct JumpThreadInfo
{
JumpThreadInfo(Compiler* comp, BasicBlock* block)
: m_block(block)
, m_trueTarget(block->GetTrueTarget())
, m_falseTarget(block->GetFalseTarget())
, m_fallThroughPred(nullptr)
, m_ambiguousVNBlock(nullptr)
, m_truePreds(BlockSetOps::MakeEmpty(comp))
, m_ambiguousPreds(BlockSetOps::MakeEmpty(comp))
, m_numPreds(0)
, m_numAmbiguousPreds(0)
, m_numTruePreds(0)
, m_numFalsePreds(0)
, m_ambiguousVN(ValueNumStore::NoVN)
, m_isPhiBased(false)
{
}
// Block we're trying to optimize
BasicBlock* const m_block;
// Block successor if predicate is true
BasicBlock* const m_trueTarget;
// Block successor if predicate is false
BasicBlock* const m_falseTarget;
// Unique pred that falls through to block, if any
BasicBlock* m_fallThroughPred;
// Block that brings in the ambiguous VN
BasicBlock* m_ambiguousVNBlock;
// Pred blocks for which the predicate will be true
BlockSet m_truePreds;
// Pred blocks that can't be threaded or for which the predicate
// value can't be determined
BlockSet m_ambiguousPreds;
// Total number of predecessors
int m_numPreds;
// Number of predecessors that can't be threaded or for which the predicate
// value can't be determined
int m_numAmbiguousPreds;
// Number of predecessors for which predicate is true
int m_numTruePreds;
// Number of predecessors for which predicate is false
int m_numFalsePreds;
// Refined VN for ambiguous cases
ValueNum m_ambiguousVN;
// True if this was a phi-based jump thread
bool m_isPhiBased;
};
//------------------------------------------------------------------------
// optJumpThreadCheck: see if block is suitable for jump threading.
//
// Arguments:
// block - block in question
// domBlock - dom block used in inferencing (if any)
//
bool Compiler::optJumpThreadCheck(BasicBlock* const block, BasicBlock* const domBlock)
{
if (fgCurBBEpochSize != (fgBBNumMax + 1))
{
JITDUMP("Looks like we've added a new block (e.g. during optLoopHoist) since last renumber, so no threading\n");
return false;