13ca95b02SDimitry Andric //===--------------------- InterleavedAccessPass.cpp ----------------------===//
23dac3a9bSDimitry Andric //
33dac3a9bSDimitry Andric //                     The LLVM Compiler Infrastructure
43dac3a9bSDimitry Andric //
53dac3a9bSDimitry Andric // This file is distributed under the University of Illinois Open Source
63dac3a9bSDimitry Andric // License. See LICENSE.TXT for details.
73dac3a9bSDimitry Andric //
83dac3a9bSDimitry Andric //===----------------------------------------------------------------------===//
93dac3a9bSDimitry Andric //
103dac3a9bSDimitry Andric // This file implements the Interleaved Access pass, which identifies
113ca95b02SDimitry Andric // interleaved memory accesses and transforms them into target specific
123ca95b02SDimitry Andric // intrinsics.
133dac3a9bSDimitry Andric //
143dac3a9bSDimitry Andric // An interleaved load reads data from memory into several vectors, with
153dac3a9bSDimitry Andric // DE-interleaving the data on a factor. An interleaved store writes several
163dac3a9bSDimitry Andric // vectors to memory with RE-interleaving the data on a factor.
173dac3a9bSDimitry Andric //
183ca95b02SDimitry Andric // As interleaved accesses are difficult to identified in CodeGen (mainly
193ca95b02SDimitry Andric // because the VECTOR_SHUFFLE DAG node is quite different from the shufflevector
203ca95b02SDimitry Andric // IR), we identify and transform them to intrinsics in this pass so the
213ca95b02SDimitry Andric // intrinsics can be easily matched into target specific instructions later in
223ca95b02SDimitry Andric // CodeGen.
233dac3a9bSDimitry Andric //
243dac3a9bSDimitry Andric // E.g. An interleaved load (Factor = 2):
253dac3a9bSDimitry Andric //        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
263dac3a9bSDimitry Andric //        %v0 = shuffle <8 x i32> %wide.vec, <8 x i32> undef, <0, 2, 4, 6>
273dac3a9bSDimitry Andric //        %v1 = shuffle <8 x i32> %wide.vec, <8 x i32> undef, <1, 3, 5, 7>
283dac3a9bSDimitry Andric //
293dac3a9bSDimitry Andric // It could be transformed into a ld2 intrinsic in AArch64 backend or a vld2
303dac3a9bSDimitry Andric // intrinsic in ARM backend.
313dac3a9bSDimitry Andric //
32d88c1a5aSDimitry Andric // In X86, this can be further optimized into a set of target
33d88c1a5aSDimitry Andric // specific loads followed by an optimized sequence of shuffles.
34d88c1a5aSDimitry Andric //
353dac3a9bSDimitry Andric // E.g. An interleaved store (Factor = 3):
363dac3a9bSDimitry Andric //        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
373dac3a9bSDimitry Andric //                                    <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
383dac3a9bSDimitry Andric //        store <12 x i32> %i.vec, <12 x i32>* %ptr
393dac3a9bSDimitry Andric //
403dac3a9bSDimitry Andric // It could be transformed into a st3 intrinsic in AArch64 backend or a vst3
413dac3a9bSDimitry Andric // intrinsic in ARM backend.
423dac3a9bSDimitry Andric //
43d88c1a5aSDimitry Andric // Similarly, a set of interleaved stores can be transformed into an optimized
44d88c1a5aSDimitry Andric // sequence of shuffles followed by a set of target specific stores for X86.
453dac3a9bSDimitry Andric //===----------------------------------------------------------------------===//
463dac3a9bSDimitry Andric 
473dac3a9bSDimitry Andric #include "llvm/CodeGen/Passes.h"
48d8866befSDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
493ca95b02SDimitry Andric #include "llvm/IR/Dominators.h"
503dac3a9bSDimitry Andric #include "llvm/IR/InstIterator.h"
513dac3a9bSDimitry Andric #include "llvm/Support/Debug.h"
523dac3a9bSDimitry Andric #include "llvm/Support/MathExtras.h"
533dac3a9bSDimitry Andric #include "llvm/Support/raw_ostream.h"
543dac3a9bSDimitry Andric #include "llvm/Target/TargetLowering.h"
553dac3a9bSDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
563dac3a9bSDimitry Andric 
573dac3a9bSDimitry Andric using namespace llvm;
583dac3a9bSDimitry Andric 
593dac3a9bSDimitry Andric #define DEBUG_TYPE "interleaved-access"
603dac3a9bSDimitry Andric 
613dac3a9bSDimitry Andric static cl::opt<bool> LowerInterleavedAccesses(
623dac3a9bSDimitry Andric     "lower-interleaved-accesses",
633dac3a9bSDimitry Andric     cl::desc("Enable lowering interleaved accesses to intrinsics"),
647d523365SDimitry Andric     cl::init(true), cl::Hidden);
653dac3a9bSDimitry Andric 
663dac3a9bSDimitry Andric namespace {
673dac3a9bSDimitry Andric 
683dac3a9bSDimitry Andric class InterleavedAccess : public FunctionPass {
693dac3a9bSDimitry Andric 
703dac3a9bSDimitry Andric public:
713dac3a9bSDimitry Andric   static char ID;
72d8866befSDimitry Andric   InterleavedAccess() : FunctionPass(ID), DT(nullptr), TLI(nullptr) {
733dac3a9bSDimitry Andric     initializeInterleavedAccessPass(*PassRegistry::getPassRegistry());
743dac3a9bSDimitry Andric   }
753dac3a9bSDimitry Andric 
76d88c1a5aSDimitry Andric   StringRef getPassName() const override { return "Interleaved Access Pass"; }
773dac3a9bSDimitry Andric 
783dac3a9bSDimitry Andric   bool runOnFunction(Function &F) override;
793dac3a9bSDimitry Andric 
803ca95b02SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
813ca95b02SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
823ca95b02SDimitry Andric     AU.addPreserved<DominatorTreeWrapperPass>();
833ca95b02SDimitry Andric   }
843ca95b02SDimitry Andric 
853dac3a9bSDimitry Andric private:
863ca95b02SDimitry Andric   DominatorTree *DT;
873dac3a9bSDimitry Andric   const TargetLowering *TLI;
883dac3a9bSDimitry Andric 
89d88c1a5aSDimitry Andric   /// The maximum supported interleave factor.
90d88c1a5aSDimitry Andric   unsigned MaxFactor;
91d88c1a5aSDimitry Andric 
923dac3a9bSDimitry Andric   /// \brief Transform an interleaved load into target specific intrinsics.
933dac3a9bSDimitry Andric   bool lowerInterleavedLoad(LoadInst *LI,
943dac3a9bSDimitry Andric                             SmallVector<Instruction *, 32> &DeadInsts);
953dac3a9bSDimitry Andric 
963dac3a9bSDimitry Andric   /// \brief Transform an interleaved store into target specific intrinsics.
973dac3a9bSDimitry Andric   bool lowerInterleavedStore(StoreInst *SI,
983dac3a9bSDimitry Andric                              SmallVector<Instruction *, 32> &DeadInsts);
993ca95b02SDimitry Andric 
1003ca95b02SDimitry Andric   /// \brief Returns true if the uses of an interleaved load by the
1013ca95b02SDimitry Andric   /// extractelement instructions in \p Extracts can be replaced by uses of the
1023ca95b02SDimitry Andric   /// shufflevector instructions in \p Shuffles instead. If so, the necessary
1033ca95b02SDimitry Andric   /// replacements are also performed.
1043ca95b02SDimitry Andric   bool tryReplaceExtracts(ArrayRef<ExtractElementInst *> Extracts,
1053ca95b02SDimitry Andric                           ArrayRef<ShuffleVectorInst *> Shuffles);
1063dac3a9bSDimitry Andric };
1073dac3a9bSDimitry Andric } // end anonymous namespace.
1083dac3a9bSDimitry Andric 
1093dac3a9bSDimitry Andric char InterleavedAccess::ID = 0;
110302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(InterleavedAccess, DEBUG_TYPE,
1113ca95b02SDimitry Andric     "Lower interleaved memory accesses to target specific intrinsics", false,
1123ca95b02SDimitry Andric     false)
1133ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
114302affcbSDimitry Andric INITIALIZE_PASS_END(InterleavedAccess, DEBUG_TYPE,
1153ca95b02SDimitry Andric     "Lower interleaved memory accesses to target specific intrinsics", false,
1163ca95b02SDimitry Andric     false)
1173dac3a9bSDimitry Andric 
118d8866befSDimitry Andric FunctionPass *llvm::createInterleavedAccessPass() {
119d8866befSDimitry Andric   return new InterleavedAccess();
1203dac3a9bSDimitry Andric }
1213dac3a9bSDimitry Andric 
1223dac3a9bSDimitry Andric /// \brief Check if the mask is a DE-interleave mask of the given factor
1233dac3a9bSDimitry Andric /// \p Factor like:
1243dac3a9bSDimitry Andric ///     <Index, Index+Factor, ..., Index+(NumElts-1)*Factor>
1253dac3a9bSDimitry Andric static bool isDeInterleaveMaskOfFactor(ArrayRef<int> Mask, unsigned Factor,
1263dac3a9bSDimitry Andric                                        unsigned &Index) {
1273dac3a9bSDimitry Andric   // Check all potential start indices from 0 to (Factor - 1).
1283dac3a9bSDimitry Andric   for (Index = 0; Index < Factor; Index++) {
1293dac3a9bSDimitry Andric     unsigned i = 0;
1303dac3a9bSDimitry Andric 
1313dac3a9bSDimitry Andric     // Check that elements are in ascending order by Factor. Ignore undef
1323dac3a9bSDimitry Andric     // elements.
1333dac3a9bSDimitry Andric     for (; i < Mask.size(); i++)
1343dac3a9bSDimitry Andric       if (Mask[i] >= 0 && static_cast<unsigned>(Mask[i]) != Index + i * Factor)
1353dac3a9bSDimitry Andric         break;
1363dac3a9bSDimitry Andric 
1373dac3a9bSDimitry Andric     if (i == Mask.size())
1383dac3a9bSDimitry Andric       return true;
1393dac3a9bSDimitry Andric   }
1403dac3a9bSDimitry Andric 
1413dac3a9bSDimitry Andric   return false;
1423dac3a9bSDimitry Andric }
1433dac3a9bSDimitry Andric 
1443dac3a9bSDimitry Andric /// \brief Check if the mask is a DE-interleave mask for an interleaved load.
1453dac3a9bSDimitry Andric ///
1463dac3a9bSDimitry Andric /// E.g. DE-interleave masks (Factor = 2) could be:
1473dac3a9bSDimitry Andric ///     <0, 2, 4, 6>    (mask of index 0 to extract even elements)
1483dac3a9bSDimitry Andric ///     <1, 3, 5, 7>    (mask of index 1 to extract odd elements)
1493dac3a9bSDimitry Andric static bool isDeInterleaveMask(ArrayRef<int> Mask, unsigned &Factor,
150d88c1a5aSDimitry Andric                                unsigned &Index, unsigned MaxFactor) {
1513dac3a9bSDimitry Andric   if (Mask.size() < 2)
1523dac3a9bSDimitry Andric     return false;
1533dac3a9bSDimitry Andric 
1543dac3a9bSDimitry Andric   // Check potential Factors.
1553dac3a9bSDimitry Andric   for (Factor = 2; Factor <= MaxFactor; Factor++)
1563dac3a9bSDimitry Andric     if (isDeInterleaveMaskOfFactor(Mask, Factor, Index))
1573dac3a9bSDimitry Andric       return true;
1583dac3a9bSDimitry Andric 
1593dac3a9bSDimitry Andric   return false;
1603dac3a9bSDimitry Andric }
1613dac3a9bSDimitry Andric 
162d88c1a5aSDimitry Andric /// \brief Check if the mask can be used in an interleaved store.
163d88c1a5aSDimitry Andric //
164d88c1a5aSDimitry Andric /// It checks for a more general pattern than the RE-interleave mask.
165d88c1a5aSDimitry Andric /// I.e. <x, y, ... z, x+1, y+1, ...z+1, x+2, y+2, ...z+2, ...>
166d88c1a5aSDimitry Andric /// E.g. For a Factor of 2 (LaneLen=4): <4, 32, 5, 33, 6, 34, 7, 35>
167d88c1a5aSDimitry Andric /// E.g. For a Factor of 3 (LaneLen=4): <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
168d88c1a5aSDimitry Andric /// E.g. For a Factor of 4 (LaneLen=2): <8, 2, 12, 4, 9, 3, 13, 5>
1693dac3a9bSDimitry Andric ///
170d88c1a5aSDimitry Andric /// The particular case of an RE-interleave mask is:
171d88c1a5aSDimitry Andric /// I.e. <0, LaneLen, ... , LaneLen*(Factor - 1), 1, LaneLen + 1, ...>
172d88c1a5aSDimitry Andric /// E.g. For a Factor of 2 (LaneLen=4): <0, 4, 1, 5, 2, 6, 3, 7>
173d88c1a5aSDimitry Andric static bool isReInterleaveMask(ArrayRef<int> Mask, unsigned &Factor,
174077e1117SDimitry Andric                                unsigned MaxFactor, unsigned OpNumElts) {
1753dac3a9bSDimitry Andric   unsigned NumElts = Mask.size();
1763dac3a9bSDimitry Andric   if (NumElts < 4)
1773dac3a9bSDimitry Andric     return false;
1783dac3a9bSDimitry Andric 
1793dac3a9bSDimitry Andric   // Check potential Factors.
1803dac3a9bSDimitry Andric   for (Factor = 2; Factor <= MaxFactor; Factor++) {
1813dac3a9bSDimitry Andric     if (NumElts % Factor)
1823dac3a9bSDimitry Andric       continue;
1833dac3a9bSDimitry Andric 
184d88c1a5aSDimitry Andric     unsigned LaneLen = NumElts / Factor;
185d88c1a5aSDimitry Andric     if (!isPowerOf2_32(LaneLen))
1863dac3a9bSDimitry Andric       continue;
1873dac3a9bSDimitry Andric 
188d88c1a5aSDimitry Andric     // Check whether each element matches the general interleaved rule.
189d88c1a5aSDimitry Andric     // Ignore undef elements, as long as the defined elements match the rule.
190d88c1a5aSDimitry Andric     // Outer loop processes all factors (x, y, z in the above example)
191d88c1a5aSDimitry Andric     unsigned I = 0, J;
192d88c1a5aSDimitry Andric     for (; I < Factor; I++) {
193d88c1a5aSDimitry Andric       unsigned SavedLaneValue;
194d88c1a5aSDimitry Andric       unsigned SavedNoUndefs = 0;
195d88c1a5aSDimitry Andric 
196d88c1a5aSDimitry Andric       // Inner loop processes consecutive accesses (x, x+1... in the example)
197d88c1a5aSDimitry Andric       for (J = 0; J < LaneLen - 1; J++) {
198d88c1a5aSDimitry Andric         // Lane computes x's position in the Mask
199d88c1a5aSDimitry Andric         unsigned Lane = J * Factor + I;
200d88c1a5aSDimitry Andric         unsigned NextLane = Lane + Factor;
201d88c1a5aSDimitry Andric         int LaneValue = Mask[Lane];
202d88c1a5aSDimitry Andric         int NextLaneValue = Mask[NextLane];
203d88c1a5aSDimitry Andric 
204d88c1a5aSDimitry Andric         // If both are defined, values must be sequential
205d88c1a5aSDimitry Andric         if (LaneValue >= 0 && NextLaneValue >= 0 &&
206d88c1a5aSDimitry Andric             LaneValue + 1 != NextLaneValue)
2073dac3a9bSDimitry Andric           break;
2083dac3a9bSDimitry Andric 
209d88c1a5aSDimitry Andric         // If the next value is undef, save the current one as reference
210d88c1a5aSDimitry Andric         if (LaneValue >= 0 && NextLaneValue < 0) {
211d88c1a5aSDimitry Andric           SavedLaneValue = LaneValue;
212d88c1a5aSDimitry Andric           SavedNoUndefs = 1;
213d88c1a5aSDimitry Andric         }
214d88c1a5aSDimitry Andric 
215d88c1a5aSDimitry Andric         // Undefs are allowed, but defined elements must still be consecutive:
216d88c1a5aSDimitry Andric         // i.e.: x,..., undef,..., x + 2,..., undef,..., undef,..., x + 5, ....
217d88c1a5aSDimitry Andric         // Verify this by storing the last non-undef followed by an undef
218d88c1a5aSDimitry Andric         // Check that following non-undef masks are incremented with the
219d88c1a5aSDimitry Andric         // corresponding distance.
220d88c1a5aSDimitry Andric         if (SavedNoUndefs > 0 && LaneValue < 0) {
221d88c1a5aSDimitry Andric           SavedNoUndefs++;
222d88c1a5aSDimitry Andric           if (NextLaneValue >= 0 &&
223d88c1a5aSDimitry Andric               SavedLaneValue + SavedNoUndefs != (unsigned)NextLaneValue)
224d88c1a5aSDimitry Andric             break;
225d88c1a5aSDimitry Andric         }
226d88c1a5aSDimitry Andric       }
227d88c1a5aSDimitry Andric 
228d88c1a5aSDimitry Andric       if (J < LaneLen - 1)
229d88c1a5aSDimitry Andric         break;
230d88c1a5aSDimitry Andric 
231d88c1a5aSDimitry Andric       int StartMask = 0;
232d88c1a5aSDimitry Andric       if (Mask[I] >= 0) {
233d88c1a5aSDimitry Andric         // Check that the start of the I range (J=0) is greater than 0
234d88c1a5aSDimitry Andric         StartMask = Mask[I];
235d88c1a5aSDimitry Andric       } else if (Mask[(LaneLen - 1) * Factor + I] >= 0) {
236d88c1a5aSDimitry Andric         // StartMask defined by the last value in lane
237d88c1a5aSDimitry Andric         StartMask = Mask[(LaneLen - 1) * Factor + I] - J;
238d88c1a5aSDimitry Andric       } else if (SavedNoUndefs > 0) {
239d88c1a5aSDimitry Andric         // StartMask defined by some non-zero value in the j loop
240d88c1a5aSDimitry Andric         StartMask = SavedLaneValue - (LaneLen - 1 - SavedNoUndefs);
241d88c1a5aSDimitry Andric       }
242d88c1a5aSDimitry Andric       // else StartMask remains set to 0, i.e. all elements are undefs
243d88c1a5aSDimitry Andric 
244d88c1a5aSDimitry Andric       if (StartMask < 0)
245d88c1a5aSDimitry Andric         break;
246077e1117SDimitry Andric       // We must stay within the vectors; This case can happen with undefs.
247077e1117SDimitry Andric       if (StartMask + LaneLen > OpNumElts*2)
248077e1117SDimitry Andric         break;
249d88c1a5aSDimitry Andric     }
250d88c1a5aSDimitry Andric 
251d88c1a5aSDimitry Andric     // Found an interleaved mask of current factor.
252d88c1a5aSDimitry Andric     if (I == Factor)
2533dac3a9bSDimitry Andric       return true;
2543dac3a9bSDimitry Andric   }
2553dac3a9bSDimitry Andric 
2563dac3a9bSDimitry Andric   return false;
2573dac3a9bSDimitry Andric }
2583dac3a9bSDimitry Andric 
2593dac3a9bSDimitry Andric bool InterleavedAccess::lowerInterleavedLoad(
2603dac3a9bSDimitry Andric     LoadInst *LI, SmallVector<Instruction *, 32> &DeadInsts) {
2613dac3a9bSDimitry Andric   if (!LI->isSimple())
2623dac3a9bSDimitry Andric     return false;
2633dac3a9bSDimitry Andric 
2643dac3a9bSDimitry Andric   SmallVector<ShuffleVectorInst *, 4> Shuffles;
2653ca95b02SDimitry Andric   SmallVector<ExtractElementInst *, 4> Extracts;
2663dac3a9bSDimitry Andric 
2673ca95b02SDimitry Andric   // Check if all users of this load are shufflevectors. If we encounter any
2683ca95b02SDimitry Andric   // users that are extractelement instructions, we save them to later check if
2693ca95b02SDimitry Andric   // they can be modifed to extract from one of the shufflevectors instead of
2703ca95b02SDimitry Andric   // the load.
2713dac3a9bSDimitry Andric   for (auto UI = LI->user_begin(), E = LI->user_end(); UI != E; UI++) {
2723ca95b02SDimitry Andric     auto *Extract = dyn_cast<ExtractElementInst>(*UI);
2733ca95b02SDimitry Andric     if (Extract && isa<ConstantInt>(Extract->getIndexOperand())) {
2743ca95b02SDimitry Andric       Extracts.push_back(Extract);
2753ca95b02SDimitry Andric       continue;
2763ca95b02SDimitry Andric     }
2773dac3a9bSDimitry Andric     ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(*UI);
2783dac3a9bSDimitry Andric     if (!SVI || !isa<UndefValue>(SVI->getOperand(1)))
2793dac3a9bSDimitry Andric       return false;
2803dac3a9bSDimitry Andric 
2813dac3a9bSDimitry Andric     Shuffles.push_back(SVI);
2823dac3a9bSDimitry Andric   }
2833dac3a9bSDimitry Andric 
2843dac3a9bSDimitry Andric   if (Shuffles.empty())
2853dac3a9bSDimitry Andric     return false;
2863dac3a9bSDimitry Andric 
2873dac3a9bSDimitry Andric   unsigned Factor, Index;
2883dac3a9bSDimitry Andric 
2893dac3a9bSDimitry Andric   // Check if the first shufflevector is DE-interleave shuffle.
290d88c1a5aSDimitry Andric   if (!isDeInterleaveMask(Shuffles[0]->getShuffleMask(), Factor, Index,
291d88c1a5aSDimitry Andric                           MaxFactor))
2923dac3a9bSDimitry Andric     return false;
2933dac3a9bSDimitry Andric 
2943dac3a9bSDimitry Andric   // Holds the corresponding index for each DE-interleave shuffle.
2953dac3a9bSDimitry Andric   SmallVector<unsigned, 4> Indices;
2963dac3a9bSDimitry Andric   Indices.push_back(Index);
2973dac3a9bSDimitry Andric 
2983dac3a9bSDimitry Andric   Type *VecTy = Shuffles[0]->getType();
2993dac3a9bSDimitry Andric 
3003dac3a9bSDimitry Andric   // Check if other shufflevectors are also DE-interleaved of the same type
3013dac3a9bSDimitry Andric   // and factor as the first shufflevector.
3023dac3a9bSDimitry Andric   for (unsigned i = 1; i < Shuffles.size(); i++) {
3033dac3a9bSDimitry Andric     if (Shuffles[i]->getType() != VecTy)
3043dac3a9bSDimitry Andric       return false;
3053dac3a9bSDimitry Andric 
3063dac3a9bSDimitry Andric     if (!isDeInterleaveMaskOfFactor(Shuffles[i]->getShuffleMask(), Factor,
3073dac3a9bSDimitry Andric                                     Index))
3083dac3a9bSDimitry Andric       return false;
3093dac3a9bSDimitry Andric 
3103dac3a9bSDimitry Andric     Indices.push_back(Index);
3113dac3a9bSDimitry Andric   }
3123dac3a9bSDimitry Andric 
3133ca95b02SDimitry Andric   // Try and modify users of the load that are extractelement instructions to
3143ca95b02SDimitry Andric   // use the shufflevector instructions instead of the load.
3153ca95b02SDimitry Andric   if (!tryReplaceExtracts(Extracts, Shuffles))
3163ca95b02SDimitry Andric     return false;
3173ca95b02SDimitry Andric 
3183dac3a9bSDimitry Andric   DEBUG(dbgs() << "IA: Found an interleaved load: " << *LI << "\n");
3193dac3a9bSDimitry Andric 
3203dac3a9bSDimitry Andric   // Try to create target specific intrinsics to replace the load and shuffles.
3213dac3a9bSDimitry Andric   if (!TLI->lowerInterleavedLoad(LI, Shuffles, Indices, Factor))
3223dac3a9bSDimitry Andric     return false;
3233dac3a9bSDimitry Andric 
3243dac3a9bSDimitry Andric   for (auto SVI : Shuffles)
3253dac3a9bSDimitry Andric     DeadInsts.push_back(SVI);
3263dac3a9bSDimitry Andric 
3273dac3a9bSDimitry Andric   DeadInsts.push_back(LI);
3283dac3a9bSDimitry Andric   return true;
3293dac3a9bSDimitry Andric }
3303dac3a9bSDimitry Andric 
3313ca95b02SDimitry Andric bool InterleavedAccess::tryReplaceExtracts(
3323ca95b02SDimitry Andric     ArrayRef<ExtractElementInst *> Extracts,
3333ca95b02SDimitry Andric     ArrayRef<ShuffleVectorInst *> Shuffles) {
3343ca95b02SDimitry Andric 
3353ca95b02SDimitry Andric   // If there aren't any extractelement instructions to modify, there's nothing
3363ca95b02SDimitry Andric   // to do.
3373ca95b02SDimitry Andric   if (Extracts.empty())
3383ca95b02SDimitry Andric     return true;
3393ca95b02SDimitry Andric 
3403ca95b02SDimitry Andric   // Maps extractelement instructions to vector-index pairs. The extractlement
3413ca95b02SDimitry Andric   // instructions will be modified to use the new vector and index operands.
3423ca95b02SDimitry Andric   DenseMap<ExtractElementInst *, std::pair<Value *, int>> ReplacementMap;
3433ca95b02SDimitry Andric 
3443ca95b02SDimitry Andric   for (auto *Extract : Extracts) {
3453ca95b02SDimitry Andric 
3463ca95b02SDimitry Andric     // The vector index that is extracted.
3473ca95b02SDimitry Andric     auto *IndexOperand = cast<ConstantInt>(Extract->getIndexOperand());
3483ca95b02SDimitry Andric     auto Index = IndexOperand->getSExtValue();
3493ca95b02SDimitry Andric 
3503ca95b02SDimitry Andric     // Look for a suitable shufflevector instruction. The goal is to modify the
3513ca95b02SDimitry Andric     // extractelement instruction (which uses an interleaved load) to use one
3523ca95b02SDimitry Andric     // of the shufflevector instructions instead of the load.
3533ca95b02SDimitry Andric     for (auto *Shuffle : Shuffles) {
3543ca95b02SDimitry Andric 
3553ca95b02SDimitry Andric       // If the shufflevector instruction doesn't dominate the extract, we
3563ca95b02SDimitry Andric       // can't create a use of it.
3573ca95b02SDimitry Andric       if (!DT->dominates(Shuffle, Extract))
3583ca95b02SDimitry Andric         continue;
3593ca95b02SDimitry Andric 
3603ca95b02SDimitry Andric       // Inspect the indices of the shufflevector instruction. If the shuffle
3613ca95b02SDimitry Andric       // selects the same index that is extracted, we can modify the
3623ca95b02SDimitry Andric       // extractelement instruction.
3633ca95b02SDimitry Andric       SmallVector<int, 4> Indices;
3643ca95b02SDimitry Andric       Shuffle->getShuffleMask(Indices);
3653ca95b02SDimitry Andric       for (unsigned I = 0; I < Indices.size(); ++I)
3663ca95b02SDimitry Andric         if (Indices[I] == Index) {
3673ca95b02SDimitry Andric           assert(Extract->getOperand(0) == Shuffle->getOperand(0) &&
3683ca95b02SDimitry Andric                  "Vector operations do not match");
3693ca95b02SDimitry Andric           ReplacementMap[Extract] = std::make_pair(Shuffle, I);
3703ca95b02SDimitry Andric           break;
3713ca95b02SDimitry Andric         }
3723ca95b02SDimitry Andric 
3733ca95b02SDimitry Andric       // If we found a suitable shufflevector instruction, stop looking.
3743ca95b02SDimitry Andric       if (ReplacementMap.count(Extract))
3753ca95b02SDimitry Andric         break;
3763ca95b02SDimitry Andric     }
3773ca95b02SDimitry Andric 
3783ca95b02SDimitry Andric     // If we did not find a suitable shufflevector instruction, the
3793ca95b02SDimitry Andric     // extractelement instruction cannot be modified, so we must give up.
3803ca95b02SDimitry Andric     if (!ReplacementMap.count(Extract))
3813ca95b02SDimitry Andric       return false;
3823ca95b02SDimitry Andric   }
3833ca95b02SDimitry Andric 
3843ca95b02SDimitry Andric   // Finally, perform the replacements.
3853ca95b02SDimitry Andric   IRBuilder<> Builder(Extracts[0]->getContext());
3863ca95b02SDimitry Andric   for (auto &Replacement : ReplacementMap) {
3873ca95b02SDimitry Andric     auto *Extract = Replacement.first;
3883ca95b02SDimitry Andric     auto *Vector = Replacement.second.first;
3893ca95b02SDimitry Andric     auto Index = Replacement.second.second;
3903ca95b02SDimitry Andric     Builder.SetInsertPoint(Extract);
3913ca95b02SDimitry Andric     Extract->replaceAllUsesWith(Builder.CreateExtractElement(Vector, Index));
3923ca95b02SDimitry Andric     Extract->eraseFromParent();
3933ca95b02SDimitry Andric   }
3943ca95b02SDimitry Andric 
3953ca95b02SDimitry Andric   return true;
3963ca95b02SDimitry Andric }
3973ca95b02SDimitry Andric 
3983dac3a9bSDimitry Andric bool InterleavedAccess::lowerInterleavedStore(
3993dac3a9bSDimitry Andric     StoreInst *SI, SmallVector<Instruction *, 32> &DeadInsts) {
4003dac3a9bSDimitry Andric   if (!SI->isSimple())
4013dac3a9bSDimitry Andric     return false;
4023dac3a9bSDimitry Andric 
4033dac3a9bSDimitry Andric   ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SI->getValueOperand());
4043dac3a9bSDimitry Andric   if (!SVI || !SVI->hasOneUse())
4053dac3a9bSDimitry Andric     return false;
4063dac3a9bSDimitry Andric 
4073dac3a9bSDimitry Andric   // Check if the shufflevector is RE-interleave shuffle.
4083dac3a9bSDimitry Andric   unsigned Factor;
409077e1117SDimitry Andric   unsigned OpNumElts = SVI->getOperand(0)->getType()->getVectorNumElements();
410077e1117SDimitry Andric   if (!isReInterleaveMask(SVI->getShuffleMask(), Factor, MaxFactor, OpNumElts))
4113dac3a9bSDimitry Andric     return false;
4123dac3a9bSDimitry Andric 
4133dac3a9bSDimitry Andric   DEBUG(dbgs() << "IA: Found an interleaved store: " << *SI << "\n");
4143dac3a9bSDimitry Andric 
4153dac3a9bSDimitry Andric   // Try to create target specific intrinsics to replace the store and shuffle.
4163dac3a9bSDimitry Andric   if (!TLI->lowerInterleavedStore(SI, SVI, Factor))
4173dac3a9bSDimitry Andric     return false;
4183dac3a9bSDimitry Andric 
4193dac3a9bSDimitry Andric   // Already have a new target specific interleaved store. Erase the old store.
4203dac3a9bSDimitry Andric   DeadInsts.push_back(SI);
4213dac3a9bSDimitry Andric   DeadInsts.push_back(SVI);
4223dac3a9bSDimitry Andric   return true;
4233dac3a9bSDimitry Andric }
4243dac3a9bSDimitry Andric 
4253dac3a9bSDimitry Andric bool InterleavedAccess::runOnFunction(Function &F) {
426d8866befSDimitry Andric   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
427d8866befSDimitry Andric   if (!TPC || !LowerInterleavedAccesses)
4283dac3a9bSDimitry Andric     return false;
4293dac3a9bSDimitry Andric 
4303dac3a9bSDimitry Andric   DEBUG(dbgs() << "*** " << getPassName() << ": " << F.getName() << "\n");
4313dac3a9bSDimitry Andric 
4323ca95b02SDimitry Andric   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
433d8866befSDimitry Andric   auto &TM = TPC->getTM<TargetMachine>();
434d8866befSDimitry Andric   TLI = TM.getSubtargetImpl(F)->getTargetLowering();
4353dac3a9bSDimitry Andric   MaxFactor = TLI->getMaxSupportedInterleaveFactor();
4363dac3a9bSDimitry Andric 
4373dac3a9bSDimitry Andric   // Holds dead instructions that will be erased later.
4383dac3a9bSDimitry Andric   SmallVector<Instruction *, 32> DeadInsts;
4393dac3a9bSDimitry Andric   bool Changed = false;
4403dac3a9bSDimitry Andric 
4417d523365SDimitry Andric   for (auto &I : instructions(F)) {
4423dac3a9bSDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(&I))
4433dac3a9bSDimitry Andric       Changed |= lowerInterleavedLoad(LI, DeadInsts);
4443dac3a9bSDimitry Andric 
4453dac3a9bSDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(&I))
4463dac3a9bSDimitry Andric       Changed |= lowerInterleavedStore(SI, DeadInsts);
4473dac3a9bSDimitry Andric   }
4483dac3a9bSDimitry Andric 
4493dac3a9bSDimitry Andric   for (auto I : DeadInsts)
4503dac3a9bSDimitry Andric     I->eraseFromParent();
4513dac3a9bSDimitry Andric 
4523dac3a9bSDimitry Andric   return Changed;
4533dac3a9bSDimitry Andric }
454