1 //===-- HexagonVectorCombine.cpp ------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 // HexagonVectorCombine is a utility class implementing a variety of functions
9 // that assist in vector-based optimizations.
10 //
11 // AlignVectors: replace unaligned vector loads and stores with aligned ones.
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/AssumptionCache.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/Analysis/VectorUtils.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/IntrinsicsHexagon.h"
32 #include "llvm/IR/Metadata.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/KnownBits.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetMachine.h"
39 
40 #include "HexagonSubtarget.h"
41 #include "HexagonTargetMachine.h"
42 
43 #include <algorithm>
44 #include <deque>
45 #include <map>
46 #include <set>
47 #include <utility>
48 #include <vector>
49 
50 #define DEBUG_TYPE "hexagon-vc"
51 
52 using namespace llvm;
53 
54 namespace {
55 class HexagonVectorCombine {
56 public:
57   HexagonVectorCombine(Function &F_, AliasAnalysis &AA_, AssumptionCache &AC_,
58                        DominatorTree &DT_, TargetLibraryInfo &TLI_,
59                        const TargetMachine &TM_)
60       : F(F_), DL(F.getParent()->getDataLayout()), AA(AA_), AC(AC_), DT(DT_),
61         TLI(TLI_),
62         HST(static_cast<const HexagonSubtarget &>(*TM_.getSubtargetImpl(F))) {}
63 
64   bool run();
65 
66   // Common integer type.
67   IntegerType *getIntTy() const;
68   // Byte type: either scalar (when Length = 0), or vector with given
69   // element count.
70   Type *getByteTy(int ElemCount = 0) const;
71   // Boolean type: either scalar (when Length = 0), or vector with given
72   // element count.
73   Type *getBoolTy(int ElemCount = 0) const;
74   // Create a ConstantInt of type returned by getIntTy with the value Val.
75   ConstantInt *getConstInt(int Val) const;
76   // Get the integer value of V, if it exists.
77   Optional<APInt> getIntValue(const Value *Val) const;
78   // Is V a constant 0, or a vector of 0s?
79   bool isZero(const Value *Val) const;
80   // Is V an undef value?
81   bool isUndef(const Value *Val) const;
82 
83   int getSizeOf(const Value *Val) const;
84   int getSizeOf(const Type *Ty) const;
85   int getTypeAlignment(Type *Ty) const;
86 
87   VectorType *getByteVectorTy(int ScLen) const;
88   Constant *getNullValue(Type *Ty) const;
89   Constant *getFullValue(Type *Ty) const;
90 
91   Value *insertb(IRBuilder<> &Builder, Value *Dest, Value *Src, int Start,
92                  int Length, int Where) const;
93   Value *vlalignb(IRBuilder<> &Builder, Value *Lo, Value *Hi, Value *Amt) const;
94   Value *vralignb(IRBuilder<> &Builder, Value *Lo, Value *Hi, Value *Amt) const;
95   Value *concat(IRBuilder<> &Builder, ArrayRef<Value *> Vecs) const;
96   Value *vresize(IRBuilder<> &Builder, Value *Val, int NewSize,
97                  Value *Pad) const;
98   Value *rescale(IRBuilder<> &Builder, Value *Mask, Type *FromTy,
99                  Type *ToTy) const;
100   Value *vlsb(IRBuilder<> &Builder, Value *Val) const;
101   Value *vbytes(IRBuilder<> &Builder, Value *Val) const;
102 
103   Value *createHvxIntrinsic(IRBuilder<> &Builder, Intrinsic::ID IntID,
104                             Type *RetTy, ArrayRef<Value *> Args) const;
105 
106   Optional<int> calculatePointerDifference(Value *Ptr0, Value *Ptr1) const;
107 
108   template <typename T = std::vector<Instruction *>>
109   bool isSafeToMoveBeforeInBB(const Instruction &In,
110                               BasicBlock::const_iterator To,
111                               const T &Ignore = {}) const;
112 
113   Function &F;
114   const DataLayout &DL;
115   AliasAnalysis &AA;
116   AssumptionCache &AC;
117   DominatorTree &DT;
118   TargetLibraryInfo &TLI;
119   const HexagonSubtarget &HST;
120 
121 private:
122 #ifndef NDEBUG
123   // These two functions are only used for assertions at the moment.
124   bool isByteVecTy(Type *Ty) const;
125   bool isSectorTy(Type *Ty) const;
126 #endif
127   Value *getElementRange(IRBuilder<> &Builder, Value *Lo, Value *Hi, int Start,
128                          int Length) const;
129 };
130 
131 class AlignVectors {
132 public:
133   AlignVectors(HexagonVectorCombine &HVC_) : HVC(HVC_) {}
134 
135   bool run();
136 
137 private:
138   using InstList = std::vector<Instruction *>;
139 
140   struct Segment {
141     void *Data;
142     int Start;
143     int Size;
144   };
145 
146   struct AddrInfo {
147     AddrInfo(const AddrInfo &) = default;
148     AddrInfo(const HexagonVectorCombine &HVC, Instruction *I, Value *A, Type *T,
149              Align H)
150         : Inst(I), Addr(A), ValTy(T), HaveAlign(H),
151           NeedAlign(HVC.getTypeAlignment(ValTy)) {}
152 
153     // XXX: add Size member?
154     Instruction *Inst;
155     Value *Addr;
156     Type *ValTy;
157     Align HaveAlign;
158     Align NeedAlign;
159     int Offset = 0; // Offset (in bytes) from the first member of the
160                     // containing AddrList.
161   };
162   using AddrList = std::vector<AddrInfo>;
163 
164   struct InstrLess {
165     bool operator()(const Instruction *A, const Instruction *B) const {
166       return A->comesBefore(B);
167     }
168   };
169   using DepList = std::set<Instruction *, InstrLess>;
170 
171   struct MoveGroup {
172     MoveGroup(const AddrInfo &AI, Instruction *B, bool Hvx, bool Load)
173         : Base(B), Main{AI.Inst}, IsHvx(Hvx), IsLoad(Load) {}
174     Instruction *Base; // Base instruction of the parent address group.
175     InstList Main;     // Main group of instructions.
176     InstList Deps;     // List of dependencies.
177     bool IsHvx;        // Is this group of HVX instructions?
178     bool IsLoad;       // Is this a load group?
179   };
180   using MoveList = std::vector<MoveGroup>;
181 
182   struct ByteSpan {
183     struct Segment {
184       // Segment of a Value: 'Len' bytes starting at byte 'Begin'.
185       Segment(Value *Val, int Begin, int Len)
186           : Val(Val), Start(Begin), Size(Len) {}
187       Segment(const Segment &Seg) = default;
188       Value *Val; // Value representable as a sequence of bytes.
189       int Start;  // First byte of the value that belongs to the segment.
190       int Size;   // Number of bytes in the segment.
191     };
192 
193     struct Block {
194       Block(Value *Val, int Len, int Pos) : Seg(Val, 0, Len), Pos(Pos) {}
195       Block(Value *Val, int Off, int Len, int Pos)
196           : Seg(Val, Off, Len), Pos(Pos) {}
197       Block(const Block &Blk) = default;
198       Segment Seg; // Value segment.
199       int Pos;     // Position (offset) of the segment in the Block.
200     };
201 
202     int extent() const;
203     ByteSpan section(int Start, int Length) const;
204     ByteSpan &shift(int Offset);
205     SmallVector<Value *, 8> values() const;
206 
207     int size() const { return Blocks.size(); }
208     Block &operator[](int i) { return Blocks[i]; }
209 
210     std::vector<Block> Blocks;
211 
212     using iterator = decltype(Blocks)::iterator;
213     iterator begin() { return Blocks.begin(); }
214     iterator end() { return Blocks.end(); }
215     using const_iterator = decltype(Blocks)::const_iterator;
216     const_iterator begin() const { return Blocks.begin(); }
217     const_iterator end() const { return Blocks.end(); }
218   };
219 
220   Align getAlignFromValue(const Value *V) const;
221   Optional<MemoryLocation> getLocation(const Instruction &In) const;
222   Optional<AddrInfo> getAddrInfo(Instruction &In) const;
223   bool isHvx(const AddrInfo &AI) const;
224 
225   Value *getPayload(Value *Val) const;
226   Value *getMask(Value *Val) const;
227   Value *getPassThrough(Value *Val) const;
228 
229   Value *createAdjustedPointer(IRBuilder<> &Builder, Value *Ptr, Type *ValTy,
230                                int Adjust) const;
231   Value *createAlignedPointer(IRBuilder<> &Builder, Value *Ptr, Type *ValTy,
232                               int Alignment) const;
233   Value *createAlignedLoad(IRBuilder<> &Builder, Type *ValTy, Value *Ptr,
234                            int Alignment, Value *Mask, Value *PassThru) const;
235   Value *createAlignedStore(IRBuilder<> &Builder, Value *Val, Value *Ptr,
236                             int Alignment, Value *Mask) const;
237 
238   bool createAddressGroups();
239   MoveList createLoadGroups(const AddrList &Group) const;
240   MoveList createStoreGroups(const AddrList &Group) const;
241   bool move(const MoveGroup &Move) const;
242   bool realignGroup(const MoveGroup &Move) const;
243 
244   friend raw_ostream &operator<<(raw_ostream &OS, const AddrInfo &AI);
245   friend raw_ostream &operator<<(raw_ostream &OS, const MoveGroup &MG);
246   friend raw_ostream &operator<<(raw_ostream &OS, const ByteSpan &BS);
247 
248   std::map<Instruction *, AddrList> AddrGroups;
249   HexagonVectorCombine &HVC;
250 };
251 
252 LLVM_ATTRIBUTE_UNUSED
253 raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::AddrInfo &AI) {
254   OS << "Inst: " << AI.Inst << "  " << *AI.Inst << '\n';
255   OS << "Addr: " << *AI.Addr << '\n';
256   OS << "Type: " << *AI.ValTy << '\n';
257   OS << "HaveAlign: " << AI.HaveAlign.value() << '\n';
258   OS << "NeedAlign: " << AI.NeedAlign.value() << '\n';
259   OS << "Offset: " << AI.Offset;
260   return OS;
261 }
262 
263 LLVM_ATTRIBUTE_UNUSED
264 raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::MoveGroup &MG) {
265   OS << "Main\n";
266   for (Instruction *I : MG.Main)
267     OS << "  " << *I << '\n';
268   OS << "Deps\n";
269   for (Instruction *I : MG.Deps)
270     OS << "  " << *I << '\n';
271   return OS;
272 }
273 
274 LLVM_ATTRIBUTE_UNUSED
275 raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::ByteSpan &BS) {
276   OS << "ByteSpan[size=" << BS.size() << ", extent=" << BS.extent() << '\n';
277   for (const AlignVectors::ByteSpan::Block &B : BS) {
278     OS << "  @" << B.Pos << " [" << B.Seg.Start << ',' << B.Seg.Size << "] "
279        << *B.Seg.Val << '\n';
280   }
281   OS << ']';
282   return OS;
283 }
284 
285 } // namespace
286 
287 namespace {
288 
289 template <typename T> T *getIfUnordered(T *MaybeT) {
290   return MaybeT && MaybeT->isUnordered() ? MaybeT : nullptr;
291 }
292 template <typename T> T *isCandidate(Instruction *In) {
293   return dyn_cast<T>(In);
294 }
295 template <> LoadInst *isCandidate<LoadInst>(Instruction *In) {
296   return getIfUnordered(dyn_cast<LoadInst>(In));
297 }
298 template <> StoreInst *isCandidate<StoreInst>(Instruction *In) {
299   return getIfUnordered(dyn_cast<StoreInst>(In));
300 }
301 
302 #if !defined(_MSC_VER) || _MSC_VER >= 1924
303 // VS2017 has trouble compiling this:
304 // error C2976: 'std::map': too few template arguments
305 template <typename Pred, typename... Ts>
306 void erase_if(std::map<Ts...> &map, Pred p)
307 #else
308 template <typename Pred, typename T, typename U>
309 void erase_if(std::map<T, U> &map, Pred p)
310 #endif
311 {
312   for (auto i = map.begin(), e = map.end(); i != e;) {
313     if (p(*i))
314       i = map.erase(i);
315     else
316       i = std::next(i);
317   }
318 }
319 
320 // Forward other erase_ifs to the LLVM implementations.
321 template <typename Pred, typename T> void erase_if(T &&container, Pred p) {
322   llvm::erase_if(std::forward<T>(container), p);
323 }
324 
325 } // namespace
326 
327 // --- Begin AlignVectors
328 
329 auto AlignVectors::ByteSpan::extent() const -> int {
330   if (size() == 0)
331     return 0;
332   int Min = Blocks[0].Pos;
333   int Max = Blocks[0].Pos + Blocks[0].Seg.Size;
334   for (int i = 1, e = size(); i != e; ++i) {
335     Min = std::min(Min, Blocks[i].Pos);
336     Max = std::max(Max, Blocks[i].Pos + Blocks[i].Seg.Size);
337   }
338   return Max - Min;
339 }
340 
341 auto AlignVectors::ByteSpan::section(int Start, int Length) const -> ByteSpan {
342   ByteSpan Section;
343   for (const ByteSpan::Block &B : Blocks) {
344     int L = std::max(B.Pos, Start);                       // Left end.
345     int R = std::min(B.Pos + B.Seg.Size, Start + Length); // Right end+1.
346     if (L < R) {
347       // How much to chop off the beginning of the segment:
348       int Off = L > B.Pos ? L - B.Pos : 0;
349       Section.Blocks.emplace_back(B.Seg.Val, B.Seg.Start + Off, R - L, L);
350     }
351   }
352   return Section;
353 }
354 
355 auto AlignVectors::ByteSpan::shift(int Offset) -> ByteSpan & {
356   for (Block &B : Blocks)
357     B.Pos += Offset;
358   return *this;
359 }
360 
361 auto AlignVectors::ByteSpan::values() const -> SmallVector<Value *, 8> {
362   SmallVector<Value *, 8> Values(Blocks.size());
363   for (int i = 0, e = Blocks.size(); i != e; ++i)
364     Values[i] = Blocks[i].Seg.Val;
365   return Values;
366 }
367 
368 auto AlignVectors::getAlignFromValue(const Value *V) const -> Align {
369   const auto *C = dyn_cast<ConstantInt>(V);
370   assert(C && "Alignment must be a compile-time constant integer");
371   return C->getAlignValue();
372 }
373 
374 auto AlignVectors::getAddrInfo(Instruction &In) const -> Optional<AddrInfo> {
375   if (auto *L = isCandidate<LoadInst>(&In))
376     return AddrInfo(HVC, L, L->getPointerOperand(), L->getType(),
377                     L->getAlign());
378   if (auto *S = isCandidate<StoreInst>(&In))
379     return AddrInfo(HVC, S, S->getPointerOperand(),
380                     S->getValueOperand()->getType(), S->getAlign());
381   if (auto *II = isCandidate<IntrinsicInst>(&In)) {
382     Intrinsic::ID ID = II->getIntrinsicID();
383     switch (ID) {
384     case Intrinsic::masked_load:
385       return AddrInfo(HVC, II, II->getArgOperand(0), II->getType(),
386                       getAlignFromValue(II->getArgOperand(1)));
387     case Intrinsic::masked_store:
388       return AddrInfo(HVC, II, II->getArgOperand(1),
389                       II->getArgOperand(0)->getType(),
390                       getAlignFromValue(II->getArgOperand(2)));
391     }
392   }
393   return Optional<AddrInfo>();
394 }
395 
396 auto AlignVectors::isHvx(const AddrInfo &AI) const -> bool {
397   return HVC.HST.isTypeForHVX(AI.ValTy);
398 }
399 
400 auto AlignVectors::getPayload(Value *Val) const -> Value * {
401   if (auto *In = dyn_cast<Instruction>(Val)) {
402     Intrinsic::ID ID = 0;
403     if (auto *II = dyn_cast<IntrinsicInst>(In))
404       ID = II->getIntrinsicID();
405     if (isa<StoreInst>(In) || ID == Intrinsic::masked_store)
406       return In->getOperand(0);
407   }
408   return Val;
409 }
410 
411 auto AlignVectors::getMask(Value *Val) const -> Value * {
412   if (auto *II = dyn_cast<IntrinsicInst>(Val)) {
413     switch (II->getIntrinsicID()) {
414     case Intrinsic::masked_load:
415       return II->getArgOperand(2);
416     case Intrinsic::masked_store:
417       return II->getArgOperand(3);
418     }
419   }
420 
421   Type *ValTy = getPayload(Val)->getType();
422   if (auto *VecTy = dyn_cast<VectorType>(ValTy)) {
423     int ElemCount = VecTy->getElementCount().getFixedValue();
424     return HVC.getFullValue(HVC.getBoolTy(ElemCount));
425   }
426   return HVC.getFullValue(HVC.getBoolTy());
427 }
428 
429 auto AlignVectors::getPassThrough(Value *Val) const -> Value * {
430   if (auto *II = dyn_cast<IntrinsicInst>(Val)) {
431     if (II->getIntrinsicID() == Intrinsic::masked_load)
432       return II->getArgOperand(3);
433   }
434   return UndefValue::get(getPayload(Val)->getType());
435 }
436 
437 auto AlignVectors::createAdjustedPointer(IRBuilder<> &Builder, Value *Ptr,
438                                          Type *ValTy, int Adjust) const
439     -> Value * {
440   // The adjustment is in bytes, but if it's a multiple of the type size,
441   // we don't need to do pointer casts.
442   Type *ElemTy = cast<PointerType>(Ptr->getType())->getElementType();
443   int ElemSize = HVC.getSizeOf(ElemTy);
444   if (Adjust % ElemSize == 0) {
445     Value *Tmp0 = Builder.CreateGEP(Ptr, HVC.getConstInt(Adjust / ElemSize));
446     return Builder.CreatePointerCast(Tmp0, ValTy->getPointerTo());
447   }
448 
449   PointerType *CharPtrTy = Type::getInt8PtrTy(HVC.F.getContext());
450   Value *Tmp0 = Builder.CreatePointerCast(Ptr, CharPtrTy);
451   Value *Tmp1 = Builder.CreateGEP(Tmp0, HVC.getConstInt(Adjust));
452   return Builder.CreatePointerCast(Tmp1, ValTy->getPointerTo());
453 }
454 
455 auto AlignVectors::createAlignedPointer(IRBuilder<> &Builder, Value *Ptr,
456                                         Type *ValTy, int Alignment) const
457     -> Value * {
458   Value *AsInt = Builder.CreatePtrToInt(Ptr, HVC.getIntTy());
459   Value *Mask = HVC.getConstInt(-Alignment);
460   Value *And = Builder.CreateAnd(AsInt, Mask);
461   return Builder.CreateIntToPtr(And, ValTy->getPointerTo());
462 }
463 
464 auto AlignVectors::createAlignedLoad(IRBuilder<> &Builder, Type *ValTy,
465                                      Value *Ptr, int Alignment, Value *Mask,
466                                      Value *PassThru) const -> Value * {
467   assert(!HVC.isUndef(Mask)); // Should this be allowed?
468   if (HVC.isZero(Mask))
469     return PassThru;
470   if (Mask == ConstantInt::getTrue(Mask->getType()))
471     return Builder.CreateAlignedLoad(ValTy, Ptr, Align(Alignment));
472   return Builder.CreateMaskedLoad(Ptr, Align(Alignment), Mask, PassThru);
473 }
474 
475 auto AlignVectors::createAlignedStore(IRBuilder<> &Builder, Value *Val,
476                                       Value *Ptr, int Alignment,
477                                       Value *Mask) const -> Value * {
478   if (HVC.isZero(Mask) || HVC.isUndef(Val) || HVC.isUndef(Mask))
479     return UndefValue::get(Val->getType());
480   if (Mask == ConstantInt::getTrue(Mask->getType()))
481     return Builder.CreateAlignedStore(Val, Ptr, Align(Alignment));
482   return Builder.CreateMaskedStore(Val, Ptr, Align(Alignment), Mask);
483 }
484 
485 auto AlignVectors::createAddressGroups() -> bool {
486   // An address group created here may contain instructions spanning
487   // multiple basic blocks.
488   AddrList WorkStack;
489 
490   auto findBaseAndOffset = [&](AddrInfo &AI) -> std::pair<Instruction *, int> {
491     for (AddrInfo &W : WorkStack) {
492       if (auto D = HVC.calculatePointerDifference(AI.Addr, W.Addr))
493         return std::make_pair(W.Inst, *D);
494     }
495     return std::make_pair(nullptr, 0);
496   };
497 
498   auto traverseBlock = [&](DomTreeNode *DomN, auto Visit) -> void {
499     BasicBlock &Block = *DomN->getBlock();
500     for (Instruction &I : Block) {
501       auto AI = this->getAddrInfo(I); // Use this-> for gcc6.
502       if (!AI)
503         continue;
504       auto F = findBaseAndOffset(*AI);
505       Instruction *GroupInst;
506       if (Instruction *BI = F.first) {
507         AI->Offset = F.second;
508         GroupInst = BI;
509       } else {
510         WorkStack.push_back(*AI);
511         GroupInst = AI->Inst;
512       }
513       AddrGroups[GroupInst].push_back(*AI);
514     }
515 
516     for (DomTreeNode *C : DomN->children())
517       Visit(C, Visit);
518 
519     while (!WorkStack.empty() && WorkStack.back().Inst->getParent() == &Block)
520       WorkStack.pop_back();
521   };
522 
523   traverseBlock(HVC.DT.getRootNode(), traverseBlock);
524   assert(WorkStack.empty());
525 
526   // AddrGroups are formed.
527 
528   // Remove groups of size 1.
529   erase_if(AddrGroups, [](auto &G) { return G.second.size() == 1; });
530   // Remove groups that don't use HVX types.
531   erase_if(AddrGroups, [&](auto &G) {
532     return !llvm::any_of(
533         G.second, [&](auto &I) { return HVC.HST.isTypeForHVX(I.ValTy); });
534   });
535 
536   return !AddrGroups.empty();
537 }
538 
539 auto AlignVectors::createLoadGroups(const AddrList &Group) const -> MoveList {
540   // Form load groups.
541   // To avoid complications with moving code across basic blocks, only form
542   // groups that are contained within a single basic block.
543 
544   auto getUpwardDeps = [](Instruction *In, Instruction *Base) {
545     BasicBlock *Parent = Base->getParent();
546     assert(In->getParent() == Parent &&
547            "Base and In should be in the same block");
548     assert(Base->comesBefore(In) && "Base should come before In");
549 
550     DepList Deps;
551     std::deque<Instruction *> WorkQ = {In};
552     while (!WorkQ.empty()) {
553       Instruction *D = WorkQ.front();
554       WorkQ.pop_front();
555       Deps.insert(D);
556       for (Value *Op : D->operands()) {
557         if (auto *I = dyn_cast<Instruction>(Op)) {
558           if (I->getParent() == Parent && Base->comesBefore(I))
559             WorkQ.push_back(I);
560         }
561       }
562     }
563     return Deps;
564   };
565 
566   auto tryAddTo = [&](const AddrInfo &Info, MoveGroup &Move) {
567     assert(!Move.Main.empty() && "Move group should have non-empty Main");
568     // Don't mix HVX and non-HVX instructions.
569     if (Move.IsHvx != isHvx(Info))
570       return false;
571     // Leading instruction in the load group.
572     Instruction *Base = Move.Main.front();
573     if (Base->getParent() != Info.Inst->getParent())
574       return false;
575 
576     auto isSafeToMoveToBase = [&](const Instruction *I) {
577       return HVC.isSafeToMoveBeforeInBB(*I, Base->getIterator());
578     };
579     DepList Deps = getUpwardDeps(Info.Inst, Base);
580     if (!llvm::all_of(Deps, isSafeToMoveToBase))
581       return false;
582 
583     // The dependencies will be moved together with the load, so make sure
584     // that none of them could be moved independently in another group.
585     Deps.erase(Info.Inst);
586     auto inAddrMap = [&](Instruction *I) { return AddrGroups.count(I) > 0; };
587     if (llvm::any_of(Deps, inAddrMap))
588       return false;
589     Move.Main.push_back(Info.Inst);
590     llvm::append_range(Move.Deps, Deps);
591     return true;
592   };
593 
594   MoveList LoadGroups;
595 
596   for (const AddrInfo &Info : Group) {
597     if (!Info.Inst->mayReadFromMemory())
598       continue;
599     if (LoadGroups.empty() || !tryAddTo(Info, LoadGroups.back()))
600       LoadGroups.emplace_back(Info, Group.front().Inst, isHvx(Info), true);
601   }
602 
603   // Erase singleton groups.
604   erase_if(LoadGroups, [](const MoveGroup &G) { return G.Main.size() <= 1; });
605   return LoadGroups;
606 }
607 
608 auto AlignVectors::createStoreGroups(const AddrList &Group) const -> MoveList {
609   // Form store groups.
610   // To avoid complications with moving code across basic blocks, only form
611   // groups that are contained within a single basic block.
612 
613   auto tryAddTo = [&](const AddrInfo &Info, MoveGroup &Move) {
614     assert(!Move.Main.empty() && "Move group should have non-empty Main");
615     // For stores with return values we'd have to collect downward depenencies.
616     // There are no such stores that we handle at the moment, so omit that.
617     assert(Info.Inst->getType()->isVoidTy() &&
618            "Not handling stores with return values");
619     // Don't mix HVX and non-HVX instructions.
620     if (Move.IsHvx != isHvx(Info))
621       return false;
622     // For stores we need to be careful whether it's safe to move them.
623     // Stores that are otherwise safe to move together may not appear safe
624     // to move over one another (i.e. isSafeToMoveBefore may return false).
625     Instruction *Base = Move.Main.front();
626     if (Base->getParent() != Info.Inst->getParent())
627       return false;
628     if (!HVC.isSafeToMoveBeforeInBB(*Info.Inst, Base->getIterator(), Move.Main))
629       return false;
630     Move.Main.push_back(Info.Inst);
631     return true;
632   };
633 
634   MoveList StoreGroups;
635 
636   for (auto I = Group.rbegin(), E = Group.rend(); I != E; ++I) {
637     const AddrInfo &Info = *I;
638     if (!Info.Inst->mayWriteToMemory())
639       continue;
640     if (StoreGroups.empty() || !tryAddTo(Info, StoreGroups.back()))
641       StoreGroups.emplace_back(Info, Group.front().Inst, isHvx(Info), false);
642   }
643 
644   // Erase singleton groups.
645   erase_if(StoreGroups, [](const MoveGroup &G) { return G.Main.size() <= 1; });
646   return StoreGroups;
647 }
648 
649 auto AlignVectors::move(const MoveGroup &Move) const -> bool {
650   assert(!Move.Main.empty() && "Move group should have non-empty Main");
651   Instruction *Where = Move.Main.front();
652 
653   if (Move.IsLoad) {
654     // Move all deps to before Where, keeping order.
655     for (Instruction *D : Move.Deps)
656       D->moveBefore(Where);
657     // Move all main instructions to after Where, keeping order.
658     ArrayRef<Instruction *> Main(Move.Main);
659     for (Instruction *M : Main.drop_front(1)) {
660       M->moveAfter(Where);
661       Where = M;
662     }
663   } else {
664     // NOTE: Deps are empty for "store" groups. If they need to be
665     // non-empty, decide on the order.
666     assert(Move.Deps.empty());
667     // Move all main instructions to before Where, inverting order.
668     ArrayRef<Instruction *> Main(Move.Main);
669     for (Instruction *M : Main.drop_front(1)) {
670       M->moveBefore(Where);
671       Where = M;
672     }
673   }
674 
675   return Move.Main.size() + Move.Deps.size() > 1;
676 }
677 
678 auto AlignVectors::realignGroup(const MoveGroup &Move) const -> bool {
679   // TODO: Needs support for masked loads/stores of "scalar" vectors.
680   if (!Move.IsHvx)
681     return false;
682 
683   // Return the element with the maximum alignment from Range,
684   // where GetValue obtains the value to compare from an element.
685   auto getMaxOf = [](auto Range, auto GetValue) {
686     return *std::max_element(
687         Range.begin(), Range.end(),
688         [&GetValue](auto &A, auto &B) { return GetValue(A) < GetValue(B); });
689   };
690 
691   const AddrList &BaseInfos = AddrGroups.at(Move.Base);
692 
693   // Conceptually, there is a vector of N bytes covering the addresses
694   // starting from the minimum offset (i.e. Base.Addr+Start). This vector
695   // represents a contiguous memory region that spans all accessed memory
696   // locations.
697   // The correspondence between loaded or stored values will be expressed
698   // in terms of this vector. For example, the 0th element of the vector
699   // from the Base address info will start at byte Start from the beginning
700   // of this conceptual vector.
701   //
702   // This vector will be loaded/stored starting at the nearest down-aligned
703   // address and the amount od the down-alignment will be AlignVal:
704   //   valign(load_vector(align_down(Base+Start)), AlignVal)
705 
706   std::set<Instruction *> TestSet(Move.Main.begin(), Move.Main.end());
707   AddrList MoveInfos;
708   llvm::copy_if(
709       BaseInfos, std::back_inserter(MoveInfos),
710       [&TestSet](const AddrInfo &AI) { return TestSet.count(AI.Inst); });
711 
712   // Maximum alignment present in the whole address group.
713   const AddrInfo &WithMaxAlign =
714       getMaxOf(BaseInfos, [](const AddrInfo &AI) { return AI.HaveAlign; });
715   Align MaxGiven = WithMaxAlign.HaveAlign;
716 
717   // Minimum alignment present in the move address group.
718   const AddrInfo &WithMinOffset =
719       getMaxOf(MoveInfos, [](const AddrInfo &AI) { return -AI.Offset; });
720 
721   const AddrInfo &WithMaxNeeded =
722       getMaxOf(MoveInfos, [](const AddrInfo &AI) { return AI.NeedAlign; });
723   Align MinNeeded = WithMaxNeeded.NeedAlign;
724 
725   // Set the builder at the top instruction in the move group.
726   Instruction *TopIn = Move.IsLoad ? Move.Main.front() : Move.Main.back();
727   IRBuilder<> Builder(TopIn);
728   Value *AlignAddr = nullptr; // Actual aligned address.
729   Value *AlignVal = nullptr;  // Right-shift amount (for valign).
730 
731   if (MinNeeded <= MaxGiven) {
732     int Start = WithMinOffset.Offset;
733     int OffAtMax = WithMaxAlign.Offset;
734     // Shift the offset of the maximally aligned instruction (OffAtMax)
735     // back by just enough multiples of the required alignment to cover the
736     // distance from Start to OffAtMax.
737     // Calculate the address adjustment amount based on the address with the
738     // maximum alignment. This is to allow a simple gep instruction instead
739     // of potential bitcasts to i8*.
740     int Adjust = -alignTo(OffAtMax - Start, MinNeeded.value());
741     AlignAddr = createAdjustedPointer(Builder, WithMaxAlign.Addr,
742                                       WithMaxAlign.ValTy, Adjust);
743     int Diff = Start - (OffAtMax + Adjust);
744     AlignVal = HVC.getConstInt(Diff);
745     // Sanity.
746     assert(Diff >= 0);
747     assert(static_cast<decltype(MinNeeded.value())>(Diff) < MinNeeded.value());
748   } else {
749     // WithMinOffset is the lowest address in the group,
750     //   WithMinOffset.Addr = Base+Start.
751     // Align instructions for both HVX (V6_valign) and scalar (S2_valignrb)
752     // mask off unnecessary bits, so it's ok to just the original pointer as
753     // the alignment amount.
754     // Do an explicit down-alignment of the address to avoid creating an
755     // aligned instruction with an address that is not really aligned.
756     AlignAddr = createAlignedPointer(Builder, WithMinOffset.Addr,
757                                      WithMinOffset.ValTy, MinNeeded.value());
758     AlignVal = Builder.CreatePtrToInt(WithMinOffset.Addr, HVC.getIntTy());
759   }
760 
761   ByteSpan VSpan;
762   for (const AddrInfo &AI : MoveInfos) {
763     VSpan.Blocks.emplace_back(AI.Inst, HVC.getSizeOf(AI.ValTy),
764                               AI.Offset - WithMinOffset.Offset);
765   }
766 
767   // The aligned loads/stores will use blocks that are either scalars,
768   // or HVX vectors. Let "sector" be the unified term for such a block.
769   // blend(scalar, vector) -> sector...
770   int ScLen = Move.IsHvx ? HVC.HST.getVectorLength()
771                          : std::max<int>(MinNeeded.value(), 4);
772   assert(!Move.IsHvx || ScLen == 64 || ScLen == 128);
773   assert(Move.IsHvx || ScLen == 4 || ScLen == 8);
774 
775   Type *SecTy = HVC.getByteTy(ScLen);
776   int NumSectors = (VSpan.extent() + ScLen - 1) / ScLen;
777   bool DoAlign = !HVC.isZero(AlignVal);
778 
779   if (Move.IsLoad) {
780     ByteSpan ASpan;
781     auto *True = HVC.getFullValue(HVC.getBoolTy(ScLen));
782     auto *Undef = UndefValue::get(SecTy);
783 
784     for (int i = 0; i != NumSectors + DoAlign; ++i) {
785       Value *Ptr = createAdjustedPointer(Builder, AlignAddr, SecTy, i * ScLen);
786       // FIXME: generate a predicated load?
787       Value *Load = createAlignedLoad(Builder, SecTy, Ptr, ScLen, True, Undef);
788       // If vector shifting is potentially needed, accumulate metadata
789       // from source sections of twice the load width.
790       int Start = (i - DoAlign) * ScLen;
791       int Width = (1 + DoAlign) * ScLen;
792       propagateMetadata(cast<Instruction>(Load),
793                         VSpan.section(Start, Width).values());
794       ASpan.Blocks.emplace_back(Load, ScLen, i * ScLen);
795     }
796 
797     if (DoAlign) {
798       for (int j = 0; j != NumSectors; ++j) {
799         ASpan[j].Seg.Val = HVC.vralignb(Builder, ASpan[j].Seg.Val,
800                                         ASpan[j + 1].Seg.Val, AlignVal);
801       }
802     }
803 
804     for (ByteSpan::Block &B : VSpan) {
805       ByteSpan ASection = ASpan.section(B.Pos, B.Seg.Size).shift(-B.Pos);
806       Value *Accum = UndefValue::get(HVC.getByteTy(B.Seg.Size));
807       for (ByteSpan::Block &S : ASection) {
808         Value *Pay = HVC.vbytes(Builder, getPayload(S.Seg.Val));
809         Accum =
810             HVC.insertb(Builder, Accum, Pay, S.Seg.Start, S.Seg.Size, S.Pos);
811       }
812       // Instead of casting everything to bytes for the vselect, cast to the
813       // original value type. This will avoid complications with casting masks.
814       // For example, in cases when the original mask applied to i32, it could
815       // be converted to a mask applicable to i8 via pred_typecast intrinsic,
816       // but if the mask is not exactly of HVX length, extra handling would be
817       // needed to make it work.
818       Type *ValTy = getPayload(B.Seg.Val)->getType();
819       Value *Cast = Builder.CreateBitCast(Accum, ValTy);
820       Value *Sel = Builder.CreateSelect(getMask(B.Seg.Val), Cast,
821                                         getPassThrough(B.Seg.Val));
822       B.Seg.Val->replaceAllUsesWith(Sel);
823     }
824   } else {
825     // Stores.
826     ByteSpan ASpanV, ASpanM;
827 
828     // Return a vector value corresponding to the input value Val:
829     // either <1 x Val> for scalar Val, or Val itself for vector Val.
830     auto MakeVec = [](IRBuilder<> &Builder, Value *Val) -> Value * {
831       Type *Ty = Val->getType();
832       if (Ty->isVectorTy())
833         return Val;
834       auto *VecTy = VectorType::get(Ty, 1, /*Scalable*/ false);
835       return Builder.CreateBitCast(Val, VecTy);
836     };
837 
838     // Create an extra "undef" sector at the beginning and at the end.
839     // They will be used as the left/right filler in the vlalign step.
840     for (int i = (DoAlign ? -1 : 0); i != NumSectors + DoAlign; ++i) {
841       // For stores, the size of each section is an aligned vector length.
842       // Adjust the store offsets relative to the section start offset.
843       ByteSpan VSection = VSpan.section(i * ScLen, ScLen).shift(-i * ScLen);
844       Value *AccumV = UndefValue::get(SecTy);
845       Value *AccumM = HVC.getNullValue(SecTy);
846       for (ByteSpan::Block &S : VSection) {
847         Value *Pay = getPayload(S.Seg.Val);
848         Value *Mask = HVC.rescale(Builder, MakeVec(Builder, getMask(S.Seg.Val)),
849                                   Pay->getType(), HVC.getByteTy());
850         AccumM = HVC.insertb(Builder, AccumM, HVC.vbytes(Builder, Mask),
851                              S.Seg.Start, S.Seg.Size, S.Pos);
852         AccumV = HVC.insertb(Builder, AccumV, HVC.vbytes(Builder, Pay),
853                              S.Seg.Start, S.Seg.Size, S.Pos);
854       }
855       ASpanV.Blocks.emplace_back(AccumV, ScLen, i * ScLen);
856       ASpanM.Blocks.emplace_back(AccumM, ScLen, i * ScLen);
857     }
858 
859     // vlalign
860     if (DoAlign) {
861       for (int j = 1; j != NumSectors + 2; ++j) {
862         ASpanV[j - 1].Seg.Val = HVC.vlalignb(Builder, ASpanV[j - 1].Seg.Val,
863                                              ASpanV[j].Seg.Val, AlignVal);
864         ASpanM[j - 1].Seg.Val = HVC.vlalignb(Builder, ASpanM[j - 1].Seg.Val,
865                                              ASpanM[j].Seg.Val, AlignVal);
866       }
867     }
868 
869     for (int i = 0; i != NumSectors + DoAlign; ++i) {
870       Value *Ptr = createAdjustedPointer(Builder, AlignAddr, SecTy, i * ScLen);
871       Value *Val = ASpanV[i].Seg.Val;
872       Value *Mask = ASpanM[i].Seg.Val; // bytes
873       if (!HVC.isUndef(Val) && !HVC.isZero(Mask)) {
874         Value *Store = createAlignedStore(Builder, Val, Ptr, ScLen,
875                                           HVC.vlsb(Builder, Mask));
876         // If vector shifting is potentially needed, accumulate metadata
877         // from source sections of twice the store width.
878         int Start = (i - DoAlign) * ScLen;
879         int Width = (1 + DoAlign) * ScLen;
880         propagateMetadata(cast<Instruction>(Store),
881                           VSpan.section(Start, Width).values());
882       }
883     }
884   }
885 
886   for (auto *Inst : Move.Main)
887     Inst->eraseFromParent();
888 
889   return true;
890 }
891 
892 auto AlignVectors::run() -> bool {
893   if (!createAddressGroups())
894     return false;
895 
896   bool Changed = false;
897   MoveList LoadGroups, StoreGroups;
898 
899   for (auto &G : AddrGroups) {
900     llvm::append_range(LoadGroups, createLoadGroups(G.second));
901     llvm::append_range(StoreGroups, createStoreGroups(G.second));
902   }
903 
904   for (auto &M : LoadGroups)
905     Changed |= move(M);
906   for (auto &M : StoreGroups)
907     Changed |= move(M);
908 
909   for (auto &M : LoadGroups)
910     Changed |= realignGroup(M);
911   for (auto &M : StoreGroups)
912     Changed |= realignGroup(M);
913 
914   return Changed;
915 }
916 
917 // --- End AlignVectors
918 
919 auto HexagonVectorCombine::run() -> bool {
920   if (!HST.useHVXOps())
921     return false;
922 
923   bool Changed = AlignVectors(*this).run();
924   return Changed;
925 }
926 
927 auto HexagonVectorCombine::getIntTy() const -> IntegerType * {
928   return Type::getInt32Ty(F.getContext());
929 }
930 
931 auto HexagonVectorCombine::getByteTy(int ElemCount) const -> Type * {
932   assert(ElemCount >= 0);
933   IntegerType *ByteTy = Type::getInt8Ty(F.getContext());
934   if (ElemCount == 0)
935     return ByteTy;
936   return VectorType::get(ByteTy, ElemCount, /*Scalable*/ false);
937 }
938 
939 auto HexagonVectorCombine::getBoolTy(int ElemCount) const -> Type * {
940   assert(ElemCount >= 0);
941   IntegerType *BoolTy = Type::getInt1Ty(F.getContext());
942   if (ElemCount == 0)
943     return BoolTy;
944   return VectorType::get(BoolTy, ElemCount, /*Scalable*/ false);
945 }
946 
947 auto HexagonVectorCombine::getConstInt(int Val) const -> ConstantInt * {
948   return ConstantInt::getSigned(getIntTy(), Val);
949 }
950 
951 auto HexagonVectorCombine::isZero(const Value *Val) const -> bool {
952   if (auto *C = dyn_cast<Constant>(Val))
953     return C->isZeroValue();
954   return false;
955 }
956 
957 auto HexagonVectorCombine::getIntValue(const Value *Val) const
958     -> Optional<APInt> {
959   if (auto *CI = dyn_cast<ConstantInt>(Val))
960     return CI->getValue();
961   return None;
962 }
963 
964 auto HexagonVectorCombine::isUndef(const Value *Val) const -> bool {
965   return isa<UndefValue>(Val);
966 }
967 
968 auto HexagonVectorCombine::getSizeOf(const Value *Val) const -> int {
969   return getSizeOf(Val->getType());
970 }
971 
972 auto HexagonVectorCombine::getSizeOf(const Type *Ty) const -> int {
973   return DL.getTypeStoreSize(const_cast<Type *>(Ty)).getFixedValue();
974 }
975 
976 auto HexagonVectorCombine::getTypeAlignment(Type *Ty) const -> int {
977   // The actual type may be shorter than the HVX vector, so determine
978   // the alignment based on subtarget info.
979   if (HST.isTypeForHVX(Ty))
980     return HST.getVectorLength();
981   return DL.getABITypeAlign(Ty).value();
982 }
983 
984 auto HexagonVectorCombine::getNullValue(Type *Ty) const -> Constant * {
985   assert(Ty->isIntOrIntVectorTy());
986   auto Zero = ConstantInt::get(Ty->getScalarType(), 0);
987   if (auto *VecTy = dyn_cast<VectorType>(Ty))
988     return ConstantVector::getSplat(VecTy->getElementCount(), Zero);
989   return Zero;
990 }
991 
992 auto HexagonVectorCombine::getFullValue(Type *Ty) const -> Constant * {
993   assert(Ty->isIntOrIntVectorTy());
994   auto Minus1 = ConstantInt::get(Ty->getScalarType(), -1);
995   if (auto *VecTy = dyn_cast<VectorType>(Ty))
996     return ConstantVector::getSplat(VecTy->getElementCount(), Minus1);
997   return Minus1;
998 }
999 
1000 // Insert bytes [Start..Start+Length) of Src into Dst at byte Where.
1001 auto HexagonVectorCombine::insertb(IRBuilder<> &Builder, Value *Dst, Value *Src,
1002                                    int Start, int Length, int Where) const
1003     -> Value * {
1004   assert(isByteVecTy(Dst->getType()) && isByteVecTy(Src->getType()));
1005   int SrcLen = getSizeOf(Src);
1006   int DstLen = getSizeOf(Dst);
1007   assert(0 <= Start && Start + Length <= SrcLen);
1008   assert(0 <= Where && Where + Length <= DstLen);
1009 
1010   int P2Len = PowerOf2Ceil(SrcLen | DstLen);
1011   auto *Undef = UndefValue::get(getByteTy());
1012   Value *P2Src = vresize(Builder, Src, P2Len, Undef);
1013   Value *P2Dst = vresize(Builder, Dst, P2Len, Undef);
1014 
1015   SmallVector<int, 256> SMask(P2Len);
1016   for (int i = 0; i != P2Len; ++i) {
1017     // If i is in [Where, Where+Length), pick Src[Start+(i-Where)].
1018     // Otherwise, pick Dst[i];
1019     SMask[i] =
1020         (Where <= i && i < Where + Length) ? P2Len + Start + (i - Where) : i;
1021   }
1022 
1023   Value *P2Insert = Builder.CreateShuffleVector(P2Dst, P2Src, SMask);
1024   return vresize(Builder, P2Insert, DstLen, Undef);
1025 }
1026 
1027 auto HexagonVectorCombine::vlalignb(IRBuilder<> &Builder, Value *Lo, Value *Hi,
1028                                     Value *Amt) const -> Value * {
1029   assert(Lo->getType() == Hi->getType() && "Argument type mismatch");
1030   assert(isSectorTy(Hi->getType()));
1031   if (isZero(Amt))
1032     return Hi;
1033   int VecLen = getSizeOf(Hi);
1034   if (auto IntAmt = getIntValue(Amt))
1035     return getElementRange(Builder, Lo, Hi, VecLen - IntAmt->getSExtValue(),
1036                            VecLen);
1037 
1038   if (HST.isTypeForHVX(Hi->getType())) {
1039     int HwLen = HST.getVectorLength();
1040     assert(VecLen == HwLen && "Expecting an exact HVX type");
1041     Intrinsic::ID V6_vlalignb = HwLen == 64
1042                                     ? Intrinsic::hexagon_V6_vlalignb
1043                                     : Intrinsic::hexagon_V6_vlalignb_128B;
1044     return createHvxIntrinsic(Builder, V6_vlalignb, Hi->getType(),
1045                               {Hi, Lo, Amt});
1046   }
1047 
1048   if (VecLen == 4) {
1049     Value *Pair = concat(Builder, {Lo, Hi});
1050     Value *Shift = Builder.CreateLShr(Builder.CreateShl(Pair, Amt), 32);
1051     Value *Trunc = Builder.CreateTrunc(Shift, Type::getInt32Ty(F.getContext()));
1052     return Builder.CreateBitCast(Trunc, Hi->getType());
1053   }
1054   if (VecLen == 8) {
1055     Value *Sub = Builder.CreateSub(getConstInt(VecLen), Amt);
1056     return vralignb(Builder, Lo, Hi, Sub);
1057   }
1058   llvm_unreachable("Unexpected vector length");
1059 }
1060 
1061 auto HexagonVectorCombine::vralignb(IRBuilder<> &Builder, Value *Lo, Value *Hi,
1062                                     Value *Amt) const -> Value * {
1063   assert(Lo->getType() == Hi->getType() && "Argument type mismatch");
1064   assert(isSectorTy(Lo->getType()));
1065   if (isZero(Amt))
1066     return Lo;
1067   int VecLen = getSizeOf(Lo);
1068   if (auto IntAmt = getIntValue(Amt))
1069     return getElementRange(Builder, Lo, Hi, IntAmt->getSExtValue(), VecLen);
1070 
1071   if (HST.isTypeForHVX(Lo->getType())) {
1072     int HwLen = HST.getVectorLength();
1073     assert(VecLen == HwLen && "Expecting an exact HVX type");
1074     Intrinsic::ID V6_valignb = HwLen == 64 ? Intrinsic::hexagon_V6_valignb
1075                                            : Intrinsic::hexagon_V6_valignb_128B;
1076     return createHvxIntrinsic(Builder, V6_valignb, Lo->getType(),
1077                               {Hi, Lo, Amt});
1078   }
1079 
1080   if (VecLen == 4) {
1081     Value *Pair = concat(Builder, {Lo, Hi});
1082     Value *Shift = Builder.CreateLShr(Pair, Amt);
1083     Value *Trunc = Builder.CreateTrunc(Shift, Type::getInt32Ty(F.getContext()));
1084     return Builder.CreateBitCast(Trunc, Lo->getType());
1085   }
1086   if (VecLen == 8) {
1087     Type *Int64Ty = Type::getInt64Ty(F.getContext());
1088     Value *Lo64 = Builder.CreateBitCast(Lo, Int64Ty);
1089     Value *Hi64 = Builder.CreateBitCast(Hi, Int64Ty);
1090     Function *FI = Intrinsic::getDeclaration(F.getParent(),
1091                                              Intrinsic::hexagon_S2_valignrb);
1092     Value *Call = Builder.CreateCall(FI, {Hi64, Lo64, Amt});
1093     return Builder.CreateBitCast(Call, Lo->getType());
1094   }
1095   llvm_unreachable("Unexpected vector length");
1096 }
1097 
1098 // Concatenates a sequence of vectors of the same type.
1099 auto HexagonVectorCombine::concat(IRBuilder<> &Builder,
1100                                   ArrayRef<Value *> Vecs) const -> Value * {
1101   assert(!Vecs.empty());
1102   SmallVector<int, 256> SMask;
1103   std::vector<Value *> Work[2];
1104   int ThisW = 0, OtherW = 1;
1105 
1106   Work[ThisW].assign(Vecs.begin(), Vecs.end());
1107   while (Work[ThisW].size() > 1) {
1108     auto *Ty = cast<VectorType>(Work[ThisW].front()->getType());
1109     int ElemCount = Ty->getElementCount().getFixedValue();
1110     SMask.resize(ElemCount * 2);
1111     std::iota(SMask.begin(), SMask.end(), 0);
1112 
1113     Work[OtherW].clear();
1114     if (Work[ThisW].size() % 2 != 0)
1115       Work[ThisW].push_back(UndefValue::get(Ty));
1116     for (int i = 0, e = Work[ThisW].size(); i < e; i += 2) {
1117       Value *Joined = Builder.CreateShuffleVector(Work[ThisW][i],
1118                                                   Work[ThisW][i + 1], SMask);
1119       Work[OtherW].push_back(Joined);
1120     }
1121     std::swap(ThisW, OtherW);
1122   }
1123 
1124   // Since there may have been some undefs appended to make shuffle operands
1125   // have the same type, perform the last shuffle to only pick the original
1126   // elements.
1127   SMask.resize(Vecs.size() * getSizeOf(Vecs.front()->getType()));
1128   std::iota(SMask.begin(), SMask.end(), 0);
1129   Value *Total = Work[OtherW].front();
1130   return Builder.CreateShuffleVector(Total, SMask);
1131 }
1132 
1133 auto HexagonVectorCombine::vresize(IRBuilder<> &Builder, Value *Val,
1134                                    int NewSize, Value *Pad) const -> Value * {
1135   assert(isa<VectorType>(Val->getType()));
1136   auto *ValTy = cast<VectorType>(Val->getType());
1137   assert(ValTy->getElementType() == Pad->getType());
1138 
1139   int CurSize = ValTy->getElementCount().getFixedValue();
1140   if (CurSize == NewSize)
1141     return Val;
1142   // Truncate?
1143   if (CurSize > NewSize)
1144     return getElementRange(Builder, Val, /*Unused*/ Val, 0, NewSize);
1145   // Extend.
1146   SmallVector<int, 128> SMask(NewSize);
1147   std::iota(SMask.begin(), SMask.begin() + CurSize, 0);
1148   std::fill(SMask.begin() + CurSize, SMask.end(), CurSize);
1149   Value *PadVec = Builder.CreateVectorSplat(CurSize, Pad);
1150   return Builder.CreateShuffleVector(Val, PadVec, SMask);
1151 }
1152 
1153 auto HexagonVectorCombine::rescale(IRBuilder<> &Builder, Value *Mask,
1154                                    Type *FromTy, Type *ToTy) const -> Value * {
1155   // Mask is a vector <N x i1>, where each element corresponds to an
1156   // element of FromTy. Remap it so that each element will correspond
1157   // to an element of ToTy.
1158   assert(isa<VectorType>(Mask->getType()));
1159 
1160   Type *FromSTy = FromTy->getScalarType();
1161   Type *ToSTy = ToTy->getScalarType();
1162   if (FromSTy == ToSTy)
1163     return Mask;
1164 
1165   int FromSize = getSizeOf(FromSTy);
1166   int ToSize = getSizeOf(ToSTy);
1167   assert(FromSize % ToSize == 0 || ToSize % FromSize == 0);
1168 
1169   auto *MaskTy = cast<VectorType>(Mask->getType());
1170   int FromCount = MaskTy->getElementCount().getFixedValue();
1171   int ToCount = (FromCount * FromSize) / ToSize;
1172   assert((FromCount * FromSize) % ToSize == 0);
1173 
1174   // Mask <N x i1> -> sext to <N x FromTy> -> bitcast to <M x ToTy> ->
1175   // -> trunc to <M x i1>.
1176   Value *Ext = Builder.CreateSExt(
1177       Mask, VectorType::get(FromSTy, FromCount, /*Scalable*/ false));
1178   Value *Cast = Builder.CreateBitCast(
1179       Ext, VectorType::get(ToSTy, ToCount, /*Scalable*/ false));
1180   return Builder.CreateTrunc(
1181       Cast, VectorType::get(getBoolTy(), ToCount, /*Scalable*/ false));
1182 }
1183 
1184 // Bitcast to bytes, and return least significant bits.
1185 auto HexagonVectorCombine::vlsb(IRBuilder<> &Builder, Value *Val) const
1186     -> Value * {
1187   Type *ScalarTy = Val->getType()->getScalarType();
1188   if (ScalarTy == getBoolTy())
1189     return Val;
1190 
1191   Value *Bytes = vbytes(Builder, Val);
1192   if (auto *VecTy = dyn_cast<VectorType>(Bytes->getType()))
1193     return Builder.CreateTrunc(Bytes, getBoolTy(getSizeOf(VecTy)));
1194   // If Bytes is a scalar (i.e. Val was a scalar byte), return i1, not
1195   // <1 x i1>.
1196   return Builder.CreateTrunc(Bytes, getBoolTy());
1197 }
1198 
1199 // Bitcast to bytes for non-bool. For bool, convert i1 -> i8.
1200 auto HexagonVectorCombine::vbytes(IRBuilder<> &Builder, Value *Val) const
1201     -> Value * {
1202   Type *ScalarTy = Val->getType()->getScalarType();
1203   if (ScalarTy == getByteTy())
1204     return Val;
1205 
1206   if (ScalarTy != getBoolTy())
1207     return Builder.CreateBitCast(Val, getByteTy(getSizeOf(Val)));
1208   // For bool, return a sext from i1 to i8.
1209   if (auto *VecTy = dyn_cast<VectorType>(Val->getType()))
1210     return Builder.CreateSExt(Val, VectorType::get(getByteTy(), VecTy));
1211   return Builder.CreateSExt(Val, getByteTy());
1212 }
1213 
1214 auto HexagonVectorCombine::createHvxIntrinsic(IRBuilder<> &Builder,
1215                                               Intrinsic::ID IntID, Type *RetTy,
1216                                               ArrayRef<Value *> Args) const
1217     -> Value * {
1218   int HwLen = HST.getVectorLength();
1219   Type *BoolTy = Type::getInt1Ty(F.getContext());
1220   Type *Int32Ty = Type::getInt32Ty(F.getContext());
1221   // HVX vector -> v16i32/v32i32
1222   // HVX vector predicate -> v512i1/v1024i1
1223   auto getTypeForIntrin = [&](Type *Ty) -> Type * {
1224     if (HST.isTypeForHVX(Ty, /*IncludeBool*/ true)) {
1225       Type *ElemTy = cast<VectorType>(Ty)->getElementType();
1226       if (ElemTy == Int32Ty)
1227         return Ty;
1228       if (ElemTy == BoolTy)
1229         return VectorType::get(BoolTy, 8 * HwLen, /*Scalable*/ false);
1230       return VectorType::get(Int32Ty, HwLen / 4, /*Scalable*/ false);
1231     }
1232     // Non-HVX type. It should be a scalar.
1233     assert(Ty == Int32Ty || Ty->isIntegerTy(64));
1234     return Ty;
1235   };
1236 
1237   auto getCast = [&](IRBuilder<> &Builder, Value *Val,
1238                      Type *DestTy) -> Value * {
1239     Type *SrcTy = Val->getType();
1240     if (SrcTy == DestTy)
1241       return Val;
1242     if (HST.isTypeForHVX(SrcTy, /*IncludeBool*/ true)) {
1243       if (cast<VectorType>(SrcTy)->getElementType() == BoolTy) {
1244         // This should take care of casts the other way too, for example
1245         // v1024i1 -> v32i1.
1246         Intrinsic::ID TC = HwLen == 64
1247                                ? Intrinsic::hexagon_V6_pred_typecast
1248                                : Intrinsic::hexagon_V6_pred_typecast_128B;
1249         Function *FI = Intrinsic::getDeclaration(F.getParent(), TC,
1250                                                  {DestTy, Val->getType()});
1251         return Builder.CreateCall(FI, {Val});
1252       }
1253       // Non-predicate HVX vector.
1254       return Builder.CreateBitCast(Val, DestTy);
1255     }
1256     // Non-HVX type. It should be a scalar, and it should already have
1257     // a valid type.
1258     llvm_unreachable("Unexpected type");
1259   };
1260 
1261   SmallVector<Value *, 4> IntOps;
1262   for (Value *A : Args)
1263     IntOps.push_back(getCast(Builder, A, getTypeForIntrin(A->getType())));
1264   Function *FI = Intrinsic::getDeclaration(F.getParent(), IntID);
1265   Value *Call = Builder.CreateCall(FI, IntOps);
1266 
1267   Type *CallTy = Call->getType();
1268   if (CallTy == RetTy)
1269     return Call;
1270   // Scalar types should have RetTy matching the call return type.
1271   assert(HST.isTypeForHVX(CallTy, /*IncludeBool*/ true));
1272   if (cast<VectorType>(CallTy)->getElementType() == BoolTy)
1273     return getCast(Builder, Call, RetTy);
1274   return Builder.CreateBitCast(Call, RetTy);
1275 }
1276 
1277 auto HexagonVectorCombine::calculatePointerDifference(Value *Ptr0,
1278                                                       Value *Ptr1) const
1279     -> Optional<int> {
1280   struct Builder : IRBuilder<> {
1281     Builder(BasicBlock *B) : IRBuilder<>(B) {}
1282     ~Builder() {
1283       for (Instruction *I : llvm::reverse(ToErase))
1284         I->eraseFromParent();
1285     }
1286     SmallVector<Instruction *, 8> ToErase;
1287   };
1288 
1289 #define CallBuilder(B, F)                                                      \
1290   [&](auto &B_) {                                                              \
1291     Value *V = B_.F;                                                           \
1292     if (auto *I = dyn_cast<Instruction>(V))                                    \
1293       B_.ToErase.push_back(I);                                                 \
1294     return V;                                                                  \
1295   }(B)
1296 
1297   auto Simplify = [&](Value *V) {
1298     if (auto *I = dyn_cast<Instruction>(V)) {
1299       SimplifyQuery Q(DL, &TLI, &DT, &AC, I);
1300       if (Value *S = SimplifyInstruction(I, Q))
1301         return S;
1302     }
1303     return V;
1304   };
1305 
1306   auto StripBitCast = [](Value *V) {
1307     while (auto *C = dyn_cast<BitCastInst>(V))
1308       V = C->getOperand(0);
1309     return V;
1310   };
1311 
1312   Ptr0 = StripBitCast(Ptr0);
1313   Ptr1 = StripBitCast(Ptr1);
1314   if (!isa<GetElementPtrInst>(Ptr0) || !isa<GetElementPtrInst>(Ptr1))
1315     return None;
1316 
1317   auto *Gep0 = cast<GetElementPtrInst>(Ptr0);
1318   auto *Gep1 = cast<GetElementPtrInst>(Ptr1);
1319   if (Gep0->getPointerOperand() != Gep1->getPointerOperand())
1320     return None;
1321 
1322   Builder B(Gep0->getParent());
1323   Value *BasePtr = Gep0->getPointerOperand();
1324   int Scale = DL.getTypeStoreSize(BasePtr->getType()->getPointerElementType());
1325 
1326   // FIXME: for now only check GEPs with a single index.
1327   if (Gep0->getNumOperands() != 2 || Gep1->getNumOperands() != 2)
1328     return None;
1329 
1330   Value *Idx0 = Gep0->getOperand(1);
1331   Value *Idx1 = Gep1->getOperand(1);
1332 
1333   // First, try to simplify the subtraction directly.
1334   if (auto *Diff = dyn_cast<ConstantInt>(
1335           Simplify(CallBuilder(B, CreateSub(Idx0, Idx1)))))
1336     return Diff->getSExtValue() * Scale;
1337 
1338   KnownBits Known0 = computeKnownBits(Idx0, DL, 0, &AC, Gep0, &DT);
1339   KnownBits Known1 = computeKnownBits(Idx1, DL, 0, &AC, Gep1, &DT);
1340   APInt Unknown = ~(Known0.Zero | Known0.One) | ~(Known1.Zero | Known1.One);
1341   if (Unknown.isAllOnesValue())
1342     return None;
1343 
1344   Value *MaskU = ConstantInt::get(Idx0->getType(), Unknown);
1345   Value *AndU0 = Simplify(CallBuilder(B, CreateAnd(Idx0, MaskU)));
1346   Value *AndU1 = Simplify(CallBuilder(B, CreateAnd(Idx1, MaskU)));
1347   Value *SubU = Simplify(CallBuilder(B, CreateSub(AndU0, AndU1)));
1348   int Diff0 = 0;
1349   if (auto *C = dyn_cast<ConstantInt>(SubU)) {
1350     Diff0 = C->getSExtValue();
1351   } else {
1352     return None;
1353   }
1354 
1355   Value *MaskK = ConstantInt::get(MaskU->getType(), ~Unknown);
1356   Value *AndK0 = Simplify(CallBuilder(B, CreateAnd(Idx0, MaskK)));
1357   Value *AndK1 = Simplify(CallBuilder(B, CreateAnd(Idx1, MaskK)));
1358   Value *SubK = Simplify(CallBuilder(B, CreateSub(AndK0, AndK1)));
1359   int Diff1 = 0;
1360   if (auto *C = dyn_cast<ConstantInt>(SubK)) {
1361     Diff1 = C->getSExtValue();
1362   } else {
1363     return None;
1364   }
1365 
1366   return (Diff0 + Diff1) * Scale;
1367 
1368 #undef CallBuilder
1369 }
1370 
1371 template <typename T>
1372 auto HexagonVectorCombine::isSafeToMoveBeforeInBB(const Instruction &In,
1373                                                   BasicBlock::const_iterator To,
1374                                                   const T &Ignore) const
1375     -> bool {
1376   auto getLocOrNone = [this](const Instruction &I) -> Optional<MemoryLocation> {
1377     if (const auto *II = dyn_cast<IntrinsicInst>(&I)) {
1378       switch (II->getIntrinsicID()) {
1379       case Intrinsic::masked_load:
1380         return MemoryLocation::getForArgument(II, 0, TLI);
1381       case Intrinsic::masked_store:
1382         return MemoryLocation::getForArgument(II, 1, TLI);
1383       }
1384     }
1385     return MemoryLocation::getOrNone(&I);
1386   };
1387 
1388   // The source and the destination must be in the same basic block.
1389   const BasicBlock &Block = *In.getParent();
1390   assert(Block.begin() == To || Block.end() == To || To->getParent() == &Block);
1391   // No PHIs.
1392   if (isa<PHINode>(In) || (To != Block.end() && isa<PHINode>(*To)))
1393     return false;
1394 
1395   if (!mayBeMemoryDependent(In))
1396     return true;
1397   bool MayWrite = In.mayWriteToMemory();
1398   auto MaybeLoc = getLocOrNone(In);
1399 
1400   auto From = In.getIterator();
1401   if (From == To)
1402     return true;
1403   bool MoveUp = (To != Block.end() && To->comesBefore(&In));
1404   auto Range =
1405       MoveUp ? std::make_pair(To, From) : std::make_pair(std::next(From), To);
1406   for (auto It = Range.first; It != Range.second; ++It) {
1407     const Instruction &I = *It;
1408     if (llvm::is_contained(Ignore, &I))
1409       continue;
1410     // assume intrinsic can be ignored
1411     if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
1412       if (II->getIntrinsicID() == Intrinsic::assume)
1413         continue;
1414     }
1415     // Parts based on isSafeToMoveBefore from CoveMoverUtils.cpp.
1416     if (I.mayThrow())
1417       return false;
1418     if (auto *CB = dyn_cast<CallBase>(&I)) {
1419       if (!CB->hasFnAttr(Attribute::WillReturn))
1420         return false;
1421       if (!CB->hasFnAttr(Attribute::NoSync))
1422         return false;
1423     }
1424     if (I.mayReadOrWriteMemory()) {
1425       auto MaybeLocI = getLocOrNone(I);
1426       if (MayWrite || I.mayWriteToMemory()) {
1427         if (!MaybeLoc || !MaybeLocI)
1428           return false;
1429         if (!AA.isNoAlias(*MaybeLoc, *MaybeLocI))
1430           return false;
1431       }
1432     }
1433   }
1434   return true;
1435 }
1436 
1437 #ifndef NDEBUG
1438 auto HexagonVectorCombine::isByteVecTy(Type *Ty) const -> bool {
1439   if (auto *VecTy = dyn_cast<VectorType>(Ty))
1440     return VecTy->getElementType() == getByteTy();
1441   return false;
1442 }
1443 
1444 auto HexagonVectorCombine::isSectorTy(Type *Ty) const -> bool {
1445   if (!isByteVecTy(Ty))
1446     return false;
1447   int Size = getSizeOf(Ty);
1448   if (HST.isTypeForHVX(Ty))
1449     return Size == static_cast<int>(HST.getVectorLength());
1450   return Size == 4 || Size == 8;
1451 }
1452 #endif
1453 
1454 auto HexagonVectorCombine::getElementRange(IRBuilder<> &Builder, Value *Lo,
1455                                            Value *Hi, int Start,
1456                                            int Length) const -> Value * {
1457   assert(0 <= Start && Start < Length);
1458   SmallVector<int, 128> SMask(Length);
1459   std::iota(SMask.begin(), SMask.end(), Start);
1460   return Builder.CreateShuffleVector(Lo, Hi, SMask);
1461 }
1462 
1463 // Pass management.
1464 
1465 namespace llvm {
1466 void initializeHexagonVectorCombineLegacyPass(PassRegistry &);
1467 FunctionPass *createHexagonVectorCombineLegacyPass();
1468 } // namespace llvm
1469 
1470 namespace {
1471 class HexagonVectorCombineLegacy : public FunctionPass {
1472 public:
1473   static char ID;
1474 
1475   HexagonVectorCombineLegacy() : FunctionPass(ID) {}
1476 
1477   StringRef getPassName() const override { return "Hexagon Vector Combine"; }
1478 
1479   void getAnalysisUsage(AnalysisUsage &AU) const override {
1480     AU.setPreservesCFG();
1481     AU.addRequired<AAResultsWrapperPass>();
1482     AU.addRequired<AssumptionCacheTracker>();
1483     AU.addRequired<DominatorTreeWrapperPass>();
1484     AU.addRequired<TargetLibraryInfoWrapperPass>();
1485     AU.addRequired<TargetPassConfig>();
1486     FunctionPass::getAnalysisUsage(AU);
1487   }
1488 
1489   bool runOnFunction(Function &F) override {
1490     if (skipFunction(F))
1491       return false;
1492     AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1493     AssumptionCache &AC =
1494         getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1495     DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1496     TargetLibraryInfo &TLI =
1497         getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1498     auto &TM = getAnalysis<TargetPassConfig>().getTM<HexagonTargetMachine>();
1499     HexagonVectorCombine HVC(F, AA, AC, DT, TLI, TM);
1500     return HVC.run();
1501   }
1502 };
1503 } // namespace
1504 
1505 char HexagonVectorCombineLegacy::ID = 0;
1506 
1507 INITIALIZE_PASS_BEGIN(HexagonVectorCombineLegacy, DEBUG_TYPE,
1508                       "Hexagon Vector Combine", false, false)
1509 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1510 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1511 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1512 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1513 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
1514 INITIALIZE_PASS_END(HexagonVectorCombineLegacy, DEBUG_TYPE,
1515                     "Hexagon Vector Combine", false, false)
1516 
1517 FunctionPass *llvm::createHexagonVectorCombineLegacyPass() {
1518   return new HexagonVectorCombineLegacy();
1519 }
1520