-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
B3ReduceStrength.cpp
3124 lines (2765 loc) · 126 KB
/
B3ReduceStrength.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) 2015-2022 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "B3ReduceStrength.h"
#if ENABLE(B3_JIT)
#include "B3AtomicValue.h"
#include "B3BasicBlockInlines.h"
#include "B3BlockInsertionSet.h"
#include "B3ComputeDivisionMagic.h"
#include "B3EliminateDeadCode.h"
#include "B3InsertionSetInlines.h"
#include "B3PhaseScope.h"
#include "B3PhiChildren.h"
#include "B3ProcedureInlines.h"
#include "B3PureCSE.h"
#include "B3UpsilonValue.h"
#include "B3ValueKeyInlines.h"
#include "B3ValueInlines.h"
#include <wtf/HashMap.h>
#include <wtf/MathExtras.h>
#include <wtf/StdLibExtras.h>
namespace JSC { namespace B3 {
namespace {
// The goal of this phase is to:
//
// - Replace operations with less expensive variants. This includes constant folding and classic
// strength reductions like turning Mul(x, 1 << k) into Shl(x, k).
//
// - Reassociate constant operations. For example, Load(Add(x, c)) is turned into Load(x, offset = c)
// and Add(Add(x, c), d) is turned into Add(x, c + d).
//
// - Canonicalize operations. There are some cases where it's not at all obvious which kind of
// operation is less expensive, but it's useful for subsequent phases - particularly LowerToAir -
// to have only one way of representing things.
//
// This phase runs to fixpoint. Therefore, the canonicalizations must be designed to be monotonic.
// For example, if we had a canonicalization that said that Add(x, -c) should be Sub(x, c) and
// another canonicalization that said that Sub(x, d) should be Add(x, -d), then this phase would end
// up running forever. We don't want that.
//
// Therefore, we need to prioritize certain canonical forms over others. Naively, we want strength
// reduction to reduce the number of values, and so a form involving fewer total values is more
// canonical. But we might break this, for example when reducing strength of Mul(x, 9). This could be
// better written as Add(Shl(x, 3), x), which also happens to be representable using a single
// instruction on x86.
//
// Here are some of the rules we have:
//
// Canonical form of logical not: BitXor(value, 1). We may have to avoid using this form if we don't
// know for sure that 'value' is 0-or-1 (i.e. returnsBool). In that case we fall back on
// Equal(value, 0).
//
// Canonical form of commutative operations: if the operation involves a constant, the constant must
// come second. Add(x, constant) is canonical, while Add(constant, x) is not. If there are no
// constants then the canonical form involves the lower-indexed value first. Given Add(x, y), it's
// canonical if x->index() <= y->index().
namespace B3ReduceStrengthInternal {
static constexpr bool verbose = false;
}
// FIXME: This IntRange stuff should be refactored into a general constant propagator. It's weird
// that it's just sitting here in this file.
class IntRange {
public:
IntRange()
{
}
IntRange(int64_t min, int64_t max)
: m_min(min)
, m_max(max)
{
}
template<typename T>
static IntRange top()
{
return IntRange(std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
}
static IntRange top(Type type)
{
switch (type.kind()) {
case Int32:
return top<int32_t>();
case Int64:
return top<int64_t>();
default:
RELEASE_ASSERT_NOT_REACHED();
return IntRange();
}
}
template<typename T>
static IntRange rangeForMask(T mask)
{
if (!(mask + 1))
return top<T>();
if (mask < 0)
return IntRange(INT_MIN & mask, mask & INT_MAX);
return IntRange(0, mask);
}
static IntRange rangeForMask(int64_t mask, Type type)
{
switch (type.kind()) {
case Int32:
return rangeForMask<int32_t>(static_cast<int32_t>(mask));
case Int64:
return rangeForMask<int64_t>(mask);
default:
RELEASE_ASSERT_NOT_REACHED();
return IntRange();
}
}
template<typename T>
static IntRange rangeForZShr(int32_t shiftAmount)
{
typename std::make_unsigned<T>::type mask = 0;
mask--;
mask >>= shiftAmount;
return rangeForMask<T>(static_cast<T>(mask));
}
static IntRange rangeForZShr(int32_t shiftAmount, Type type)
{
switch (type.kind()) {
case Int32:
return rangeForZShr<int32_t>(shiftAmount);
case Int64:
return rangeForZShr<int64_t>(shiftAmount);
default:
RELEASE_ASSERT_NOT_REACHED();
return IntRange();
}
}
int64_t min() const { return m_min; }
int64_t max() const { return m_max; }
void dump(PrintStream& out) const
{
out.print("[", m_min, ",", m_max, "]");
}
template<typename T>
bool couldOverflowAdd(const IntRange& other)
{
return sumOverflows<T>(m_min, other.m_min)
|| sumOverflows<T>(m_min, other.m_max)
|| sumOverflows<T>(m_max, other.m_min)
|| sumOverflows<T>(m_max, other.m_max);
}
bool couldOverflowAdd(const IntRange& other, Type type)
{
switch (type.kind()) {
case Int32:
return couldOverflowAdd<int32_t>(other);
case Int64:
return couldOverflowAdd<int64_t>(other);
default:
return true;
}
}
template<typename T>
bool couldOverflowSub(const IntRange& other)
{
return differenceOverflows<T>(m_min, other.m_min)
|| differenceOverflows<T>(m_min, other.m_max)
|| differenceOverflows<T>(m_max, other.m_min)
|| differenceOverflows<T>(m_max, other.m_max);
}
bool couldOverflowSub(const IntRange& other, Type type)
{
switch (type.kind()) {
case Int32:
return couldOverflowSub<int32_t>(other);
case Int64:
return couldOverflowSub<int64_t>(other);
default:
return true;
}
}
template<typename T>
bool couldOverflowMul(const IntRange& other)
{
return productOverflows<T>(m_min, other.m_min)
|| productOverflows<T>(m_min, other.m_max)
|| productOverflows<T>(m_max, other.m_min)
|| productOverflows<T>(m_max, other.m_max);
}
bool couldOverflowMul(const IntRange& other, Type type)
{
switch (type.kind()) {
case Int32:
return couldOverflowMul<int32_t>(other);
case Int64:
return couldOverflowMul<int64_t>(other);
default:
return true;
}
}
template<typename T>
IntRange shl(int32_t shiftAmount)
{
T newMin = static_cast<T>(m_min) << static_cast<T>(shiftAmount);
T newMax = static_cast<T>(m_max) << static_cast<T>(shiftAmount);
if (((newMin >> shiftAmount) != static_cast<T>(m_min))
|| ((newMax >> shiftAmount) != static_cast<T>(m_max))) {
newMin = std::numeric_limits<T>::min();
newMax = std::numeric_limits<T>::max();
}
return IntRange(newMin, newMax);
}
IntRange shl(int32_t shiftAmount, Type type)
{
switch (type.kind()) {
case Int32:
return shl<int32_t>(shiftAmount);
case Int64:
return shl<int64_t>(shiftAmount);
default:
RELEASE_ASSERT_NOT_REACHED();
return IntRange();
}
}
template<typename T>
IntRange sShr(int32_t shiftAmount)
{
T newMin = static_cast<T>(m_min) >> static_cast<T>(shiftAmount);
T newMax = static_cast<T>(m_max) >> static_cast<T>(shiftAmount);
return IntRange(newMin, newMax);
}
IntRange sShr(int32_t shiftAmount, Type type)
{
switch (type.kind()) {
case Int32:
return sShr<int32_t>(shiftAmount);
case Int64:
return sShr<int64_t>(shiftAmount);
default:
RELEASE_ASSERT_NOT_REACHED();
return IntRange();
}
}
template<typename T>
IntRange zShr(int32_t shiftAmount)
{
// This is an awkward corner case for all of the other logic.
if (!shiftAmount)
return *this;
// If the input range may be negative, then all we can say about the output range is that it
// will be masked. That's because -1 right shifted just produces that mask.
if (m_min < 0)
return rangeForZShr<T>(shiftAmount);
// If the input range is non-negative, then this just brings the range closer to zero.
typedef typename std::make_unsigned<T>::type UnsignedT;
UnsignedT newMin = static_cast<UnsignedT>(m_min) >> static_cast<UnsignedT>(shiftAmount);
UnsignedT newMax = static_cast<UnsignedT>(m_max) >> static_cast<UnsignedT>(shiftAmount);
return IntRange(newMin, newMax);
}
IntRange zShr(int32_t shiftAmount, Type type)
{
switch (type.kind()) {
case Int32:
return zShr<int32_t>(shiftAmount);
case Int64:
return zShr<int64_t>(shiftAmount);
default:
RELEASE_ASSERT_NOT_REACHED();
return IntRange();
}
}
template<typename T>
IntRange add(const IntRange& other)
{
if (couldOverflowAdd<T>(other))
return top<T>();
return IntRange(m_min + other.m_min, m_max + other.m_max);
}
IntRange add(const IntRange& other, Type type)
{
switch (type.kind()) {
case Int32:
return add<int32_t>(other);
case Int64:
return add<int64_t>(other);
default:
RELEASE_ASSERT_NOT_REACHED();
return IntRange();
}
}
template<typename T>
IntRange sub(const IntRange& other)
{
if (couldOverflowSub<T>(other))
return top<T>();
return IntRange(m_min - other.m_max, m_max - other.m_min);
}
IntRange sub(const IntRange& other, Type type)
{
switch (type.kind()) {
case Int32:
return sub<int32_t>(other);
case Int64:
return sub<int64_t>(other);
default:
RELEASE_ASSERT_NOT_REACHED();
return IntRange();
}
}
template<typename T>
IntRange mul(const IntRange& other)
{
if (couldOverflowMul<T>(other))
return top<T>();
return IntRange(
std::min(
std::min(m_min * other.m_min, m_min * other.m_max),
std::min(m_max * other.m_min, m_max * other.m_max)),
std::max(
std::max(m_min * other.m_min, m_min * other.m_max),
std::max(m_max * other.m_min, m_max * other.m_max)));
}
IntRange mul(const IntRange& other, Type type)
{
switch (type.kind()) {
case Int32:
return mul<int32_t>(other);
case Int64:
return mul<int64_t>(other);
default:
RELEASE_ASSERT_NOT_REACHED();
return IntRange();
}
}
template<typename T>
IntRange sExt()
{
ASSERT(m_min >= INT32_MIN);
ASSERT(m_max <= INT32_MAX);
int64_t typeMin = std::numeric_limits<T>::min();
int64_t typeMax = std::numeric_limits<T>::max();
auto min = m_min;
auto max = m_max;
if (typeMin <= min && min <= typeMax
&& typeMin <= max && max <= typeMax)
return IntRange(min, max);
// Given type T with N bits, signed extension will turn bit N-1 as
// a sign bit. If bits N-1 upwards are identical for both min and max,
// then we're guaranteed that even after the sign extension, min and
// max will still be in increasing order.
//
// For example, when T is int8_t, the space of numbers from highest to
// lowest are as follows (in binary bits):
//
// highest 0 111 1111 ^
// ... |
// 1 0 000 0001 | top segment
// 0 0 000 0000 v
//
// -1 1 111 1111 ^
// -2 1 111 1110 | bottom segment
// ... |
// lowest 1 000 0000 v
//
// Note that if we exclude the sign bit, the range is made up of 2 segments
// of contiguous increasing numbers. If min and max are both in the same
// segment before the sign extension, then min and max will continue to be
// in a contiguous segment after the sign extension. Only when min and max
// spans across more than 1 of these segments, will min and max no longer
// be guaranteed to be in a contiguous range after the sign extension.
//
// Hence, we can check if bits N-1 and up are identical for the range min
// and max. If so, then the new min and max can be be computed by simply
// applying sign extension to their original values.
constexpr unsigned numberOfBits = countOfBits<T>;
constexpr int64_t segmentMask = (1ll << (numberOfBits - 1)) - 1;
constexpr int64_t topBitsMask = ~segmentMask;
int64_t minTopBits = topBitsMask & min;
int64_t maxTopBits = topBitsMask & max;
if (minTopBits == maxTopBits)
return IntRange(static_cast<int64_t>(static_cast<T>(min)), static_cast<int64_t>(static_cast<T>(max)));
return top<T>();
}
IntRange zExt32()
{
ASSERT(m_min >= INT32_MIN);
ASSERT(m_max <= INT32_MAX);
int32_t min = m_min;
int32_t max = m_max;
return IntRange(static_cast<uint64_t>(static_cast<uint32_t>(min)), static_cast<uint64_t>(static_cast<uint32_t>(max)));
}
private:
int64_t m_min { 0 };
int64_t m_max { 0 };
};
class ReduceStrength {
public:
ReduceStrength(Procedure& proc)
: m_proc(proc)
, m_insertionSet(proc)
, m_blockInsertionSet(proc)
, m_root(proc.at(0))
{
}
bool run()
{
bool result = false;
bool first = true;
unsigned index = 0;
do {
m_changed = false;
m_changedCFG = false;
++index;
if (first)
first = false;
else if (B3ReduceStrengthInternal::verbose) {
dataLog("B3 after iteration #", index - 1, " of reduceStrength:\n");
dataLog(m_proc);
}
simplifyCFG();
if (m_changedCFG) {
m_proc.resetReachability();
m_proc.invalidateCFG();
m_changed = true;
}
// We definitely want to do DCE before we do CSE so that we don't hoist things. For
// example:
//
// @dead = Mul(@a, @b)
// ... lots of control flow and stuff
// @thing = Mul(@a, @b)
//
// If we do CSE before DCE, we will remove @thing and keep @dead. Effectively, we will
// "hoist" @thing. On the other hand, if we run DCE before CSE, we will kill @dead and
// keep @thing. That's better, since we usually want things to stay wherever the client
// put them. We're not actually smart enough to move things around at random.
m_changed |= eliminateDeadCodeImpl(m_proc);
m_valueForConstant.clear();
simplifySSA();
if (m_proc.optLevel() >= 2) {
m_proc.resetValueOwners();
m_dominators = &m_proc.dominators(); // Recompute if necessary.
m_pureCSE.clear();
}
for (BasicBlock* block : m_proc.blocksInPreOrder()) {
m_block = block;
for (m_index = 0; m_index < block->size(); ++m_index) {
if (B3ReduceStrengthInternal::verbose) {
dataLog(
"Looking at ", *block, " #", m_index, ": ",
deepDump(m_proc, block->at(m_index)), "\n");
}
m_value = m_block->at(m_index);
m_value->performSubstitution();
reduceValueStrength();
if (m_proc.optLevel() >= 2)
replaceIfRedundant();
}
m_insertionSet.execute(m_block);
}
m_changedCFG |= m_blockInsertionSet.execute();
handleChangedCFGIfNecessary();
result |= m_changed;
} while (m_changed && m_proc.optLevel() >= 2);
if (m_proc.optLevel() < 2) {
m_changedCFG = false;
simplifyCFG();
handleChangedCFGIfNecessary();
}
return result;
}
private:
void reduceValueStrength()
{
switch (m_value->opcode()) {
case Opaque:
// Turn this: Opaque(Opaque(value))
// Into this: Opaque(value)
if (m_value->child(0)->opcode() == Opaque) {
replaceWithIdentity(m_value->child(0));
break;
}
break;
case Add:
handleCommutativity();
if (m_value->child(0)->opcode() == Add && m_value->isInteger()) {
// Turn this: Add(Add(value, constant1), constant2)
// Into this: Add(value, constant1 + constant2)
Value* newSum = m_value->child(1)->addConstant(m_proc, m_value->child(0)->child(1));
if (newSum) {
m_insertionSet.insertValue(m_index, newSum);
m_value->child(0) = m_value->child(0)->child(0);
m_value->child(1) = newSum;
m_changed = true;
break;
}
// Turn this: Add(Add(value, constant), otherValue)
// Into this: Add(Add(value, otherValue), constant)
if (!m_value->child(1)->hasInt() && m_value->child(0)->child(1)->hasInt()) {
Value* value = m_value->child(0)->child(0);
Value* constant = m_value->child(0)->child(1);
Value* otherValue = m_value->child(1);
// This could create duplicate code if Add(value, constant) is used elsewhere.
// However, we already model adding a constant as if it was free in other places
// so let's just roll with it. The alternative would mean having to do good use
// counts, which reduceStrength() currently doesn't have.
m_value->child(0) =
m_insertionSet.insert<Value>(
m_index, Add, m_value->origin(), value, otherValue);
m_value->child(1) = constant;
m_changed = true;
break;
}
}
// Turn this: Add(otherValue, Add(value, constant))
// Into this: Add(Add(value, otherValue), constant)
if (m_value->isInteger()
&& !m_value->child(0)->hasInt()
&& m_value->child(1)->opcode() == Add
&& m_value->child(1)->child(1)->hasInt()) {
Value* value = m_value->child(1)->child(0);
Value* constant = m_value->child(1)->child(1);
Value* otherValue = m_value->child(0);
// This creates a duplicate add. That's dangerous but probably fine, see above.
m_value->child(0) =
m_insertionSet.insert<Value>(
m_index, Add, m_value->origin(), value, otherValue);
m_value->child(1) = constant;
m_changed = true;
break;
}
// Turn this: Add(constant1, constant2)
// Into this: constant1 + constant2
if (Value* constantAdd = m_value->child(0)->addConstant(m_proc, m_value->child(1))) {
replaceWithNewValue(constantAdd);
break;
}
// Turn this: Integer Add(value, value)
// Into this: Shl(value, 1)
// This is a useful canonicalization. It's not meant to be a strength reduction.
if (m_value->isInteger() && m_value->child(0) == m_value->child(1)) {
replaceWithNewValue(
m_proc.add<Value>(
Shl, m_value->origin(), m_value->child(0),
m_insertionSet.insert<Const32Value>(m_index, m_value->origin(), 1)));
break;
}
// Turn this: Add(value, zero)
// Into an Identity.
//
// Addition is subtle with doubles. Zero is not the neutral value, negative zero is:
// 0 + 0 = 0
// 0 + -0 = 0
// -0 + 0 = 0
// -0 + -0 = -0
if (m_value->child(1)->isInt(0) || m_value->child(1)->isNegativeZero()) {
replaceWithIdentity(m_value->child(0));
break;
}
if (m_value->isInteger()) {
// Turn this: Integer Add(value, Neg(otherValue))
// Into this: Sub(value, otherValue)
if (m_value->child(1)->opcode() == Neg) {
replaceWithNew<Value>(Sub, m_value->origin(), m_value->child(0), m_value->child(1)->child(0));
break;
}
// Turn this: Integer Add(Neg(value), otherValue)
// Into this: Sub(otherValue, value)
if (m_value->child(0)->opcode() == Neg) {
replaceWithNew<Value>(Sub, m_value->origin(), m_value->child(1), m_value->child(0)->child(0));
break;
}
// Turn this: Integer Add(Sub(0, value), -1)
// Into this: BitXor(value, -1)
if (m_value->child(0)->opcode() == Sub
&& m_value->child(1)->isInt(-1)
&& m_value->child(0)->child(0)->isInt(0)) {
replaceWithNew<Value>(BitXor, m_value->origin(), m_value->child(0)->child(1), m_value->child(1));
break;
}
if (handleMulDistributivity())
break;
}
break;
case Sub:
// Turn this: Sub(BitXor(BitAnd(value, mask1), mask2), mask2)
// Into this: SShr(Shl(value, amount), amount)
// Conditions:
// 1. mask1 = (1 << width) - 1
// 2. mask2 = 1 << (width - 1)
// 3. amount = datasize - width
// 4. 0 < width < datasize
if (m_value->child(0)->opcode() == BitXor
&& m_value->child(0)->child(0)->opcode() == BitAnd
&& m_value->child(0)->child(0)->child(1)->hasInt()
&& m_value->child(0)->child(1)->hasInt()
&& m_value->child(1)->hasInt()) {
uint64_t mask1 = m_value->child(0)->child(0)->child(1)->asInt();
uint64_t mask2 = m_value->child(0)->child(1)->asInt();
uint64_t mask3 = m_value->child(1)->asInt();
uint64_t width = WTF::bitCount(mask1);
uint64_t datasize = m_value->child(0)->child(0)->type() == Int64 ? 64 : 32;
bool isValidMask1 = mask1 && !(mask1 & (mask1 + 1)) && width < datasize;
bool isValidMask2 = mask2 == mask3 && ((mask2 << 1) - 1) == mask1;
if (isValidMask1 && isValidMask2) {
Value* amount = m_insertionSet.insert<Const32Value>(m_index, m_value->origin(), datasize - width);
Value* shlValue = m_insertionSet.insert<Value>(m_index, Shl, m_value->origin(), m_value->child(0)->child(0)->child(0), amount);
replaceWithNew<Value>(SShr, m_value->origin(), shlValue, amount);
break;
}
}
// Turn this: Sub(constant1, constant2)
// Into this: constant1 - constant2
if (Value* constantSub = m_value->child(0)->subConstant(m_proc, m_value->child(1))) {
replaceWithNewValue(constantSub);
break;
}
if (m_value->isInteger()) {
// Turn this: Sub(Neg(value), 1)
// Into this: BitXor(value, -1)
if (m_value->child(0)->opcode() == Neg && m_value->child(1)->isInt(1)) {
Value* minusOne;
if (m_value->child(0)->child(0)->type() == Int32)
minusOne = m_insertionSet.insert<Const32Value>(m_index, m_value->origin(), -1);
else
minusOne = m_insertionSet.insert<Const64Value>(m_index, m_value->origin(), -1);
replaceWithNew<Value>(BitXor, m_value->origin(), m_value->child(0)->child(0), minusOne);
break;
}
// Turn this: Sub(value, constant)
// Into this: Add(value, -constant)
if (Value* negatedConstant = m_value->child(1)->negConstant(m_proc)) {
m_insertionSet.insertValue(m_index, negatedConstant);
replaceWithNew<Value>(
Add, m_value->origin(), m_value->child(0), negatedConstant);
break;
}
// Turn this: Sub(0, value)
// Into this: Neg(value)
if (m_value->child(0)->isInt(0)) {
replaceWithNew<Value>(Neg, m_value->origin(), m_value->child(1));
break;
}
// Turn this: Sub(value, value)
// Into this: 0
if (m_value->child(0) == m_value->child(1)) {
replaceWithNewValue(m_proc.addIntConstant(m_value, 0));
break;
}
// Turn this: Sub(value, Neg(otherValue))
// Into this: Add(value, otherValue)
if (m_value->child(1)->opcode() == Neg) {
replaceWithNew<Value>(Add, m_value->origin(), m_value->child(0), m_value->child(1)->child(0));
break;
}
// Turn this: Sub(Neg(value), value2)
// Into this: Neg(Add(value, value2))
if (m_value->child(0)->opcode() == Neg) {
replaceWithNew<Value>(Neg, m_value->origin(),
m_insertionSet.insert<Value>(m_index, Add, m_value->origin(), m_value->child(0)->child(0), m_value->child(1)));
break;
}
// Turn this: Sub(Sub(a, b), c)
// Into this: Sub(a, Add(b, c))
if (m_value->child(0)->opcode() == Sub) {
replaceWithNew<Value>(Sub, m_value->origin(), m_value->child(0)->child(0),
m_insertionSet.insert<Value>(m_index, Add, m_value->origin(), m_value->child(0)->child(1), m_value->child(1)));
break;
}
// Turn this: Sub(a, Sub(b, c))
// Into this: Add(Sub(a, b), c)
if (m_value->child(1)->opcode() == Sub) {
replaceWithNew<Value>(Add, m_value->origin(),
m_insertionSet.insert<Value>(m_index, Sub, m_value->origin(), m_value->child(0), m_value->child(1)->child(0)),
m_value->child(1)->child(1));
break;
}
// Turn this: Sub(Add(a, b), c)
// Into this: Add(a, Sub(b, c))
if (m_value->child(0)->opcode() == Add) {
replaceWithNew<Value>(Add, m_value->origin(), m_value->child(0)->child(0),
m_insertionSet.insert<Value>(m_index, Sub, m_value->origin(), m_value->child(0)->child(1), m_value->child(1)));
break;
}
if (handleMulDistributivity())
break;
}
break;
case Neg:
// Turn this: Neg(constant)
// Into this: -constant
if (Value* constant = m_value->child(0)->negConstant(m_proc)) {
replaceWithNewValue(constant);
break;
}
// Turn this: Neg(Neg(value))
// Into this: value
if (m_value->child(0)->opcode() == Neg) {
replaceWithIdentity(m_value->child(0)->child(0));
break;
}
if (m_value->isInteger()) {
// Turn this: Integer Neg(Sub(value, otherValue))
// Into this: Sub(otherValue, value)
if (m_value->child(0)->opcode() == Sub) {
replaceWithNew<Value>(Sub, m_value->origin(), m_value->child(0)->child(1), m_value->child(0)->child(0));
break;
}
// Turn this: Integer Neg(Mul(value, c))
// Into this: Mul(value, -c), as long as -c does not overflow
if (m_value->child(0)->opcode() == Mul && m_value->child(0)->child(1)->hasInt()) {
int64_t factor = m_value->child(0)->child(1)->asInt();
if (m_value->type() == Int32 && factor != std::numeric_limits<int32_t>::min()) {
Value* newFactor = m_insertionSet.insert<Const32Value>(m_index, m_value->child(0)->child(1)->origin(), -factor);
replaceWithNew<Value>(Mul, m_value->origin(), m_value->child(0)->child(0), newFactor);
} else if (m_value->type() == Int64 && factor != std::numeric_limits<int64_t>::min()) {
Value* newFactor = m_insertionSet.insert<Const64Value>(m_index, m_value->child(0)->child(1)->origin(), -factor);
replaceWithNew<Value>(Mul, m_value->origin(), m_value->child(0)->child(0), newFactor);
}
}
}
break;
case Mul:
handleCommutativity();
// Turn this: Mul(constant1, constant2)
// Into this: constant1 * constant2
if (Value* value = m_value->child(0)->mulConstant(m_proc, m_value->child(1))) {
replaceWithNewValue(value);
break;
}
if (m_value->child(1)->hasInt()) {
int64_t factor = m_value->child(1)->asInt();
// Turn this: Mul(value, 0)
// Into this: 0
// Note that we don't do this for doubles because that's wrong. For example, -1 * 0
// and 1 * 0 yield different results.
if (!factor) {
replaceWithIdentity(m_value->child(1));
break;
}
// Turn this: Mul(value, 1)
// Into this: value
if (factor == 1) {
replaceWithIdentity(m_value->child(0));
break;
}
// Turn this: Mul(value, -1)
// Into this: Neg(value)
if (factor == -1) {
replaceWithNew<Value>(Neg, m_value->origin(), m_value->child(0));
break;
}
// Turn this: Mul(value, constant)
// Into this: Shl(value, log2(constant))
if (hasOneBitSet(factor)) {
unsigned shiftAmount = WTF::fastLog2(static_cast<uint64_t>(factor));
replaceWithNewValue(
m_proc.add<Value>(
Shl, m_value->origin(), m_value->child(0),
m_insertionSet.insert<Const32Value>(
m_index, m_value->origin(), shiftAmount)));
break;
}
} else if (m_value->child(1)->hasDouble()) {
double factor = m_value->child(1)->asDouble();
// Turn this: Mul(value, 1)
// Into this: value
if (factor == 1) {
replaceWithIdentity(m_value->child(0));
break;
}
}
if (m_value->isInteger()) {
// Turn this: Integer Mul(value, Neg(otherValue))
// Into this: Neg(Mul(value, otherValue))
if (m_value->child(1)->opcode() == Neg) {
Value* newMul = m_insertionSet.insert<Value>(m_index, Mul, m_value->origin(), m_value->child(0), m_value->child(1)->child(0));
replaceWithNew<Value>(Neg, m_value->origin(), newMul);
break;
}
// Turn this: Integer Mul(Neg(value), otherValue)
// Into this: Neg(Mul(value, value2))
if (m_value->child(0)->opcode() == Neg) {
Value* newMul = m_insertionSet.insert<Value>(m_index, Mul, m_value->origin(), m_value->child(0)->child(0), m_value->child(1));
replaceWithNew<Value>(Neg, m_value->origin(), newMul);
break;
}
}
break;
case Div:
// Turn this: Div(constant1, constant2)
// Into this: constant1 / constant2
// Note that this uses Div<Chill> semantics. That's fine, because the rules for Div
// are strictly weaker: it has corner cases where it's allowed to do anything it
// likes.
if (replaceWithNewValue(m_value->child(0)->divConstant(m_proc, m_value->child(1))))
break;
if (m_value->child(1)->hasInt()) {
switch (m_value->child(1)->asInt()) {
case -1:
// Turn this: Div(value, -1)
// Into this: Neg(value)
replaceWithNewValue(
m_proc.add<Value>(Neg, m_value->origin(), m_value->child(0)));
break;
case 0:
// Turn this: Div(value, 0)
// Into this: 0
// We can do this because it's precisely correct for ChillDiv and for Div we
// are allowed to do whatever we want.
replaceWithIdentity(m_value->child(1));
break;
case 1:
// Turn this: Div(value, 1)
// Into this: value
replaceWithIdentity(m_value->child(0));
break;
default:
// Perform super comprehensive strength reduction of division. Currently we
// only do this for 32-bit divisions, since we need a high multiply
// operation. We emulate it using 64-bit multiply. We can't emulate 64-bit
// high multiply with a 128-bit multiply because we don't have a 128-bit
// multiply. We could do it with a patchpoint if we cared badly enough.
if (m_value->type() != Int32)
break;
if (m_proc.optLevel() < 2)
break;
int32_t divisor = m_value->child(1)->asInt32();
DivisionMagic<int32_t> magic = computeDivisionMagic(divisor);
// Perform the "high" multiplication. We do it just to get the high bits.
// This is sort of like multiplying by the reciprocal, just more gnarly. It's
// from Hacker's Delight and I don't claim to understand it.
Value* magicQuotient = m_insertionSet.insert<Value>(
m_index, Trunc, m_value->origin(),
m_insertionSet.insert<Value>(
m_index, ZShr, m_value->origin(),
m_insertionSet.insert<Value>(
m_index, Mul, m_value->origin(),
m_insertionSet.insert<Value>(
m_index, SExt32, m_value->origin(), m_value->child(0)),
m_insertionSet.insert<Const64Value>(
m_index, m_value->origin(), magic.magicMultiplier)),
m_insertionSet.insert<Const32Value>(
m_index, m_value->origin(), 32)));
if (divisor > 0 && magic.magicMultiplier < 0) {
magicQuotient = m_insertionSet.insert<Value>(
m_index, Add, m_value->origin(), magicQuotient, m_value->child(0));
}
if (divisor < 0 && magic.magicMultiplier > 0) {
magicQuotient = m_insertionSet.insert<Value>(
m_index, Sub, m_value->origin(), magicQuotient, m_value->child(0));
}
if (magic.shift > 0) {
magicQuotient = m_insertionSet.insert<Value>(
m_index, SShr, m_value->origin(), magicQuotient,
m_insertionSet.insert<Const32Value>(
m_index, m_value->origin(), magic.shift));
}
replaceWithIdentity(
m_insertionSet.insert<Value>(
m_index, Add, m_value->origin(), magicQuotient,
m_insertionSet.insert<Value>(
m_index, ZShr, m_value->origin(), magicQuotient,
m_insertionSet.insert<Const32Value>(
m_index, m_value->origin(), 31))));
break;
}
break;
}
break;