13dac3a9bSDimitry Andric //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
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 defines vectorizer utilities.
113dac3a9bSDimitry Andric //
123dac3a9bSDimitry Andric //===----------------------------------------------------------------------===//
133dac3a9bSDimitry Andric 
14db17bf38SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
157d523365SDimitry Andric #include "llvm/ADT/EquivalenceClasses.h"
167d523365SDimitry Andric #include "llvm/Analysis/DemandedBits.h"
17875ed548SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
18*b5893f02SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
19875ed548SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
20db17bf38SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
217d523365SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
223ca95b02SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
23db17bf38SDimitry Andric #include "llvm/IR/Constants.h"
24875ed548SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
25db17bf38SDimitry Andric #include "llvm/IR/IRBuilder.h"
26875ed548SDimitry Andric #include "llvm/IR/PatternMatch.h"
27875ed548SDimitry Andric #include "llvm/IR/Value.h"
287d523365SDimitry Andric 
29*b5893f02SDimitry Andric #define DEBUG_TYPE "vectorutils"
30*b5893f02SDimitry Andric 
317d523365SDimitry Andric using namespace llvm;
327d523365SDimitry Andric using namespace llvm::PatternMatch;
333dac3a9bSDimitry Andric 
34*b5893f02SDimitry Andric /// Maximum factor for an interleaved memory access.
35*b5893f02SDimitry Andric static cl::opt<unsigned> MaxInterleaveGroupFactor(
36*b5893f02SDimitry Andric     "max-interleave-group-factor", cl::Hidden,
37*b5893f02SDimitry Andric     cl::desc("Maximum factor for an interleaved access group (default = 8)"),
38*b5893f02SDimitry Andric     cl::init(8));
39*b5893f02SDimitry Andric 
40*b5893f02SDimitry Andric /// Return true if all of the intrinsic's arguments and return type are scalars
41*b5893f02SDimitry Andric /// for the scalar form of the intrinsic and vectors for the vector form of the
42*b5893f02SDimitry Andric /// intrinsic.
isTriviallyVectorizable(Intrinsic::ID ID)433dac3a9bSDimitry Andric bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
443dac3a9bSDimitry Andric   switch (ID) {
45*b5893f02SDimitry Andric   case Intrinsic::bswap: // Begin integer bit-manipulation.
46*b5893f02SDimitry Andric   case Intrinsic::bitreverse:
47*b5893f02SDimitry Andric   case Intrinsic::ctpop:
48*b5893f02SDimitry Andric   case Intrinsic::ctlz:
49*b5893f02SDimitry Andric   case Intrinsic::cttz:
50*b5893f02SDimitry Andric   case Intrinsic::fshl:
51*b5893f02SDimitry Andric   case Intrinsic::fshr:
52*b5893f02SDimitry Andric   case Intrinsic::sqrt: // Begin floating-point.
533dac3a9bSDimitry Andric   case Intrinsic::sin:
543dac3a9bSDimitry Andric   case Intrinsic::cos:
553dac3a9bSDimitry Andric   case Intrinsic::exp:
563dac3a9bSDimitry Andric   case Intrinsic::exp2:
573dac3a9bSDimitry Andric   case Intrinsic::log:
583dac3a9bSDimitry Andric   case Intrinsic::log10:
593dac3a9bSDimitry Andric   case Intrinsic::log2:
603dac3a9bSDimitry Andric   case Intrinsic::fabs:
613dac3a9bSDimitry Andric   case Intrinsic::minnum:
623dac3a9bSDimitry Andric   case Intrinsic::maxnum:
63*b5893f02SDimitry Andric   case Intrinsic::minimum:
64*b5893f02SDimitry Andric   case Intrinsic::maximum:
653dac3a9bSDimitry Andric   case Intrinsic::copysign:
663dac3a9bSDimitry Andric   case Intrinsic::floor:
673dac3a9bSDimitry Andric   case Intrinsic::ceil:
683dac3a9bSDimitry Andric   case Intrinsic::trunc:
693dac3a9bSDimitry Andric   case Intrinsic::rint:
703dac3a9bSDimitry Andric   case Intrinsic::nearbyint:
713dac3a9bSDimitry Andric   case Intrinsic::round:
723dac3a9bSDimitry Andric   case Intrinsic::pow:
733dac3a9bSDimitry Andric   case Intrinsic::fma:
743dac3a9bSDimitry Andric   case Intrinsic::fmuladd:
753dac3a9bSDimitry Andric   case Intrinsic::powi:
76*b5893f02SDimitry Andric   case Intrinsic::canonicalize:
77*b5893f02SDimitry Andric   case Intrinsic::sadd_sat:
78*b5893f02SDimitry Andric   case Intrinsic::ssub_sat:
79*b5893f02SDimitry Andric   case Intrinsic::uadd_sat:
80*b5893f02SDimitry Andric   case Intrinsic::usub_sat:
813dac3a9bSDimitry Andric     return true;
823dac3a9bSDimitry Andric   default:
833dac3a9bSDimitry Andric     return false;
843dac3a9bSDimitry Andric   }
853dac3a9bSDimitry Andric }
863dac3a9bSDimitry Andric 
874ba319b5SDimitry Andric /// Identifies if the intrinsic has a scalar operand. It check for
883dac3a9bSDimitry Andric /// ctlz,cttz and powi special intrinsics whose argument is scalar.
hasVectorInstrinsicScalarOpd(Intrinsic::ID ID,unsigned ScalarOpdIdx)893dac3a9bSDimitry Andric bool llvm::hasVectorInstrinsicScalarOpd(Intrinsic::ID ID,
903dac3a9bSDimitry Andric                                         unsigned ScalarOpdIdx) {
913dac3a9bSDimitry Andric   switch (ID) {
923dac3a9bSDimitry Andric   case Intrinsic::ctlz:
933dac3a9bSDimitry Andric   case Intrinsic::cttz:
943dac3a9bSDimitry Andric   case Intrinsic::powi:
953dac3a9bSDimitry Andric     return (ScalarOpdIdx == 1);
963dac3a9bSDimitry Andric   default:
973dac3a9bSDimitry Andric     return false;
983dac3a9bSDimitry Andric   }
993dac3a9bSDimitry Andric }
1003dac3a9bSDimitry Andric 
1014ba319b5SDimitry Andric /// Returns intrinsic ID for call.
1023dac3a9bSDimitry Andric /// For the input call instruction it finds mapping intrinsic and returns
1033dac3a9bSDimitry Andric /// its ID, in case it does not found it return not_intrinsic.
getVectorIntrinsicIDForCall(const CallInst * CI,const TargetLibraryInfo * TLI)1043ca95b02SDimitry Andric Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI,
1053dac3a9bSDimitry Andric                                                 const TargetLibraryInfo *TLI) {
1063ca95b02SDimitry Andric   Intrinsic::ID ID = getIntrinsicForCallSite(CI, TLI);
1073ca95b02SDimitry Andric   if (ID == Intrinsic::not_intrinsic)
1083ca95b02SDimitry Andric     return Intrinsic::not_intrinsic;
1093ca95b02SDimitry Andric 
1103dac3a9bSDimitry Andric   if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
1112cab237bSDimitry Andric       ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
1122cab237bSDimitry Andric       ID == Intrinsic::sideeffect)
1133dac3a9bSDimitry Andric     return ID;
1143dac3a9bSDimitry Andric   return Intrinsic::not_intrinsic;
1153dac3a9bSDimitry Andric }
1163dac3a9bSDimitry Andric 
1174ba319b5SDimitry Andric /// Find the operand of the GEP that should be checked for consecutive
118875ed548SDimitry Andric /// stores. This ignores trailing indices that have no effect on the final
119875ed548SDimitry Andric /// pointer.
getGEPInductionOperand(const GetElementPtrInst * Gep)120875ed548SDimitry Andric unsigned llvm::getGEPInductionOperand(const GetElementPtrInst *Gep) {
121875ed548SDimitry Andric   const DataLayout &DL = Gep->getModule()->getDataLayout();
122875ed548SDimitry Andric   unsigned LastOperand = Gep->getNumOperands() - 1;
1233ca95b02SDimitry Andric   unsigned GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
124875ed548SDimitry Andric 
125875ed548SDimitry Andric   // Walk backwards and try to peel off zeros.
1267d523365SDimitry Andric   while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
127875ed548SDimitry Andric     // Find the type we're currently indexing into.
128875ed548SDimitry Andric     gep_type_iterator GEPTI = gep_type_begin(Gep);
129d88c1a5aSDimitry Andric     std::advance(GEPTI, LastOperand - 2);
130875ed548SDimitry Andric 
131875ed548SDimitry Andric     // If it's a type with the same allocation size as the result of the GEP we
132875ed548SDimitry Andric     // can peel off the zero index.
133d88c1a5aSDimitry Andric     if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize)
134875ed548SDimitry Andric       break;
135875ed548SDimitry Andric     --LastOperand;
136875ed548SDimitry Andric   }
137875ed548SDimitry Andric 
138875ed548SDimitry Andric   return LastOperand;
139875ed548SDimitry Andric }
140875ed548SDimitry Andric 
1414ba319b5SDimitry Andric /// If the argument is a GEP, then returns the operand identified by
142875ed548SDimitry Andric /// getGEPInductionOperand. However, if there is some other non-loop-invariant
143875ed548SDimitry Andric /// operand, it returns that instead.
stripGetElementPtr(Value * Ptr,ScalarEvolution * SE,Loop * Lp)1447d523365SDimitry Andric Value *llvm::stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
145875ed548SDimitry Andric   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
146875ed548SDimitry Andric   if (!GEP)
147875ed548SDimitry Andric     return Ptr;
148875ed548SDimitry Andric 
149875ed548SDimitry Andric   unsigned InductionOperand = getGEPInductionOperand(GEP);
150875ed548SDimitry Andric 
151875ed548SDimitry Andric   // Check that all of the gep indices are uniform except for our induction
152875ed548SDimitry Andric   // operand.
153875ed548SDimitry Andric   for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
154875ed548SDimitry Andric     if (i != InductionOperand &&
155875ed548SDimitry Andric         !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
156875ed548SDimitry Andric       return Ptr;
157875ed548SDimitry Andric   return GEP->getOperand(InductionOperand);
158875ed548SDimitry Andric }
159875ed548SDimitry Andric 
1604ba319b5SDimitry Andric /// If a value has only one user that is a CastInst, return it.
getUniqueCastUse(Value * Ptr,Loop * Lp,Type * Ty)1617d523365SDimitry Andric Value *llvm::getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
1627d523365SDimitry Andric   Value *UniqueCast = nullptr;
163875ed548SDimitry Andric   for (User *U : Ptr->users()) {
164875ed548SDimitry Andric     CastInst *CI = dyn_cast<CastInst>(U);
165875ed548SDimitry Andric     if (CI && CI->getType() == Ty) {
166875ed548SDimitry Andric       if (!UniqueCast)
167875ed548SDimitry Andric         UniqueCast = CI;
168875ed548SDimitry Andric       else
169875ed548SDimitry Andric         return nullptr;
170875ed548SDimitry Andric     }
171875ed548SDimitry Andric   }
172875ed548SDimitry Andric   return UniqueCast;
173875ed548SDimitry Andric }
174875ed548SDimitry Andric 
1754ba319b5SDimitry Andric /// Get the stride of a pointer access in a loop. Looks for symbolic
176875ed548SDimitry Andric /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
getStrideFromPointer(Value * Ptr,ScalarEvolution * SE,Loop * Lp)1777d523365SDimitry Andric Value *llvm::getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
1787d523365SDimitry Andric   auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
179875ed548SDimitry Andric   if (!PtrTy || PtrTy->isAggregateType())
180875ed548SDimitry Andric     return nullptr;
181875ed548SDimitry Andric 
182875ed548SDimitry Andric   // Try to remove a gep instruction to make the pointer (actually index at this
1834ba319b5SDimitry Andric   // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
184875ed548SDimitry Andric   // pointer, otherwise, we are analyzing the index.
1857d523365SDimitry Andric   Value *OrigPtr = Ptr;
186875ed548SDimitry Andric 
187875ed548SDimitry Andric   // The size of the pointer access.
188875ed548SDimitry Andric   int64_t PtrAccessSize = 1;
189875ed548SDimitry Andric 
190875ed548SDimitry Andric   Ptr = stripGetElementPtr(Ptr, SE, Lp);
191875ed548SDimitry Andric   const SCEV *V = SE->getSCEV(Ptr);
192875ed548SDimitry Andric 
193875ed548SDimitry Andric   if (Ptr != OrigPtr)
194875ed548SDimitry Andric     // Strip off casts.
195875ed548SDimitry Andric     while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
196875ed548SDimitry Andric       V = C->getOperand();
197875ed548SDimitry Andric 
198875ed548SDimitry Andric   const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
199875ed548SDimitry Andric   if (!S)
200875ed548SDimitry Andric     return nullptr;
201875ed548SDimitry Andric 
202875ed548SDimitry Andric   V = S->getStepRecurrence(*SE);
203875ed548SDimitry Andric   if (!V)
204875ed548SDimitry Andric     return nullptr;
205875ed548SDimitry Andric 
206875ed548SDimitry Andric   // Strip off the size of access multiplication if we are still analyzing the
207875ed548SDimitry Andric   // pointer.
208875ed548SDimitry Andric   if (OrigPtr == Ptr) {
209875ed548SDimitry Andric     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
210875ed548SDimitry Andric       if (M->getOperand(0)->getSCEVType() != scConstant)
211875ed548SDimitry Andric         return nullptr;
212875ed548SDimitry Andric 
2137d523365SDimitry Andric       const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
214875ed548SDimitry Andric 
215875ed548SDimitry Andric       // Huge step value - give up.
216875ed548SDimitry Andric       if (APStepVal.getBitWidth() > 64)
217875ed548SDimitry Andric         return nullptr;
218875ed548SDimitry Andric 
219875ed548SDimitry Andric       int64_t StepVal = APStepVal.getSExtValue();
220875ed548SDimitry Andric       if (PtrAccessSize != StepVal)
221875ed548SDimitry Andric         return nullptr;
222875ed548SDimitry Andric       V = M->getOperand(1);
223875ed548SDimitry Andric     }
224875ed548SDimitry Andric   }
225875ed548SDimitry Andric 
226875ed548SDimitry Andric   // Strip off casts.
227875ed548SDimitry Andric   Type *StripedOffRecurrenceCast = nullptr;
228875ed548SDimitry Andric   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
229875ed548SDimitry Andric     StripedOffRecurrenceCast = C->getType();
230875ed548SDimitry Andric     V = C->getOperand();
231875ed548SDimitry Andric   }
232875ed548SDimitry Andric 
233875ed548SDimitry Andric   // Look for the loop invariant symbolic value.
234875ed548SDimitry Andric   const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
235875ed548SDimitry Andric   if (!U)
236875ed548SDimitry Andric     return nullptr;
237875ed548SDimitry Andric 
2387d523365SDimitry Andric   Value *Stride = U->getValue();
239875ed548SDimitry Andric   if (!Lp->isLoopInvariant(Stride))
240875ed548SDimitry Andric     return nullptr;
241875ed548SDimitry Andric 
242875ed548SDimitry Andric   // If we have stripped off the recurrence cast we have to make sure that we
243875ed548SDimitry Andric   // return the value that is used in this loop so that we can replace it later.
244875ed548SDimitry Andric   if (StripedOffRecurrenceCast)
245875ed548SDimitry Andric     Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
246875ed548SDimitry Andric 
247875ed548SDimitry Andric   return Stride;
248875ed548SDimitry Andric }
249875ed548SDimitry Andric 
2504ba319b5SDimitry Andric /// Given a vector and an element number, see if the scalar value is
251875ed548SDimitry Andric /// already around as a register, for example if it were inserted then extracted
252875ed548SDimitry Andric /// from the vector.
findScalarElement(Value * V,unsigned EltNo)2537d523365SDimitry Andric Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
254875ed548SDimitry Andric   assert(V->getType()->isVectorTy() && "Not looking at a vector?");
255875ed548SDimitry Andric   VectorType *VTy = cast<VectorType>(V->getType());
256875ed548SDimitry Andric   unsigned Width = VTy->getNumElements();
257875ed548SDimitry Andric   if (EltNo >= Width)  // Out of range access.
258875ed548SDimitry Andric     return UndefValue::get(VTy->getElementType());
259875ed548SDimitry Andric 
260875ed548SDimitry Andric   if (Constant *C = dyn_cast<Constant>(V))
261875ed548SDimitry Andric     return C->getAggregateElement(EltNo);
262875ed548SDimitry Andric 
263875ed548SDimitry Andric   if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
264875ed548SDimitry Andric     // If this is an insert to a variable element, we don't know what it is.
265875ed548SDimitry Andric     if (!isa<ConstantInt>(III->getOperand(2)))
266875ed548SDimitry Andric       return nullptr;
267875ed548SDimitry Andric     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
268875ed548SDimitry Andric 
269875ed548SDimitry Andric     // If this is an insert to the element we are looking for, return the
270875ed548SDimitry Andric     // inserted value.
271875ed548SDimitry Andric     if (EltNo == IIElt)
272875ed548SDimitry Andric       return III->getOperand(1);
273875ed548SDimitry Andric 
274875ed548SDimitry Andric     // Otherwise, the insertelement doesn't modify the value, recurse on its
275875ed548SDimitry Andric     // vector input.
276875ed548SDimitry Andric     return findScalarElement(III->getOperand(0), EltNo);
277875ed548SDimitry Andric   }
278875ed548SDimitry Andric 
279875ed548SDimitry Andric   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
280875ed548SDimitry Andric     unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
281875ed548SDimitry Andric     int InEl = SVI->getMaskValue(EltNo);
282875ed548SDimitry Andric     if (InEl < 0)
283875ed548SDimitry Andric       return UndefValue::get(VTy->getElementType());
284875ed548SDimitry Andric     if (InEl < (int)LHSWidth)
285875ed548SDimitry Andric       return findScalarElement(SVI->getOperand(0), InEl);
286875ed548SDimitry Andric     return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
287875ed548SDimitry Andric   }
288875ed548SDimitry Andric 
289875ed548SDimitry Andric   // Extract a value from a vector add operation with a constant zero.
290*b5893f02SDimitry Andric   // TODO: Use getBinOpIdentity() to generalize this.
291*b5893f02SDimitry Andric   Value *Val; Constant *C;
292*b5893f02SDimitry Andric   if (match(V, m_Add(m_Value(Val), m_Constant(C))))
293*b5893f02SDimitry Andric     if (Constant *Elt = C->getAggregateElement(EltNo))
294b6c25e0eSDimitry Andric       if (Elt->isNullValue())
295875ed548SDimitry Andric         return findScalarElement(Val, EltNo);
296875ed548SDimitry Andric 
297875ed548SDimitry Andric   // Otherwise, we don't know.
298875ed548SDimitry Andric   return nullptr;
299875ed548SDimitry Andric }
3007d523365SDimitry Andric 
3014ba319b5SDimitry Andric /// Get splat value if the input is a splat vector or return nullptr.
3027d523365SDimitry Andric /// This function is not fully general. It checks only 2 cases:
3037d523365SDimitry Andric /// the input value is (1) a splat constants vector or (2) a sequence
3047d523365SDimitry Andric /// of instructions that broadcast a single value into a vector.
3057d523365SDimitry Andric ///
getSplatValue(const Value * V)3067d523365SDimitry Andric const llvm::Value *llvm::getSplatValue(const Value *V) {
3077d523365SDimitry Andric 
3087d523365SDimitry Andric   if (auto *C = dyn_cast<Constant>(V))
3097d523365SDimitry Andric     if (isa<VectorType>(V->getType()))
3107d523365SDimitry Andric       return C->getSplatValue();
3117d523365SDimitry Andric 
3127d523365SDimitry Andric   auto *ShuffleInst = dyn_cast<ShuffleVectorInst>(V);
3137d523365SDimitry Andric   if (!ShuffleInst)
3147d523365SDimitry Andric     return nullptr;
3157d523365SDimitry Andric   // All-zero (or undef) shuffle mask elements.
3167d523365SDimitry Andric   for (int MaskElt : ShuffleInst->getShuffleMask())
3177d523365SDimitry Andric     if (MaskElt != 0 && MaskElt != -1)
3187d523365SDimitry Andric       return nullptr;
3197d523365SDimitry Andric   // The first shuffle source is 'insertelement' with index 0.
3207d523365SDimitry Andric   auto *InsertEltInst =
3217d523365SDimitry Andric     dyn_cast<InsertElementInst>(ShuffleInst->getOperand(0));
3227d523365SDimitry Andric   if (!InsertEltInst || !isa<ConstantInt>(InsertEltInst->getOperand(2)) ||
323c4394386SDimitry Andric       !cast<ConstantInt>(InsertEltInst->getOperand(2))->isZero())
3247d523365SDimitry Andric     return nullptr;
3257d523365SDimitry Andric 
3267d523365SDimitry Andric   return InsertEltInst->getOperand(1);
3277d523365SDimitry Andric }
3287d523365SDimitry Andric 
3297d523365SDimitry Andric MapVector<Instruction *, uint64_t>
computeMinimumValueSizes(ArrayRef<BasicBlock * > Blocks,DemandedBits & DB,const TargetTransformInfo * TTI)3307d523365SDimitry Andric llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB,
3317d523365SDimitry Andric                                const TargetTransformInfo *TTI) {
3327d523365SDimitry Andric 
3337d523365SDimitry Andric   // DemandedBits will give us every value's live-out bits. But we want
3347d523365SDimitry Andric   // to ensure no extra casts would need to be inserted, so every DAG
3357d523365SDimitry Andric   // of connected values must have the same minimum bitwidth.
3367d523365SDimitry Andric   EquivalenceClasses<Value *> ECs;
3377d523365SDimitry Andric   SmallVector<Value *, 16> Worklist;
3387d523365SDimitry Andric   SmallPtrSet<Value *, 4> Roots;
3397d523365SDimitry Andric   SmallPtrSet<Value *, 16> Visited;
3407d523365SDimitry Andric   DenseMap<Value *, uint64_t> DBits;
3417d523365SDimitry Andric   SmallPtrSet<Instruction *, 4> InstructionSet;
3427d523365SDimitry Andric   MapVector<Instruction *, uint64_t> MinBWs;
3437d523365SDimitry Andric 
3447d523365SDimitry Andric   // Determine the roots. We work bottom-up, from truncs or icmps.
3457d523365SDimitry Andric   bool SeenExtFromIllegalType = false;
3467d523365SDimitry Andric   for (auto *BB : Blocks)
3477d523365SDimitry Andric     for (auto &I : *BB) {
3487d523365SDimitry Andric       InstructionSet.insert(&I);
3497d523365SDimitry Andric 
3507d523365SDimitry Andric       if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
3517d523365SDimitry Andric           !TTI->isTypeLegal(I.getOperand(0)->getType()))
3527d523365SDimitry Andric         SeenExtFromIllegalType = true;
3537d523365SDimitry Andric 
3547d523365SDimitry Andric       // Only deal with non-vector integers up to 64-bits wide.
3557d523365SDimitry Andric       if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
3567d523365SDimitry Andric           !I.getType()->isVectorTy() &&
3577d523365SDimitry Andric           I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
3587d523365SDimitry Andric         // Don't make work for ourselves. If we know the loaded type is legal,
3597d523365SDimitry Andric         // don't add it to the worklist.
3607d523365SDimitry Andric         if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
3617d523365SDimitry Andric           continue;
3627d523365SDimitry Andric 
3637d523365SDimitry Andric         Worklist.push_back(&I);
3647d523365SDimitry Andric         Roots.insert(&I);
3657d523365SDimitry Andric       }
3667d523365SDimitry Andric     }
3677d523365SDimitry Andric   // Early exit.
3687d523365SDimitry Andric   if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
3697d523365SDimitry Andric     return MinBWs;
3707d523365SDimitry Andric 
3717d523365SDimitry Andric   // Now proceed breadth-first, unioning values together.
3727d523365SDimitry Andric   while (!Worklist.empty()) {
3737d523365SDimitry Andric     Value *Val = Worklist.pop_back_val();
3747d523365SDimitry Andric     Value *Leader = ECs.getOrInsertLeaderValue(Val);
3757d523365SDimitry Andric 
3767d523365SDimitry Andric     if (Visited.count(Val))
3777d523365SDimitry Andric       continue;
3787d523365SDimitry Andric     Visited.insert(Val);
3797d523365SDimitry Andric 
3807d523365SDimitry Andric     // Non-instructions terminate a chain successfully.
3817d523365SDimitry Andric     if (!isa<Instruction>(Val))
3827d523365SDimitry Andric       continue;
3837d523365SDimitry Andric     Instruction *I = cast<Instruction>(Val);
3847d523365SDimitry Andric 
3857d523365SDimitry Andric     // If we encounter a type that is larger than 64 bits, we can't represent
3867d523365SDimitry Andric     // it so bail out.
3877d523365SDimitry Andric     if (DB.getDemandedBits(I).getBitWidth() > 64)
3887d523365SDimitry Andric       return MapVector<Instruction *, uint64_t>();
3897d523365SDimitry Andric 
3907d523365SDimitry Andric     uint64_t V = DB.getDemandedBits(I).getZExtValue();
3917d523365SDimitry Andric     DBits[Leader] |= V;
3923ca95b02SDimitry Andric     DBits[I] = V;
3937d523365SDimitry Andric 
3947d523365SDimitry Andric     // Casts, loads and instructions outside of our range terminate a chain
3957d523365SDimitry Andric     // successfully.
3967d523365SDimitry Andric     if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
3977d523365SDimitry Andric         !InstructionSet.count(I))
3987d523365SDimitry Andric       continue;
3997d523365SDimitry Andric 
4007d523365SDimitry Andric     // Unsafe casts terminate a chain unsuccessfully. We can't do anything
4017d523365SDimitry Andric     // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
4027d523365SDimitry Andric     // transform anything that relies on them.
4037d523365SDimitry Andric     if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
4047d523365SDimitry Andric         !I->getType()->isIntegerTy()) {
4057d523365SDimitry Andric       DBits[Leader] |= ~0ULL;
4067d523365SDimitry Andric       continue;
4077d523365SDimitry Andric     }
4087d523365SDimitry Andric 
4097d523365SDimitry Andric     // We don't modify the types of PHIs. Reductions will already have been
4107d523365SDimitry Andric     // truncated if possible, and inductions' sizes will have been chosen by
4117d523365SDimitry Andric     // indvars.
4127d523365SDimitry Andric     if (isa<PHINode>(I))
4137d523365SDimitry Andric       continue;
4147d523365SDimitry Andric 
4157d523365SDimitry Andric     if (DBits[Leader] == ~0ULL)
4167d523365SDimitry Andric       // All bits demanded, no point continuing.
4177d523365SDimitry Andric       continue;
4187d523365SDimitry Andric 
4197d523365SDimitry Andric     for (Value *O : cast<User>(I)->operands()) {
4207d523365SDimitry Andric       ECs.unionSets(Leader, O);
4217d523365SDimitry Andric       Worklist.push_back(O);
4227d523365SDimitry Andric     }
4237d523365SDimitry Andric   }
4247d523365SDimitry Andric 
4257d523365SDimitry Andric   // Now we've discovered all values, walk them to see if there are
4267d523365SDimitry Andric   // any users we didn't see. If there are, we can't optimize that
4277d523365SDimitry Andric   // chain.
4287d523365SDimitry Andric   for (auto &I : DBits)
4297d523365SDimitry Andric     for (auto *U : I.first->users())
4307d523365SDimitry Andric       if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
4317d523365SDimitry Andric         DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
4327d523365SDimitry Andric 
4337d523365SDimitry Andric   for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
4347d523365SDimitry Andric     uint64_t LeaderDemandedBits = 0;
4357d523365SDimitry Andric     for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
4367d523365SDimitry Andric       LeaderDemandedBits |= DBits[*MI];
4377d523365SDimitry Andric 
4387d523365SDimitry Andric     uint64_t MinBW = (sizeof(LeaderDemandedBits) * 8) -
4397d523365SDimitry Andric                      llvm::countLeadingZeros(LeaderDemandedBits);
4407d523365SDimitry Andric     // Round up to a power of 2
4417d523365SDimitry Andric     if (!isPowerOf2_64((uint64_t)MinBW))
4427d523365SDimitry Andric       MinBW = NextPowerOf2(MinBW);
4433ca95b02SDimitry Andric 
4443ca95b02SDimitry Andric     // We don't modify the types of PHIs. Reductions will already have been
4453ca95b02SDimitry Andric     // truncated if possible, and inductions' sizes will have been chosen by
4463ca95b02SDimitry Andric     // indvars.
4473ca95b02SDimitry Andric     // If we are required to shrink a PHI, abandon this entire equivalence class.
4483ca95b02SDimitry Andric     bool Abort = false;
4493ca95b02SDimitry Andric     for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
4503ca95b02SDimitry Andric       if (isa<PHINode>(*MI) && MinBW < (*MI)->getType()->getScalarSizeInBits()) {
4513ca95b02SDimitry Andric         Abort = true;
4523ca95b02SDimitry Andric         break;
4533ca95b02SDimitry Andric       }
4543ca95b02SDimitry Andric     if (Abort)
4553ca95b02SDimitry Andric       continue;
4563ca95b02SDimitry Andric 
4577d523365SDimitry Andric     for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI) {
4587d523365SDimitry Andric       if (!isa<Instruction>(*MI))
4597d523365SDimitry Andric         continue;
4607d523365SDimitry Andric       Type *Ty = (*MI)->getType();
4617d523365SDimitry Andric       if (Roots.count(*MI))
4627d523365SDimitry Andric         Ty = cast<Instruction>(*MI)->getOperand(0)->getType();
4637d523365SDimitry Andric       if (MinBW < Ty->getScalarSizeInBits())
4647d523365SDimitry Andric         MinBWs[cast<Instruction>(*MI)] = MinBW;
4657d523365SDimitry Andric     }
4667d523365SDimitry Andric   }
4677d523365SDimitry Andric 
4687d523365SDimitry Andric   return MinBWs;
4697d523365SDimitry Andric }
4703ca95b02SDimitry Andric 
471*b5893f02SDimitry Andric /// Add all access groups in @p AccGroups to @p List.
472*b5893f02SDimitry Andric template <typename ListT>
addToAccessGroupList(ListT & List,MDNode * AccGroups)473*b5893f02SDimitry Andric static void addToAccessGroupList(ListT &List, MDNode *AccGroups) {
474*b5893f02SDimitry Andric   // Interpret an access group as a list containing itself.
475*b5893f02SDimitry Andric   if (AccGroups->getNumOperands() == 0) {
476*b5893f02SDimitry Andric     assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group");
477*b5893f02SDimitry Andric     List.insert(AccGroups);
478*b5893f02SDimitry Andric     return;
479*b5893f02SDimitry Andric   }
480*b5893f02SDimitry Andric 
481*b5893f02SDimitry Andric   for (auto &AccGroupListOp : AccGroups->operands()) {
482*b5893f02SDimitry Andric     auto *Item = cast<MDNode>(AccGroupListOp.get());
483*b5893f02SDimitry Andric     assert(isValidAsAccessGroup(Item) && "List item must be an access group");
484*b5893f02SDimitry Andric     List.insert(Item);
485*b5893f02SDimitry Andric   }
486*b5893f02SDimitry Andric }
487*b5893f02SDimitry Andric 
uniteAccessGroups(MDNode * AccGroups1,MDNode * AccGroups2)488*b5893f02SDimitry Andric MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) {
489*b5893f02SDimitry Andric   if (!AccGroups1)
490*b5893f02SDimitry Andric     return AccGroups2;
491*b5893f02SDimitry Andric   if (!AccGroups2)
492*b5893f02SDimitry Andric     return AccGroups1;
493*b5893f02SDimitry Andric   if (AccGroups1 == AccGroups2)
494*b5893f02SDimitry Andric     return AccGroups1;
495*b5893f02SDimitry Andric 
496*b5893f02SDimitry Andric   SmallSetVector<Metadata *, 4> Union;
497*b5893f02SDimitry Andric   addToAccessGroupList(Union, AccGroups1);
498*b5893f02SDimitry Andric   addToAccessGroupList(Union, AccGroups2);
499*b5893f02SDimitry Andric 
500*b5893f02SDimitry Andric   if (Union.size() == 0)
501*b5893f02SDimitry Andric     return nullptr;
502*b5893f02SDimitry Andric   if (Union.size() == 1)
503*b5893f02SDimitry Andric     return cast<MDNode>(Union.front());
504*b5893f02SDimitry Andric 
505*b5893f02SDimitry Andric   LLVMContext &Ctx = AccGroups1->getContext();
506*b5893f02SDimitry Andric   return MDNode::get(Ctx, Union.getArrayRef());
507*b5893f02SDimitry Andric }
508*b5893f02SDimitry Andric 
intersectAccessGroups(const Instruction * Inst1,const Instruction * Inst2)509*b5893f02SDimitry Andric MDNode *llvm::intersectAccessGroups(const Instruction *Inst1,
510*b5893f02SDimitry Andric                                     const Instruction *Inst2) {
511*b5893f02SDimitry Andric   bool MayAccessMem1 = Inst1->mayReadOrWriteMemory();
512*b5893f02SDimitry Andric   bool MayAccessMem2 = Inst2->mayReadOrWriteMemory();
513*b5893f02SDimitry Andric 
514*b5893f02SDimitry Andric   if (!MayAccessMem1 && !MayAccessMem2)
515*b5893f02SDimitry Andric     return nullptr;
516*b5893f02SDimitry Andric   if (!MayAccessMem1)
517*b5893f02SDimitry Andric     return Inst2->getMetadata(LLVMContext::MD_access_group);
518*b5893f02SDimitry Andric   if (!MayAccessMem2)
519*b5893f02SDimitry Andric     return Inst1->getMetadata(LLVMContext::MD_access_group);
520*b5893f02SDimitry Andric 
521*b5893f02SDimitry Andric   MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group);
522*b5893f02SDimitry Andric   MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group);
523*b5893f02SDimitry Andric   if (!MD1 || !MD2)
524*b5893f02SDimitry Andric     return nullptr;
525*b5893f02SDimitry Andric   if (MD1 == MD2)
526*b5893f02SDimitry Andric     return MD1;
527*b5893f02SDimitry Andric 
528*b5893f02SDimitry Andric   // Use set for scalable 'contains' check.
529*b5893f02SDimitry Andric   SmallPtrSet<Metadata *, 4> AccGroupSet2;
530*b5893f02SDimitry Andric   addToAccessGroupList(AccGroupSet2, MD2);
531*b5893f02SDimitry Andric 
532*b5893f02SDimitry Andric   SmallVector<Metadata *, 4> Intersection;
533*b5893f02SDimitry Andric   if (MD1->getNumOperands() == 0) {
534*b5893f02SDimitry Andric     assert(isValidAsAccessGroup(MD1) && "Node must be an access group");
535*b5893f02SDimitry Andric     if (AccGroupSet2.count(MD1))
536*b5893f02SDimitry Andric       Intersection.push_back(MD1);
537*b5893f02SDimitry Andric   } else {
538*b5893f02SDimitry Andric     for (const MDOperand &Node : MD1->operands()) {
539*b5893f02SDimitry Andric       auto *Item = cast<MDNode>(Node.get());
540*b5893f02SDimitry Andric       assert(isValidAsAccessGroup(Item) && "List item must be an access group");
541*b5893f02SDimitry Andric       if (AccGroupSet2.count(Item))
542*b5893f02SDimitry Andric         Intersection.push_back(Item);
543*b5893f02SDimitry Andric     }
544*b5893f02SDimitry Andric   }
545*b5893f02SDimitry Andric 
546*b5893f02SDimitry Andric   if (Intersection.size() == 0)
547*b5893f02SDimitry Andric     return nullptr;
548*b5893f02SDimitry Andric   if (Intersection.size() == 1)
549*b5893f02SDimitry Andric     return cast<MDNode>(Intersection.front());
550*b5893f02SDimitry Andric 
551*b5893f02SDimitry Andric   LLVMContext &Ctx = Inst1->getContext();
552*b5893f02SDimitry Andric   return MDNode::get(Ctx, Intersection);
553*b5893f02SDimitry Andric }
554*b5893f02SDimitry Andric 
5553ca95b02SDimitry Andric /// \returns \p I after propagating metadata from \p VL.
propagateMetadata(Instruction * Inst,ArrayRef<Value * > VL)5563ca95b02SDimitry Andric Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
5573ca95b02SDimitry Andric   Instruction *I0 = cast<Instruction>(VL[0]);
5583ca95b02SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
5593ca95b02SDimitry Andric   I0->getAllMetadataOtherThanDebugLoc(Metadata);
5603ca95b02SDimitry Andric 
561*b5893f02SDimitry Andric   for (auto Kind : {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
5623ca95b02SDimitry Andric                     LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
563*b5893f02SDimitry Andric                     LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load,
564*b5893f02SDimitry Andric                     LLVMContext::MD_access_group}) {
5653ca95b02SDimitry Andric     MDNode *MD = I0->getMetadata(Kind);
5663ca95b02SDimitry Andric 
5673ca95b02SDimitry Andric     for (int J = 1, E = VL.size(); MD && J != E; ++J) {
5683ca95b02SDimitry Andric       const Instruction *IJ = cast<Instruction>(VL[J]);
5693ca95b02SDimitry Andric       MDNode *IMD = IJ->getMetadata(Kind);
5703ca95b02SDimitry Andric       switch (Kind) {
5713ca95b02SDimitry Andric       case LLVMContext::MD_tbaa:
5723ca95b02SDimitry Andric         MD = MDNode::getMostGenericTBAA(MD, IMD);
5733ca95b02SDimitry Andric         break;
5743ca95b02SDimitry Andric       case LLVMContext::MD_alias_scope:
5753ca95b02SDimitry Andric         MD = MDNode::getMostGenericAliasScope(MD, IMD);
5763ca95b02SDimitry Andric         break;
5773ca95b02SDimitry Andric       case LLVMContext::MD_fpmath:
5783ca95b02SDimitry Andric         MD = MDNode::getMostGenericFPMath(MD, IMD);
5793ca95b02SDimitry Andric         break;
580d88c1a5aSDimitry Andric       case LLVMContext::MD_noalias:
5813ca95b02SDimitry Andric       case LLVMContext::MD_nontemporal:
582d88c1a5aSDimitry Andric       case LLVMContext::MD_invariant_load:
5833ca95b02SDimitry Andric         MD = MDNode::intersect(MD, IMD);
5843ca95b02SDimitry Andric         break;
585*b5893f02SDimitry Andric       case LLVMContext::MD_access_group:
586*b5893f02SDimitry Andric         MD = intersectAccessGroups(Inst, IJ);
587*b5893f02SDimitry Andric         break;
5883ca95b02SDimitry Andric       default:
5893ca95b02SDimitry Andric         llvm_unreachable("unhandled metadata");
5903ca95b02SDimitry Andric       }
5913ca95b02SDimitry Andric     }
5923ca95b02SDimitry Andric 
5933ca95b02SDimitry Andric     Inst->setMetadata(Kind, MD);
5943ca95b02SDimitry Andric   }
5953ca95b02SDimitry Andric 
5963ca95b02SDimitry Andric   return Inst;
5973ca95b02SDimitry Andric }
5987a7e6055SDimitry Andric 
599*b5893f02SDimitry Andric Constant *
createBitMaskForGaps(IRBuilder<> & Builder,unsigned VF,const InterleaveGroup<Instruction> & Group)600*b5893f02SDimitry Andric llvm::createBitMaskForGaps(IRBuilder<> &Builder, unsigned VF,
601*b5893f02SDimitry Andric                            const InterleaveGroup<Instruction> &Group) {
602*b5893f02SDimitry Andric   // All 1's means mask is not needed.
603*b5893f02SDimitry Andric   if (Group.getNumMembers() == Group.getFactor())
604*b5893f02SDimitry Andric     return nullptr;
605*b5893f02SDimitry Andric 
606*b5893f02SDimitry Andric   // TODO: support reversed access.
607*b5893f02SDimitry Andric   assert(!Group.isReverse() && "Reversed group not supported.");
608*b5893f02SDimitry Andric 
609*b5893f02SDimitry Andric   SmallVector<Constant *, 16> Mask;
610*b5893f02SDimitry Andric   for (unsigned i = 0; i < VF; i++)
611*b5893f02SDimitry Andric     for (unsigned j = 0; j < Group.getFactor(); ++j) {
612*b5893f02SDimitry Andric       unsigned HasMember = Group.getMember(j) ? 1 : 0;
613*b5893f02SDimitry Andric       Mask.push_back(Builder.getInt1(HasMember));
614*b5893f02SDimitry Andric     }
615*b5893f02SDimitry Andric 
616*b5893f02SDimitry Andric   return ConstantVector::get(Mask);
617*b5893f02SDimitry Andric }
618*b5893f02SDimitry Andric 
createReplicatedMask(IRBuilder<> & Builder,unsigned ReplicationFactor,unsigned VF)619*b5893f02SDimitry Andric Constant *llvm::createReplicatedMask(IRBuilder<> &Builder,
620*b5893f02SDimitry Andric                                      unsigned ReplicationFactor, unsigned VF) {
621*b5893f02SDimitry Andric   SmallVector<Constant *, 16> MaskVec;
622*b5893f02SDimitry Andric   for (unsigned i = 0; i < VF; i++)
623*b5893f02SDimitry Andric     for (unsigned j = 0; j < ReplicationFactor; j++)
624*b5893f02SDimitry Andric       MaskVec.push_back(Builder.getInt32(i));
625*b5893f02SDimitry Andric 
626*b5893f02SDimitry Andric   return ConstantVector::get(MaskVec);
627*b5893f02SDimitry Andric }
628*b5893f02SDimitry Andric 
createInterleaveMask(IRBuilder<> & Builder,unsigned VF,unsigned NumVecs)6297a7e6055SDimitry Andric Constant *llvm::createInterleaveMask(IRBuilder<> &Builder, unsigned VF,
6307a7e6055SDimitry Andric                                      unsigned NumVecs) {
6317a7e6055SDimitry Andric   SmallVector<Constant *, 16> Mask;
6327a7e6055SDimitry Andric   for (unsigned i = 0; i < VF; i++)
6337a7e6055SDimitry Andric     for (unsigned j = 0; j < NumVecs; j++)
6347a7e6055SDimitry Andric       Mask.push_back(Builder.getInt32(j * VF + i));
6357a7e6055SDimitry Andric 
6367a7e6055SDimitry Andric   return ConstantVector::get(Mask);
6377a7e6055SDimitry Andric }
6387a7e6055SDimitry Andric 
createStrideMask(IRBuilder<> & Builder,unsigned Start,unsigned Stride,unsigned VF)6397a7e6055SDimitry Andric Constant *llvm::createStrideMask(IRBuilder<> &Builder, unsigned Start,
6407a7e6055SDimitry Andric                                  unsigned Stride, unsigned VF) {
6417a7e6055SDimitry Andric   SmallVector<Constant *, 16> Mask;
6427a7e6055SDimitry Andric   for (unsigned i = 0; i < VF; i++)
6437a7e6055SDimitry Andric     Mask.push_back(Builder.getInt32(Start + i * Stride));
6447a7e6055SDimitry Andric 
6457a7e6055SDimitry Andric   return ConstantVector::get(Mask);
6467a7e6055SDimitry Andric }
6477a7e6055SDimitry Andric 
createSequentialMask(IRBuilder<> & Builder,unsigned Start,unsigned NumInts,unsigned NumUndefs)6487a7e6055SDimitry Andric Constant *llvm::createSequentialMask(IRBuilder<> &Builder, unsigned Start,
6497a7e6055SDimitry Andric                                      unsigned NumInts, unsigned NumUndefs) {
6507a7e6055SDimitry Andric   SmallVector<Constant *, 16> Mask;
6517a7e6055SDimitry Andric   for (unsigned i = 0; i < NumInts; i++)
6527a7e6055SDimitry Andric     Mask.push_back(Builder.getInt32(Start + i));
6537a7e6055SDimitry Andric 
6547a7e6055SDimitry Andric   Constant *Undef = UndefValue::get(Builder.getInt32Ty());
6557a7e6055SDimitry Andric   for (unsigned i = 0; i < NumUndefs; i++)
6567a7e6055SDimitry Andric     Mask.push_back(Undef);
6577a7e6055SDimitry Andric 
6587a7e6055SDimitry Andric   return ConstantVector::get(Mask);
6597a7e6055SDimitry Andric }
6607a7e6055SDimitry Andric 
6617a7e6055SDimitry Andric /// A helper function for concatenating vectors. This function concatenates two
6627a7e6055SDimitry Andric /// vectors having the same element type. If the second vector has fewer
6637a7e6055SDimitry Andric /// elements than the first, it is padded with undefs.
concatenateTwoVectors(IRBuilder<> & Builder,Value * V1,Value * V2)6647a7e6055SDimitry Andric static Value *concatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
6657a7e6055SDimitry Andric                                     Value *V2) {
6667a7e6055SDimitry Andric   VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
6677a7e6055SDimitry Andric   VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
6687a7e6055SDimitry Andric   assert(VecTy1 && VecTy2 &&
6697a7e6055SDimitry Andric          VecTy1->getScalarType() == VecTy2->getScalarType() &&
6707a7e6055SDimitry Andric          "Expect two vectors with the same element type");
6717a7e6055SDimitry Andric 
6727a7e6055SDimitry Andric   unsigned NumElts1 = VecTy1->getNumElements();
6737a7e6055SDimitry Andric   unsigned NumElts2 = VecTy2->getNumElements();
6747a7e6055SDimitry Andric   assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
6757a7e6055SDimitry Andric 
6767a7e6055SDimitry Andric   if (NumElts1 > NumElts2) {
6777a7e6055SDimitry Andric     // Extend with UNDEFs.
6787a7e6055SDimitry Andric     Constant *ExtMask =
6797a7e6055SDimitry Andric         createSequentialMask(Builder, 0, NumElts2, NumElts1 - NumElts2);
6807a7e6055SDimitry Andric     V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
6817a7e6055SDimitry Andric   }
6827a7e6055SDimitry Andric 
6837a7e6055SDimitry Andric   Constant *Mask = createSequentialMask(Builder, 0, NumElts1 + NumElts2, 0);
6847a7e6055SDimitry Andric   return Builder.CreateShuffleVector(V1, V2, Mask);
6857a7e6055SDimitry Andric }
6867a7e6055SDimitry Andric 
concatenateVectors(IRBuilder<> & Builder,ArrayRef<Value * > Vecs)6877a7e6055SDimitry Andric Value *llvm::concatenateVectors(IRBuilder<> &Builder, ArrayRef<Value *> Vecs) {
6887a7e6055SDimitry Andric   unsigned NumVecs = Vecs.size();
6897a7e6055SDimitry Andric   assert(NumVecs > 1 && "Should be at least two vectors");
6907a7e6055SDimitry Andric 
6917a7e6055SDimitry Andric   SmallVector<Value *, 8> ResList;
6927a7e6055SDimitry Andric   ResList.append(Vecs.begin(), Vecs.end());
6937a7e6055SDimitry Andric   do {
6947a7e6055SDimitry Andric     SmallVector<Value *, 8> TmpList;
6957a7e6055SDimitry Andric     for (unsigned i = 0; i < NumVecs - 1; i += 2) {
6967a7e6055SDimitry Andric       Value *V0 = ResList[i], *V1 = ResList[i + 1];
6977a7e6055SDimitry Andric       assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
6987a7e6055SDimitry Andric              "Only the last vector may have a different type");
6997a7e6055SDimitry Andric 
7007a7e6055SDimitry Andric       TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
7017a7e6055SDimitry Andric     }
7027a7e6055SDimitry Andric 
7037a7e6055SDimitry Andric     // Push the last vector if the total number of vectors is odd.
7047a7e6055SDimitry Andric     if (NumVecs % 2 != 0)
7057a7e6055SDimitry Andric       TmpList.push_back(ResList[NumVecs - 1]);
7067a7e6055SDimitry Andric 
7077a7e6055SDimitry Andric     ResList = TmpList;
7087a7e6055SDimitry Andric     NumVecs = ResList.size();
7097a7e6055SDimitry Andric   } while (NumVecs > 1);
7107a7e6055SDimitry Andric 
7117a7e6055SDimitry Andric   return ResList[0];
7127a7e6055SDimitry Andric }
713*b5893f02SDimitry Andric 
isStrided(int Stride)714*b5893f02SDimitry Andric bool InterleavedAccessInfo::isStrided(int Stride) {
715*b5893f02SDimitry Andric   unsigned Factor = std::abs(Stride);
716*b5893f02SDimitry Andric   return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
717*b5893f02SDimitry Andric }
718*b5893f02SDimitry Andric 
collectConstStrideAccesses(MapVector<Instruction *,StrideDescriptor> & AccessStrideInfo,const ValueToValueMap & Strides)719*b5893f02SDimitry Andric void InterleavedAccessInfo::collectConstStrideAccesses(
720*b5893f02SDimitry Andric     MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
721*b5893f02SDimitry Andric     const ValueToValueMap &Strides) {
722*b5893f02SDimitry Andric   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
723*b5893f02SDimitry Andric 
724*b5893f02SDimitry Andric   // Since it's desired that the load/store instructions be maintained in
725*b5893f02SDimitry Andric   // "program order" for the interleaved access analysis, we have to visit the
726*b5893f02SDimitry Andric   // blocks in the loop in reverse postorder (i.e., in a topological order).
727*b5893f02SDimitry Andric   // Such an ordering will ensure that any load/store that may be executed
728*b5893f02SDimitry Andric   // before a second load/store will precede the second load/store in
729*b5893f02SDimitry Andric   // AccessStrideInfo.
730*b5893f02SDimitry Andric   LoopBlocksDFS DFS(TheLoop);
731*b5893f02SDimitry Andric   DFS.perform(LI);
732*b5893f02SDimitry Andric   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
733*b5893f02SDimitry Andric     for (auto &I : *BB) {
734*b5893f02SDimitry Andric       auto *LI = dyn_cast<LoadInst>(&I);
735*b5893f02SDimitry Andric       auto *SI = dyn_cast<StoreInst>(&I);
736*b5893f02SDimitry Andric       if (!LI && !SI)
737*b5893f02SDimitry Andric         continue;
738*b5893f02SDimitry Andric 
739*b5893f02SDimitry Andric       Value *Ptr = getLoadStorePointerOperand(&I);
740*b5893f02SDimitry Andric       // We don't check wrapping here because we don't know yet if Ptr will be
741*b5893f02SDimitry Andric       // part of a full group or a group with gaps. Checking wrapping for all
742*b5893f02SDimitry Andric       // pointers (even those that end up in groups with no gaps) will be overly
743*b5893f02SDimitry Andric       // conservative. For full groups, wrapping should be ok since if we would
744*b5893f02SDimitry Andric       // wrap around the address space we would do a memory access at nullptr
745*b5893f02SDimitry Andric       // even without the transformation. The wrapping checks are therefore
746*b5893f02SDimitry Andric       // deferred until after we've formed the interleaved groups.
747*b5893f02SDimitry Andric       int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
748*b5893f02SDimitry Andric                                     /*Assume=*/true, /*ShouldCheckWrap=*/false);
749*b5893f02SDimitry Andric 
750*b5893f02SDimitry Andric       const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
751*b5893f02SDimitry Andric       PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
752*b5893f02SDimitry Andric       uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
753*b5893f02SDimitry Andric 
754*b5893f02SDimitry Andric       // An alignment of 0 means target ABI alignment.
755*b5893f02SDimitry Andric       unsigned Align = getLoadStoreAlignment(&I);
756*b5893f02SDimitry Andric       if (!Align)
757*b5893f02SDimitry Andric         Align = DL.getABITypeAlignment(PtrTy->getElementType());
758*b5893f02SDimitry Andric 
759*b5893f02SDimitry Andric       AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
760*b5893f02SDimitry Andric     }
761*b5893f02SDimitry Andric }
762*b5893f02SDimitry Andric 
763*b5893f02SDimitry Andric // Analyze interleaved accesses and collect them into interleaved load and
764*b5893f02SDimitry Andric // store groups.
765*b5893f02SDimitry Andric //
766*b5893f02SDimitry Andric // When generating code for an interleaved load group, we effectively hoist all
767*b5893f02SDimitry Andric // loads in the group to the location of the first load in program order. When
768*b5893f02SDimitry Andric // generating code for an interleaved store group, we sink all stores to the
769*b5893f02SDimitry Andric // location of the last store. This code motion can change the order of load
770*b5893f02SDimitry Andric // and store instructions and may break dependences.
771*b5893f02SDimitry Andric //
772*b5893f02SDimitry Andric // The code generation strategy mentioned above ensures that we won't violate
773*b5893f02SDimitry Andric // any write-after-read (WAR) dependences.
774*b5893f02SDimitry Andric //
775*b5893f02SDimitry Andric // E.g., for the WAR dependence:  a = A[i];      // (1)
776*b5893f02SDimitry Andric //                                A[i] = b;      // (2)
777*b5893f02SDimitry Andric //
778*b5893f02SDimitry Andric // The store group of (2) is always inserted at or below (2), and the load
779*b5893f02SDimitry Andric // group of (1) is always inserted at or above (1). Thus, the instructions will
780*b5893f02SDimitry Andric // never be reordered. All other dependences are checked to ensure the
781*b5893f02SDimitry Andric // correctness of the instruction reordering.
782*b5893f02SDimitry Andric //
783*b5893f02SDimitry Andric // The algorithm visits all memory accesses in the loop in bottom-up program
784*b5893f02SDimitry Andric // order. Program order is established by traversing the blocks in the loop in
785*b5893f02SDimitry Andric // reverse postorder when collecting the accesses.
786*b5893f02SDimitry Andric //
787*b5893f02SDimitry Andric // We visit the memory accesses in bottom-up order because it can simplify the
788*b5893f02SDimitry Andric // construction of store groups in the presence of write-after-write (WAW)
789*b5893f02SDimitry Andric // dependences.
790*b5893f02SDimitry Andric //
791*b5893f02SDimitry Andric // E.g., for the WAW dependence:  A[i] = a;      // (1)
792*b5893f02SDimitry Andric //                                A[i] = b;      // (2)
793*b5893f02SDimitry Andric //                                A[i + 1] = c;  // (3)
794*b5893f02SDimitry Andric //
795*b5893f02SDimitry Andric // We will first create a store group with (3) and (2). (1) can't be added to
796*b5893f02SDimitry Andric // this group because it and (2) are dependent. However, (1) can be grouped
797*b5893f02SDimitry Andric // with other accesses that may precede it in program order. Note that a
798*b5893f02SDimitry Andric // bottom-up order does not imply that WAW dependences should not be checked.
analyzeInterleaving(bool EnablePredicatedInterleavedMemAccesses)799*b5893f02SDimitry Andric void InterleavedAccessInfo::analyzeInterleaving(
800*b5893f02SDimitry Andric                                  bool EnablePredicatedInterleavedMemAccesses) {
801*b5893f02SDimitry Andric   LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
802*b5893f02SDimitry Andric   const ValueToValueMap &Strides = LAI->getSymbolicStrides();
803*b5893f02SDimitry Andric 
804*b5893f02SDimitry Andric   // Holds all accesses with a constant stride.
805*b5893f02SDimitry Andric   MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
806*b5893f02SDimitry Andric   collectConstStrideAccesses(AccessStrideInfo, Strides);
807*b5893f02SDimitry Andric 
808*b5893f02SDimitry Andric   if (AccessStrideInfo.empty())
809*b5893f02SDimitry Andric     return;
810*b5893f02SDimitry Andric 
811*b5893f02SDimitry Andric   // Collect the dependences in the loop.
812*b5893f02SDimitry Andric   collectDependences();
813*b5893f02SDimitry Andric 
814*b5893f02SDimitry Andric   // Holds all interleaved store groups temporarily.
815*b5893f02SDimitry Andric   SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups;
816*b5893f02SDimitry Andric   // Holds all interleaved load groups temporarily.
817*b5893f02SDimitry Andric   SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups;
818*b5893f02SDimitry Andric 
819*b5893f02SDimitry Andric   // Search in bottom-up program order for pairs of accesses (A and B) that can
820*b5893f02SDimitry Andric   // form interleaved load or store groups. In the algorithm below, access A
821*b5893f02SDimitry Andric   // precedes access B in program order. We initialize a group for B in the
822*b5893f02SDimitry Andric   // outer loop of the algorithm, and then in the inner loop, we attempt to
823*b5893f02SDimitry Andric   // insert each A into B's group if:
824*b5893f02SDimitry Andric   //
825*b5893f02SDimitry Andric   //  1. A and B have the same stride,
826*b5893f02SDimitry Andric   //  2. A and B have the same memory object size, and
827*b5893f02SDimitry Andric   //  3. A belongs in B's group according to its distance from B.
828*b5893f02SDimitry Andric   //
829*b5893f02SDimitry Andric   // Special care is taken to ensure group formation will not break any
830*b5893f02SDimitry Andric   // dependences.
831*b5893f02SDimitry Andric   for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
832*b5893f02SDimitry Andric        BI != E; ++BI) {
833*b5893f02SDimitry Andric     Instruction *B = BI->first;
834*b5893f02SDimitry Andric     StrideDescriptor DesB = BI->second;
835*b5893f02SDimitry Andric 
836*b5893f02SDimitry Andric     // Initialize a group for B if it has an allowable stride. Even if we don't
837*b5893f02SDimitry Andric     // create a group for B, we continue with the bottom-up algorithm to ensure
838*b5893f02SDimitry Andric     // we don't break any of B's dependences.
839*b5893f02SDimitry Andric     InterleaveGroup<Instruction> *Group = nullptr;
840*b5893f02SDimitry Andric     if (isStrided(DesB.Stride) &&
841*b5893f02SDimitry Andric         (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
842*b5893f02SDimitry Andric       Group = getInterleaveGroup(B);
843*b5893f02SDimitry Andric       if (!Group) {
844*b5893f02SDimitry Andric         LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
845*b5893f02SDimitry Andric                           << '\n');
846*b5893f02SDimitry Andric         Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
847*b5893f02SDimitry Andric       }
848*b5893f02SDimitry Andric       if (B->mayWriteToMemory())
849*b5893f02SDimitry Andric         StoreGroups.insert(Group);
850*b5893f02SDimitry Andric       else
851*b5893f02SDimitry Andric         LoadGroups.insert(Group);
852*b5893f02SDimitry Andric     }
853*b5893f02SDimitry Andric 
854*b5893f02SDimitry Andric     for (auto AI = std::next(BI); AI != E; ++AI) {
855*b5893f02SDimitry Andric       Instruction *A = AI->first;
856*b5893f02SDimitry Andric       StrideDescriptor DesA = AI->second;
857*b5893f02SDimitry Andric 
858*b5893f02SDimitry Andric       // Our code motion strategy implies that we can't have dependences
859*b5893f02SDimitry Andric       // between accesses in an interleaved group and other accesses located
860*b5893f02SDimitry Andric       // between the first and last member of the group. Note that this also
861*b5893f02SDimitry Andric       // means that a group can't have more than one member at a given offset.
862*b5893f02SDimitry Andric       // The accesses in a group can have dependences with other accesses, but
863*b5893f02SDimitry Andric       // we must ensure we don't extend the boundaries of the group such that
864*b5893f02SDimitry Andric       // we encompass those dependent accesses.
865*b5893f02SDimitry Andric       //
866*b5893f02SDimitry Andric       // For example, assume we have the sequence of accesses shown below in a
867*b5893f02SDimitry Andric       // stride-2 loop:
868*b5893f02SDimitry Andric       //
869*b5893f02SDimitry Andric       //  (1, 2) is a group | A[i]   = a;  // (1)
870*b5893f02SDimitry Andric       //                    | A[i-1] = b;  // (2) |
871*b5893f02SDimitry Andric       //                      A[i-3] = c;  // (3)
872*b5893f02SDimitry Andric       //                      A[i]   = d;  // (4) | (2, 4) is not a group
873*b5893f02SDimitry Andric       //
874*b5893f02SDimitry Andric       // Because accesses (2) and (3) are dependent, we can group (2) with (1)
875*b5893f02SDimitry Andric       // but not with (4). If we did, the dependent access (3) would be within
876*b5893f02SDimitry Andric       // the boundaries of the (2, 4) group.
877*b5893f02SDimitry Andric       if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
878*b5893f02SDimitry Andric         // If a dependence exists and A is already in a group, we know that A
879*b5893f02SDimitry Andric         // must be a store since A precedes B and WAR dependences are allowed.
880*b5893f02SDimitry Andric         // Thus, A would be sunk below B. We release A's group to prevent this
881*b5893f02SDimitry Andric         // illegal code motion. A will then be free to form another group with
882*b5893f02SDimitry Andric         // instructions that precede it.
883*b5893f02SDimitry Andric         if (isInterleaved(A)) {
884*b5893f02SDimitry Andric           InterleaveGroup<Instruction> *StoreGroup = getInterleaveGroup(A);
885*b5893f02SDimitry Andric           StoreGroups.remove(StoreGroup);
886*b5893f02SDimitry Andric           releaseGroup(StoreGroup);
887*b5893f02SDimitry Andric         }
888*b5893f02SDimitry Andric 
889*b5893f02SDimitry Andric         // If a dependence exists and A is not already in a group (or it was
890*b5893f02SDimitry Andric         // and we just released it), B might be hoisted above A (if B is a
891*b5893f02SDimitry Andric         // load) or another store might be sunk below A (if B is a store). In
892*b5893f02SDimitry Andric         // either case, we can't add additional instructions to B's group. B
893*b5893f02SDimitry Andric         // will only form a group with instructions that it precedes.
894*b5893f02SDimitry Andric         break;
895*b5893f02SDimitry Andric       }
896*b5893f02SDimitry Andric 
897*b5893f02SDimitry Andric       // At this point, we've checked for illegal code motion. If either A or B
898*b5893f02SDimitry Andric       // isn't strided, there's nothing left to do.
899*b5893f02SDimitry Andric       if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
900*b5893f02SDimitry Andric         continue;
901*b5893f02SDimitry Andric 
902*b5893f02SDimitry Andric       // Ignore A if it's already in a group or isn't the same kind of memory
903*b5893f02SDimitry Andric       // operation as B.
904*b5893f02SDimitry Andric       // Note that mayReadFromMemory() isn't mutually exclusive to
905*b5893f02SDimitry Andric       // mayWriteToMemory in the case of atomic loads. We shouldn't see those
906*b5893f02SDimitry Andric       // here, canVectorizeMemory() should have returned false - except for the
907*b5893f02SDimitry Andric       // case we asked for optimization remarks.
908*b5893f02SDimitry Andric       if (isInterleaved(A) ||
909*b5893f02SDimitry Andric           (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
910*b5893f02SDimitry Andric           (A->mayWriteToMemory() != B->mayWriteToMemory()))
911*b5893f02SDimitry Andric         continue;
912*b5893f02SDimitry Andric 
913*b5893f02SDimitry Andric       // Check rules 1 and 2. Ignore A if its stride or size is different from
914*b5893f02SDimitry Andric       // that of B.
915*b5893f02SDimitry Andric       if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
916*b5893f02SDimitry Andric         continue;
917*b5893f02SDimitry Andric 
918*b5893f02SDimitry Andric       // Ignore A if the memory object of A and B don't belong to the same
919*b5893f02SDimitry Andric       // address space
920*b5893f02SDimitry Andric       if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
921*b5893f02SDimitry Andric         continue;
922*b5893f02SDimitry Andric 
923*b5893f02SDimitry Andric       // Calculate the distance from A to B.
924*b5893f02SDimitry Andric       const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
925*b5893f02SDimitry Andric           PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
926*b5893f02SDimitry Andric       if (!DistToB)
927*b5893f02SDimitry Andric         continue;
928*b5893f02SDimitry Andric       int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
929*b5893f02SDimitry Andric 
930*b5893f02SDimitry Andric       // Check rule 3. Ignore A if its distance to B is not a multiple of the
931*b5893f02SDimitry Andric       // size.
932*b5893f02SDimitry Andric       if (DistanceToB % static_cast<int64_t>(DesB.Size))
933*b5893f02SDimitry Andric         continue;
934*b5893f02SDimitry Andric 
935*b5893f02SDimitry Andric       // All members of a predicated interleave-group must have the same predicate,
936*b5893f02SDimitry Andric       // and currently must reside in the same BB.
937*b5893f02SDimitry Andric       BasicBlock *BlockA = A->getParent();
938*b5893f02SDimitry Andric       BasicBlock *BlockB = B->getParent();
939*b5893f02SDimitry Andric       if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
940*b5893f02SDimitry Andric           (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
941*b5893f02SDimitry Andric         continue;
942*b5893f02SDimitry Andric 
943*b5893f02SDimitry Andric       // The index of A is the index of B plus A's distance to B in multiples
944*b5893f02SDimitry Andric       // of the size.
945*b5893f02SDimitry Andric       int IndexA =
946*b5893f02SDimitry Andric           Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
947*b5893f02SDimitry Andric 
948*b5893f02SDimitry Andric       // Try to insert A into B's group.
949*b5893f02SDimitry Andric       if (Group->insertMember(A, IndexA, DesA.Align)) {
950*b5893f02SDimitry Andric         LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
951*b5893f02SDimitry Andric                           << "    into the interleave group with" << *B
952*b5893f02SDimitry Andric                           << '\n');
953*b5893f02SDimitry Andric         InterleaveGroupMap[A] = Group;
954*b5893f02SDimitry Andric 
955*b5893f02SDimitry Andric         // Set the first load in program order as the insert position.
956*b5893f02SDimitry Andric         if (A->mayReadFromMemory())
957*b5893f02SDimitry Andric           Group->setInsertPos(A);
958*b5893f02SDimitry Andric       }
959*b5893f02SDimitry Andric     } // Iteration over A accesses.
960*b5893f02SDimitry Andric   }   // Iteration over B accesses.
961*b5893f02SDimitry Andric 
962*b5893f02SDimitry Andric   // Remove interleaved store groups with gaps.
963*b5893f02SDimitry Andric   for (auto *Group : StoreGroups)
964*b5893f02SDimitry Andric     if (Group->getNumMembers() != Group->getFactor()) {
965*b5893f02SDimitry Andric       LLVM_DEBUG(
966*b5893f02SDimitry Andric           dbgs() << "LV: Invalidate candidate interleaved store group due "
967*b5893f02SDimitry Andric                     "to gaps.\n");
968*b5893f02SDimitry Andric       releaseGroup(Group);
969*b5893f02SDimitry Andric     }
970*b5893f02SDimitry Andric   // Remove interleaved groups with gaps (currently only loads) whose memory
971*b5893f02SDimitry Andric   // accesses may wrap around. We have to revisit the getPtrStride analysis,
972*b5893f02SDimitry Andric   // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
973*b5893f02SDimitry Andric   // not check wrapping (see documentation there).
974*b5893f02SDimitry Andric   // FORNOW we use Assume=false;
975*b5893f02SDimitry Andric   // TODO: Change to Assume=true but making sure we don't exceed the threshold
976*b5893f02SDimitry Andric   // of runtime SCEV assumptions checks (thereby potentially failing to
977*b5893f02SDimitry Andric   // vectorize altogether).
978*b5893f02SDimitry Andric   // Additional optional optimizations:
979*b5893f02SDimitry Andric   // TODO: If we are peeling the loop and we know that the first pointer doesn't
980*b5893f02SDimitry Andric   // wrap then we can deduce that all pointers in the group don't wrap.
981*b5893f02SDimitry Andric   // This means that we can forcefully peel the loop in order to only have to
982*b5893f02SDimitry Andric   // check the first pointer for no-wrap. When we'll change to use Assume=true
983*b5893f02SDimitry Andric   // we'll only need at most one runtime check per interleaved group.
984*b5893f02SDimitry Andric   for (auto *Group : LoadGroups) {
985*b5893f02SDimitry Andric     // Case 1: A full group. Can Skip the checks; For full groups, if the wide
986*b5893f02SDimitry Andric     // load would wrap around the address space we would do a memory access at
987*b5893f02SDimitry Andric     // nullptr even without the transformation.
988*b5893f02SDimitry Andric     if (Group->getNumMembers() == Group->getFactor())
989*b5893f02SDimitry Andric       continue;
990*b5893f02SDimitry Andric 
991*b5893f02SDimitry Andric     // Case 2: If first and last members of the group don't wrap this implies
992*b5893f02SDimitry Andric     // that all the pointers in the group don't wrap.
993*b5893f02SDimitry Andric     // So we check only group member 0 (which is always guaranteed to exist),
994*b5893f02SDimitry Andric     // and group member Factor - 1; If the latter doesn't exist we rely on
995*b5893f02SDimitry Andric     // peeling (if it is a non-reveresed accsess -- see Case 3).
996*b5893f02SDimitry Andric     Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0));
997*b5893f02SDimitry Andric     if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
998*b5893f02SDimitry Andric                       /*ShouldCheckWrap=*/true)) {
999*b5893f02SDimitry Andric       LLVM_DEBUG(
1000*b5893f02SDimitry Andric           dbgs() << "LV: Invalidate candidate interleaved group due to "
1001*b5893f02SDimitry Andric                     "first group member potentially pointer-wrapping.\n");
1002*b5893f02SDimitry Andric       releaseGroup(Group);
1003*b5893f02SDimitry Andric       continue;
1004*b5893f02SDimitry Andric     }
1005*b5893f02SDimitry Andric     Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
1006*b5893f02SDimitry Andric     if (LastMember) {
1007*b5893f02SDimitry Andric       Value *LastMemberPtr = getLoadStorePointerOperand(LastMember);
1008*b5893f02SDimitry Andric       if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
1009*b5893f02SDimitry Andric                         /*ShouldCheckWrap=*/true)) {
1010*b5893f02SDimitry Andric         LLVM_DEBUG(
1011*b5893f02SDimitry Andric             dbgs() << "LV: Invalidate candidate interleaved group due to "
1012*b5893f02SDimitry Andric                       "last group member potentially pointer-wrapping.\n");
1013*b5893f02SDimitry Andric         releaseGroup(Group);
1014*b5893f02SDimitry Andric       }
1015*b5893f02SDimitry Andric     } else {
1016*b5893f02SDimitry Andric       // Case 3: A non-reversed interleaved load group with gaps: We need
1017*b5893f02SDimitry Andric       // to execute at least one scalar epilogue iteration. This will ensure
1018*b5893f02SDimitry Andric       // we don't speculatively access memory out-of-bounds. We only need
1019*b5893f02SDimitry Andric       // to look for a member at index factor - 1, since every group must have
1020*b5893f02SDimitry Andric       // a member at index zero.
1021*b5893f02SDimitry Andric       if (Group->isReverse()) {
1022*b5893f02SDimitry Andric         LLVM_DEBUG(
1023*b5893f02SDimitry Andric             dbgs() << "LV: Invalidate candidate interleaved group due to "
1024*b5893f02SDimitry Andric                       "a reverse access with gaps.\n");
1025*b5893f02SDimitry Andric         releaseGroup(Group);
1026*b5893f02SDimitry Andric         continue;
1027*b5893f02SDimitry Andric       }
1028*b5893f02SDimitry Andric       LLVM_DEBUG(
1029*b5893f02SDimitry Andric           dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
1030*b5893f02SDimitry Andric       RequiresScalarEpilogue = true;
1031*b5893f02SDimitry Andric     }
1032*b5893f02SDimitry Andric   }
1033*b5893f02SDimitry Andric }
1034*b5893f02SDimitry Andric 
invalidateGroupsRequiringScalarEpilogue()1035*b5893f02SDimitry Andric void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
1036*b5893f02SDimitry Andric   // If no group had triggered the requirement to create an epilogue loop,
1037*b5893f02SDimitry Andric   // there is nothing to do.
1038*b5893f02SDimitry Andric   if (!requiresScalarEpilogue())
1039*b5893f02SDimitry Andric     return;
1040*b5893f02SDimitry Andric 
1041*b5893f02SDimitry Andric   // Avoid releasing a Group twice.
1042*b5893f02SDimitry Andric   SmallPtrSet<InterleaveGroup<Instruction> *, 4> DelSet;
1043*b5893f02SDimitry Andric   for (auto &I : InterleaveGroupMap) {
1044*b5893f02SDimitry Andric     InterleaveGroup<Instruction> *Group = I.second;
1045*b5893f02SDimitry Andric     if (Group->requiresScalarEpilogue())
1046*b5893f02SDimitry Andric       DelSet.insert(Group);
1047*b5893f02SDimitry Andric   }
1048*b5893f02SDimitry Andric   for (auto *Ptr : DelSet) {
1049*b5893f02SDimitry Andric     LLVM_DEBUG(
1050*b5893f02SDimitry Andric         dbgs()
1051*b5893f02SDimitry Andric         << "LV: Invalidate candidate interleaved group due to gaps that "
1052*b5893f02SDimitry Andric            "require a scalar epilogue (not allowed under optsize) and cannot "
1053*b5893f02SDimitry Andric            "be masked (not enabled). \n");
1054*b5893f02SDimitry Andric     releaseGroup(Ptr);
1055*b5893f02SDimitry Andric   }
1056*b5893f02SDimitry Andric 
1057*b5893f02SDimitry Andric   RequiresScalarEpilogue = false;
1058*b5893f02SDimitry Andric }
1059*b5893f02SDimitry Andric 
1060*b5893f02SDimitry Andric template <typename InstT>
addMetadata(InstT * NewInst) const1061*b5893f02SDimitry Andric void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
1062*b5893f02SDimitry Andric   llvm_unreachable("addMetadata can only be used for Instruction");
1063*b5893f02SDimitry Andric }
1064*b5893f02SDimitry Andric 
1065*b5893f02SDimitry Andric namespace llvm {
1066*b5893f02SDimitry Andric template <>
addMetadata(Instruction * NewInst) const1067*b5893f02SDimitry Andric void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const {
1068*b5893f02SDimitry Andric   SmallVector<Value *, 4> VL;
1069*b5893f02SDimitry Andric   std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
1070*b5893f02SDimitry Andric                  [](std::pair<int, Instruction *> p) { return p.second; });
1071*b5893f02SDimitry Andric   propagateMetadata(NewInst, VL);
1072*b5893f02SDimitry Andric }
1073*b5893f02SDimitry Andric }
1074