forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInterleavedLoadCombinePass.cpp
1363 lines (1177 loc) · 42.3 KB
/
InterleavedLoadCombinePass.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
//===- InterleavedLoadCombine.cpp - Combine Interleaved Loads ---*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// \file
//
// This file defines the interleaved-load-combine pass. The pass searches for
// ShuffleVectorInstruction that execute interleaving loads. If a matching
// pattern is found, it adds a combined load and further instructions in a
// pattern that is detectable by InterleavedAccesPass. The old instructions are
// left dead to be removed later. The pass is specifically designed to be
// executed just before InterleavedAccesPass to find any left-over instances
// that are not detected within former passes.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/MemoryLocation.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <cassert>
#include <list>
using namespace llvm;
#define DEBUG_TYPE "interleaved-load-combine"
namespace {
/// Statistic counter
STATISTIC(NumInterleavedLoadCombine, "Number of combined loads");
/// Option to disable the pass
static cl::opt<bool> DisableInterleavedLoadCombine(
"disable-" DEBUG_TYPE, cl::init(false), cl::Hidden,
cl::desc("Disable combining of interleaved loads"));
struct VectorInfo;
struct InterleavedLoadCombineImpl {
public:
InterleavedLoadCombineImpl(Function &F, DominatorTree &DT, MemorySSA &MSSA,
TargetMachine &TM)
: F(F), DT(DT), MSSA(MSSA),
TLI(*TM.getSubtargetImpl(F)->getTargetLowering()),
TTI(TM.getTargetTransformInfo(F)) {}
/// Scan the function for interleaved load candidates and execute the
/// replacement if applicable.
bool run();
private:
/// Function this pass is working on
Function &F;
/// Dominator Tree Analysis
DominatorTree &DT;
/// Memory Alias Analyses
MemorySSA &MSSA;
/// Target Lowering Information
const TargetLowering &TLI;
/// Target Transform Information
const TargetTransformInfo TTI;
/// Find the instruction in sets LIs that dominates all others, return nullptr
/// if there is none.
LoadInst *findFirstLoad(const std::set<LoadInst *> &LIs);
/// Replace interleaved load candidates. It does additional
/// analyses if this makes sense. Returns true on success and false
/// of nothing has been changed.
bool combine(std::list<VectorInfo> &InterleavedLoad,
OptimizationRemarkEmitter &ORE);
/// Given a set of VectorInfo containing candidates for a given interleave
/// factor, find a set that represents a 'factor' interleaved load.
bool findPattern(std::list<VectorInfo> &Candidates,
std::list<VectorInfo> &InterleavedLoad, unsigned Factor,
const DataLayout &DL);
}; // InterleavedLoadCombine
/// First Order Polynomial on an n-Bit Integer Value
///
/// Polynomial(Value) = Value * B + A + E*2^(n-e)
///
/// A and B are the coefficients. E*2^(n-e) is an error within 'e' most
/// significant bits. It is introduced if an exact computation cannot be proven
/// (e.q. division by 2).
///
/// As part of this optimization multiple loads will be combined. It necessary
/// to prove that loads are within some relative offset to each other. This
/// class is used to prove relative offsets of values loaded from memory.
///
/// Representing an integer in this form is sound since addition in two's
/// complement is associative (trivial) and multiplication distributes over the
/// addition (see Proof(1) in Polynomial::mul). Further, both operations
/// commute.
//
// Example:
// declare @fn(i64 %IDX, <4 x float>* %PTR) {
// %Pa1 = add i64 %IDX, 2
// %Pa2 = lshr i64 %Pa1, 1
// %Pa3 = getelementptr inbounds <4 x float>, <4 x float>* %PTR, i64 %Pa2
// %Va = load <4 x float>, <4 x float>* %Pa3
//
// %Pb1 = add i64 %IDX, 4
// %Pb2 = lshr i64 %Pb1, 1
// %Pb3 = getelementptr inbounds <4 x float>, <4 x float>* %PTR, i64 %Pb2
// %Vb = load <4 x float>, <4 x float>* %Pb3
// ... }
//
// The goal is to prove that two loads load consecutive addresses.
//
// In this case the polynomials are constructed by the following
// steps.
//
// The number tag #e specifies the error bits.
//
// Pa_0 = %IDX #0
// Pa_1 = %IDX + 2 #0 | add 2
// Pa_2 = %IDX/2 + 1 #1 | lshr 1
// Pa_3 = %IDX/2 + 1 #1 | GEP, step signext to i64
// Pa_4 = (%IDX/2)*16 + 16 #0 | GEP, multiply index by sizeof(4) for floats
// Pa_5 = (%IDX/2)*16 + 16 #0 | GEP, add offset of leading components
//
// Pb_0 = %IDX #0
// Pb_1 = %IDX + 4 #0 | add 2
// Pb_2 = %IDX/2 + 2 #1 | lshr 1
// Pb_3 = %IDX/2 + 2 #1 | GEP, step signext to i64
// Pb_4 = (%IDX/2)*16 + 32 #0 | GEP, multiply index by sizeof(4) for floats
// Pb_5 = (%IDX/2)*16 + 16 #0 | GEP, add offset of leading components
//
// Pb_5 - Pa_5 = 16 #0 | subtract to get the offset
//
// Remark: %PTR is not maintained within this class. So in this instance the
// offset of 16 can only be assumed if the pointers are equal.
//
class Polynomial {
/// Operations on B
enum BOps {
LShr,
Mul,
SExt,
Trunc,
};
/// Number of Error Bits e
unsigned ErrorMSBs;
/// Value
Value *V;
/// Coefficient B
SmallVector<std::pair<BOps, APInt>, 4> B;
/// Coefficient A
APInt A;
public:
Polynomial(Value *V) : ErrorMSBs((unsigned)-1), V(V) {
IntegerType *Ty = dyn_cast<IntegerType>(V->getType());
if (Ty) {
ErrorMSBs = 0;
this->V = V;
A = APInt(Ty->getBitWidth(), 0);
}
}
Polynomial(const APInt &A, unsigned ErrorMSBs = 0)
: ErrorMSBs(ErrorMSBs), V(nullptr), A(A) {}
Polynomial(unsigned BitWidth, uint64_t A, unsigned ErrorMSBs = 0)
: ErrorMSBs(ErrorMSBs), V(nullptr), A(BitWidth, A) {}
Polynomial() : ErrorMSBs((unsigned)-1), V(nullptr) {}
/// Increment and clamp the number of undefined bits.
void incErrorMSBs(unsigned amt) {
if (ErrorMSBs == (unsigned)-1)
return;
ErrorMSBs += amt;
if (ErrorMSBs > A.getBitWidth())
ErrorMSBs = A.getBitWidth();
}
/// Decrement and clamp the number of undefined bits.
void decErrorMSBs(unsigned amt) {
if (ErrorMSBs == (unsigned)-1)
return;
if (ErrorMSBs > amt)
ErrorMSBs -= amt;
else
ErrorMSBs = 0;
}
/// Apply an add on the polynomial
Polynomial &add(const APInt &C) {
// Note: Addition is associative in two's complement even when in case of
// signed overflow.
//
// Error bits can only propagate into higher significant bits. As these are
// already regarded as undefined, there is no change.
//
// Theorem: Adding a constant to a polynomial does not change the error
// term.
//
// Proof:
//
// Since the addition is associative and commutes:
//
// (B + A + E*2^(n-e)) + C = B + (A + C) + E*2^(n-e)
// [qed]
if (C.getBitWidth() != A.getBitWidth()) {
ErrorMSBs = (unsigned)-1;
return *this;
}
A += C;
return *this;
}
/// Apply a multiplication onto the polynomial.
Polynomial &mul(const APInt &C) {
// Note: Multiplication distributes over the addition
//
// Theorem: Multiplication distributes over the addition
//
// Proof(1):
//
// (B+A)*C =-
// = (B + A) + (B + A) + .. {C Times}
// addition is associative and commutes, hence
// = B + B + .. {C Times} .. + A + A + .. {C times}
// = B*C + A*C
// (see (function add) for signed values and overflows)
// [qed]
//
// Theorem: If C has c trailing zeros, errors bits in A or B are shifted out
// to the left.
//
// Proof(2):
//
// Let B' and A' be the n-Bit inputs with some unknown errors EA,
// EB at e leading bits. B' and A' can be written down as:
//
// B' = B + 2^(n-e)*EB
// A' = A + 2^(n-e)*EA
//
// Let C' be an input with c trailing zero bits. C' can be written as
//
// C' = C*2^c
//
// Therefore we can compute the result by using distributivity and
// commutativity.
//
// (B'*C' + A'*C') = [B + 2^(n-e)*EB] * C' + [A + 2^(n-e)*EA] * C' =
// = [B + 2^(n-e)*EB + A + 2^(n-e)*EA] * C' =
// = (B'+A') * C' =
// = [B + 2^(n-e)*EB + A + 2^(n-e)*EA] * C' =
// = [B + A + 2^(n-e)*EB + 2^(n-e)*EA] * C' =
// = (B + A) * C' + [2^(n-e)*EB + 2^(n-e)*EA)] * C' =
// = (B + A) * C' + [2^(n-e)*EB + 2^(n-e)*EA)] * C*2^c =
// = (B + A) * C' + C*(EB + EA)*2^(n-e)*2^c =
//
// Let EC be the final error with EC = C*(EB + EA)
//
// = (B + A)*C' + EC*2^(n-e)*2^c =
// = (B + A)*C' + EC*2^(n-(e-c))
//
// Since EC is multiplied by 2^(n-(e-c)) the resulting error contains c
// less error bits than the input. c bits are shifted out to the left.
// [qed]
if (C.getBitWidth() != A.getBitWidth()) {
ErrorMSBs = (unsigned)-1;
return *this;
}
// Multiplying by one is a no-op.
if (C.isOne()) {
return *this;
}
// Multiplying by zero removes the coefficient B and defines all bits.
if (C.isZero()) {
ErrorMSBs = 0;
deleteB();
}
// See Proof(2): Trailing zero bits indicate a left shift. This removes
// leading bits from the result even if they are undefined.
decErrorMSBs(C.countTrailingZeros());
A *= C;
pushBOperation(Mul, C);
return *this;
}
/// Apply a logical shift right on the polynomial
Polynomial &lshr(const APInt &C) {
// Theorem(1): (B + A + E*2^(n-e)) >> 1 => (B >> 1) + (A >> 1) + E'*2^(n-e')
// where
// e' = e + 1,
// E is a e-bit number,
// E' is a e'-bit number,
// holds under the following precondition:
// pre(1): A % 2 = 0
// pre(2): e < n, (see Theorem(2) for the trivial case with e=n)
// where >> expresses a logical shift to the right, with adding zeros.
//
// We need to show that for every, E there is a E'
//
// B = b_h * 2^(n-1) + b_m * 2 + b_l
// A = a_h * 2^(n-1) + a_m * 2 (pre(1))
//
// where a_h, b_h, b_l are single bits, and a_m, b_m are (n-2) bit numbers
//
// Let X = (B + A + E*2^(n-e)) >> 1
// Let Y = (B >> 1) + (A >> 1) + E*2^(n-e) >> 1
//
// X = [B + A + E*2^(n-e)] >> 1 =
// = [ b_h * 2^(n-1) + b_m * 2 + b_l +
// + a_h * 2^(n-1) + a_m * 2 +
// + E * 2^(n-e) ] >> 1 =
//
// The sum is built by putting the overflow of [a_m + b+n] into the term
// 2^(n-1). As there are no more bits beyond 2^(n-1) the overflow within
// this bit is discarded. This is expressed by % 2.
//
// The bit in position 0 cannot overflow into the term (b_m + a_m).
//
// = [ ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-1) +
// + ((b_m + a_m) % 2^(n-2)) * 2 +
// + b_l + E * 2^(n-e) ] >> 1 =
//
// The shift is computed by dividing the terms by 2 and by cutting off
// b_l.
//
// = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + E * 2^(n-(e+1)) =
//
// by the definition in the Theorem e+1 = e'
//
// = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + E * 2^(n-e') =
//
// Compute Y by applying distributivity first
//
// Y = (B >> 1) + (A >> 1) + E*2^(n-e') =
// = (b_h * 2^(n-1) + b_m * 2 + b_l) >> 1 +
// + (a_h * 2^(n-1) + a_m * 2) >> 1 +
// + E * 2^(n-e) >> 1 =
//
// Again, the shift is computed by dividing the terms by 2 and by cutting
// off b_l.
//
// = b_h * 2^(n-2) + b_m +
// + a_h * 2^(n-2) + a_m +
// + E * 2^(n-(e+1)) =
//
// Again, the sum is built by putting the overflow of [a_m + b+n] into
// the term 2^(n-1). But this time there is room for a second bit in the
// term 2^(n-2) we add this bit to a new term and denote it o_h in a
// second step.
//
// = ([b_h + a_h + (b_m + a_m) >> (n-2)] >> 1) * 2^(n-1) +
// + ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + E * 2^(n-(e+1)) =
//
// Let o_h = [b_h + a_h + (b_m + a_m) >> (n-2)] >> 1
// Further replace e+1 by e'.
//
// = o_h * 2^(n-1) +
// + ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + E * 2^(n-e') =
//
// Move o_h into the error term and construct E'. To ensure that there is
// no 2^x with negative x, this step requires pre(2) (e < n).
//
// = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + o_h * 2^(e'-1) * 2^(n-e') + | pre(2), move 2^(e'-1)
// | out of the old exponent
// + E * 2^(n-e') =
// = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + [o_h * 2^(e'-1) + E] * 2^(n-e') + | move 2^(e'-1) out of
// | the old exponent
//
// Let E' = o_h * 2^(e'-1) + E
//
// = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + E' * 2^(n-e')
//
// Because X and Y are distinct only in there error terms and E' can be
// constructed as shown the theorem holds.
// [qed]
//
// For completeness in case of the case e=n it is also required to show that
// distributivity can be applied.
//
// In this case Theorem(1) transforms to (the pre-condition on A can also be
// dropped)
//
// Theorem(2): (B + A + E) >> 1 => (B >> 1) + (A >> 1) + E'
// where
// A, B, E, E' are two's complement numbers with the same bit
// width
//
// Let A + B + E = X
// Let (B >> 1) + (A >> 1) = Y
//
// Therefore we need to show that for every X and Y there is an E' which
// makes the equation
//
// X = Y + E'
//
// hold. This is trivially the case for E' = X - Y.
//
// [qed]
//
// Remark: Distributing lshr with and arbitrary number n can be expressed as
// ((((B + A) lshr 1) lshr 1) ... ) {n times}.
// This construction induces n additional error bits at the left.
if (C.getBitWidth() != A.getBitWidth()) {
ErrorMSBs = (unsigned)-1;
return *this;
}
if (C.isZero())
return *this;
// Test if the result will be zero
unsigned shiftAmt = C.getZExtValue();
if (shiftAmt >= C.getBitWidth())
return mul(APInt(C.getBitWidth(), 0));
// The proof that shiftAmt LSBs are zero for at least one summand is only
// possible for the constant number.
//
// If this can be proven add shiftAmt to the error counter
// `ErrorMSBs`. Otherwise set all bits as undefined.
if (A.countTrailingZeros() < shiftAmt)
ErrorMSBs = A.getBitWidth();
else
incErrorMSBs(shiftAmt);
// Apply the operation.
pushBOperation(LShr, C);
A = A.lshr(shiftAmt);
return *this;
}
/// Apply a sign-extend or truncate operation on the polynomial.
Polynomial &sextOrTrunc(unsigned n) {
if (n < A.getBitWidth()) {
// Truncate: Clearly undefined Bits on the MSB side are removed
// if there are any.
decErrorMSBs(A.getBitWidth() - n);
A = A.trunc(n);
pushBOperation(Trunc, APInt(sizeof(n) * 8, n));
}
if (n > A.getBitWidth()) {
// Extend: Clearly extending first and adding later is different
// to adding first and extending later in all extended bits.
incErrorMSBs(n - A.getBitWidth());
A = A.sext(n);
pushBOperation(SExt, APInt(sizeof(n) * 8, n));
}
return *this;
}
/// Test if there is a coefficient B.
bool isFirstOrder() const { return V != nullptr; }
/// Test coefficient B of two Polynomials are equal.
bool isCompatibleTo(const Polynomial &o) const {
// The polynomial use different bit width.
if (A.getBitWidth() != o.A.getBitWidth())
return false;
// If neither Polynomial has the Coefficient B.
if (!isFirstOrder() && !o.isFirstOrder())
return true;
// The index variable is different.
if (V != o.V)
return false;
// Check the operations.
if (B.size() != o.B.size())
return false;
auto ob = o.B.begin();
for (auto &b : B) {
if (b != *ob)
return false;
ob++;
}
return true;
}
/// Subtract two polynomials, return an undefined polynomial if
/// subtraction is not possible.
Polynomial operator-(const Polynomial &o) const {
// Return an undefined polynomial if incompatible.
if (!isCompatibleTo(o))
return Polynomial();
// If the polynomials are compatible (meaning they have the same
// coefficient on B), B is eliminated. Thus a polynomial solely
// containing A is returned
return Polynomial(A - o.A, std::max(ErrorMSBs, o.ErrorMSBs));
}
/// Subtract a constant from a polynomial,
Polynomial operator-(uint64_t C) const {
Polynomial Result(*this);
Result.A -= C;
return Result;
}
/// Add a constant to a polynomial,
Polynomial operator+(uint64_t C) const {
Polynomial Result(*this);
Result.A += C;
return Result;
}
/// Returns true if it can be proven that two Polynomials are equal.
bool isProvenEqualTo(const Polynomial &o) {
// Subtract both polynomials and test if it is fully defined and zero.
Polynomial r = *this - o;
return (r.ErrorMSBs == 0) && (!r.isFirstOrder()) && (r.A.isZero());
}
/// Print the polynomial into a stream.
void print(raw_ostream &OS) const {
OS << "[{#ErrBits:" << ErrorMSBs << "} ";
if (V) {
for (auto b : B)
OS << "(";
OS << "(" << *V << ") ";
for (auto b : B) {
switch (b.first) {
case LShr:
OS << "LShr ";
break;
case Mul:
OS << "Mul ";
break;
case SExt:
OS << "SExt ";
break;
case Trunc:
OS << "Trunc ";
break;
}
OS << b.second << ") ";
}
}
OS << "+ " << A << "]";
}
private:
void deleteB() {
V = nullptr;
B.clear();
}
void pushBOperation(const BOps Op, const APInt &C) {
if (isFirstOrder()) {
B.push_back(std::make_pair(Op, C));
return;
}
}
};
#ifndef NDEBUG
static raw_ostream &operator<<(raw_ostream &OS, const Polynomial &S) {
S.print(OS);
return OS;
}
#endif
/// VectorInfo stores abstract the following information for each vector
/// element:
///
/// 1) The the memory address loaded into the element as Polynomial
/// 2) a set of load instruction necessary to construct the vector,
/// 3) a set of all other instructions that are necessary to create the vector and
/// 4) a pointer value that can be used as relative base for all elements.
struct VectorInfo {
private:
VectorInfo(const VectorInfo &c) : VTy(c.VTy) {
llvm_unreachable(
"Copying VectorInfo is neither implemented nor necessary,");
}
public:
/// Information of a Vector Element
struct ElementInfo {
/// Offset Polynomial.
Polynomial Ofs;
/// The Load Instruction used to Load the entry. LI is null if the pointer
/// of the load instruction does not point on to the entry
LoadInst *LI;
ElementInfo(Polynomial Offset = Polynomial(), LoadInst *LI = nullptr)
: Ofs(Offset), LI(LI) {}
};
/// Basic-block the load instructions are within
BasicBlock *BB = nullptr;
/// Pointer value of all participation load instructions
Value *PV = nullptr;
/// Participating load instructions
std::set<LoadInst *> LIs;
/// Participating instructions
std::set<Instruction *> Is;
/// Final shuffle-vector instruction
ShuffleVectorInst *SVI = nullptr;
/// Information of the offset for each vector element
ElementInfo *EI;
/// Vector Type
FixedVectorType *const VTy;
VectorInfo(FixedVectorType *VTy) : VTy(VTy) {
EI = new ElementInfo[VTy->getNumElements()];
}
virtual ~VectorInfo() { delete[] EI; }
unsigned getDimension() const { return VTy->getNumElements(); }
/// Test if the VectorInfo can be part of an interleaved load with the
/// specified factor.
///
/// \param Factor of the interleave
/// \param DL Targets Datalayout
///
/// \returns true if this is possible and false if not
bool isInterleaved(unsigned Factor, const DataLayout &DL) const {
unsigned Size = DL.getTypeAllocSize(VTy->getElementType());
for (unsigned i = 1; i < getDimension(); i++) {
if (!EI[i].Ofs.isProvenEqualTo(EI[0].Ofs + i * Factor * Size)) {
return false;
}
}
return true;
}
/// Recursively computes the vector information stored in V.
///
/// This function delegates the work to specialized implementations
///
/// \param V Value to operate on
/// \param Result Result of the computation
///
/// \returns false if no sensible information can be gathered.
static bool compute(Value *V, VectorInfo &Result, const DataLayout &DL) {
ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V);
if (SVI)
return computeFromSVI(SVI, Result, DL);
LoadInst *LI = dyn_cast<LoadInst>(V);
if (LI)
return computeFromLI(LI, Result, DL);
BitCastInst *BCI = dyn_cast<BitCastInst>(V);
if (BCI)
return computeFromBCI(BCI, Result, DL);
return false;
}
/// BitCastInst specialization to compute the vector information.
///
/// \param BCI BitCastInst to operate on
/// \param Result Result of the computation
///
/// \returns false if no sensible information can be gathered.
static bool computeFromBCI(BitCastInst *BCI, VectorInfo &Result,
const DataLayout &DL) {
Instruction *Op = dyn_cast<Instruction>(BCI->getOperand(0));
if (!Op)
return false;
FixedVectorType *VTy = dyn_cast<FixedVectorType>(Op->getType());
if (!VTy)
return false;
// We can only cast from large to smaller vectors
if (Result.VTy->getNumElements() % VTy->getNumElements())
return false;
unsigned Factor = Result.VTy->getNumElements() / VTy->getNumElements();
unsigned NewSize = DL.getTypeAllocSize(Result.VTy->getElementType());
unsigned OldSize = DL.getTypeAllocSize(VTy->getElementType());
if (NewSize * Factor != OldSize)
return false;
VectorInfo Old(VTy);
if (!compute(Op, Old, DL))
return false;
for (unsigned i = 0; i < Result.VTy->getNumElements(); i += Factor) {
for (unsigned j = 0; j < Factor; j++) {
Result.EI[i + j] =
ElementInfo(Old.EI[i / Factor].Ofs + j * NewSize,
j == 0 ? Old.EI[i / Factor].LI : nullptr);
}
}
Result.BB = Old.BB;
Result.PV = Old.PV;
Result.LIs.insert(Old.LIs.begin(), Old.LIs.end());
Result.Is.insert(Old.Is.begin(), Old.Is.end());
Result.Is.insert(BCI);
Result.SVI = nullptr;
return true;
}
/// ShuffleVectorInst specialization to compute vector information.
///
/// \param SVI ShuffleVectorInst to operate on
/// \param Result Result of the computation
///
/// Compute the left and the right side vector information and merge them by
/// applying the shuffle operation. This function also ensures that the left
/// and right side have compatible loads. This means that all loads are with
/// in the same basic block and are based on the same pointer.
///
/// \returns false if no sensible information can be gathered.
static bool computeFromSVI(ShuffleVectorInst *SVI, VectorInfo &Result,
const DataLayout &DL) {
FixedVectorType *ArgTy =
cast<FixedVectorType>(SVI->getOperand(0)->getType());
// Compute the left hand vector information.
VectorInfo LHS(ArgTy);
if (!compute(SVI->getOperand(0), LHS, DL))
LHS.BB = nullptr;
// Compute the right hand vector information.
VectorInfo RHS(ArgTy);
if (!compute(SVI->getOperand(1), RHS, DL))
RHS.BB = nullptr;
// Neither operand produced sensible results?
if (!LHS.BB && !RHS.BB)
return false;
// Only RHS produced sensible results?
else if (!LHS.BB) {
Result.BB = RHS.BB;
Result.PV = RHS.PV;
}
// Only LHS produced sensible results?
else if (!RHS.BB) {
Result.BB = LHS.BB;
Result.PV = LHS.PV;
}
// Both operands produced sensible results?
else if ((LHS.BB == RHS.BB) && (LHS.PV == RHS.PV)) {
Result.BB = LHS.BB;
Result.PV = LHS.PV;
}
// Both operands produced sensible results but they are incompatible.
else {
return false;
}
// Merge and apply the operation on the offset information.
if (LHS.BB) {
Result.LIs.insert(LHS.LIs.begin(), LHS.LIs.end());
Result.Is.insert(LHS.Is.begin(), LHS.Is.end());
}
if (RHS.BB) {
Result.LIs.insert(RHS.LIs.begin(), RHS.LIs.end());
Result.Is.insert(RHS.Is.begin(), RHS.Is.end());
}
Result.Is.insert(SVI);
Result.SVI = SVI;
int j = 0;
for (int i : SVI->getShuffleMask()) {
assert((i < 2 * (signed)ArgTy->getNumElements()) &&
"Invalid ShuffleVectorInst (index out of bounds)");
if (i < 0)
Result.EI[j] = ElementInfo();
else if (i < (signed)ArgTy->getNumElements()) {
if (LHS.BB)
Result.EI[j] = LHS.EI[i];
else
Result.EI[j] = ElementInfo();
} else {
if (RHS.BB)
Result.EI[j] = RHS.EI[i - ArgTy->getNumElements()];
else
Result.EI[j] = ElementInfo();
}
j++;
}
return true;
}
/// LoadInst specialization to compute vector information.
///
/// This function also acts as abort condition to the recursion.
///
/// \param LI LoadInst to operate on
/// \param Result Result of the computation
///
/// \returns false if no sensible information can be gathered.
static bool computeFromLI(LoadInst *LI, VectorInfo &Result,
const DataLayout &DL) {
Value *BasePtr;
Polynomial Offset;
if (LI->isVolatile())
return false;
if (LI->isAtomic())
return false;
// Get the base polynomial
computePolynomialFromPointer(*LI->getPointerOperand(), Offset, BasePtr, DL);
Result.BB = LI->getParent();
Result.PV = BasePtr;
Result.LIs.insert(LI);
Result.Is.insert(LI);
for (unsigned i = 0; i < Result.getDimension(); i++) {
Value *Idx[2] = {
ConstantInt::get(Type::getInt32Ty(LI->getContext()), 0),
ConstantInt::get(Type::getInt32Ty(LI->getContext()), i),
};
int64_t Ofs = DL.getIndexedOffsetInType(Result.VTy, makeArrayRef(Idx, 2));
Result.EI[i] = ElementInfo(Offset + Ofs, i == 0 ? LI : nullptr);
}
return true;
}
/// Recursively compute polynomial of a value.
///
/// \param BO Input binary operation
/// \param Result Result polynomial
static void computePolynomialBinOp(BinaryOperator &BO, Polynomial &Result) {
Value *LHS = BO.getOperand(0);
Value *RHS = BO.getOperand(1);
// Find the RHS Constant if any
ConstantInt *C = dyn_cast<ConstantInt>(RHS);
if ((!C) && BO.isCommutative()) {
C = dyn_cast<ConstantInt>(LHS);
if (C)
std::swap(LHS, RHS);
}
switch (BO.getOpcode()) {
case Instruction::Add:
if (!C)
break;
computePolynomial(*LHS, Result);
Result.add(C->getValue());
return;
case Instruction::LShr:
if (!C)
break;
computePolynomial(*LHS, Result);
Result.lshr(C->getValue());
return;
default:
break;
}
Result = Polynomial(&BO);
}
/// Recursively compute polynomial of a value
///
/// \param V input value
/// \param Result result polynomial
static void computePolynomial(Value &V, Polynomial &Result) {
if (auto *BO = dyn_cast<BinaryOperator>(&V))
computePolynomialBinOp(*BO, Result);
else
Result = Polynomial(&V);
}
/// Compute the Polynomial representation of a Pointer type.
///
/// \param Ptr input pointer value
/// \param Result result polynomial
/// \param BasePtr pointer the polynomial is based on
/// \param DL Datalayout of the target machine
static void computePolynomialFromPointer(Value &Ptr, Polynomial &Result,
Value *&BasePtr,
const DataLayout &DL) {
// Not a pointer type? Return an undefined polynomial
PointerType *PtrTy = dyn_cast<PointerType>(Ptr.getType());
if (!PtrTy) {
Result = Polynomial();
BasePtr = nullptr;
return;
}
unsigned PointerBits =
DL.getIndexSizeInBits(PtrTy->getPointerAddressSpace());
/// Skip pointer casts. Return Zero polynomial otherwise
if (isa<CastInst>(&Ptr)) {
CastInst &CI = *cast<CastInst>(&Ptr);
switch (CI.getOpcode()) {
case Instruction::BitCast:
computePolynomialFromPointer(*CI.getOperand(0), Result, BasePtr, DL);
break;
default:
BasePtr = &Ptr;
Polynomial(PointerBits, 0);
break;
}
}
/// Resolve GetElementPtrInst.
else if (isa<GetElementPtrInst>(&Ptr)) {
GetElementPtrInst &GEP = *cast<GetElementPtrInst>(&Ptr);
APInt BaseOffset(PointerBits, 0);
// Check if we can compute the Offset with accumulateConstantOffset
if (GEP.accumulateConstantOffset(DL, BaseOffset)) {
Result = Polynomial(BaseOffset);
BasePtr = GEP.getPointerOperand();
return;
} else {
// Otherwise we allow that the last index operand of the GEP is
// non-constant.
unsigned idxOperand, e;
SmallVector<Value *, 4> Indices;
for (idxOperand = 1, e = GEP.getNumOperands(); idxOperand < e;
idxOperand++) {
ConstantInt *IDX = dyn_cast<ConstantInt>(GEP.getOperand(idxOperand));