1 //===- InterleavedLoadCombine.cpp - Combine Interleaved Loads ---*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
11 // This file defines the interleaved-load-combine pass. The pass searches for
12 // ShuffleVectorInstruction that execute interleaving loads. If a matching
13 // pattern is found, it adds a combined load and further instructions in a
14 // pattern that is detectable by InterleavedAccesPass. The old instructions are
15 // left dead to be removed later. The pass is specifically designed to be
16 // executed just before InterleavedAccesPass to find any left-over instances
17 // that are not detected within former passes.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/MemoryLocation.h"
23 #include "llvm/Analysis/MemorySSA.h"
24 #include "llvm/Analysis/MemorySSAUpdater.h"
25 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/TargetLowering.h"
29 #include "llvm/CodeGen/TargetPassConfig.h"
30 #include "llvm/CodeGen/TargetSubtargetInfo.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/LegacyPassManager.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetMachine.h"
51 #define DEBUG_TYPE "interleaved-load-combine"
56 STATISTIC(NumInterleavedLoadCombine, "Number of combined loads");
58 /// Option to disable the pass
59 static cl::opt<bool> DisableInterleavedLoadCombine(
60 "disable-" DEBUG_TYPE, cl::init(false), cl::Hidden,
61 cl::desc("Disable combining of interleaved loads"));
65 struct InterleavedLoadCombineImpl {
67 InterleavedLoadCombineImpl(Function &F, DominatorTree &DT, MemorySSA &MSSA,
69 : F(F), DT(DT), MSSA(MSSA),
70 TLI(*TM.getSubtargetImpl(F)->getTargetLowering()),
71 TTI(TM.getTargetTransformInfo(F)) {}
73 /// Scan the function for interleaved load candidates and execute the
74 /// replacement if applicable.
78 /// Function this pass is working on
81 /// Dominator Tree Analysis
84 /// Memory Alias Analyses
87 /// Target Lowering Information
88 const TargetLowering &TLI;
90 /// Target Transform Information
91 const TargetTransformInfo TTI;
93 /// Find the instruction in sets LIs that dominates all others, return nullptr
95 LoadInst *findFirstLoad(const std::set<LoadInst *> &LIs);
97 /// Replace interleaved load candidates. It does additional
98 /// analyses if this makes sense. Returns true on success and false
99 /// of nothing has been changed.
100 bool combine(std::list<VectorInfo> &InterleavedLoad,
101 OptimizationRemarkEmitter &ORE);
103 /// Given a set of VectorInfo containing candidates for a given interleave
104 /// factor, find a set that represents a 'factor' interleaved load.
105 bool findPattern(std::list<VectorInfo> &Candidates,
106 std::list<VectorInfo> &InterleavedLoad, unsigned Factor,
107 const DataLayout &DL);
108 }; // InterleavedLoadCombine
110 /// First Order Polynomial on an n-Bit Integer Value
112 /// Polynomial(Value) = Value * B + A + E*2^(n-e)
114 /// A and B are the coefficients. E*2^(n-e) is an error within 'e' most
115 /// significant bits. It is introduced if an exact computation cannot be proven
116 /// (e.q. division by 2).
118 /// As part of this optimization multiple loads will be combined. It necessary
119 /// to prove that loads are within some relative offset to each other. This
120 /// class is used to prove relative offsets of values loaded from memory.
122 /// Representing an integer in this form is sound since addition in two's
123 /// complement is associative (trivial) and multiplication distributes over the
124 /// addition (see Proof(1) in Polynomial::mul). Further, both operations
128 // declare @fn(i64 %IDX, <4 x float>* %PTR) {
129 // %Pa1 = add i64 %IDX, 2
130 // %Pa2 = lshr i64 %Pa1, 1
131 // %Pa3 = getelementptr inbounds <4 x float>, <4 x float>* %PTR, i64 %Pa2
132 // %Va = load <4 x float>, <4 x float>* %Pa3
134 // %Pb1 = add i64 %IDX, 4
135 // %Pb2 = lshr i64 %Pb1, 1
136 // %Pb3 = getelementptr inbounds <4 x float>, <4 x float>* %PTR, i64 %Pb2
137 // %Vb = load <4 x float>, <4 x float>* %Pb3
140 // The goal is to prove that two loads load consecutive addresses.
142 // In this case the polynomials are constructed by the following
145 // The number tag #e specifies the error bits.
148 // Pa_1 = %IDX + 2 #0 | add 2
149 // Pa_2 = %IDX/2 + 1 #1 | lshr 1
150 // Pa_3 = %IDX/2 + 1 #1 | GEP, step signext to i64
151 // Pa_4 = (%IDX/2)*16 + 16 #0 | GEP, multiply index by sizeof(4) for floats
152 // Pa_5 = (%IDX/2)*16 + 16 #0 | GEP, add offset of leading components
155 // Pb_1 = %IDX + 4 #0 | add 2
156 // Pb_2 = %IDX/2 + 2 #1 | lshr 1
157 // Pb_3 = %IDX/2 + 2 #1 | GEP, step signext to i64
158 // Pb_4 = (%IDX/2)*16 + 32 #0 | GEP, multiply index by sizeof(4) for floats
159 // Pb_5 = (%IDX/2)*16 + 16 #0 | GEP, add offset of leading components
161 // Pb_5 - Pa_5 = 16 #0 | subtract to get the offset
163 // Remark: %PTR is not maintained within this class. So in this instance the
164 // offset of 16 can only be assumed if the pointers are equal.
175 /// Number of Error Bits e
182 SmallVector<std::pair<BOps, APInt>, 4> B;
188 Polynomial(Value *V) : ErrorMSBs((unsigned)-1), V(V) {
189 IntegerType *Ty = dyn_cast<IntegerType>(V->getType());
193 A = APInt(Ty->getBitWidth(), 0);
197 Polynomial(const APInt &A, unsigned ErrorMSBs = 0)
198 : ErrorMSBs(ErrorMSBs), V(nullptr), A(A) {}
200 Polynomial(unsigned BitWidth, uint64_t A, unsigned ErrorMSBs = 0)
201 : ErrorMSBs(ErrorMSBs), V(nullptr), A(BitWidth, A) {}
203 Polynomial() : ErrorMSBs((unsigned)-1), V(nullptr) {}
205 /// Increment and clamp the number of undefined bits.
206 void incErrorMSBs(unsigned amt) {
207 if (ErrorMSBs == (unsigned)-1)
211 if (ErrorMSBs > A.getBitWidth())
212 ErrorMSBs = A.getBitWidth();
215 /// Decrement and clamp the number of undefined bits.
216 void decErrorMSBs(unsigned amt) {
217 if (ErrorMSBs == (unsigned)-1)
226 /// Apply an add on the polynomial
227 Polynomial &add(const APInt &C) {
228 // Note: Addition is associative in two's complement even when in case of
231 // Error bits can only propagate into higher significant bits. As these are
232 // already regarded as undefined, there is no change.
234 // Theorem: Adding a constant to a polynomial does not change the error
239 // Since the addition is associative and commutes:
241 // (B + A + E*2^(n-e)) + C = B + (A + C) + E*2^(n-e)
244 if (C.getBitWidth() != A.getBitWidth()) {
245 ErrorMSBs = (unsigned)-1;
253 /// Apply a multiplication onto the polynomial.
254 Polynomial &mul(const APInt &C) {
255 // Note: Multiplication distributes over the addition
257 // Theorem: Multiplication distributes over the addition
262 // = (B + A) + (B + A) + .. {C Times}
263 // addition is associative and commutes, hence
264 // = B + B + .. {C Times} .. + A + A + .. {C times}
266 // (see (function add) for signed values and overflows)
269 // Theorem: If C has c trailing zeros, errors bits in A or B are shifted out
274 // Let B' and A' be the n-Bit inputs with some unknown errors EA,
275 // EB at e leading bits. B' and A' can be written down as:
277 // B' = B + 2^(n-e)*EB
278 // A' = A + 2^(n-e)*EA
280 // Let C' be an input with c trailing zero bits. C' can be written as
284 // Therefore we can compute the result by using distributivity and
287 // (B'*C' + A'*C') = [B + 2^(n-e)*EB] * C' + [A + 2^(n-e)*EA] * C' =
288 // = [B + 2^(n-e)*EB + A + 2^(n-e)*EA] * C' =
290 // = [B + 2^(n-e)*EB + A + 2^(n-e)*EA] * C' =
291 // = [B + A + 2^(n-e)*EB + 2^(n-e)*EA] * C' =
292 // = (B + A) * C' + [2^(n-e)*EB + 2^(n-e)*EA)] * C' =
293 // = (B + A) * C' + [2^(n-e)*EB + 2^(n-e)*EA)] * C*2^c =
294 // = (B + A) * C' + C*(EB + EA)*2^(n-e)*2^c =
296 // Let EC be the final error with EC = C*(EB + EA)
298 // = (B + A)*C' + EC*2^(n-e)*2^c =
299 // = (B + A)*C' + EC*2^(n-(e-c))
301 // Since EC is multiplied by 2^(n-(e-c)) the resulting error contains c
302 // less error bits than the input. c bits are shifted out to the left.
305 if (C.getBitWidth() != A.getBitWidth()) {
306 ErrorMSBs = (unsigned)-1;
310 // Multiplying by one is a no-op.
315 // Multiplying by zero removes the coefficient B and defines all bits.
321 // See Proof(2): Trailing zero bits indicate a left shift. This removes
322 // leading bits from the result even if they are undefined.
323 decErrorMSBs(C.countTrailingZeros());
326 pushBOperation(Mul, C);
330 /// Apply a logical shift right on the polynomial
331 Polynomial &lshr(const APInt &C) {
332 // Theorem(1): (B + A + E*2^(n-e)) >> 1 => (B >> 1) + (A >> 1) + E'*2^(n-e')
335 // E is a e-bit number,
336 // E' is a e'-bit number,
337 // holds under the following precondition:
339 // pre(2): e < n, (see Theorem(2) for the trivial case with e=n)
340 // where >> expresses a logical shift to the right, with adding zeros.
342 // We need to show that for every, E there is a E'
344 // B = b_h * 2^(n-1) + b_m * 2 + b_l
345 // A = a_h * 2^(n-1) + a_m * 2 (pre(1))
347 // where a_h, b_h, b_l are single bits, and a_m, b_m are (n-2) bit numbers
349 // Let X = (B + A + E*2^(n-e)) >> 1
350 // Let Y = (B >> 1) + (A >> 1) + E*2^(n-e) >> 1
352 // X = [B + A + E*2^(n-e)] >> 1 =
353 // = [ b_h * 2^(n-1) + b_m * 2 + b_l +
354 // + a_h * 2^(n-1) + a_m * 2 +
355 // + E * 2^(n-e) ] >> 1 =
357 // The sum is built by putting the overflow of [a_m + b+n] into the term
358 // 2^(n-1). As there are no more bits beyond 2^(n-1) the overflow within
359 // this bit is discarded. This is expressed by % 2.
361 // The bit in position 0 cannot overflow into the term (b_m + a_m).
363 // = [ ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-1) +
364 // + ((b_m + a_m) % 2^(n-2)) * 2 +
365 // + b_l + E * 2^(n-e) ] >> 1 =
367 // The shift is computed by dividing the terms by 2 and by cutting off
370 // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
371 // + ((b_m + a_m) % 2^(n-2)) +
372 // + E * 2^(n-(e+1)) =
374 // by the definition in the Theorem e+1 = e'
376 // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
377 // + ((b_m + a_m) % 2^(n-2)) +
380 // Compute Y by applying distributivity first
382 // Y = (B >> 1) + (A >> 1) + E*2^(n-e') =
383 // = (b_h * 2^(n-1) + b_m * 2 + b_l) >> 1 +
384 // + (a_h * 2^(n-1) + a_m * 2) >> 1 +
385 // + E * 2^(n-e) >> 1 =
387 // Again, the shift is computed by dividing the terms by 2 and by cutting
390 // = b_h * 2^(n-2) + b_m +
391 // + a_h * 2^(n-2) + a_m +
392 // + E * 2^(n-(e+1)) =
394 // Again, the sum is built by putting the overflow of [a_m + b+n] into
395 // the term 2^(n-1). But this time there is room for a second bit in the
396 // term 2^(n-2) we add this bit to a new term and denote it o_h in a
399 // = ([b_h + a_h + (b_m + a_m) >> (n-2)] >> 1) * 2^(n-1) +
400 // + ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
401 // + ((b_m + a_m) % 2^(n-2)) +
402 // + E * 2^(n-(e+1)) =
404 // Let o_h = [b_h + a_h + (b_m + a_m) >> (n-2)] >> 1
405 // Further replace e+1 by e'.
408 // + ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
409 // + ((b_m + a_m) % 2^(n-2)) +
412 // Move o_h into the error term and construct E'. To ensure that there is
413 // no 2^x with negative x, this step requires pre(2) (e < n).
415 // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
416 // + ((b_m + a_m) % 2^(n-2)) +
417 // + o_h * 2^(e'-1) * 2^(n-e') + | pre(2), move 2^(e'-1)
418 // | out of the old exponent
420 // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
421 // + ((b_m + a_m) % 2^(n-2)) +
422 // + [o_h * 2^(e'-1) + E] * 2^(n-e') + | move 2^(e'-1) out of
423 // | the old exponent
425 // Let E' = o_h * 2^(e'-1) + E
427 // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
428 // + ((b_m + a_m) % 2^(n-2)) +
431 // Because X and Y are distinct only in there error terms and E' can be
432 // constructed as shown the theorem holds.
435 // For completeness in case of the case e=n it is also required to show that
436 // distributivity can be applied.
438 // In this case Theorem(1) transforms to (the pre-condition on A can also be
441 // Theorem(2): (B + A + E) >> 1 => (B >> 1) + (A >> 1) + E'
443 // A, B, E, E' are two's complement numbers with the same bit
447 // Let (B >> 1) + (A >> 1) = Y
449 // Therefore we need to show that for every X and Y there is an E' which
450 // makes the equation
454 // hold. This is trivially the case for E' = X - Y.
458 // Remark: Distributing lshr with and arbitrary number n can be expressed as
459 // ((((B + A) lshr 1) lshr 1) ... ) {n times}.
460 // This construction induces n additional error bits at the left.
462 if (C.getBitWidth() != A.getBitWidth()) {
463 ErrorMSBs = (unsigned)-1;
470 // Test if the result will be zero
471 unsigned shiftAmt = C.getZExtValue();
472 if (shiftAmt >= C.getBitWidth())
473 return mul(APInt(C.getBitWidth(), 0));
475 // The proof that shiftAmt LSBs are zero for at least one summand is only
476 // possible for the constant number.
478 // If this can be proven add shiftAmt to the error counter
479 // `ErrorMSBs`. Otherwise set all bits as undefined.
480 if (A.countTrailingZeros() < shiftAmt)
481 ErrorMSBs = A.getBitWidth();
483 incErrorMSBs(shiftAmt);
485 // Apply the operation.
486 pushBOperation(LShr, C);
487 A = A.lshr(shiftAmt);
492 /// Apply a sign-extend or truncate operation on the polynomial.
493 Polynomial &sextOrTrunc(unsigned n) {
494 if (n < A.getBitWidth()) {
495 // Truncate: Clearly undefined Bits on the MSB side are removed
497 decErrorMSBs(A.getBitWidth() - n);
499 pushBOperation(Trunc, APInt(sizeof(n) * 8, n));
501 if (n > A.getBitWidth()) {
502 // Extend: Clearly extending first and adding later is different
503 // to adding first and extending later in all extended bits.
504 incErrorMSBs(n - A.getBitWidth());
506 pushBOperation(SExt, APInt(sizeof(n) * 8, n));
512 /// Test if there is a coefficient B.
513 bool isFirstOrder() const { return V != nullptr; }
515 /// Test coefficient B of two Polynomials are equal.
516 bool isCompatibleTo(const Polynomial &o) const {
517 // The polynomial use different bit width.
518 if (A.getBitWidth() != o.A.getBitWidth())
521 // If neither Polynomial has the Coefficient B.
522 if (!isFirstOrder() && !o.isFirstOrder())
525 // The index variable is different.
529 // Check the operations.
530 if (B.size() != o.B.size())
533 auto ob = o.B.begin();
543 /// Subtract two polynomials, return an undefined polynomial if
544 /// subtraction is not possible.
545 Polynomial operator-(const Polynomial &o) const {
546 // Return an undefined polynomial if incompatible.
547 if (!isCompatibleTo(o))
550 // If the polynomials are compatible (meaning they have the same
551 // coefficient on B), B is eliminated. Thus a polynomial solely
552 // containing A is returned
553 return Polynomial(A - o.A, std::max(ErrorMSBs, o.ErrorMSBs));
556 /// Subtract a constant from a polynomial,
557 Polynomial operator-(uint64_t C) const {
558 Polynomial Result(*this);
563 /// Add a constant to a polynomial,
564 Polynomial operator+(uint64_t C) const {
565 Polynomial Result(*this);
570 /// Returns true if it can be proven that two Polynomials are equal.
571 bool isProvenEqualTo(const Polynomial &o) {
572 // Subtract both polynomials and test if it is fully defined and zero.
573 Polynomial r = *this - o;
574 return (r.ErrorMSBs == 0) && (!r.isFirstOrder()) && (r.A.isZero());
577 /// Print the polynomial into a stream.
578 void print(raw_ostream &OS) const {
579 OS << "[{#ErrBits:" << ErrorMSBs << "} ";
584 OS << "(" << *V << ") ";
602 OS << b.second << ") ";
606 OS << "+ " << A << "]";
615 void pushBOperation(const BOps Op, const APInt &C) {
616 if (isFirstOrder()) {
617 B.push_back(std::make_pair(Op, C));
624 static raw_ostream &operator<<(raw_ostream &OS, const Polynomial &S) {
630 /// VectorInfo stores abstract the following information for each vector
633 /// 1) The the memory address loaded into the element as Polynomial
634 /// 2) a set of load instruction necessary to construct the vector,
635 /// 3) a set of all other instructions that are necessary to create the vector and
636 /// 4) a pointer value that can be used as relative base for all elements.
639 VectorInfo(const VectorInfo &c) : VTy(c.VTy) {
641 "Copying VectorInfo is neither implemented nor necessary,");
645 /// Information of a Vector Element
647 /// Offset Polynomial.
650 /// The Load Instruction used to Load the entry. LI is null if the pointer
651 /// of the load instruction does not point on to the entry
654 ElementInfo(Polynomial Offset = Polynomial(), LoadInst *LI = nullptr)
655 : Ofs(Offset), LI(LI) {}
658 /// Basic-block the load instructions are within
659 BasicBlock *BB = nullptr;
661 /// Pointer value of all participation load instructions
664 /// Participating load instructions
665 std::set<LoadInst *> LIs;
667 /// Participating instructions
668 std::set<Instruction *> Is;
670 /// Final shuffle-vector instruction
671 ShuffleVectorInst *SVI = nullptr;
673 /// Information of the offset for each vector element
677 FixedVectorType *const VTy;
679 VectorInfo(FixedVectorType *VTy) : VTy(VTy) {
680 EI = new ElementInfo[VTy->getNumElements()];
683 virtual ~VectorInfo() { delete[] EI; }
685 unsigned getDimension() const { return VTy->getNumElements(); }
687 /// Test if the VectorInfo can be part of an interleaved load with the
688 /// specified factor.
690 /// \param Factor of the interleave
691 /// \param DL Targets Datalayout
693 /// \returns true if this is possible and false if not
694 bool isInterleaved(unsigned Factor, const DataLayout &DL) const {
695 unsigned Size = DL.getTypeAllocSize(VTy->getElementType());
696 for (unsigned i = 1; i < getDimension(); i++) {
697 if (!EI[i].Ofs.isProvenEqualTo(EI[0].Ofs + i * Factor * Size)) {
704 /// Recursively computes the vector information stored in V.
706 /// This function delegates the work to specialized implementations
708 /// \param V Value to operate on
709 /// \param Result Result of the computation
711 /// \returns false if no sensible information can be gathered.
712 static bool compute(Value *V, VectorInfo &Result, const DataLayout &DL) {
713 ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V);
715 return computeFromSVI(SVI, Result, DL);
716 LoadInst *LI = dyn_cast<LoadInst>(V);
718 return computeFromLI(LI, Result, DL);
719 BitCastInst *BCI = dyn_cast<BitCastInst>(V);
721 return computeFromBCI(BCI, Result, DL);
725 /// BitCastInst specialization to compute the vector information.
727 /// \param BCI BitCastInst to operate on
728 /// \param Result Result of the computation
730 /// \returns false if no sensible information can be gathered.
731 static bool computeFromBCI(BitCastInst *BCI, VectorInfo &Result,
732 const DataLayout &DL) {
733 Instruction *Op = dyn_cast<Instruction>(BCI->getOperand(0));
738 FixedVectorType *VTy = dyn_cast<FixedVectorType>(Op->getType());
742 // We can only cast from large to smaller vectors
743 if (Result.VTy->getNumElements() % VTy->getNumElements())
746 unsigned Factor = Result.VTy->getNumElements() / VTy->getNumElements();
747 unsigned NewSize = DL.getTypeAllocSize(Result.VTy->getElementType());
748 unsigned OldSize = DL.getTypeAllocSize(VTy->getElementType());
750 if (NewSize * Factor != OldSize)
754 if (!compute(Op, Old, DL))
757 for (unsigned i = 0; i < Result.VTy->getNumElements(); i += Factor) {
758 for (unsigned j = 0; j < Factor; j++) {
760 ElementInfo(Old.EI[i / Factor].Ofs + j * NewSize,
761 j == 0 ? Old.EI[i / Factor].LI : nullptr);
767 Result.LIs.insert(Old.LIs.begin(), Old.LIs.end());
768 Result.Is.insert(Old.Is.begin(), Old.Is.end());
769 Result.Is.insert(BCI);
770 Result.SVI = nullptr;
775 /// ShuffleVectorInst specialization to compute vector information.
777 /// \param SVI ShuffleVectorInst to operate on
778 /// \param Result Result of the computation
780 /// Compute the left and the right side vector information and merge them by
781 /// applying the shuffle operation. This function also ensures that the left
782 /// and right side have compatible loads. This means that all loads are with
783 /// in the same basic block and are based on the same pointer.
785 /// \returns false if no sensible information can be gathered.
786 static bool computeFromSVI(ShuffleVectorInst *SVI, VectorInfo &Result,
787 const DataLayout &DL) {
788 FixedVectorType *ArgTy =
789 cast<FixedVectorType>(SVI->getOperand(0)->getType());
791 // Compute the left hand vector information.
792 VectorInfo LHS(ArgTy);
793 if (!compute(SVI->getOperand(0), LHS, DL))
796 // Compute the right hand vector information.
797 VectorInfo RHS(ArgTy);
798 if (!compute(SVI->getOperand(1), RHS, DL))
801 // Neither operand produced sensible results?
802 if (!LHS.BB && !RHS.BB)
804 // Only RHS produced sensible results?
809 // Only LHS produced sensible results?
814 // Both operands produced sensible results?
815 else if ((LHS.BB == RHS.BB) && (LHS.PV == RHS.PV)) {
819 // Both operands produced sensible results but they are incompatible.
824 // Merge and apply the operation on the offset information.
826 Result.LIs.insert(LHS.LIs.begin(), LHS.LIs.end());
827 Result.Is.insert(LHS.Is.begin(), LHS.Is.end());
830 Result.LIs.insert(RHS.LIs.begin(), RHS.LIs.end());
831 Result.Is.insert(RHS.Is.begin(), RHS.Is.end());
833 Result.Is.insert(SVI);
837 for (int i : SVI->getShuffleMask()) {
838 assert((i < 2 * (signed)ArgTy->getNumElements()) &&
839 "Invalid ShuffleVectorInst (index out of bounds)");
842 Result.EI[j] = ElementInfo();
843 else if (i < (signed)ArgTy->getNumElements()) {
845 Result.EI[j] = LHS.EI[i];
847 Result.EI[j] = ElementInfo();
850 Result.EI[j] = RHS.EI[i - ArgTy->getNumElements()];
852 Result.EI[j] = ElementInfo();
860 /// LoadInst specialization to compute vector information.
862 /// This function also acts as abort condition to the recursion.
864 /// \param LI LoadInst to operate on
865 /// \param Result Result of the computation
867 /// \returns false if no sensible information can be gathered.
868 static bool computeFromLI(LoadInst *LI, VectorInfo &Result,
869 const DataLayout &DL) {
873 if (LI->isVolatile())
879 // Get the base polynomial
880 computePolynomialFromPointer(*LI->getPointerOperand(), Offset, BasePtr, DL);
882 Result.BB = LI->getParent();
884 Result.LIs.insert(LI);
885 Result.Is.insert(LI);
887 for (unsigned i = 0; i < Result.getDimension(); i++) {
889 ConstantInt::get(Type::getInt32Ty(LI->getContext()), 0),
890 ConstantInt::get(Type::getInt32Ty(LI->getContext()), i),
892 int64_t Ofs = DL.getIndexedOffsetInType(Result.VTy, makeArrayRef(Idx, 2));
893 Result.EI[i] = ElementInfo(Offset + Ofs, i == 0 ? LI : nullptr);
899 /// Recursively compute polynomial of a value.
901 /// \param BO Input binary operation
902 /// \param Result Result polynomial
903 static void computePolynomialBinOp(BinaryOperator &BO, Polynomial &Result) {
904 Value *LHS = BO.getOperand(0);
905 Value *RHS = BO.getOperand(1);
907 // Find the RHS Constant if any
908 ConstantInt *C = dyn_cast<ConstantInt>(RHS);
909 if ((!C) && BO.isCommutative()) {
910 C = dyn_cast<ConstantInt>(LHS);
915 switch (BO.getOpcode()) {
916 case Instruction::Add:
920 computePolynomial(*LHS, Result);
921 Result.add(C->getValue());
924 case Instruction::LShr:
928 computePolynomial(*LHS, Result);
929 Result.lshr(C->getValue());
936 Result = Polynomial(&BO);
939 /// Recursively compute polynomial of a value
941 /// \param V input value
942 /// \param Result result polynomial
943 static void computePolynomial(Value &V, Polynomial &Result) {
944 if (auto *BO = dyn_cast<BinaryOperator>(&V))
945 computePolynomialBinOp(*BO, Result);
947 Result = Polynomial(&V);
950 /// Compute the Polynomial representation of a Pointer type.
952 /// \param Ptr input pointer value
953 /// \param Result result polynomial
954 /// \param BasePtr pointer the polynomial is based on
955 /// \param DL Datalayout of the target machine
956 static void computePolynomialFromPointer(Value &Ptr, Polynomial &Result,
958 const DataLayout &DL) {
959 // Not a pointer type? Return an undefined polynomial
960 PointerType *PtrTy = dyn_cast<PointerType>(Ptr.getType());
962 Result = Polynomial();
966 unsigned PointerBits =
967 DL.getIndexSizeInBits(PtrTy->getPointerAddressSpace());
969 /// Skip pointer casts. Return Zero polynomial otherwise
970 if (isa<CastInst>(&Ptr)) {
971 CastInst &CI = *cast<CastInst>(&Ptr);
972 switch (CI.getOpcode()) {
973 case Instruction::BitCast:
974 computePolynomialFromPointer(*CI.getOperand(0), Result, BasePtr, DL);
978 Polynomial(PointerBits, 0);
982 /// Resolve GetElementPtrInst.
983 else if (isa<GetElementPtrInst>(&Ptr)) {
984 GetElementPtrInst &GEP = *cast<GetElementPtrInst>(&Ptr);
986 APInt BaseOffset(PointerBits, 0);
988 // Check if we can compute the Offset with accumulateConstantOffset
989 if (GEP.accumulateConstantOffset(DL, BaseOffset)) {
990 Result = Polynomial(BaseOffset);
991 BasePtr = GEP.getPointerOperand();
994 // Otherwise we allow that the last index operand of the GEP is
996 unsigned idxOperand, e;
997 SmallVector<Value *, 4> Indices;
998 for (idxOperand = 1, e = GEP.getNumOperands(); idxOperand < e;
1000 ConstantInt *IDX = dyn_cast<ConstantInt>(GEP.getOperand(idxOperand));
1003 Indices.push_back(IDX);
1006 // It must also be the last operand.
1007 if (idxOperand + 1 != e) {
1008 Result = Polynomial();
1013 // Compute the polynomial of the index operand.
1014 computePolynomial(*GEP.getOperand(idxOperand), Result);
1016 // Compute base offset from zero based index, excluding the last
1017 // variable operand.
1019 DL.getIndexedOffsetInType(GEP.getSourceElementType(), Indices);
1021 // Apply the operations of GEP to the polynomial.
1022 unsigned ResultSize = DL.getTypeAllocSize(GEP.getResultElementType());
1023 Result.sextOrTrunc(PointerBits);
1024 Result.mul(APInt(PointerBits, ResultSize));
1025 Result.add(BaseOffset);
1026 BasePtr = GEP.getPointerOperand();
1029 // All other instructions are handled by using the value as base pointer and
1030 // a zero polynomial.
1033 Polynomial(DL.getIndexSizeInBits(PtrTy->getPointerAddressSpace()), 0);
1038 void print(raw_ostream &OS) const {
1044 for (unsigned i = 0; i < getDimension(); i++)
1045 OS << ((i == 0) ? "[" : ", ") << EI[i].Ofs;
1051 } // anonymous namespace
1053 bool InterleavedLoadCombineImpl::findPattern(
1054 std::list<VectorInfo> &Candidates, std::list<VectorInfo> &InterleavedLoad,
1055 unsigned Factor, const DataLayout &DL) {
1056 for (auto C0 = Candidates.begin(), E0 = Candidates.end(); C0 != E0; ++C0) {
1058 // Try to find an interleaved load using the front of Worklist as first line
1059 unsigned Size = DL.getTypeAllocSize(C0->VTy->getElementType());
1061 // List containing iterators pointing to the VectorInfos of the candidates
1062 std::vector<std::list<VectorInfo>::iterator> Res(Factor, Candidates.end());
1064 for (auto C = Candidates.begin(), E = Candidates.end(); C != E; C++) {
1065 if (C->VTy != C0->VTy)
1067 if (C->BB != C0->BB)
1069 if (C->PV != C0->PV)
1072 // Check the current value matches any of factor - 1 remaining lines
1073 for (i = 1; i < Factor; i++) {
1074 if (C->EI[0].Ofs.isProvenEqualTo(C0->EI[0].Ofs + i * Size)) {
1079 for (i = 1; i < Factor; i++) {
1080 if (Res[i] == Candidates.end())
1089 if (Res[0] != Candidates.end()) {
1090 // Move the result into the output
1091 for (unsigned i = 0; i < Factor; i++) {
1092 InterleavedLoad.splice(InterleavedLoad.end(), Candidates, Res[i]);
1102 InterleavedLoadCombineImpl::findFirstLoad(const std::set<LoadInst *> &LIs) {
1103 assert(!LIs.empty() && "No load instructions given.");
1105 // All LIs are within the same BB. Select the first for a reference.
1106 BasicBlock *BB = (*LIs.begin())->getParent();
1107 BasicBlock::iterator FLI = llvm::find_if(
1108 *BB, [&LIs](Instruction &I) -> bool { return is_contained(LIs, &I); });
1109 assert(FLI != BB->end());
1111 return cast<LoadInst>(FLI);
1114 bool InterleavedLoadCombineImpl::combine(std::list<VectorInfo> &InterleavedLoad,
1115 OptimizationRemarkEmitter &ORE) {
1116 LLVM_DEBUG(dbgs() << "Checking interleaved load\n");
1118 // The insertion point is the LoadInst which loads the first values. The
1119 // following tests are used to proof that the combined load can be inserted
1120 // just before InsertionPoint.
1121 LoadInst *InsertionPoint = InterleavedLoad.front().EI[0].LI;
1123 // Test if the offset is computed
1124 if (!InsertionPoint)
1127 std::set<LoadInst *> LIs;
1128 std::set<Instruction *> Is;
1129 std::set<Instruction *> SVIs;
1131 InstructionCost InterleavedCost;
1132 InstructionCost InstructionCost = 0;
1133 const TTI::TargetCostKind CostKind = TTI::TCK_SizeAndLatency;
1135 // Get the interleave factor
1136 unsigned Factor = InterleavedLoad.size();
1138 // Merge all input sets used in analysis
1139 for (auto &VI : InterleavedLoad) {
1140 // Generate a set of all load instructions to be combined
1141 LIs.insert(VI.LIs.begin(), VI.LIs.end());
1143 // Generate a set of all instructions taking part in load
1144 // interleaved. This list excludes the instructions necessary for the
1145 // polynomial construction.
1146 Is.insert(VI.Is.begin(), VI.Is.end());
1148 // Generate the set of the final ShuffleVectorInst.
1149 SVIs.insert(VI.SVI);
1152 // There is nothing to combine.
1156 // Test if all participating instruction will be dead after the
1157 // transformation. If intermediate results are used, no performance gain can
1158 // be expected. Also sum the cost of the Instructions beeing left dead.
1159 for (auto &I : Is) {
1160 // Compute the old cost
1161 InstructionCost += TTI.getInstructionCost(I, CostKind);
1163 // The final SVIs are allowed not to be dead, all uses will be replaced
1164 if (SVIs.find(I) != SVIs.end())
1167 // If there are users outside the set to be eliminated, we abort the
1168 // transformation. No gain can be expected.
1169 for (auto *U : I->users()) {
1170 if (Is.find(dyn_cast<Instruction>(U)) == Is.end())
1175 // We need to have a valid cost in order to proceed.
1176 if (!InstructionCost.isValid())
1179 // We know that all LoadInst are within the same BB. This guarantees that
1180 // either everything or nothing is loaded.
1181 LoadInst *First = findFirstLoad(LIs);
1183 // To be safe that the loads can be combined, iterate over all loads and test
1184 // that the corresponding defining access dominates first LI. This guarantees
1185 // that there are no aliasing stores in between the loads.
1186 auto FMA = MSSA.getMemoryAccess(First);
1187 for (auto LI : LIs) {
1188 auto MADef = MSSA.getMemoryAccess(LI)->getDefiningAccess();
1189 if (!MSSA.dominates(MADef, FMA))
1192 assert(!LIs.empty() && "There are no LoadInst to combine");
1194 // It is necessary that insertion point dominates all final ShuffleVectorInst.
1195 for (auto &VI : InterleavedLoad) {
1196 if (!DT.dominates(InsertionPoint, VI.SVI))
1200 // All checks are done. Add instructions detectable by InterleavedAccessPass
1201 // The old instruction will are left dead.
1202 IRBuilder<> Builder(InsertionPoint);
1203 Type *ETy = InterleavedLoad.front().SVI->getType()->getElementType();
1204 unsigned ElementsPerSVI =
1205 cast<FixedVectorType>(InterleavedLoad.front().SVI->getType())
1207 FixedVectorType *ILTy = FixedVectorType::get(ETy, Factor * ElementsPerSVI);
1209 SmallVector<unsigned, 4> Indices;
1210 for (unsigned i = 0; i < Factor; i++)
1211 Indices.push_back(i);
1212 InterleavedCost = TTI.getInterleavedMemoryOpCost(
1213 Instruction::Load, ILTy, Factor, Indices, InsertionPoint->getAlign(),
1214 InsertionPoint->getPointerAddressSpace(), CostKind);
1216 if (InterleavedCost >= InstructionCost) {
1220 // Create a pointer cast for the wide load.
1221 auto CI = Builder.CreatePointerCast(InsertionPoint->getOperand(0),
1222 ILTy->getPointerTo(),
1223 "interleaved.wide.ptrcast");
1225 // Create the wide load and update the MemorySSA.
1226 auto LI = Builder.CreateAlignedLoad(ILTy, CI, InsertionPoint->getAlign(),
1227 "interleaved.wide.load");
1228 auto MSSAU = MemorySSAUpdater(&MSSA);
1229 MemoryUse *MSSALoad = cast<MemoryUse>(MSSAU.createMemoryAccessBefore(
1230 LI, nullptr, MSSA.getMemoryAccess(InsertionPoint)));
1231 MSSAU.insertUse(MSSALoad);
1233 // Create the final SVIs and replace all uses.
1235 for (auto &VI : InterleavedLoad) {
1236 SmallVector<int, 4> Mask;
1237 for (unsigned j = 0; j < ElementsPerSVI; j++)
1238 Mask.push_back(i + j * Factor);
1240 Builder.SetInsertPoint(VI.SVI);
1241 auto SVI = Builder.CreateShuffleVector(LI, Mask, "interleaved.shuffle");
1242 VI.SVI->replaceAllUsesWith(SVI);
1246 NumInterleavedLoadCombine++;
1248 return OptimizationRemark(DEBUG_TYPE, "Combined Interleaved Load", LI)
1249 << "Load interleaved combined with factor "
1250 << ore::NV("Factor", Factor);
1256 bool InterleavedLoadCombineImpl::run() {
1257 OptimizationRemarkEmitter ORE(&F);
1258 bool changed = false;
1259 unsigned MaxFactor = TLI.getMaxSupportedInterleaveFactor();
1261 auto &DL = F.getParent()->getDataLayout();
1263 // Start with the highest factor to avoid combining and recombining.
1264 for (unsigned Factor = MaxFactor; Factor >= 2; Factor--) {
1265 std::list<VectorInfo> Candidates;
1267 for (BasicBlock &BB : F) {
1268 for (Instruction &I : BB) {
1269 if (auto SVI = dyn_cast<ShuffleVectorInst>(&I)) {
1270 // We don't support scalable vectors in this pass.
1271 if (isa<ScalableVectorType>(SVI->getType()))
1274 Candidates.emplace_back(cast<FixedVectorType>(SVI->getType()));
1276 if (!VectorInfo::computeFromSVI(SVI, Candidates.back(), DL)) {
1277 Candidates.pop_back();
1281 if (!Candidates.back().isInterleaved(Factor, DL)) {
1282 Candidates.pop_back();
1288 std::list<VectorInfo> InterleavedLoad;
1289 while (findPattern(Candidates, InterleavedLoad, Factor, DL)) {
1290 if (combine(InterleavedLoad, ORE)) {
1293 // Remove the first element of the Interleaved Load but put the others
1294 // back on the list and continue searching
1295 Candidates.splice(Candidates.begin(), InterleavedLoad,
1296 std::next(InterleavedLoad.begin()),
1297 InterleavedLoad.end());
1299 InterleavedLoad.clear();
1307 /// This pass combines interleaved loads into a pattern detectable by
1308 /// InterleavedAccessPass.
1309 struct InterleavedLoadCombine : public FunctionPass {
1312 InterleavedLoadCombine() : FunctionPass(ID) {
1313 initializeInterleavedLoadCombinePass(*PassRegistry::getPassRegistry());
1316 StringRef getPassName() const override {
1317 return "Interleaved Load Combine Pass";
1320 bool runOnFunction(Function &F) override {
1321 if (DisableInterleavedLoadCombine)
1324 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
1328 LLVM_DEBUG(dbgs() << "*** " << getPassName() << ": " << F.getName()
1331 return InterleavedLoadCombineImpl(
1332 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1333 getAnalysis<MemorySSAWrapperPass>().getMSSA(),
1334 TPC->getTM<TargetMachine>())
1338 void getAnalysisUsage(AnalysisUsage &AU) const override {
1339 AU.addRequired<MemorySSAWrapperPass>();
1340 AU.addRequired<DominatorTreeWrapperPass>();
1341 FunctionPass::getAnalysisUsage(AU);
1346 } // anonymous namespace
1348 char InterleavedLoadCombine::ID = 0;
1350 INITIALIZE_PASS_BEGIN(
1351 InterleavedLoadCombine, DEBUG_TYPE,
1352 "Combine interleaved loads into wide loads and shufflevector instructions",
1354 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1355 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1356 INITIALIZE_PASS_END(
1357 InterleavedLoadCombine, DEBUG_TYPE,
1358 "Combine interleaved loads into wide loads and shufflevector instructions",
1362 llvm::createInterleavedLoadCombinePass() {
1363 auto P = new InterleavedLoadCombine();