1 //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines vectorizer utilities.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/VectorUtils.h"
15 #include "llvm/ADT/EquivalenceClasses.h"
16 #include "llvm/Analysis/DemandedBits.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Analysis/LoopIterator.h"
19 #include "llvm/Analysis/ScalarEvolution.h"
20 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/GetElementPtrTypeIterator.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/IR/Value.h"
28 
29 #define DEBUG_TYPE "vectorutils"
30 
31 using namespace llvm;
32 using namespace llvm::PatternMatch;
33 
34 /// Maximum factor for an interleaved memory access.
35 static cl::opt<unsigned> MaxInterleaveGroupFactor(
36     "max-interleave-group-factor", cl::Hidden,
37     cl::desc("Maximum factor for an interleaved access group (default = 8)"),
38     cl::init(8));
39 
40 /// Return true if all of the intrinsic's arguments and return type are scalars
41 /// for the scalar form of the intrinsic and vectors for the vector form of the
42 /// intrinsic.
43 bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
44   switch (ID) {
45   case Intrinsic::bswap: // Begin integer bit-manipulation.
46   case Intrinsic::bitreverse:
47   case Intrinsic::ctpop:
48   case Intrinsic::ctlz:
49   case Intrinsic::cttz:
50   case Intrinsic::fshl:
51   case Intrinsic::fshr:
52   case Intrinsic::sqrt: // Begin floating-point.
53   case Intrinsic::sin:
54   case Intrinsic::cos:
55   case Intrinsic::exp:
56   case Intrinsic::exp2:
57   case Intrinsic::log:
58   case Intrinsic::log10:
59   case Intrinsic::log2:
60   case Intrinsic::fabs:
61   case Intrinsic::minnum:
62   case Intrinsic::maxnum:
63   case Intrinsic::minimum:
64   case Intrinsic::maximum:
65   case Intrinsic::copysign:
66   case Intrinsic::floor:
67   case Intrinsic::ceil:
68   case Intrinsic::trunc:
69   case Intrinsic::rint:
70   case Intrinsic::nearbyint:
71   case Intrinsic::round:
72   case Intrinsic::pow:
73   case Intrinsic::fma:
74   case Intrinsic::fmuladd:
75   case Intrinsic::powi:
76   case Intrinsic::canonicalize:
77     return true;
78   default:
79     return false;
80   }
81 }
82 
83 /// Identifies if the intrinsic has a scalar operand. It check for
84 /// ctlz,cttz and powi special intrinsics whose argument is scalar.
85 bool llvm::hasVectorInstrinsicScalarOpd(Intrinsic::ID ID,
86                                         unsigned ScalarOpdIdx) {
87   switch (ID) {
88   case Intrinsic::ctlz:
89   case Intrinsic::cttz:
90   case Intrinsic::powi:
91     return (ScalarOpdIdx == 1);
92   default:
93     return false;
94   }
95 }
96 
97 /// Returns intrinsic ID for call.
98 /// For the input call instruction it finds mapping intrinsic and returns
99 /// its ID, in case it does not found it return not_intrinsic.
100 Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI,
101                                                 const TargetLibraryInfo *TLI) {
102   Intrinsic::ID ID = getIntrinsicForCallSite(CI, TLI);
103   if (ID == Intrinsic::not_intrinsic)
104     return Intrinsic::not_intrinsic;
105 
106   if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
107       ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
108       ID == Intrinsic::sideeffect)
109     return ID;
110   return Intrinsic::not_intrinsic;
111 }
112 
113 /// Find the operand of the GEP that should be checked for consecutive
114 /// stores. This ignores trailing indices that have no effect on the final
115 /// pointer.
116 unsigned llvm::getGEPInductionOperand(const GetElementPtrInst *Gep) {
117   const DataLayout &DL = Gep->getModule()->getDataLayout();
118   unsigned LastOperand = Gep->getNumOperands() - 1;
119   unsigned GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
120 
121   // Walk backwards and try to peel off zeros.
122   while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
123     // Find the type we're currently indexing into.
124     gep_type_iterator GEPTI = gep_type_begin(Gep);
125     std::advance(GEPTI, LastOperand - 2);
126 
127     // If it's a type with the same allocation size as the result of the GEP we
128     // can peel off the zero index.
129     if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize)
130       break;
131     --LastOperand;
132   }
133 
134   return LastOperand;
135 }
136 
137 /// If the argument is a GEP, then returns the operand identified by
138 /// getGEPInductionOperand. However, if there is some other non-loop-invariant
139 /// operand, it returns that instead.
140 Value *llvm::stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
141   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
142   if (!GEP)
143     return Ptr;
144 
145   unsigned InductionOperand = getGEPInductionOperand(GEP);
146 
147   // Check that all of the gep indices are uniform except for our induction
148   // operand.
149   for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
150     if (i != InductionOperand &&
151         !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
152       return Ptr;
153   return GEP->getOperand(InductionOperand);
154 }
155 
156 /// If a value has only one user that is a CastInst, return it.
157 Value *llvm::getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
158   Value *UniqueCast = nullptr;
159   for (User *U : Ptr->users()) {
160     CastInst *CI = dyn_cast<CastInst>(U);
161     if (CI && CI->getType() == Ty) {
162       if (!UniqueCast)
163         UniqueCast = CI;
164       else
165         return nullptr;
166     }
167   }
168   return UniqueCast;
169 }
170 
171 /// Get the stride of a pointer access in a loop. Looks for symbolic
172 /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
173 Value *llvm::getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
174   auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
175   if (!PtrTy || PtrTy->isAggregateType())
176     return nullptr;
177 
178   // Try to remove a gep instruction to make the pointer (actually index at this
179   // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
180   // pointer, otherwise, we are analyzing the index.
181   Value *OrigPtr = Ptr;
182 
183   // The size of the pointer access.
184   int64_t PtrAccessSize = 1;
185 
186   Ptr = stripGetElementPtr(Ptr, SE, Lp);
187   const SCEV *V = SE->getSCEV(Ptr);
188 
189   if (Ptr != OrigPtr)
190     // Strip off casts.
191     while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
192       V = C->getOperand();
193 
194   const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
195   if (!S)
196     return nullptr;
197 
198   V = S->getStepRecurrence(*SE);
199   if (!V)
200     return nullptr;
201 
202   // Strip off the size of access multiplication if we are still analyzing the
203   // pointer.
204   if (OrigPtr == Ptr) {
205     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
206       if (M->getOperand(0)->getSCEVType() != scConstant)
207         return nullptr;
208 
209       const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
210 
211       // Huge step value - give up.
212       if (APStepVal.getBitWidth() > 64)
213         return nullptr;
214 
215       int64_t StepVal = APStepVal.getSExtValue();
216       if (PtrAccessSize != StepVal)
217         return nullptr;
218       V = M->getOperand(1);
219     }
220   }
221 
222   // Strip off casts.
223   Type *StripedOffRecurrenceCast = nullptr;
224   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
225     StripedOffRecurrenceCast = C->getType();
226     V = C->getOperand();
227   }
228 
229   // Look for the loop invariant symbolic value.
230   const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
231   if (!U)
232     return nullptr;
233 
234   Value *Stride = U->getValue();
235   if (!Lp->isLoopInvariant(Stride))
236     return nullptr;
237 
238   // If we have stripped off the recurrence cast we have to make sure that we
239   // return the value that is used in this loop so that we can replace it later.
240   if (StripedOffRecurrenceCast)
241     Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
242 
243   return Stride;
244 }
245 
246 /// Given a vector and an element number, see if the scalar value is
247 /// already around as a register, for example if it were inserted then extracted
248 /// from the vector.
249 Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
250   assert(V->getType()->isVectorTy() && "Not looking at a vector?");
251   VectorType *VTy = cast<VectorType>(V->getType());
252   unsigned Width = VTy->getNumElements();
253   if (EltNo >= Width)  // Out of range access.
254     return UndefValue::get(VTy->getElementType());
255 
256   if (Constant *C = dyn_cast<Constant>(V))
257     return C->getAggregateElement(EltNo);
258 
259   if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
260     // If this is an insert to a variable element, we don't know what it is.
261     if (!isa<ConstantInt>(III->getOperand(2)))
262       return nullptr;
263     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
264 
265     // If this is an insert to the element we are looking for, return the
266     // inserted value.
267     if (EltNo == IIElt)
268       return III->getOperand(1);
269 
270     // Otherwise, the insertelement doesn't modify the value, recurse on its
271     // vector input.
272     return findScalarElement(III->getOperand(0), EltNo);
273   }
274 
275   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
276     unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
277     int InEl = SVI->getMaskValue(EltNo);
278     if (InEl < 0)
279       return UndefValue::get(VTy->getElementType());
280     if (InEl < (int)LHSWidth)
281       return findScalarElement(SVI->getOperand(0), InEl);
282     return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
283   }
284 
285   // Extract a value from a vector add operation with a constant zero.
286   // TODO: Use getBinOpIdentity() to generalize this.
287   Value *Val; Constant *C;
288   if (match(V, m_Add(m_Value(Val), m_Constant(C))))
289     if (Constant *Elt = C->getAggregateElement(EltNo))
290       if (Elt->isNullValue())
291         return findScalarElement(Val, EltNo);
292 
293   // Otherwise, we don't know.
294   return nullptr;
295 }
296 
297 /// Get splat value if the input is a splat vector or return nullptr.
298 /// This function is not fully general. It checks only 2 cases:
299 /// the input value is (1) a splat constants vector or (2) a sequence
300 /// of instructions that broadcast a single value into a vector.
301 ///
302 const llvm::Value *llvm::getSplatValue(const Value *V) {
303 
304   if (auto *C = dyn_cast<Constant>(V))
305     if (isa<VectorType>(V->getType()))
306       return C->getSplatValue();
307 
308   auto *ShuffleInst = dyn_cast<ShuffleVectorInst>(V);
309   if (!ShuffleInst)
310     return nullptr;
311   // All-zero (or undef) shuffle mask elements.
312   for (int MaskElt : ShuffleInst->getShuffleMask())
313     if (MaskElt != 0 && MaskElt != -1)
314       return nullptr;
315   // The first shuffle source is 'insertelement' with index 0.
316   auto *InsertEltInst =
317     dyn_cast<InsertElementInst>(ShuffleInst->getOperand(0));
318   if (!InsertEltInst || !isa<ConstantInt>(InsertEltInst->getOperand(2)) ||
319       !cast<ConstantInt>(InsertEltInst->getOperand(2))->isZero())
320     return nullptr;
321 
322   return InsertEltInst->getOperand(1);
323 }
324 
325 MapVector<Instruction *, uint64_t>
326 llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB,
327                                const TargetTransformInfo *TTI) {
328 
329   // DemandedBits will give us every value's live-out bits. But we want
330   // to ensure no extra casts would need to be inserted, so every DAG
331   // of connected values must have the same minimum bitwidth.
332   EquivalenceClasses<Value *> ECs;
333   SmallVector<Value *, 16> Worklist;
334   SmallPtrSet<Value *, 4> Roots;
335   SmallPtrSet<Value *, 16> Visited;
336   DenseMap<Value *, uint64_t> DBits;
337   SmallPtrSet<Instruction *, 4> InstructionSet;
338   MapVector<Instruction *, uint64_t> MinBWs;
339 
340   // Determine the roots. We work bottom-up, from truncs or icmps.
341   bool SeenExtFromIllegalType = false;
342   for (auto *BB : Blocks)
343     for (auto &I : *BB) {
344       InstructionSet.insert(&I);
345 
346       if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
347           !TTI->isTypeLegal(I.getOperand(0)->getType()))
348         SeenExtFromIllegalType = true;
349 
350       // Only deal with non-vector integers up to 64-bits wide.
351       if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
352           !I.getType()->isVectorTy() &&
353           I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
354         // Don't make work for ourselves. If we know the loaded type is legal,
355         // don't add it to the worklist.
356         if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
357           continue;
358 
359         Worklist.push_back(&I);
360         Roots.insert(&I);
361       }
362     }
363   // Early exit.
364   if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
365     return MinBWs;
366 
367   // Now proceed breadth-first, unioning values together.
368   while (!Worklist.empty()) {
369     Value *Val = Worklist.pop_back_val();
370     Value *Leader = ECs.getOrInsertLeaderValue(Val);
371 
372     if (Visited.count(Val))
373       continue;
374     Visited.insert(Val);
375 
376     // Non-instructions terminate a chain successfully.
377     if (!isa<Instruction>(Val))
378       continue;
379     Instruction *I = cast<Instruction>(Val);
380 
381     // If we encounter a type that is larger than 64 bits, we can't represent
382     // it so bail out.
383     if (DB.getDemandedBits(I).getBitWidth() > 64)
384       return MapVector<Instruction *, uint64_t>();
385 
386     uint64_t V = DB.getDemandedBits(I).getZExtValue();
387     DBits[Leader] |= V;
388     DBits[I] = V;
389 
390     // Casts, loads and instructions outside of our range terminate a chain
391     // successfully.
392     if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
393         !InstructionSet.count(I))
394       continue;
395 
396     // Unsafe casts terminate a chain unsuccessfully. We can't do anything
397     // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
398     // transform anything that relies on them.
399     if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
400         !I->getType()->isIntegerTy()) {
401       DBits[Leader] |= ~0ULL;
402       continue;
403     }
404 
405     // We don't modify the types of PHIs. Reductions will already have been
406     // truncated if possible, and inductions' sizes will have been chosen by
407     // indvars.
408     if (isa<PHINode>(I))
409       continue;
410 
411     if (DBits[Leader] == ~0ULL)
412       // All bits demanded, no point continuing.
413       continue;
414 
415     for (Value *O : cast<User>(I)->operands()) {
416       ECs.unionSets(Leader, O);
417       Worklist.push_back(O);
418     }
419   }
420 
421   // Now we've discovered all values, walk them to see if there are
422   // any users we didn't see. If there are, we can't optimize that
423   // chain.
424   for (auto &I : DBits)
425     for (auto *U : I.first->users())
426       if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
427         DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
428 
429   for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
430     uint64_t LeaderDemandedBits = 0;
431     for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
432       LeaderDemandedBits |= DBits[*MI];
433 
434     uint64_t MinBW = (sizeof(LeaderDemandedBits) * 8) -
435                      llvm::countLeadingZeros(LeaderDemandedBits);
436     // Round up to a power of 2
437     if (!isPowerOf2_64((uint64_t)MinBW))
438       MinBW = NextPowerOf2(MinBW);
439 
440     // We don't modify the types of PHIs. Reductions will already have been
441     // truncated if possible, and inductions' sizes will have been chosen by
442     // indvars.
443     // If we are required to shrink a PHI, abandon this entire equivalence class.
444     bool Abort = false;
445     for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
446       if (isa<PHINode>(*MI) && MinBW < (*MI)->getType()->getScalarSizeInBits()) {
447         Abort = true;
448         break;
449       }
450     if (Abort)
451       continue;
452 
453     for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI) {
454       if (!isa<Instruction>(*MI))
455         continue;
456       Type *Ty = (*MI)->getType();
457       if (Roots.count(*MI))
458         Ty = cast<Instruction>(*MI)->getOperand(0)->getType();
459       if (MinBW < Ty->getScalarSizeInBits())
460         MinBWs[cast<Instruction>(*MI)] = MinBW;
461     }
462   }
463 
464   return MinBWs;
465 }
466 
467 /// \returns \p I after propagating metadata from \p VL.
468 Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
469   Instruction *I0 = cast<Instruction>(VL[0]);
470   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
471   I0->getAllMetadataOtherThanDebugLoc(Metadata);
472 
473   for (auto Kind :
474        {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
475         LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
476         LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load}) {
477     MDNode *MD = I0->getMetadata(Kind);
478 
479     for (int J = 1, E = VL.size(); MD && J != E; ++J) {
480       const Instruction *IJ = cast<Instruction>(VL[J]);
481       MDNode *IMD = IJ->getMetadata(Kind);
482       switch (Kind) {
483       case LLVMContext::MD_tbaa:
484         MD = MDNode::getMostGenericTBAA(MD, IMD);
485         break;
486       case LLVMContext::MD_alias_scope:
487         MD = MDNode::getMostGenericAliasScope(MD, IMD);
488         break;
489       case LLVMContext::MD_fpmath:
490         MD = MDNode::getMostGenericFPMath(MD, IMD);
491         break;
492       case LLVMContext::MD_noalias:
493       case LLVMContext::MD_nontemporal:
494       case LLVMContext::MD_invariant_load:
495         MD = MDNode::intersect(MD, IMD);
496         break;
497       default:
498         llvm_unreachable("unhandled metadata");
499       }
500     }
501 
502     Inst->setMetadata(Kind, MD);
503   }
504 
505   return Inst;
506 }
507 
508 Constant *
509 llvm::createBitMaskForGaps(IRBuilder<> &Builder, unsigned VF,
510                            const InterleaveGroup<Instruction> &Group) {
511   // All 1's means mask is not needed.
512   if (Group.getNumMembers() == Group.getFactor())
513     return nullptr;
514 
515   // TODO: support reversed access.
516   assert(!Group.isReverse() && "Reversed group not supported.");
517 
518   SmallVector<Constant *, 16> Mask;
519   for (unsigned i = 0; i < VF; i++)
520     for (unsigned j = 0; j < Group.getFactor(); ++j) {
521       unsigned HasMember = Group.getMember(j) ? 1 : 0;
522       Mask.push_back(Builder.getInt1(HasMember));
523     }
524 
525   return ConstantVector::get(Mask);
526 }
527 
528 Constant *llvm::createReplicatedMask(IRBuilder<> &Builder,
529                                      unsigned ReplicationFactor, unsigned VF) {
530   SmallVector<Constant *, 16> MaskVec;
531   for (unsigned i = 0; i < VF; i++)
532     for (unsigned j = 0; j < ReplicationFactor; j++)
533       MaskVec.push_back(Builder.getInt32(i));
534 
535   return ConstantVector::get(MaskVec);
536 }
537 
538 Constant *llvm::createInterleaveMask(IRBuilder<> &Builder, unsigned VF,
539                                      unsigned NumVecs) {
540   SmallVector<Constant *, 16> Mask;
541   for (unsigned i = 0; i < VF; i++)
542     for (unsigned j = 0; j < NumVecs; j++)
543       Mask.push_back(Builder.getInt32(j * VF + i));
544 
545   return ConstantVector::get(Mask);
546 }
547 
548 Constant *llvm::createStrideMask(IRBuilder<> &Builder, unsigned Start,
549                                  unsigned Stride, unsigned VF) {
550   SmallVector<Constant *, 16> Mask;
551   for (unsigned i = 0; i < VF; i++)
552     Mask.push_back(Builder.getInt32(Start + i * Stride));
553 
554   return ConstantVector::get(Mask);
555 }
556 
557 Constant *llvm::createSequentialMask(IRBuilder<> &Builder, unsigned Start,
558                                      unsigned NumInts, unsigned NumUndefs) {
559   SmallVector<Constant *, 16> Mask;
560   for (unsigned i = 0; i < NumInts; i++)
561     Mask.push_back(Builder.getInt32(Start + i));
562 
563   Constant *Undef = UndefValue::get(Builder.getInt32Ty());
564   for (unsigned i = 0; i < NumUndefs; i++)
565     Mask.push_back(Undef);
566 
567   return ConstantVector::get(Mask);
568 }
569 
570 /// A helper function for concatenating vectors. This function concatenates two
571 /// vectors having the same element type. If the second vector has fewer
572 /// elements than the first, it is padded with undefs.
573 static Value *concatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
574                                     Value *V2) {
575   VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
576   VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
577   assert(VecTy1 && VecTy2 &&
578          VecTy1->getScalarType() == VecTy2->getScalarType() &&
579          "Expect two vectors with the same element type");
580 
581   unsigned NumElts1 = VecTy1->getNumElements();
582   unsigned NumElts2 = VecTy2->getNumElements();
583   assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
584 
585   if (NumElts1 > NumElts2) {
586     // Extend with UNDEFs.
587     Constant *ExtMask =
588         createSequentialMask(Builder, 0, NumElts2, NumElts1 - NumElts2);
589     V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
590   }
591 
592   Constant *Mask = createSequentialMask(Builder, 0, NumElts1 + NumElts2, 0);
593   return Builder.CreateShuffleVector(V1, V2, Mask);
594 }
595 
596 Value *llvm::concatenateVectors(IRBuilder<> &Builder, ArrayRef<Value *> Vecs) {
597   unsigned NumVecs = Vecs.size();
598   assert(NumVecs > 1 && "Should be at least two vectors");
599 
600   SmallVector<Value *, 8> ResList;
601   ResList.append(Vecs.begin(), Vecs.end());
602   do {
603     SmallVector<Value *, 8> TmpList;
604     for (unsigned i = 0; i < NumVecs - 1; i += 2) {
605       Value *V0 = ResList[i], *V1 = ResList[i + 1];
606       assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
607              "Only the last vector may have a different type");
608 
609       TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
610     }
611 
612     // Push the last vector if the total number of vectors is odd.
613     if (NumVecs % 2 != 0)
614       TmpList.push_back(ResList[NumVecs - 1]);
615 
616     ResList = TmpList;
617     NumVecs = ResList.size();
618   } while (NumVecs > 1);
619 
620   return ResList[0];
621 }
622 
623 bool InterleavedAccessInfo::isStrided(int Stride) {
624   unsigned Factor = std::abs(Stride);
625   return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
626 }
627 
628 void InterleavedAccessInfo::collectConstStrideAccesses(
629     MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
630     const ValueToValueMap &Strides) {
631   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
632 
633   // Since it's desired that the load/store instructions be maintained in
634   // "program order" for the interleaved access analysis, we have to visit the
635   // blocks in the loop in reverse postorder (i.e., in a topological order).
636   // Such an ordering will ensure that any load/store that may be executed
637   // before a second load/store will precede the second load/store in
638   // AccessStrideInfo.
639   LoopBlocksDFS DFS(TheLoop);
640   DFS.perform(LI);
641   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
642     for (auto &I : *BB) {
643       auto *LI = dyn_cast<LoadInst>(&I);
644       auto *SI = dyn_cast<StoreInst>(&I);
645       if (!LI && !SI)
646         continue;
647 
648       Value *Ptr = getLoadStorePointerOperand(&I);
649       // We don't check wrapping here because we don't know yet if Ptr will be
650       // part of a full group or a group with gaps. Checking wrapping for all
651       // pointers (even those that end up in groups with no gaps) will be overly
652       // conservative. For full groups, wrapping should be ok since if we would
653       // wrap around the address space we would do a memory access at nullptr
654       // even without the transformation. The wrapping checks are therefore
655       // deferred until after we've formed the interleaved groups.
656       int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
657                                     /*Assume=*/true, /*ShouldCheckWrap=*/false);
658 
659       const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
660       PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
661       uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
662 
663       // An alignment of 0 means target ABI alignment.
664       unsigned Align = getLoadStoreAlignment(&I);
665       if (!Align)
666         Align = DL.getABITypeAlignment(PtrTy->getElementType());
667 
668       AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
669     }
670 }
671 
672 // Analyze interleaved accesses and collect them into interleaved load and
673 // store groups.
674 //
675 // When generating code for an interleaved load group, we effectively hoist all
676 // loads in the group to the location of the first load in program order. When
677 // generating code for an interleaved store group, we sink all stores to the
678 // location of the last store. This code motion can change the order of load
679 // and store instructions and may break dependences.
680 //
681 // The code generation strategy mentioned above ensures that we won't violate
682 // any write-after-read (WAR) dependences.
683 //
684 // E.g., for the WAR dependence:  a = A[i];      // (1)
685 //                                A[i] = b;      // (2)
686 //
687 // The store group of (2) is always inserted at or below (2), and the load
688 // group of (1) is always inserted at or above (1). Thus, the instructions will
689 // never be reordered. All other dependences are checked to ensure the
690 // correctness of the instruction reordering.
691 //
692 // The algorithm visits all memory accesses in the loop in bottom-up program
693 // order. Program order is established by traversing the blocks in the loop in
694 // reverse postorder when collecting the accesses.
695 //
696 // We visit the memory accesses in bottom-up order because it can simplify the
697 // construction of store groups in the presence of write-after-write (WAW)
698 // dependences.
699 //
700 // E.g., for the WAW dependence:  A[i] = a;      // (1)
701 //                                A[i] = b;      // (2)
702 //                                A[i + 1] = c;  // (3)
703 //
704 // We will first create a store group with (3) and (2). (1) can't be added to
705 // this group because it and (2) are dependent. However, (1) can be grouped
706 // with other accesses that may precede it in program order. Note that a
707 // bottom-up order does not imply that WAW dependences should not be checked.
708 void InterleavedAccessInfo::analyzeInterleaving(
709                                  bool EnablePredicatedInterleavedMemAccesses) {
710   LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
711   const ValueToValueMap &Strides = LAI->getSymbolicStrides();
712 
713   // Holds all accesses with a constant stride.
714   MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
715   collectConstStrideAccesses(AccessStrideInfo, Strides);
716 
717   if (AccessStrideInfo.empty())
718     return;
719 
720   // Collect the dependences in the loop.
721   collectDependences();
722 
723   // Holds all interleaved store groups temporarily.
724   SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups;
725   // Holds all interleaved load groups temporarily.
726   SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups;
727 
728   // Search in bottom-up program order for pairs of accesses (A and B) that can
729   // form interleaved load or store groups. In the algorithm below, access A
730   // precedes access B in program order. We initialize a group for B in the
731   // outer loop of the algorithm, and then in the inner loop, we attempt to
732   // insert each A into B's group if:
733   //
734   //  1. A and B have the same stride,
735   //  2. A and B have the same memory object size, and
736   //  3. A belongs in B's group according to its distance from B.
737   //
738   // Special care is taken to ensure group formation will not break any
739   // dependences.
740   for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
741        BI != E; ++BI) {
742     Instruction *B = BI->first;
743     StrideDescriptor DesB = BI->second;
744 
745     // Initialize a group for B if it has an allowable stride. Even if we don't
746     // create a group for B, we continue with the bottom-up algorithm to ensure
747     // we don't break any of B's dependences.
748     InterleaveGroup<Instruction> *Group = nullptr;
749     if (isStrided(DesB.Stride) &&
750         (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
751       Group = getInterleaveGroup(B);
752       if (!Group) {
753         LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
754                           << '\n');
755         Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
756       }
757       if (B->mayWriteToMemory())
758         StoreGroups.insert(Group);
759       else
760         LoadGroups.insert(Group);
761     }
762 
763     for (auto AI = std::next(BI); AI != E; ++AI) {
764       Instruction *A = AI->first;
765       StrideDescriptor DesA = AI->second;
766 
767       // Our code motion strategy implies that we can't have dependences
768       // between accesses in an interleaved group and other accesses located
769       // between the first and last member of the group. Note that this also
770       // means that a group can't have more than one member at a given offset.
771       // The accesses in a group can have dependences with other accesses, but
772       // we must ensure we don't extend the boundaries of the group such that
773       // we encompass those dependent accesses.
774       //
775       // For example, assume we have the sequence of accesses shown below in a
776       // stride-2 loop:
777       //
778       //  (1, 2) is a group | A[i]   = a;  // (1)
779       //                    | A[i-1] = b;  // (2) |
780       //                      A[i-3] = c;  // (3)
781       //                      A[i]   = d;  // (4) | (2, 4) is not a group
782       //
783       // Because accesses (2) and (3) are dependent, we can group (2) with (1)
784       // but not with (4). If we did, the dependent access (3) would be within
785       // the boundaries of the (2, 4) group.
786       if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
787         // If a dependence exists and A is already in a group, we know that A
788         // must be a store since A precedes B and WAR dependences are allowed.
789         // Thus, A would be sunk below B. We release A's group to prevent this
790         // illegal code motion. A will then be free to form another group with
791         // instructions that precede it.
792         if (isInterleaved(A)) {
793           InterleaveGroup<Instruction> *StoreGroup = getInterleaveGroup(A);
794           StoreGroups.remove(StoreGroup);
795           releaseGroup(StoreGroup);
796         }
797 
798         // If a dependence exists and A is not already in a group (or it was
799         // and we just released it), B might be hoisted above A (if B is a
800         // load) or another store might be sunk below A (if B is a store). In
801         // either case, we can't add additional instructions to B's group. B
802         // will only form a group with instructions that it precedes.
803         break;
804       }
805 
806       // At this point, we've checked for illegal code motion. If either A or B
807       // isn't strided, there's nothing left to do.
808       if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
809         continue;
810 
811       // Ignore A if it's already in a group or isn't the same kind of memory
812       // operation as B.
813       // Note that mayReadFromMemory() isn't mutually exclusive to
814       // mayWriteToMemory in the case of atomic loads. We shouldn't see those
815       // here, canVectorizeMemory() should have returned false - except for the
816       // case we asked for optimization remarks.
817       if (isInterleaved(A) ||
818           (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
819           (A->mayWriteToMemory() != B->mayWriteToMemory()))
820         continue;
821 
822       // Check rules 1 and 2. Ignore A if its stride or size is different from
823       // that of B.
824       if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
825         continue;
826 
827       // Ignore A if the memory object of A and B don't belong to the same
828       // address space
829       if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
830         continue;
831 
832       // Calculate the distance from A to B.
833       const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
834           PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
835       if (!DistToB)
836         continue;
837       int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
838 
839       // Check rule 3. Ignore A if its distance to B is not a multiple of the
840       // size.
841       if (DistanceToB % static_cast<int64_t>(DesB.Size))
842         continue;
843 
844       // All members of a predicated interleave-group must have the same predicate,
845       // and currently must reside in the same BB.
846       BasicBlock *BlockA = A->getParent();
847       BasicBlock *BlockB = B->getParent();
848       if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
849           (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
850         continue;
851 
852       // The index of A is the index of B plus A's distance to B in multiples
853       // of the size.
854       int IndexA =
855           Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
856 
857       // Try to insert A into B's group.
858       if (Group->insertMember(A, IndexA, DesA.Align)) {
859         LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
860                           << "    into the interleave group with" << *B
861                           << '\n');
862         InterleaveGroupMap[A] = Group;
863 
864         // Set the first load in program order as the insert position.
865         if (A->mayReadFromMemory())
866           Group->setInsertPos(A);
867       }
868     } // Iteration over A accesses.
869   }   // Iteration over B accesses.
870 
871   // Remove interleaved store groups with gaps.
872   for (auto *Group : StoreGroups)
873     if (Group->getNumMembers() != Group->getFactor()) {
874       LLVM_DEBUG(
875           dbgs() << "LV: Invalidate candidate interleaved store group due "
876                     "to gaps.\n");
877       releaseGroup(Group);
878     }
879   // Remove interleaved groups with gaps (currently only loads) whose memory
880   // accesses may wrap around. We have to revisit the getPtrStride analysis,
881   // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
882   // not check wrapping (see documentation there).
883   // FORNOW we use Assume=false;
884   // TODO: Change to Assume=true but making sure we don't exceed the threshold
885   // of runtime SCEV assumptions checks (thereby potentially failing to
886   // vectorize altogether).
887   // Additional optional optimizations:
888   // TODO: If we are peeling the loop and we know that the first pointer doesn't
889   // wrap then we can deduce that all pointers in the group don't wrap.
890   // This means that we can forcefully peel the loop in order to only have to
891   // check the first pointer for no-wrap. When we'll change to use Assume=true
892   // we'll only need at most one runtime check per interleaved group.
893   for (auto *Group : LoadGroups) {
894     // Case 1: A full group. Can Skip the checks; For full groups, if the wide
895     // load would wrap around the address space we would do a memory access at
896     // nullptr even without the transformation.
897     if (Group->getNumMembers() == Group->getFactor())
898       continue;
899 
900     // Case 2: If first and last members of the group don't wrap this implies
901     // that all the pointers in the group don't wrap.
902     // So we check only group member 0 (which is always guaranteed to exist),
903     // and group member Factor - 1; If the latter doesn't exist we rely on
904     // peeling (if it is a non-reveresed accsess -- see Case 3).
905     Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0));
906     if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
907                       /*ShouldCheckWrap=*/true)) {
908       LLVM_DEBUG(
909           dbgs() << "LV: Invalidate candidate interleaved group due to "
910                     "first group member potentially pointer-wrapping.\n");
911       releaseGroup(Group);
912       continue;
913     }
914     Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
915     if (LastMember) {
916       Value *LastMemberPtr = getLoadStorePointerOperand(LastMember);
917       if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
918                         /*ShouldCheckWrap=*/true)) {
919         LLVM_DEBUG(
920             dbgs() << "LV: Invalidate candidate interleaved group due to "
921                       "last group member potentially pointer-wrapping.\n");
922         releaseGroup(Group);
923       }
924     } else {
925       // Case 3: A non-reversed interleaved load group with gaps: We need
926       // to execute at least one scalar epilogue iteration. This will ensure
927       // we don't speculatively access memory out-of-bounds. We only need
928       // to look for a member at index factor - 1, since every group must have
929       // a member at index zero.
930       if (Group->isReverse()) {
931         LLVM_DEBUG(
932             dbgs() << "LV: Invalidate candidate interleaved group due to "
933                       "a reverse access with gaps.\n");
934         releaseGroup(Group);
935         continue;
936       }
937       LLVM_DEBUG(
938           dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
939       RequiresScalarEpilogue = true;
940     }
941   }
942 }
943 
944 void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
945   // If no group had triggered the requirement to create an epilogue loop,
946   // there is nothing to do.
947   if (!requiresScalarEpilogue())
948     return;
949 
950   // Avoid releasing a Group twice.
951   SmallPtrSet<InterleaveGroup<Instruction> *, 4> DelSet;
952   for (auto &I : InterleaveGroupMap) {
953     InterleaveGroup<Instruction> *Group = I.second;
954     if (Group->requiresScalarEpilogue())
955       DelSet.insert(Group);
956   }
957   for (auto *Ptr : DelSet) {
958     LLVM_DEBUG(
959         dbgs()
960         << "LV: Invalidate candidate interleaved group due to gaps that "
961            "require a scalar epilogue (not allowed under optsize) and cannot "
962            "be masked (not enabled). \n");
963     releaseGroup(Ptr);
964   }
965 
966   RequiresScalarEpilogue = false;
967 }
968 
969 template <typename InstT>
970 void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
971   llvm_unreachable("addMetadata can only be used for Instruction");
972 }
973 
974 namespace llvm {
975 template <>
976 void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const {
977   SmallVector<Value *, 4> VL;
978   std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
979                  [](std::pair<int, Instruction *> p) { return p.second; });
980   propagateMetadata(NewInst, VL);
981 }
982 }
983