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 /// Add all access groups in @p AccGroups to @p List.
468 template <typename ListT>
469 static void addToAccessGroupList(ListT &List, MDNode *AccGroups) {
470   // Interpret an access group as a list containing itself.
471   if (AccGroups->getNumOperands() == 0) {
472     assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group");
473     List.insert(AccGroups);
474     return;
475   }
476 
477   for (auto &AccGroupListOp : AccGroups->operands()) {
478     auto *Item = cast<MDNode>(AccGroupListOp.get());
479     assert(isValidAsAccessGroup(Item) && "List item must be an access group");
480     List.insert(Item);
481   }
482 }
483 
484 MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) {
485   if (!AccGroups1)
486     return AccGroups2;
487   if (!AccGroups2)
488     return AccGroups1;
489   if (AccGroups1 == AccGroups2)
490     return AccGroups1;
491 
492   SmallSetVector<Metadata *, 4> Union;
493   addToAccessGroupList(Union, AccGroups1);
494   addToAccessGroupList(Union, AccGroups2);
495 
496   if (Union.size() == 0)
497     return nullptr;
498   if (Union.size() == 1)
499     return cast<MDNode>(Union.front());
500 
501   LLVMContext &Ctx = AccGroups1->getContext();
502   return MDNode::get(Ctx, Union.getArrayRef());
503 }
504 
505 MDNode *llvm::intersectAccessGroups(const Instruction *Inst1,
506                                     const Instruction *Inst2) {
507   bool MayAccessMem1 = Inst1->mayReadOrWriteMemory();
508   bool MayAccessMem2 = Inst2->mayReadOrWriteMemory();
509 
510   if (!MayAccessMem1 && !MayAccessMem2)
511     return nullptr;
512   if (!MayAccessMem1)
513     return Inst2->getMetadata(LLVMContext::MD_access_group);
514   if (!MayAccessMem2)
515     return Inst1->getMetadata(LLVMContext::MD_access_group);
516 
517   MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group);
518   MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group);
519   if (!MD1 || !MD2)
520     return nullptr;
521   if (MD1 == MD2)
522     return MD1;
523 
524   // Use set for scalable 'contains' check.
525   SmallPtrSet<Metadata *, 4> AccGroupSet2;
526   addToAccessGroupList(AccGroupSet2, MD2);
527 
528   SmallVector<Metadata *, 4> Intersection;
529   if (MD1->getNumOperands() == 0) {
530     assert(isValidAsAccessGroup(MD1) && "Node must be an access group");
531     if (AccGroupSet2.count(MD1))
532       Intersection.push_back(MD1);
533   } else {
534     for (const MDOperand &Node : MD1->operands()) {
535       auto *Item = cast<MDNode>(Node.get());
536       assert(isValidAsAccessGroup(Item) && "List item must be an access group");
537       if (AccGroupSet2.count(Item))
538         Intersection.push_back(Item);
539     }
540   }
541 
542   if (Intersection.size() == 0)
543     return nullptr;
544   if (Intersection.size() == 1)
545     return cast<MDNode>(Intersection.front());
546 
547   LLVMContext &Ctx = Inst1->getContext();
548   return MDNode::get(Ctx, Intersection);
549 }
550 
551 /// \returns \p I after propagating metadata from \p VL.
552 Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
553   Instruction *I0 = cast<Instruction>(VL[0]);
554   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
555   I0->getAllMetadataOtherThanDebugLoc(Metadata);
556 
557   for (auto Kind : {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
558                     LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
559                     LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load,
560                     LLVMContext::MD_access_group}) {
561     MDNode *MD = I0->getMetadata(Kind);
562 
563     for (int J = 1, E = VL.size(); MD && J != E; ++J) {
564       const Instruction *IJ = cast<Instruction>(VL[J]);
565       MDNode *IMD = IJ->getMetadata(Kind);
566       switch (Kind) {
567       case LLVMContext::MD_tbaa:
568         MD = MDNode::getMostGenericTBAA(MD, IMD);
569         break;
570       case LLVMContext::MD_alias_scope:
571         MD = MDNode::getMostGenericAliasScope(MD, IMD);
572         break;
573       case LLVMContext::MD_fpmath:
574         MD = MDNode::getMostGenericFPMath(MD, IMD);
575         break;
576       case LLVMContext::MD_noalias:
577       case LLVMContext::MD_nontemporal:
578       case LLVMContext::MD_invariant_load:
579         MD = MDNode::intersect(MD, IMD);
580         break;
581       case LLVMContext::MD_access_group:
582         MD = intersectAccessGroups(Inst, IJ);
583         break;
584       default:
585         llvm_unreachable("unhandled metadata");
586       }
587     }
588 
589     Inst->setMetadata(Kind, MD);
590   }
591 
592   return Inst;
593 }
594 
595 Constant *
596 llvm::createBitMaskForGaps(IRBuilder<> &Builder, unsigned VF,
597                            const InterleaveGroup<Instruction> &Group) {
598   // All 1's means mask is not needed.
599   if (Group.getNumMembers() == Group.getFactor())
600     return nullptr;
601 
602   // TODO: support reversed access.
603   assert(!Group.isReverse() && "Reversed group not supported.");
604 
605   SmallVector<Constant *, 16> Mask;
606   for (unsigned i = 0; i < VF; i++)
607     for (unsigned j = 0; j < Group.getFactor(); ++j) {
608       unsigned HasMember = Group.getMember(j) ? 1 : 0;
609       Mask.push_back(Builder.getInt1(HasMember));
610     }
611 
612   return ConstantVector::get(Mask);
613 }
614 
615 Constant *llvm::createReplicatedMask(IRBuilder<> &Builder,
616                                      unsigned ReplicationFactor, unsigned VF) {
617   SmallVector<Constant *, 16> MaskVec;
618   for (unsigned i = 0; i < VF; i++)
619     for (unsigned j = 0; j < ReplicationFactor; j++)
620       MaskVec.push_back(Builder.getInt32(i));
621 
622   return ConstantVector::get(MaskVec);
623 }
624 
625 Constant *llvm::createInterleaveMask(IRBuilder<> &Builder, unsigned VF,
626                                      unsigned NumVecs) {
627   SmallVector<Constant *, 16> Mask;
628   for (unsigned i = 0; i < VF; i++)
629     for (unsigned j = 0; j < NumVecs; j++)
630       Mask.push_back(Builder.getInt32(j * VF + i));
631 
632   return ConstantVector::get(Mask);
633 }
634 
635 Constant *llvm::createStrideMask(IRBuilder<> &Builder, unsigned Start,
636                                  unsigned Stride, unsigned VF) {
637   SmallVector<Constant *, 16> Mask;
638   for (unsigned i = 0; i < VF; i++)
639     Mask.push_back(Builder.getInt32(Start + i * Stride));
640 
641   return ConstantVector::get(Mask);
642 }
643 
644 Constant *llvm::createSequentialMask(IRBuilder<> &Builder, unsigned Start,
645                                      unsigned NumInts, unsigned NumUndefs) {
646   SmallVector<Constant *, 16> Mask;
647   for (unsigned i = 0; i < NumInts; i++)
648     Mask.push_back(Builder.getInt32(Start + i));
649 
650   Constant *Undef = UndefValue::get(Builder.getInt32Ty());
651   for (unsigned i = 0; i < NumUndefs; i++)
652     Mask.push_back(Undef);
653 
654   return ConstantVector::get(Mask);
655 }
656 
657 /// A helper function for concatenating vectors. This function concatenates two
658 /// vectors having the same element type. If the second vector has fewer
659 /// elements than the first, it is padded with undefs.
660 static Value *concatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
661                                     Value *V2) {
662   VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
663   VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
664   assert(VecTy1 && VecTy2 &&
665          VecTy1->getScalarType() == VecTy2->getScalarType() &&
666          "Expect two vectors with the same element type");
667 
668   unsigned NumElts1 = VecTy1->getNumElements();
669   unsigned NumElts2 = VecTy2->getNumElements();
670   assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
671 
672   if (NumElts1 > NumElts2) {
673     // Extend with UNDEFs.
674     Constant *ExtMask =
675         createSequentialMask(Builder, 0, NumElts2, NumElts1 - NumElts2);
676     V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
677   }
678 
679   Constant *Mask = createSequentialMask(Builder, 0, NumElts1 + NumElts2, 0);
680   return Builder.CreateShuffleVector(V1, V2, Mask);
681 }
682 
683 Value *llvm::concatenateVectors(IRBuilder<> &Builder, ArrayRef<Value *> Vecs) {
684   unsigned NumVecs = Vecs.size();
685   assert(NumVecs > 1 && "Should be at least two vectors");
686 
687   SmallVector<Value *, 8> ResList;
688   ResList.append(Vecs.begin(), Vecs.end());
689   do {
690     SmallVector<Value *, 8> TmpList;
691     for (unsigned i = 0; i < NumVecs - 1; i += 2) {
692       Value *V0 = ResList[i], *V1 = ResList[i + 1];
693       assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
694              "Only the last vector may have a different type");
695 
696       TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
697     }
698 
699     // Push the last vector if the total number of vectors is odd.
700     if (NumVecs % 2 != 0)
701       TmpList.push_back(ResList[NumVecs - 1]);
702 
703     ResList = TmpList;
704     NumVecs = ResList.size();
705   } while (NumVecs > 1);
706 
707   return ResList[0];
708 }
709 
710 bool InterleavedAccessInfo::isStrided(int Stride) {
711   unsigned Factor = std::abs(Stride);
712   return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
713 }
714 
715 void InterleavedAccessInfo::collectConstStrideAccesses(
716     MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
717     const ValueToValueMap &Strides) {
718   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
719 
720   // Since it's desired that the load/store instructions be maintained in
721   // "program order" for the interleaved access analysis, we have to visit the
722   // blocks in the loop in reverse postorder (i.e., in a topological order).
723   // Such an ordering will ensure that any load/store that may be executed
724   // before a second load/store will precede the second load/store in
725   // AccessStrideInfo.
726   LoopBlocksDFS DFS(TheLoop);
727   DFS.perform(LI);
728   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
729     for (auto &I : *BB) {
730       auto *LI = dyn_cast<LoadInst>(&I);
731       auto *SI = dyn_cast<StoreInst>(&I);
732       if (!LI && !SI)
733         continue;
734 
735       Value *Ptr = getLoadStorePointerOperand(&I);
736       // We don't check wrapping here because we don't know yet if Ptr will be
737       // part of a full group or a group with gaps. Checking wrapping for all
738       // pointers (even those that end up in groups with no gaps) will be overly
739       // conservative. For full groups, wrapping should be ok since if we would
740       // wrap around the address space we would do a memory access at nullptr
741       // even without the transformation. The wrapping checks are therefore
742       // deferred until after we've formed the interleaved groups.
743       int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
744                                     /*Assume=*/true, /*ShouldCheckWrap=*/false);
745 
746       const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
747       PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
748       uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
749 
750       // An alignment of 0 means target ABI alignment.
751       unsigned Align = getLoadStoreAlignment(&I);
752       if (!Align)
753         Align = DL.getABITypeAlignment(PtrTy->getElementType());
754 
755       AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
756     }
757 }
758 
759 // Analyze interleaved accesses and collect them into interleaved load and
760 // store groups.
761 //
762 // When generating code for an interleaved load group, we effectively hoist all
763 // loads in the group to the location of the first load in program order. When
764 // generating code for an interleaved store group, we sink all stores to the
765 // location of the last store. This code motion can change the order of load
766 // and store instructions and may break dependences.
767 //
768 // The code generation strategy mentioned above ensures that we won't violate
769 // any write-after-read (WAR) dependences.
770 //
771 // E.g., for the WAR dependence:  a = A[i];      // (1)
772 //                                A[i] = b;      // (2)
773 //
774 // The store group of (2) is always inserted at or below (2), and the load
775 // group of (1) is always inserted at or above (1). Thus, the instructions will
776 // never be reordered. All other dependences are checked to ensure the
777 // correctness of the instruction reordering.
778 //
779 // The algorithm visits all memory accesses in the loop in bottom-up program
780 // order. Program order is established by traversing the blocks in the loop in
781 // reverse postorder when collecting the accesses.
782 //
783 // We visit the memory accesses in bottom-up order because it can simplify the
784 // construction of store groups in the presence of write-after-write (WAW)
785 // dependences.
786 //
787 // E.g., for the WAW dependence:  A[i] = a;      // (1)
788 //                                A[i] = b;      // (2)
789 //                                A[i + 1] = c;  // (3)
790 //
791 // We will first create a store group with (3) and (2). (1) can't be added to
792 // this group because it and (2) are dependent. However, (1) can be grouped
793 // with other accesses that may precede it in program order. Note that a
794 // bottom-up order does not imply that WAW dependences should not be checked.
795 void InterleavedAccessInfo::analyzeInterleaving(
796                                  bool EnablePredicatedInterleavedMemAccesses) {
797   LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
798   const ValueToValueMap &Strides = LAI->getSymbolicStrides();
799 
800   // Holds all accesses with a constant stride.
801   MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
802   collectConstStrideAccesses(AccessStrideInfo, Strides);
803 
804   if (AccessStrideInfo.empty())
805     return;
806 
807   // Collect the dependences in the loop.
808   collectDependences();
809 
810   // Holds all interleaved store groups temporarily.
811   SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups;
812   // Holds all interleaved load groups temporarily.
813   SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups;
814 
815   // Search in bottom-up program order for pairs of accesses (A and B) that can
816   // form interleaved load or store groups. In the algorithm below, access A
817   // precedes access B in program order. We initialize a group for B in the
818   // outer loop of the algorithm, and then in the inner loop, we attempt to
819   // insert each A into B's group if:
820   //
821   //  1. A and B have the same stride,
822   //  2. A and B have the same memory object size, and
823   //  3. A belongs in B's group according to its distance from B.
824   //
825   // Special care is taken to ensure group formation will not break any
826   // dependences.
827   for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
828        BI != E; ++BI) {
829     Instruction *B = BI->first;
830     StrideDescriptor DesB = BI->second;
831 
832     // Initialize a group for B if it has an allowable stride. Even if we don't
833     // create a group for B, we continue with the bottom-up algorithm to ensure
834     // we don't break any of B's dependences.
835     InterleaveGroup<Instruction> *Group = nullptr;
836     if (isStrided(DesB.Stride) &&
837         (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
838       Group = getInterleaveGroup(B);
839       if (!Group) {
840         LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
841                           << '\n');
842         Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
843       }
844       if (B->mayWriteToMemory())
845         StoreGroups.insert(Group);
846       else
847         LoadGroups.insert(Group);
848     }
849 
850     for (auto AI = std::next(BI); AI != E; ++AI) {
851       Instruction *A = AI->first;
852       StrideDescriptor DesA = AI->second;
853 
854       // Our code motion strategy implies that we can't have dependences
855       // between accesses in an interleaved group and other accesses located
856       // between the first and last member of the group. Note that this also
857       // means that a group can't have more than one member at a given offset.
858       // The accesses in a group can have dependences with other accesses, but
859       // we must ensure we don't extend the boundaries of the group such that
860       // we encompass those dependent accesses.
861       //
862       // For example, assume we have the sequence of accesses shown below in a
863       // stride-2 loop:
864       //
865       //  (1, 2) is a group | A[i]   = a;  // (1)
866       //                    | A[i-1] = b;  // (2) |
867       //                      A[i-3] = c;  // (3)
868       //                      A[i]   = d;  // (4) | (2, 4) is not a group
869       //
870       // Because accesses (2) and (3) are dependent, we can group (2) with (1)
871       // but not with (4). If we did, the dependent access (3) would be within
872       // the boundaries of the (2, 4) group.
873       if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
874         // If a dependence exists and A is already in a group, we know that A
875         // must be a store since A precedes B and WAR dependences are allowed.
876         // Thus, A would be sunk below B. We release A's group to prevent this
877         // illegal code motion. A will then be free to form another group with
878         // instructions that precede it.
879         if (isInterleaved(A)) {
880           InterleaveGroup<Instruction> *StoreGroup = getInterleaveGroup(A);
881           StoreGroups.remove(StoreGroup);
882           releaseGroup(StoreGroup);
883         }
884 
885         // If a dependence exists and A is not already in a group (or it was
886         // and we just released it), B might be hoisted above A (if B is a
887         // load) or another store might be sunk below A (if B is a store). In
888         // either case, we can't add additional instructions to B's group. B
889         // will only form a group with instructions that it precedes.
890         break;
891       }
892 
893       // At this point, we've checked for illegal code motion. If either A or B
894       // isn't strided, there's nothing left to do.
895       if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
896         continue;
897 
898       // Ignore A if it's already in a group or isn't the same kind of memory
899       // operation as B.
900       // Note that mayReadFromMemory() isn't mutually exclusive to
901       // mayWriteToMemory in the case of atomic loads. We shouldn't see those
902       // here, canVectorizeMemory() should have returned false - except for the
903       // case we asked for optimization remarks.
904       if (isInterleaved(A) ||
905           (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
906           (A->mayWriteToMemory() != B->mayWriteToMemory()))
907         continue;
908 
909       // Check rules 1 and 2. Ignore A if its stride or size is different from
910       // that of B.
911       if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
912         continue;
913 
914       // Ignore A if the memory object of A and B don't belong to the same
915       // address space
916       if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
917         continue;
918 
919       // Calculate the distance from A to B.
920       const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
921           PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
922       if (!DistToB)
923         continue;
924       int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
925 
926       // Check rule 3. Ignore A if its distance to B is not a multiple of the
927       // size.
928       if (DistanceToB % static_cast<int64_t>(DesB.Size))
929         continue;
930 
931       // All members of a predicated interleave-group must have the same predicate,
932       // and currently must reside in the same BB.
933       BasicBlock *BlockA = A->getParent();
934       BasicBlock *BlockB = B->getParent();
935       if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
936           (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
937         continue;
938 
939       // The index of A is the index of B plus A's distance to B in multiples
940       // of the size.
941       int IndexA =
942           Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
943 
944       // Try to insert A into B's group.
945       if (Group->insertMember(A, IndexA, DesA.Align)) {
946         LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
947                           << "    into the interleave group with" << *B
948                           << '\n');
949         InterleaveGroupMap[A] = Group;
950 
951         // Set the first load in program order as the insert position.
952         if (A->mayReadFromMemory())
953           Group->setInsertPos(A);
954       }
955     } // Iteration over A accesses.
956   }   // Iteration over B accesses.
957 
958   // Remove interleaved store groups with gaps.
959   for (auto *Group : StoreGroups)
960     if (Group->getNumMembers() != Group->getFactor()) {
961       LLVM_DEBUG(
962           dbgs() << "LV: Invalidate candidate interleaved store group due "
963                     "to gaps.\n");
964       releaseGroup(Group);
965     }
966   // Remove interleaved groups with gaps (currently only loads) whose memory
967   // accesses may wrap around. We have to revisit the getPtrStride analysis,
968   // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
969   // not check wrapping (see documentation there).
970   // FORNOW we use Assume=false;
971   // TODO: Change to Assume=true but making sure we don't exceed the threshold
972   // of runtime SCEV assumptions checks (thereby potentially failing to
973   // vectorize altogether).
974   // Additional optional optimizations:
975   // TODO: If we are peeling the loop and we know that the first pointer doesn't
976   // wrap then we can deduce that all pointers in the group don't wrap.
977   // This means that we can forcefully peel the loop in order to only have to
978   // check the first pointer for no-wrap. When we'll change to use Assume=true
979   // we'll only need at most one runtime check per interleaved group.
980   for (auto *Group : LoadGroups) {
981     // Case 1: A full group. Can Skip the checks; For full groups, if the wide
982     // load would wrap around the address space we would do a memory access at
983     // nullptr even without the transformation.
984     if (Group->getNumMembers() == Group->getFactor())
985       continue;
986 
987     // Case 2: If first and last members of the group don't wrap this implies
988     // that all the pointers in the group don't wrap.
989     // So we check only group member 0 (which is always guaranteed to exist),
990     // and group member Factor - 1; If the latter doesn't exist we rely on
991     // peeling (if it is a non-reveresed accsess -- see Case 3).
992     Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0));
993     if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
994                       /*ShouldCheckWrap=*/true)) {
995       LLVM_DEBUG(
996           dbgs() << "LV: Invalidate candidate interleaved group due to "
997                     "first group member potentially pointer-wrapping.\n");
998       releaseGroup(Group);
999       continue;
1000     }
1001     Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
1002     if (LastMember) {
1003       Value *LastMemberPtr = getLoadStorePointerOperand(LastMember);
1004       if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
1005                         /*ShouldCheckWrap=*/true)) {
1006         LLVM_DEBUG(
1007             dbgs() << "LV: Invalidate candidate interleaved group due to "
1008                       "last group member potentially pointer-wrapping.\n");
1009         releaseGroup(Group);
1010       }
1011     } else {
1012       // Case 3: A non-reversed interleaved load group with gaps: We need
1013       // to execute at least one scalar epilogue iteration. This will ensure
1014       // we don't speculatively access memory out-of-bounds. We only need
1015       // to look for a member at index factor - 1, since every group must have
1016       // a member at index zero.
1017       if (Group->isReverse()) {
1018         LLVM_DEBUG(
1019             dbgs() << "LV: Invalidate candidate interleaved group due to "
1020                       "a reverse access with gaps.\n");
1021         releaseGroup(Group);
1022         continue;
1023       }
1024       LLVM_DEBUG(
1025           dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
1026       RequiresScalarEpilogue = true;
1027     }
1028   }
1029 }
1030 
1031 void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
1032   // If no group had triggered the requirement to create an epilogue loop,
1033   // there is nothing to do.
1034   if (!requiresScalarEpilogue())
1035     return;
1036 
1037   // Avoid releasing a Group twice.
1038   SmallPtrSet<InterleaveGroup<Instruction> *, 4> DelSet;
1039   for (auto &I : InterleaveGroupMap) {
1040     InterleaveGroup<Instruction> *Group = I.second;
1041     if (Group->requiresScalarEpilogue())
1042       DelSet.insert(Group);
1043   }
1044   for (auto *Ptr : DelSet) {
1045     LLVM_DEBUG(
1046         dbgs()
1047         << "LV: Invalidate candidate interleaved group due to gaps that "
1048            "require a scalar epilogue (not allowed under optsize) and cannot "
1049            "be masked (not enabled). \n");
1050     releaseGroup(Ptr);
1051   }
1052 
1053   RequiresScalarEpilogue = false;
1054 }
1055 
1056 template <typename InstT>
1057 void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
1058   llvm_unreachable("addMetadata can only be used for Instruction");
1059 }
1060 
1061 namespace llvm {
1062 template <>
1063 void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const {
1064   SmallVector<Value *, 4> VL;
1065   std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
1066                  [](std::pair<int, Instruction *> p) { return p.second; });
1067   propagateMetadata(NewInst, VL);
1068 }
1069 }
1070