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