xref: /llvm-project/llvm/lib/Target/Hexagon/HexagonVectorCombine.cpp (revision 1c7c7377cb5e12b7bc90d075fc7c79acf48d155a)
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/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/AssumptionCache.h"
21 #include "llvm/Analysis/InstSimplifyFolder.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/CodeGen/ValueTypes.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/IntrinsicsHexagon.h"
33 #include "llvm/IR/Metadata.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/InitializePasses.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/KnownBits.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Transforms/Utils/Local.h"
42 
43 #include "HexagonSubtarget.h"
44 #include "HexagonTargetMachine.h"
45 
46 #include <algorithm>
47 #include <deque>
48 #include <map>
49 #include <optional>
50 #include <set>
51 #include <utility>
52 #include <vector>
53 
54 #define DEBUG_TYPE "hexagon-vc"
55 
56 using namespace llvm;
57 
58 namespace {
59 class HexagonVectorCombine {
60 public:
61   HexagonVectorCombine(Function &F_, AliasAnalysis &AA_, AssumptionCache &AC_,
62                        DominatorTree &DT_, TargetLibraryInfo &TLI_,
63                        const TargetMachine &TM_)
64       : F(F_), DL(F.getParent()->getDataLayout()), AA(AA_), AC(AC_), DT(DT_),
65         TLI(TLI_),
66         HST(static_cast<const HexagonSubtarget &>(*TM_.getSubtargetImpl(F))) {}
67 
68   bool run();
69 
70   // Common integer type.
71   IntegerType *getIntTy(unsigned Width = 32) const;
72   // Byte type: either scalar (when Length = 0), or vector with given
73   // element count.
74   Type *getByteTy(int ElemCount = 0) const;
75   // Boolean type: either scalar (when Length = 0), or vector with given
76   // element count.
77   Type *getBoolTy(int ElemCount = 0) const;
78   // Create a ConstantInt of type returned by getIntTy with the value Val.
79   ConstantInt *getConstInt(int Val, unsigned Width = 32) const;
80   // Get the integer value of V, if it exists.
81   std::optional<APInt> getIntValue(const Value *Val) const;
82   // Is V a constant 0, or a vector of 0s?
83   bool isZero(const Value *Val) const;
84   // Is V an undef value?
85   bool isUndef(const Value *Val) const;
86 
87   // Get HVX vector type with the given element type.
88   VectorType *getHvxTy(Type *ElemTy, bool Pair = false) const;
89 
90   enum SizeKind {
91     Store, // Store size
92     Alloc, // Alloc size
93   };
94   int getSizeOf(const Value *Val, SizeKind Kind = Store) const;
95   int getSizeOf(const Type *Ty, SizeKind Kind = Store) const;
96   int getTypeAlignment(Type *Ty) const;
97   size_t length(Value *Val) const;
98   size_t length(Type *Ty) const;
99 
100   Constant *getNullValue(Type *Ty) const;
101   Constant *getFullValue(Type *Ty) const;
102   Constant *getConstSplat(Type *Ty, int Val) const;
103 
104   Value *simplify(Value *Val) const;
105 
106   Value *insertb(IRBuilderBase &Builder, Value *Dest, Value *Src, int Start,
107                  int Length, int Where) const;
108   Value *vlalignb(IRBuilderBase &Builder, Value *Lo, Value *Hi,
109                   Value *Amt) const;
110   Value *vralignb(IRBuilderBase &Builder, Value *Lo, Value *Hi,
111                   Value *Amt) const;
112   Value *concat(IRBuilderBase &Builder, ArrayRef<Value *> Vecs) const;
113   Value *vresize(IRBuilderBase &Builder, Value *Val, int NewSize,
114                  Value *Pad) const;
115   Value *rescale(IRBuilderBase &Builder, Value *Mask, Type *FromTy,
116                  Type *ToTy) const;
117   Value *vlsb(IRBuilderBase &Builder, Value *Val) const;
118   Value *vbytes(IRBuilderBase &Builder, Value *Val) const;
119   Value *subvector(IRBuilderBase &Builder, Value *Val, unsigned Start,
120                    unsigned Length) const;
121   Value *sublo(IRBuilderBase &Builder, Value *Val) const;
122   Value *subhi(IRBuilderBase &Builder, Value *Val) const;
123   Value *vdeal(IRBuilderBase &Builder, Value *Val0, Value *Val1) const;
124   Value *vshuff(IRBuilderBase &Builder, Value *Val0, Value *Val1) const;
125 
126   Value *createHvxIntrinsic(IRBuilderBase &Builder, Intrinsic::ID IntID,
127                             Type *RetTy, ArrayRef<Value *> Args,
128                             ArrayRef<Type *> ArgTys = std::nullopt) const;
129   SmallVector<Value *> splitVectorElements(IRBuilderBase &Builder, Value *Vec,
130                                            unsigned ToWidth) const;
131   Value *joinVectorElements(IRBuilderBase &Builder, ArrayRef<Value *> Values,
132                             VectorType *ToType) const;
133 
134   std::optional<int> calculatePointerDifference(Value *Ptr0, Value *Ptr1) const;
135 
136   unsigned getNumSignificantBits(const Value *V,
137                                  const Instruction *CtxI = nullptr) const;
138   KnownBits getKnownBits(const Value *V,
139                          const Instruction *CtxI = nullptr) const;
140 
141   template <typename T = std::vector<Instruction *>>
142   bool isSafeToMoveBeforeInBB(const Instruction &In,
143                               BasicBlock::const_iterator To,
144                               const T &IgnoreInsts = {}) const;
145 
146   // This function is only used for assertions at the moment.
147   [[maybe_unused]] bool isByteVecTy(Type *Ty) const;
148 
149   Function &F;
150   const DataLayout &DL;
151   AliasAnalysis &AA;
152   AssumptionCache &AC;
153   DominatorTree &DT;
154   TargetLibraryInfo &TLI;
155   const HexagonSubtarget &HST;
156 
157 private:
158   Value *getElementRange(IRBuilderBase &Builder, Value *Lo, Value *Hi,
159                          int Start, int Length) const;
160 };
161 
162 class AlignVectors {
163 public:
164   AlignVectors(const HexagonVectorCombine &HVC_) : HVC(HVC_) {}
165 
166   bool run();
167 
168 private:
169   using InstList = std::vector<Instruction *>;
170 
171   struct Segment {
172     void *Data;
173     int Start;
174     int Size;
175   };
176 
177   struct AddrInfo {
178     AddrInfo(const AddrInfo &) = default;
179     AddrInfo(const HexagonVectorCombine &HVC, Instruction *I, Value *A, Type *T,
180              Align H)
181         : Inst(I), Addr(A), ValTy(T), HaveAlign(H),
182           NeedAlign(HVC.getTypeAlignment(ValTy)) {}
183     AddrInfo &operator=(const AddrInfo &) = default;
184 
185     // XXX: add Size member?
186     Instruction *Inst;
187     Value *Addr;
188     Type *ValTy;
189     Align HaveAlign;
190     Align NeedAlign;
191     int Offset = 0; // Offset (in bytes) from the first member of the
192                     // containing AddrList.
193   };
194   using AddrList = std::vector<AddrInfo>;
195 
196   struct InstrLess {
197     bool operator()(const Instruction *A, const Instruction *B) const {
198       return A->comesBefore(B);
199     }
200   };
201   using DepList = std::set<Instruction *, InstrLess>;
202 
203   struct MoveGroup {
204     MoveGroup(const AddrInfo &AI, Instruction *B, bool Hvx, bool Load)
205         : Base(B), Main{AI.Inst}, IsHvx(Hvx), IsLoad(Load) {}
206     Instruction *Base; // Base instruction of the parent address group.
207     InstList Main;     // Main group of instructions.
208     InstList Deps;     // List of dependencies.
209     bool IsHvx;        // Is this group of HVX instructions?
210     bool IsLoad;       // Is this a load group?
211   };
212   using MoveList = std::vector<MoveGroup>;
213 
214   struct ByteSpan {
215     struct Segment {
216       // Segment of a Value: 'Len' bytes starting at byte 'Begin'.
217       Segment(Value *Val, int Begin, int Len)
218           : Val(Val), Start(Begin), Size(Len) {}
219       Segment(const Segment &Seg) = default;
220       Segment &operator=(const Segment &Seg) = default;
221       Value *Val; // Value representable as a sequence of bytes.
222       int Start;  // First byte of the value that belongs to the segment.
223       int Size;   // Number of bytes in the segment.
224     };
225 
226     struct Block {
227       Block(Value *Val, int Len, int Pos) : Seg(Val, 0, Len), Pos(Pos) {}
228       Block(Value *Val, int Off, int Len, int Pos)
229           : Seg(Val, Off, Len), Pos(Pos) {}
230       Block(const Block &Blk) = default;
231       Block &operator=(const Block &Blk) = default;
232       Segment Seg; // Value segment.
233       int Pos;     // Position (offset) of the segment in the Block.
234     };
235 
236     int extent() const;
237     ByteSpan section(int Start, int Length) const;
238     ByteSpan &shift(int Offset);
239     SmallVector<Value *, 8> values() const;
240 
241     int size() const { return Blocks.size(); }
242     Block &operator[](int i) { return Blocks[i]; }
243 
244     std::vector<Block> Blocks;
245 
246     using iterator = decltype(Blocks)::iterator;
247     iterator begin() { return Blocks.begin(); }
248     iterator end() { return Blocks.end(); }
249     using const_iterator = decltype(Blocks)::const_iterator;
250     const_iterator begin() const { return Blocks.begin(); }
251     const_iterator end() const { return Blocks.end(); }
252   };
253 
254   Align getAlignFromValue(const Value *V) const;
255   std::optional<MemoryLocation> getLocation(const Instruction &In) const;
256   std::optional<AddrInfo> getAddrInfo(Instruction &In) const;
257   bool isHvx(const AddrInfo &AI) const;
258   // This function is only used for assertions at the moment.
259   [[maybe_unused]] bool isSectorTy(Type *Ty) const;
260 
261   Value *getPayload(Value *Val) const;
262   Value *getMask(Value *Val) const;
263   Value *getPassThrough(Value *Val) const;
264 
265   Value *createAdjustedPointer(IRBuilderBase &Builder, Value *Ptr, Type *ValTy,
266                                int Adjust) const;
267   Value *createAlignedPointer(IRBuilderBase &Builder, Value *Ptr, Type *ValTy,
268                               int Alignment) const;
269   Value *createAlignedLoad(IRBuilderBase &Builder, Type *ValTy, Value *Ptr,
270                            int Alignment, Value *Mask, Value *PassThru) const;
271   Value *createAlignedStore(IRBuilderBase &Builder, Value *Val, Value *Ptr,
272                             int Alignment, Value *Mask) const;
273 
274   DepList getUpwardDeps(Instruction *In, Instruction *Base) const;
275   bool createAddressGroups();
276   MoveList createLoadGroups(const AddrList &Group) const;
277   MoveList createStoreGroups(const AddrList &Group) const;
278   bool move(const MoveGroup &Move) const;
279   void realignLoadGroup(IRBuilderBase &Builder, const ByteSpan &VSpan,
280                         int ScLen, Value *AlignVal, Value *AlignAddr) const;
281   void realignStoreGroup(IRBuilderBase &Builder, const ByteSpan &VSpan,
282                          int ScLen, Value *AlignVal, Value *AlignAddr) const;
283   bool realignGroup(const MoveGroup &Move) const;
284 
285   friend raw_ostream &operator<<(raw_ostream &OS, const AddrInfo &AI);
286   friend raw_ostream &operator<<(raw_ostream &OS, const MoveGroup &MG);
287   friend raw_ostream &operator<<(raw_ostream &OS, const ByteSpan::Block &B);
288   friend raw_ostream &operator<<(raw_ostream &OS, const ByteSpan &BS);
289 
290   std::map<Instruction *, AddrList> AddrGroups;
291   const HexagonVectorCombine &HVC;
292 };
293 
294 LLVM_ATTRIBUTE_UNUSED
295 raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::AddrInfo &AI) {
296   OS << "Inst: " << AI.Inst << "  " << *AI.Inst << '\n';
297   OS << "Addr: " << *AI.Addr << '\n';
298   OS << "Type: " << *AI.ValTy << '\n';
299   OS << "HaveAlign: " << AI.HaveAlign.value() << '\n';
300   OS << "NeedAlign: " << AI.NeedAlign.value() << '\n';
301   OS << "Offset: " << AI.Offset;
302   return OS;
303 }
304 
305 LLVM_ATTRIBUTE_UNUSED
306 raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::MoveGroup &MG) {
307   OS << "Main\n";
308   for (Instruction *I : MG.Main)
309     OS << "  " << *I << '\n';
310   OS << "Deps\n";
311   for (Instruction *I : MG.Deps)
312     OS << "  " << *I << '\n';
313   return OS;
314 }
315 
316 LLVM_ATTRIBUTE_UNUSED
317 raw_ostream &operator<<(raw_ostream &OS,
318                         const AlignVectors::ByteSpan::Block &B) {
319   OS << "  @" << B.Pos << " [" << B.Seg.Start << ',' << B.Seg.Size << "] "
320      << *B.Seg.Val;
321   return OS;
322 }
323 
324 LLVM_ATTRIBUTE_UNUSED
325 raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::ByteSpan &BS) {
326   OS << "ByteSpan[size=" << BS.size() << ", extent=" << BS.extent() << '\n';
327   for (const AlignVectors::ByteSpan::Block &B : BS)
328     OS << B << '\n';
329   OS << ']';
330   return OS;
331 }
332 
333 class HvxIdioms {
334 public:
335   HvxIdioms(const HexagonVectorCombine &HVC_) : HVC(HVC_) {
336     auto *Int32Ty = HVC.getIntTy(32);
337     HvxI32Ty = HVC.getHvxTy(Int32Ty, /*Pair=*/false);
338     HvxP32Ty = HVC.getHvxTy(Int32Ty, /*Pair=*/true);
339   }
340 
341   bool run();
342 
343 private:
344   enum Signedness { Positive, Signed, Unsigned };
345 
346   // Value + sign
347   // This is to keep track of whether the value should be treated as signed
348   // or unsigned, or is known to be positive.
349   struct SValue {
350     Value *Val;
351     Signedness Sgn;
352   };
353 
354   struct FxpOp {
355     unsigned Opcode;
356     unsigned Frac; // Number of fraction bits
357     SValue X, Y;
358     // If present, add 1 << RoundAt before shift:
359     std::optional<unsigned> RoundAt;
360   };
361 
362   auto getNumSignificantBits(Value *V, Instruction *In) const
363       -> std::pair<unsigned, Signedness>;
364   auto canonSgn(SValue X, SValue Y) const -> std::pair<SValue, SValue>;
365 
366   auto matchFxpMul(Instruction &In) const -> std::optional<FxpOp>;
367   auto processFxpMul(Instruction &In, const FxpOp &Op) const -> Value *;
368 
369   auto processFxpMulChopped(IRBuilderBase &Builder, Instruction &In,
370                             const FxpOp &Op) const -> Value *;
371   auto createMulQ15(IRBuilderBase &Builder, SValue X, SValue Y,
372                     bool Rounding) const -> Value *;
373   auto createMulQ31(IRBuilderBase &Builder, SValue X, SValue Y,
374                     bool Rounding) const -> Value *;
375   // Return {Result, Carry}, where Carry is a vector predicate.
376   auto createAddCarry(IRBuilderBase &Builder, Value *X, Value *Y,
377                       Value *CarryIn = nullptr) const
378       -> std::pair<Value *, Value *>;
379   auto createMul16(IRBuilderBase &Builder, SValue X, SValue Y) const -> Value *;
380   auto createMulH16(IRBuilderBase &Builder, SValue X, SValue Y) const
381       -> Value *;
382   auto createMul32(IRBuilderBase &Builder, SValue X, SValue Y) const
383       -> std::pair<Value *, Value *>;
384   auto createAddLong(IRBuilderBase &Builder, ArrayRef<Value *> WordX,
385                      ArrayRef<Value *> WordY) const -> SmallVector<Value *>;
386   auto createMulLong(IRBuilderBase &Builder, ArrayRef<Value *> WordX,
387                      Signedness SgnX, ArrayRef<Value *> WordY,
388                      Signedness SgnY) const -> SmallVector<Value *>;
389 
390   VectorType *HvxI32Ty;
391   VectorType *HvxP32Ty;
392   const HexagonVectorCombine &HVC;
393 
394   friend raw_ostream &operator<<(raw_ostream &, const FxpOp &);
395 };
396 
397 [[maybe_unused]] raw_ostream &operator<<(raw_ostream &OS,
398                                          const HvxIdioms::FxpOp &Op) {
399   static const char *SgnNames[] = {"Positive", "Signed", "Unsigned"};
400   OS << Instruction::getOpcodeName(Op.Opcode) << '.' << Op.Frac;
401   if (Op.RoundAt.has_value()) {
402     if (Op.Frac != 0 && Op.RoundAt.value() == Op.Frac - 1) {
403       OS << ":rnd";
404     } else {
405       OS << " + 1<<" << Op.RoundAt.value();
406     }
407   }
408   OS << "\n  X:(" << SgnNames[Op.X.Sgn] << ") " << *Op.X.Val << "\n"
409      << "  Y:(" << SgnNames[Op.Y.Sgn] << ") " << *Op.Y.Val;
410   return OS;
411 }
412 
413 } // namespace
414 
415 namespace {
416 
417 template <typename T> T *getIfUnordered(T *MaybeT) {
418   return MaybeT && MaybeT->isUnordered() ? MaybeT : nullptr;
419 }
420 template <typename T> T *isCandidate(Instruction *In) {
421   return dyn_cast<T>(In);
422 }
423 template <> LoadInst *isCandidate<LoadInst>(Instruction *In) {
424   return getIfUnordered(dyn_cast<LoadInst>(In));
425 }
426 template <> StoreInst *isCandidate<StoreInst>(Instruction *In) {
427   return getIfUnordered(dyn_cast<StoreInst>(In));
428 }
429 
430 #if !defined(_MSC_VER) || _MSC_VER >= 1926
431 // VS2017 and some versions of VS2019 have trouble compiling this:
432 // error C2976: 'std::map': too few template arguments
433 // VS 2019 16.x is known to work, except for 16.4/16.5 (MSC_VER 1924/1925)
434 template <typename Pred, typename... Ts>
435 void erase_if(std::map<Ts...> &map, Pred p)
436 #else
437 template <typename Pred, typename T, typename U>
438 void erase_if(std::map<T, U> &map, Pred p)
439 #endif
440 {
441   for (auto i = map.begin(), e = map.end(); i != e;) {
442     if (p(*i))
443       i = map.erase(i);
444     else
445       i = std::next(i);
446   }
447 }
448 
449 // Forward other erase_ifs to the LLVM implementations.
450 template <typename Pred, typename T> void erase_if(T &&container, Pred p) {
451   llvm::erase_if(std::forward<T>(container), p);
452 }
453 
454 } // namespace
455 
456 // --- Begin AlignVectors
457 
458 auto AlignVectors::ByteSpan::extent() const -> int {
459   if (size() == 0)
460     return 0;
461   int Min = Blocks[0].Pos;
462   int Max = Blocks[0].Pos + Blocks[0].Seg.Size;
463   for (int i = 1, e = size(); i != e; ++i) {
464     Min = std::min(Min, Blocks[i].Pos);
465     Max = std::max(Max, Blocks[i].Pos + Blocks[i].Seg.Size);
466   }
467   return Max - Min;
468 }
469 
470 auto AlignVectors::ByteSpan::section(int Start, int Length) const -> ByteSpan {
471   ByteSpan Section;
472   for (const ByteSpan::Block &B : Blocks) {
473     int L = std::max(B.Pos, Start);                       // Left end.
474     int R = std::min(B.Pos + B.Seg.Size, Start + Length); // Right end+1.
475     if (L < R) {
476       // How much to chop off the beginning of the segment:
477       int Off = L > B.Pos ? L - B.Pos : 0;
478       Section.Blocks.emplace_back(B.Seg.Val, B.Seg.Start + Off, R - L, L);
479     }
480   }
481   return Section;
482 }
483 
484 auto AlignVectors::ByteSpan::shift(int Offset) -> ByteSpan & {
485   for (Block &B : Blocks)
486     B.Pos += Offset;
487   return *this;
488 }
489 
490 auto AlignVectors::ByteSpan::values() const -> SmallVector<Value *, 8> {
491   SmallVector<Value *, 8> Values(Blocks.size());
492   for (int i = 0, e = Blocks.size(); i != e; ++i)
493     Values[i] = Blocks[i].Seg.Val;
494   return Values;
495 }
496 
497 auto AlignVectors::getAlignFromValue(const Value *V) const -> Align {
498   const auto *C = dyn_cast<ConstantInt>(V);
499   assert(C && "Alignment must be a compile-time constant integer");
500   return C->getAlignValue();
501 }
502 
503 auto AlignVectors::getAddrInfo(Instruction &In) const
504     -> std::optional<AddrInfo> {
505   if (auto *L = isCandidate<LoadInst>(&In))
506     return AddrInfo(HVC, L, L->getPointerOperand(), L->getType(),
507                     L->getAlign());
508   if (auto *S = isCandidate<StoreInst>(&In))
509     return AddrInfo(HVC, S, S->getPointerOperand(),
510                     S->getValueOperand()->getType(), S->getAlign());
511   if (auto *II = isCandidate<IntrinsicInst>(&In)) {
512     Intrinsic::ID ID = II->getIntrinsicID();
513     switch (ID) {
514     case Intrinsic::masked_load:
515       return AddrInfo(HVC, II, II->getArgOperand(0), II->getType(),
516                       getAlignFromValue(II->getArgOperand(1)));
517     case Intrinsic::masked_store:
518       return AddrInfo(HVC, II, II->getArgOperand(1),
519                       II->getArgOperand(0)->getType(),
520                       getAlignFromValue(II->getArgOperand(2)));
521     }
522   }
523   return std::nullopt;
524 }
525 
526 auto AlignVectors::isHvx(const AddrInfo &AI) const -> bool {
527   return HVC.HST.isTypeForHVX(AI.ValTy);
528 }
529 
530 auto AlignVectors::getPayload(Value *Val) const -> Value * {
531   if (auto *In = dyn_cast<Instruction>(Val)) {
532     Intrinsic::ID ID = 0;
533     if (auto *II = dyn_cast<IntrinsicInst>(In))
534       ID = II->getIntrinsicID();
535     if (isa<StoreInst>(In) || ID == Intrinsic::masked_store)
536       return In->getOperand(0);
537   }
538   return Val;
539 }
540 
541 auto AlignVectors::getMask(Value *Val) const -> Value * {
542   if (auto *II = dyn_cast<IntrinsicInst>(Val)) {
543     switch (II->getIntrinsicID()) {
544     case Intrinsic::masked_load:
545       return II->getArgOperand(2);
546     case Intrinsic::masked_store:
547       return II->getArgOperand(3);
548     }
549   }
550 
551   Type *ValTy = getPayload(Val)->getType();
552   if (auto *VecTy = dyn_cast<VectorType>(ValTy))
553     return HVC.getFullValue(HVC.getBoolTy(HVC.length(VecTy)));
554   return HVC.getFullValue(HVC.getBoolTy());
555 }
556 
557 auto AlignVectors::getPassThrough(Value *Val) const -> Value * {
558   if (auto *II = dyn_cast<IntrinsicInst>(Val)) {
559     if (II->getIntrinsicID() == Intrinsic::masked_load)
560       return II->getArgOperand(3);
561   }
562   return UndefValue::get(getPayload(Val)->getType());
563 }
564 
565 auto AlignVectors::createAdjustedPointer(IRBuilderBase &Builder, Value *Ptr,
566                                          Type *ValTy, int Adjust) const
567     -> Value * {
568   // The adjustment is in bytes, but if it's a multiple of the type size,
569   // we don't need to do pointer casts.
570   auto *PtrTy = cast<PointerType>(Ptr->getType());
571   if (!PtrTy->isOpaque()) {
572     Type *ElemTy = PtrTy->getNonOpaquePointerElementType();
573     int ElemSize = HVC.getSizeOf(ElemTy, HVC.Alloc);
574     if (Adjust % ElemSize == 0 && Adjust != 0) {
575       Value *Tmp0 =
576           Builder.CreateGEP(ElemTy, Ptr, HVC.getConstInt(Adjust / ElemSize));
577       return Builder.CreatePointerCast(Tmp0, ValTy->getPointerTo());
578     }
579   }
580 
581   PointerType *CharPtrTy = Type::getInt8PtrTy(HVC.F.getContext());
582   Value *Tmp0 = Builder.CreatePointerCast(Ptr, CharPtrTy);
583   Value *Tmp1 = Builder.CreateGEP(Type::getInt8Ty(HVC.F.getContext()), Tmp0,
584                                   HVC.getConstInt(Adjust));
585   return Builder.CreatePointerCast(Tmp1, ValTy->getPointerTo());
586 }
587 
588 auto AlignVectors::createAlignedPointer(IRBuilderBase &Builder, Value *Ptr,
589                                         Type *ValTy, int Alignment) const
590     -> Value * {
591   Value *AsInt = Builder.CreatePtrToInt(Ptr, HVC.getIntTy());
592   Value *Mask = HVC.getConstInt(-Alignment);
593   Value *And = Builder.CreateAnd(AsInt, Mask);
594   return Builder.CreateIntToPtr(And, ValTy->getPointerTo());
595 }
596 
597 auto AlignVectors::createAlignedLoad(IRBuilderBase &Builder, Type *ValTy,
598                                      Value *Ptr, int Alignment, Value *Mask,
599                                      Value *PassThru) const -> Value * {
600   assert(!HVC.isUndef(Mask)); // Should this be allowed?
601   if (HVC.isZero(Mask))
602     return PassThru;
603   if (Mask == ConstantInt::getTrue(Mask->getType()))
604     return Builder.CreateAlignedLoad(ValTy, Ptr, Align(Alignment));
605   return Builder.CreateMaskedLoad(ValTy, Ptr, Align(Alignment), Mask, PassThru);
606 }
607 
608 auto AlignVectors::createAlignedStore(IRBuilderBase &Builder, Value *Val,
609                                       Value *Ptr, int Alignment,
610                                       Value *Mask) const -> Value * {
611   if (HVC.isZero(Mask) || HVC.isUndef(Val) || HVC.isUndef(Mask))
612     return UndefValue::get(Val->getType());
613   if (Mask == ConstantInt::getTrue(Mask->getType()))
614     return Builder.CreateAlignedStore(Val, Ptr, Align(Alignment));
615   return Builder.CreateMaskedStore(Val, Ptr, Align(Alignment), Mask);
616 }
617 
618 auto AlignVectors::getUpwardDeps(Instruction *In, Instruction *Base) const
619     -> DepList {
620   BasicBlock *Parent = Base->getParent();
621   assert(In->getParent() == Parent &&
622          "Base and In should be in the same block");
623   assert(Base->comesBefore(In) && "Base should come before In");
624 
625   DepList Deps;
626   std::deque<Instruction *> WorkQ = {In};
627   while (!WorkQ.empty()) {
628     Instruction *D = WorkQ.front();
629     WorkQ.pop_front();
630     Deps.insert(D);
631     for (Value *Op : D->operands()) {
632       if (auto *I = dyn_cast<Instruction>(Op)) {
633         if (I->getParent() == Parent && Base->comesBefore(I))
634           WorkQ.push_back(I);
635       }
636     }
637   }
638   return Deps;
639 }
640 
641 auto AlignVectors::createAddressGroups() -> bool {
642   // An address group created here may contain instructions spanning
643   // multiple basic blocks.
644   AddrList WorkStack;
645 
646   auto findBaseAndOffset = [&](AddrInfo &AI) -> std::pair<Instruction *, int> {
647     for (AddrInfo &W : WorkStack) {
648       if (auto D = HVC.calculatePointerDifference(AI.Addr, W.Addr))
649         return std::make_pair(W.Inst, *D);
650     }
651     return std::make_pair(nullptr, 0);
652   };
653 
654   auto traverseBlock = [&](DomTreeNode *DomN, auto Visit) -> void {
655     BasicBlock &Block = *DomN->getBlock();
656     for (Instruction &I : Block) {
657       auto AI = this->getAddrInfo(I); // Use this-> for gcc6.
658       if (!AI)
659         continue;
660       auto F = findBaseAndOffset(*AI);
661       Instruction *GroupInst;
662       if (Instruction *BI = F.first) {
663         AI->Offset = F.second;
664         GroupInst = BI;
665       } else {
666         WorkStack.push_back(*AI);
667         GroupInst = AI->Inst;
668       }
669       AddrGroups[GroupInst].push_back(*AI);
670     }
671 
672     for (DomTreeNode *C : DomN->children())
673       Visit(C, Visit);
674 
675     while (!WorkStack.empty() && WorkStack.back().Inst->getParent() == &Block)
676       WorkStack.pop_back();
677   };
678 
679   traverseBlock(HVC.DT.getRootNode(), traverseBlock);
680   assert(WorkStack.empty());
681 
682   // AddrGroups are formed.
683 
684   // Remove groups of size 1.
685   erase_if(AddrGroups, [](auto &G) { return G.second.size() == 1; });
686   // Remove groups that don't use HVX types.
687   erase_if(AddrGroups, [&](auto &G) {
688     return llvm::none_of(
689         G.second, [&](auto &I) { return HVC.HST.isTypeForHVX(I.ValTy); });
690   });
691 
692   return !AddrGroups.empty();
693 }
694 
695 auto AlignVectors::createLoadGroups(const AddrList &Group) const -> MoveList {
696   // Form load groups.
697   // To avoid complications with moving code across basic blocks, only form
698   // groups that are contained within a single basic block.
699 
700   auto tryAddTo = [&](const AddrInfo &Info, MoveGroup &Move) {
701     assert(!Move.Main.empty() && "Move group should have non-empty Main");
702     // Don't mix HVX and non-HVX instructions.
703     if (Move.IsHvx != isHvx(Info))
704       return false;
705     // Leading instruction in the load group.
706     Instruction *Base = Move.Main.front();
707     if (Base->getParent() != Info.Inst->getParent())
708       return false;
709 
710     auto isSafeToMoveToBase = [&](const Instruction *I) {
711       return HVC.isSafeToMoveBeforeInBB(*I, Base->getIterator());
712     };
713     DepList Deps = getUpwardDeps(Info.Inst, Base);
714     if (!llvm::all_of(Deps, isSafeToMoveToBase))
715       return false;
716 
717     // The dependencies will be moved together with the load, so make sure
718     // that none of them could be moved independently in another group.
719     Deps.erase(Info.Inst);
720     auto inAddrMap = [&](Instruction *I) { return AddrGroups.count(I) > 0; };
721     if (llvm::any_of(Deps, inAddrMap))
722       return false;
723     Move.Main.push_back(Info.Inst);
724     llvm::append_range(Move.Deps, Deps);
725     return true;
726   };
727 
728   MoveList LoadGroups;
729 
730   for (const AddrInfo &Info : Group) {
731     if (!Info.Inst->mayReadFromMemory())
732       continue;
733     if (LoadGroups.empty() || !tryAddTo(Info, LoadGroups.back()))
734       LoadGroups.emplace_back(Info, Group.front().Inst, isHvx(Info), true);
735   }
736 
737   // Erase singleton groups.
738   erase_if(LoadGroups, [](const MoveGroup &G) { return G.Main.size() <= 1; });
739   return LoadGroups;
740 }
741 
742 auto AlignVectors::createStoreGroups(const AddrList &Group) const -> MoveList {
743   // Form store groups.
744   // To avoid complications with moving code across basic blocks, only form
745   // groups that are contained within a single basic block.
746 
747   auto tryAddTo = [&](const AddrInfo &Info, MoveGroup &Move) {
748     assert(!Move.Main.empty() && "Move group should have non-empty Main");
749     // For stores with return values we'd have to collect downward depenencies.
750     // There are no such stores that we handle at the moment, so omit that.
751     assert(Info.Inst->getType()->isVoidTy() &&
752            "Not handling stores with return values");
753     // Don't mix HVX and non-HVX instructions.
754     if (Move.IsHvx != isHvx(Info))
755       return false;
756     // For stores we need to be careful whether it's safe to move them.
757     // Stores that are otherwise safe to move together may not appear safe
758     // to move over one another (i.e. isSafeToMoveBefore may return false).
759     Instruction *Base = Move.Main.front();
760     if (Base->getParent() != Info.Inst->getParent())
761       return false;
762     if (!HVC.isSafeToMoveBeforeInBB(*Info.Inst, Base->getIterator(), Move.Main))
763       return false;
764     Move.Main.push_back(Info.Inst);
765     return true;
766   };
767 
768   MoveList StoreGroups;
769 
770   for (auto I = Group.rbegin(), E = Group.rend(); I != E; ++I) {
771     const AddrInfo &Info = *I;
772     if (!Info.Inst->mayWriteToMemory())
773       continue;
774     if (StoreGroups.empty() || !tryAddTo(Info, StoreGroups.back()))
775       StoreGroups.emplace_back(Info, Group.front().Inst, isHvx(Info), false);
776   }
777 
778   // Erase singleton groups.
779   erase_if(StoreGroups, [](const MoveGroup &G) { return G.Main.size() <= 1; });
780   return StoreGroups;
781 }
782 
783 auto AlignVectors::move(const MoveGroup &Move) const -> bool {
784   assert(!Move.Main.empty() && "Move group should have non-empty Main");
785   Instruction *Where = Move.Main.front();
786 
787   if (Move.IsLoad) {
788     // Move all deps to before Where, keeping order.
789     for (Instruction *D : Move.Deps)
790       D->moveBefore(Where);
791     // Move all main instructions to after Where, keeping order.
792     ArrayRef<Instruction *> Main(Move.Main);
793     for (Instruction *M : Main.drop_front(1)) {
794       M->moveAfter(Where);
795       Where = M;
796     }
797   } else {
798     // NOTE: Deps are empty for "store" groups. If they need to be
799     // non-empty, decide on the order.
800     assert(Move.Deps.empty());
801     // Move all main instructions to before Where, inverting order.
802     ArrayRef<Instruction *> Main(Move.Main);
803     for (Instruction *M : Main.drop_front(1)) {
804       M->moveBefore(Where);
805       Where = M;
806     }
807   }
808 
809   return Move.Main.size() + Move.Deps.size() > 1;
810 }
811 
812 auto AlignVectors::realignLoadGroup(IRBuilderBase &Builder,
813                                     const ByteSpan &VSpan, int ScLen,
814                                     Value *AlignVal, Value *AlignAddr) const
815     -> void {
816   Type *SecTy = HVC.getByteTy(ScLen);
817   int NumSectors = (VSpan.extent() + ScLen - 1) / ScLen;
818   bool DoAlign = !HVC.isZero(AlignVal);
819   BasicBlock::iterator BasePos = Builder.GetInsertPoint();
820   BasicBlock *BaseBlock = Builder.GetInsertBlock();
821 
822   ByteSpan ASpan;
823   auto *True = HVC.getFullValue(HVC.getBoolTy(ScLen));
824   auto *Undef = UndefValue::get(SecTy);
825 
826   SmallVector<Instruction *> Loads(NumSectors + DoAlign, nullptr);
827 
828   // We could create all of the aligned loads, and generate the valigns
829   // at the location of the first load, but for large load groups, this
830   // could create highly suboptimal code (there have been groups of 140+
831   // loads in real code).
832   // Instead, place the loads/valigns as close to the users as possible.
833   // In any case we need to have a mapping from the blocks of VSpan (the
834   // span covered by the pre-existing loads) to ASpan (the span covered
835   // by the aligned loads). There is a small problem, though: ASpan needs
836   // to have pointers to the loads/valigns, but we don't know where to put
837   // them yet. We can't use nullptr, because when we create sections of
838   // ASpan (corresponding to blocks from VSpan), for each block in the
839   // section we need to know which blocks of ASpan they are a part of.
840   // To have 1-1 mapping between blocks of ASpan and the temporary value
841   // pointers, use the addresses of the blocks themselves.
842 
843   // Populate the blocks first, to avoid reallocations of the vector
844   // interfering with generating the placeholder addresses.
845   for (int Index = 0; Index != NumSectors; ++Index)
846     ASpan.Blocks.emplace_back(nullptr, ScLen, Index * ScLen);
847   for (int Index = 0; Index != NumSectors; ++Index) {
848     ASpan.Blocks[Index].Seg.Val =
849         reinterpret_cast<Value *>(&ASpan.Blocks[Index]);
850   }
851 
852   // Multiple values from VSpan can map to the same value in ASpan. Since we
853   // try to create loads lazily, we need to find the earliest use for each
854   // value from ASpan.
855   DenseMap<void *, Instruction *> EarliestUser;
856   auto isEarlier = [](Instruction *A, Instruction *B) {
857     if (B == nullptr)
858       return true;
859     if (A == nullptr)
860       return false;
861     assert(A->getParent() == B->getParent());
862     return A->comesBefore(B);
863   };
864   auto earliestUser = [&](const auto &Uses) {
865     Instruction *User = nullptr;
866     for (const Use &U : Uses) {
867       auto *I = dyn_cast<Instruction>(U.getUser());
868       assert(I != nullptr && "Load used in a non-instruction?");
869       // Make sure we only consider at users in this block, but we need
870       // to remember if there were users outside the block too. This is
871       // because if there are no users, aligned loads will not be created.
872       if (I->getParent() == BaseBlock) {
873         if (!isa<PHINode>(I))
874           User = std::min(User, I, isEarlier);
875       } else {
876         User = std::min(User, BaseBlock->getTerminator(), isEarlier);
877       }
878     }
879     return User;
880   };
881 
882   for (const ByteSpan::Block &B : VSpan) {
883     ByteSpan ASection = ASpan.section(B.Pos, B.Seg.Size);
884     for (const ByteSpan::Block &S : ASection) {
885       EarliestUser[S.Seg.Val] = std::min(
886           EarliestUser[S.Seg.Val], earliestUser(B.Seg.Val->uses()), isEarlier);
887     }
888   }
889 
890   auto createLoad = [&](IRBuilderBase &Builder, const ByteSpan &VSpan,
891                         int Index) {
892     Value *Ptr =
893         createAdjustedPointer(Builder, AlignAddr, SecTy, Index * ScLen);
894     // FIXME: generate a predicated load?
895     Value *Load = createAlignedLoad(Builder, SecTy, Ptr, ScLen, True, Undef);
896     // If vector shifting is potentially needed, accumulate metadata
897     // from source sections of twice the load width.
898     int Start = (Index - DoAlign) * ScLen;
899     int Width = (1 + DoAlign) * ScLen;
900     propagateMetadata(cast<Instruction>(Load),
901                       VSpan.section(Start, Width).values());
902     return cast<Instruction>(Load);
903   };
904 
905   auto moveBefore = [this](Instruction *In, Instruction *To) {
906     // Move In and its upward dependencies to before To.
907     assert(In->getParent() == To->getParent());
908     DepList Deps = getUpwardDeps(In, To);
909     // DepList is sorted with respect to positions in the basic block.
910     for (Instruction *I : Deps)
911       I->moveBefore(To);
912   };
913 
914   // Generate necessary loads at appropriate locations.
915   for (int Index = 0; Index != NumSectors + 1; ++Index) {
916     // In ASpan, each block will be either a single aligned load, or a
917     // valign of a pair of loads. In the latter case, an aligned load j
918     // will belong to the current valign, and the one in the previous
919     // block (for j > 0).
920     Instruction *PrevAt =
921         DoAlign && Index > 0 ? EarliestUser[&ASpan[Index - 1]] : nullptr;
922     Instruction *ThisAt =
923         Index < NumSectors ? EarliestUser[&ASpan[Index]] : nullptr;
924     if (auto *Where = std::min(PrevAt, ThisAt, isEarlier)) {
925       Builder.SetInsertPoint(Where);
926       Loads[Index] = createLoad(Builder, VSpan, Index);
927       // We know it's safe to put the load at BasePos, so if it's not safe
928       // to move it from this location to BasePos, then the current location
929       // is not valid.
930       // We can't do this check proactively because we need the load to exist
931       // in order to check legality.
932       if (!HVC.isSafeToMoveBeforeInBB(*Loads[Index], BasePos))
933         moveBefore(Loads[Index], &*BasePos);
934     }
935   }
936   // Generate valigns if needed, and fill in proper values in ASpan
937   for (int Index = 0; Index != NumSectors; ++Index) {
938     ASpan[Index].Seg.Val = nullptr;
939     if (auto *Where = EarliestUser[&ASpan[Index]]) {
940       Builder.SetInsertPoint(Where);
941       Value *Val = Loads[Index];
942       assert(Val != nullptr);
943       if (DoAlign) {
944         Value *NextLoad = Loads[Index + 1];
945         assert(NextLoad != nullptr);
946         Val = HVC.vralignb(Builder, Val, NextLoad, AlignVal);
947       }
948       ASpan[Index].Seg.Val = Val;
949     }
950   }
951 
952   for (const ByteSpan::Block &B : VSpan) {
953     ByteSpan ASection = ASpan.section(B.Pos, B.Seg.Size).shift(-B.Pos);
954     Value *Accum = UndefValue::get(HVC.getByteTy(B.Seg.Size));
955     Builder.SetInsertPoint(cast<Instruction>(B.Seg.Val));
956 
957     for (ByteSpan::Block &S : ASection) {
958       if (S.Seg.Val == nullptr)
959         continue;
960       // The processing of the data loaded by the aligned loads
961       // needs to be inserted after the data is available.
962       Instruction *SegI = cast<Instruction>(S.Seg.Val);
963       Builder.SetInsertPoint(&*std::next(SegI->getIterator()));
964       Value *Pay = HVC.vbytes(Builder, getPayload(S.Seg.Val));
965       Accum = HVC.insertb(Builder, Accum, Pay, S.Seg.Start, S.Seg.Size, S.Pos);
966     }
967     // Instead of casting everything to bytes for the vselect, cast to the
968     // original value type. This will avoid complications with casting masks.
969     // For example, in cases when the original mask applied to i32, it could
970     // be converted to a mask applicable to i8 via pred_typecast intrinsic,
971     // but if the mask is not exactly of HVX length, extra handling would be
972     // needed to make it work.
973     Type *ValTy = getPayload(B.Seg.Val)->getType();
974     Value *Cast = Builder.CreateBitCast(Accum, ValTy);
975     Value *Sel = Builder.CreateSelect(getMask(B.Seg.Val), Cast,
976                                       getPassThrough(B.Seg.Val));
977     B.Seg.Val->replaceAllUsesWith(Sel);
978   }
979 }
980 
981 auto AlignVectors::realignStoreGroup(IRBuilderBase &Builder,
982                                      const ByteSpan &VSpan, int ScLen,
983                                      Value *AlignVal, Value *AlignAddr) const
984     -> void {
985   Type *SecTy = HVC.getByteTy(ScLen);
986   int NumSectors = (VSpan.extent() + ScLen - 1) / ScLen;
987   bool DoAlign = !HVC.isZero(AlignVal);
988 
989   // Stores.
990   ByteSpan ASpanV, ASpanM;
991 
992   // Return a vector value corresponding to the input value Val:
993   // either <1 x Val> for scalar Val, or Val itself for vector Val.
994   auto MakeVec = [](IRBuilderBase &Builder, Value *Val) -> Value * {
995     Type *Ty = Val->getType();
996     if (Ty->isVectorTy())
997       return Val;
998     auto *VecTy = VectorType::get(Ty, 1, /*Scalable=*/false);
999     return Builder.CreateBitCast(Val, VecTy);
1000   };
1001 
1002   // Create an extra "undef" sector at the beginning and at the end.
1003   // They will be used as the left/right filler in the vlalign step.
1004   for (int i = (DoAlign ? -1 : 0); i != NumSectors + DoAlign; ++i) {
1005     // For stores, the size of each section is an aligned vector length.
1006     // Adjust the store offsets relative to the section start offset.
1007     ByteSpan VSection = VSpan.section(i * ScLen, ScLen).shift(-i * ScLen);
1008     Value *AccumV = UndefValue::get(SecTy);
1009     Value *AccumM = HVC.getNullValue(SecTy);
1010     for (ByteSpan::Block &S : VSection) {
1011       Value *Pay = getPayload(S.Seg.Val);
1012       Value *Mask = HVC.rescale(Builder, MakeVec(Builder, getMask(S.Seg.Val)),
1013                                 Pay->getType(), HVC.getByteTy());
1014       AccumM = HVC.insertb(Builder, AccumM, HVC.vbytes(Builder, Mask),
1015                            S.Seg.Start, S.Seg.Size, S.Pos);
1016       AccumV = HVC.insertb(Builder, AccumV, HVC.vbytes(Builder, Pay),
1017                            S.Seg.Start, S.Seg.Size, S.Pos);
1018     }
1019     ASpanV.Blocks.emplace_back(AccumV, ScLen, i * ScLen);
1020     ASpanM.Blocks.emplace_back(AccumM, ScLen, i * ScLen);
1021   }
1022 
1023   // vlalign
1024   if (DoAlign) {
1025     for (int j = 1; j != NumSectors + 2; ++j) {
1026       Value *PrevV = ASpanV[j - 1].Seg.Val, *ThisV = ASpanV[j].Seg.Val;
1027       Value *PrevM = ASpanM[j - 1].Seg.Val, *ThisM = ASpanM[j].Seg.Val;
1028       assert(isSectorTy(PrevV->getType()) && isSectorTy(PrevM->getType()));
1029       ASpanV[j - 1].Seg.Val = HVC.vlalignb(Builder, PrevV, ThisV, AlignVal);
1030       ASpanM[j - 1].Seg.Val = HVC.vlalignb(Builder, PrevM, ThisM, AlignVal);
1031     }
1032   }
1033 
1034   for (int i = 0; i != NumSectors + DoAlign; ++i) {
1035     Value *Ptr = createAdjustedPointer(Builder, AlignAddr, SecTy, i * ScLen);
1036     Value *Val = ASpanV[i].Seg.Val;
1037     Value *Mask = ASpanM[i].Seg.Val; // bytes
1038     if (!HVC.isUndef(Val) && !HVC.isZero(Mask)) {
1039       Value *Store =
1040           createAlignedStore(Builder, Val, Ptr, ScLen, HVC.vlsb(Builder, Mask));
1041       // If vector shifting is potentially needed, accumulate metadata
1042       // from source sections of twice the store width.
1043       int Start = (i - DoAlign) * ScLen;
1044       int Width = (1 + DoAlign) * ScLen;
1045       propagateMetadata(cast<Instruction>(Store),
1046                         VSpan.section(Start, Width).values());
1047     }
1048   }
1049 }
1050 
1051 auto AlignVectors::realignGroup(const MoveGroup &Move) const -> bool {
1052   // TODO: Needs support for masked loads/stores of "scalar" vectors.
1053   if (!Move.IsHvx)
1054     return false;
1055 
1056   // Return the element with the maximum alignment from Range,
1057   // where GetValue obtains the value to compare from an element.
1058   auto getMaxOf = [](auto Range, auto GetValue) {
1059     return *std::max_element(
1060         Range.begin(), Range.end(),
1061         [&GetValue](auto &A, auto &B) { return GetValue(A) < GetValue(B); });
1062   };
1063 
1064   const AddrList &BaseInfos = AddrGroups.at(Move.Base);
1065 
1066   // Conceptually, there is a vector of N bytes covering the addresses
1067   // starting from the minimum offset (i.e. Base.Addr+Start). This vector
1068   // represents a contiguous memory region that spans all accessed memory
1069   // locations.
1070   // The correspondence between loaded or stored values will be expressed
1071   // in terms of this vector. For example, the 0th element of the vector
1072   // from the Base address info will start at byte Start from the beginning
1073   // of this conceptual vector.
1074   //
1075   // This vector will be loaded/stored starting at the nearest down-aligned
1076   // address and the amount od the down-alignment will be AlignVal:
1077   //   valign(load_vector(align_down(Base+Start)), AlignVal)
1078 
1079   std::set<Instruction *> TestSet(Move.Main.begin(), Move.Main.end());
1080   AddrList MoveInfos;
1081   llvm::copy_if(
1082       BaseInfos, std::back_inserter(MoveInfos),
1083       [&TestSet](const AddrInfo &AI) { return TestSet.count(AI.Inst); });
1084 
1085   // Maximum alignment present in the whole address group.
1086   const AddrInfo &WithMaxAlign =
1087       getMaxOf(MoveInfos, [](const AddrInfo &AI) { return AI.HaveAlign; });
1088   Align MaxGiven = WithMaxAlign.HaveAlign;
1089 
1090   // Minimum alignment present in the move address group.
1091   const AddrInfo &WithMinOffset =
1092       getMaxOf(MoveInfos, [](const AddrInfo &AI) { return -AI.Offset; });
1093 
1094   const AddrInfo &WithMaxNeeded =
1095       getMaxOf(MoveInfos, [](const AddrInfo &AI) { return AI.NeedAlign; });
1096   Align MinNeeded = WithMaxNeeded.NeedAlign;
1097 
1098   // Set the builder's insertion point right before the load group, or
1099   // immediately after the store group. (Instructions in a store group are
1100   // listed in reverse order.)
1101   Instruction *InsertAt = Move.Main.front();
1102   if (!Move.IsLoad) {
1103     // There should be a terminator (which store isn't, but check anyways).
1104     assert(InsertAt->getIterator() != InsertAt->getParent()->end());
1105     InsertAt = &*std::next(InsertAt->getIterator());
1106   }
1107 
1108   IRBuilder Builder(InsertAt->getParent(), InsertAt->getIterator(),
1109                     InstSimplifyFolder(HVC.DL));
1110   Value *AlignAddr = nullptr; // Actual aligned address.
1111   Value *AlignVal = nullptr;  // Right-shift amount (for valign).
1112 
1113   if (MinNeeded <= MaxGiven) {
1114     int Start = WithMinOffset.Offset;
1115     int OffAtMax = WithMaxAlign.Offset;
1116     // Shift the offset of the maximally aligned instruction (OffAtMax)
1117     // back by just enough multiples of the required alignment to cover the
1118     // distance from Start to OffAtMax.
1119     // Calculate the address adjustment amount based on the address with the
1120     // maximum alignment. This is to allow a simple gep instruction instead
1121     // of potential bitcasts to i8*.
1122     int Adjust = -alignTo(OffAtMax - Start, MinNeeded.value());
1123     AlignAddr = createAdjustedPointer(Builder, WithMaxAlign.Addr,
1124                                       WithMaxAlign.ValTy, Adjust);
1125     int Diff = Start - (OffAtMax + Adjust);
1126     AlignVal = HVC.getConstInt(Diff);
1127     assert(Diff >= 0);
1128     assert(static_cast<decltype(MinNeeded.value())>(Diff) < MinNeeded.value());
1129   } else {
1130     // WithMinOffset is the lowest address in the group,
1131     //   WithMinOffset.Addr = Base+Start.
1132     // Align instructions for both HVX (V6_valign) and scalar (S2_valignrb)
1133     // mask off unnecessary bits, so it's ok to just the original pointer as
1134     // the alignment amount.
1135     // Do an explicit down-alignment of the address to avoid creating an
1136     // aligned instruction with an address that is not really aligned.
1137     AlignAddr = createAlignedPointer(Builder, WithMinOffset.Addr,
1138                                      WithMinOffset.ValTy, MinNeeded.value());
1139     AlignVal = Builder.CreatePtrToInt(WithMinOffset.Addr, HVC.getIntTy());
1140   }
1141 
1142   ByteSpan VSpan;
1143   for (const AddrInfo &AI : MoveInfos) {
1144     VSpan.Blocks.emplace_back(AI.Inst, HVC.getSizeOf(AI.ValTy),
1145                               AI.Offset - WithMinOffset.Offset);
1146   }
1147 
1148   // The aligned loads/stores will use blocks that are either scalars,
1149   // or HVX vectors. Let "sector" be the unified term for such a block.
1150   // blend(scalar, vector) -> sector...
1151   int ScLen = Move.IsHvx ? HVC.HST.getVectorLength()
1152                          : std::max<int>(MinNeeded.value(), 4);
1153   assert(!Move.IsHvx || ScLen == 64 || ScLen == 128);
1154   assert(Move.IsHvx || ScLen == 4 || ScLen == 8);
1155 
1156   if (Move.IsLoad)
1157     realignLoadGroup(Builder, VSpan, ScLen, AlignVal, AlignAddr);
1158   else
1159     realignStoreGroup(Builder, VSpan, ScLen, AlignVal, AlignAddr);
1160 
1161   for (auto *Inst : Move.Main)
1162     Inst->eraseFromParent();
1163 
1164   return true;
1165 }
1166 
1167 auto AlignVectors::isSectorTy(Type *Ty) const -> bool {
1168   if (!HVC.isByteVecTy(Ty))
1169     return false;
1170   int Size = HVC.getSizeOf(Ty);
1171   if (HVC.HST.isTypeForHVX(Ty))
1172     return Size == static_cast<int>(HVC.HST.getVectorLength());
1173   return Size == 4 || Size == 8;
1174 }
1175 
1176 auto AlignVectors::run() -> bool {
1177   if (!createAddressGroups())
1178     return false;
1179 
1180   bool Changed = false;
1181   MoveList LoadGroups, StoreGroups;
1182 
1183   for (auto &G : AddrGroups) {
1184     llvm::append_range(LoadGroups, createLoadGroups(G.second));
1185     llvm::append_range(StoreGroups, createStoreGroups(G.second));
1186   }
1187 
1188   for (auto &M : LoadGroups)
1189     Changed |= move(M);
1190   for (auto &M : StoreGroups)
1191     Changed |= move(M);
1192 
1193   for (auto &M : LoadGroups)
1194     Changed |= realignGroup(M);
1195   for (auto &M : StoreGroups)
1196     Changed |= realignGroup(M);
1197 
1198   return Changed;
1199 }
1200 
1201 // --- End AlignVectors
1202 
1203 // --- Begin HvxIdioms
1204 
1205 auto HvxIdioms::getNumSignificantBits(Value *V, Instruction *In) const
1206     -> std::pair<unsigned, Signedness> {
1207   unsigned Bits = HVC.getNumSignificantBits(V, In);
1208   // The significant bits are calculated including the sign bit. This may
1209   // add an extra bit for zero-extended values, e.g. (zext i32 to i64) may
1210   // result in 33 significant bits. To avoid extra words, skip the extra
1211   // sign bit, but keep information that the value is to be treated as
1212   // unsigned.
1213   KnownBits Known = HVC.getKnownBits(V, In);
1214   Signedness Sign = Signed;
1215   unsigned NumToTest = 0; // Number of bits used in test for unsignedness.
1216   if (isPowerOf2_32(Bits))
1217     NumToTest = Bits;
1218   else if (Bits > 1 && isPowerOf2_32(Bits - 1))
1219     NumToTest = Bits - 1;
1220 
1221   if (NumToTest != 0 && Known.Zero.ashr(NumToTest).isAllOnes()) {
1222     Sign = Unsigned;
1223     Bits = NumToTest;
1224   }
1225 
1226   // If the top bit of the nearest power-of-2 is zero, this value is
1227   // positive. It could be treated as either signed or unsigned.
1228   if (unsigned Pow2 = PowerOf2Ceil(Bits); Pow2 != Bits) {
1229     if (Known.Zero.ashr(Pow2 - 1).isAllOnes())
1230       Sign = Positive;
1231   }
1232   return {Bits, Sign};
1233 }
1234 
1235 auto HvxIdioms::canonSgn(SValue X, SValue Y) const
1236     -> std::pair<SValue, SValue> {
1237   // Canonicalize the signedness of X and Y, so that the result is one of:
1238   //   S, S
1239   //   U/P, S
1240   //   U/P, U/P
1241   if (X.Sgn == Signed && Y.Sgn != Signed)
1242     std::swap(X, Y);
1243   return {X, Y};
1244 }
1245 
1246 // Match
1247 //   (X * Y) [>> N], or
1248 //   ((X * Y) + (1 << N-1)) >> N
1249 auto HvxIdioms::matchFxpMul(Instruction &In) const -> std::optional<FxpOp> {
1250   using namespace PatternMatch;
1251   auto *Ty = In.getType();
1252 
1253   if (!Ty->isVectorTy() || !Ty->getScalarType()->isIntegerTy())
1254     return std::nullopt;
1255 
1256   unsigned Width = cast<IntegerType>(Ty->getScalarType())->getBitWidth();
1257 
1258   FxpOp Op;
1259   Value *Exp = &In;
1260 
1261   // Fixed-point multiplication is always shifted right (except when the
1262   // fraction is 0 bits).
1263   auto m_Shr = [](auto &&V, auto &&S) {
1264     return m_CombineOr(m_LShr(V, S), m_AShr(V, S));
1265   };
1266 
1267   const APInt *Qn = nullptr;
1268   if (Value * T; match(Exp, m_Shr(m_Value(T), m_APInt(Qn)))) {
1269     Op.Frac = Qn->getZExtValue();
1270     Exp = T;
1271   } else {
1272     Op.Frac = 0;
1273   }
1274 
1275   if (Op.Frac > Width)
1276     return std::nullopt;
1277 
1278   // Check if there is rounding added.
1279   const APInt *C = nullptr;
1280   if (Value * T; Op.Frac > 0 && match(Exp, m_Add(m_Value(T), m_APInt(C)))) {
1281     uint64_t CV = C->getZExtValue();
1282     if (CV != 0 && !isPowerOf2_64(CV))
1283       return std::nullopt;
1284     if (CV != 0)
1285       Op.RoundAt = Log2_64(CV);
1286     Exp = T;
1287   }
1288 
1289   // Check if the rest is a multiplication.
1290   if (match(Exp, m_Mul(m_Value(Op.X.Val), m_Value(Op.Y.Val)))) {
1291     Op.Opcode = Instruction::Mul;
1292     // FIXME: The information below is recomputed.
1293     Op.X.Sgn = getNumSignificantBits(Op.X.Val, &In).second;
1294     Op.Y.Sgn = getNumSignificantBits(Op.Y.Val, &In).second;
1295     return Op;
1296   }
1297 
1298   return std::nullopt;
1299 }
1300 
1301 auto HvxIdioms::processFxpMul(Instruction &In, const FxpOp &Op) const
1302     -> Value * {
1303   assert(Op.X.Val->getType() == Op.Y.Val->getType());
1304 
1305   auto *VecTy = dyn_cast<VectorType>(Op.X.Val->getType());
1306   if (VecTy == nullptr)
1307     return nullptr;
1308   auto *ElemTy = cast<IntegerType>(VecTy->getElementType());
1309   unsigned ElemWidth = ElemTy->getBitWidth();
1310 
1311   // TODO: This can be relaxed after legalization is done pre-isel.
1312   if ((HVC.length(VecTy) * ElemWidth) % (8 * HVC.HST.getVectorLength()) != 0)
1313     return nullptr;
1314 
1315   // There are no special intrinsics that should be used for multiplying
1316   // signed 8-bit values, so just skip them. Normal codegen should handle
1317   // this just fine.
1318   if (ElemWidth <= 8)
1319     return nullptr;
1320   // Similarly, if this is just a multiplication that can be handled without
1321   // intervention, then leave it alone.
1322   if (ElemWidth <= 32 && Op.Frac == 0)
1323     return nullptr;
1324 
1325   auto [BitsX, SignX] = getNumSignificantBits(Op.X.Val, &In);
1326   auto [BitsY, SignY] = getNumSignificantBits(Op.Y.Val, &In);
1327 
1328   // TODO: Add multiplication of vectors by scalar registers (up to 4 bytes).
1329 
1330   Value *X = Op.X.Val, *Y = Op.Y.Val;
1331   IRBuilder Builder(In.getParent(), In.getIterator(),
1332                     InstSimplifyFolder(HVC.DL));
1333 
1334   auto roundUpWidth = [](unsigned Width) -> unsigned {
1335     if (Width <= 32 && !isPowerOf2_32(Width)) {
1336       // If the element width is not a power of 2, round it up
1337       // to the next one. Do this for widths not exceeding 32.
1338       return PowerOf2Ceil(Width);
1339     }
1340     if (Width > 32 && Width % 32 != 0) {
1341       // For wider elements, round it up to the multiple of 32.
1342       return alignTo(Width, 32u);
1343     }
1344     return Width;
1345   };
1346 
1347   BitsX = roundUpWidth(BitsX);
1348   BitsY = roundUpWidth(BitsY);
1349 
1350   // For elementwise multiplication vectors must have the same lengths, so
1351   // resize the elements of both inputs to the same width, the max of the
1352   // calculated significant bits.
1353   unsigned Width = std::max(BitsX, BitsY);
1354 
1355   auto *ResizeTy = VectorType::get(HVC.getIntTy(Width), VecTy);
1356   if (Width < ElemWidth) {
1357     X = Builder.CreateTrunc(X, ResizeTy);
1358     Y = Builder.CreateTrunc(Y, ResizeTy);
1359   } else if (Width > ElemWidth) {
1360     X = SignX == Signed ? Builder.CreateSExt(X, ResizeTy)
1361                         : Builder.CreateZExt(X, ResizeTy);
1362     Y = SignY == Signed ? Builder.CreateSExt(Y, ResizeTy)
1363                         : Builder.CreateZExt(Y, ResizeTy);
1364   };
1365 
1366   assert(X->getType() == Y->getType() && X->getType() == ResizeTy);
1367 
1368   unsigned VecLen = HVC.length(ResizeTy);
1369   unsigned ChopLen = (8 * HVC.HST.getVectorLength()) / std::min(Width, 32u);
1370 
1371   SmallVector<Value *> Results;
1372   FxpOp ChopOp = Op;
1373 
1374   for (unsigned V = 0; V != VecLen / ChopLen; ++V) {
1375     ChopOp.X.Val = HVC.subvector(Builder, X, V * ChopLen, ChopLen);
1376     ChopOp.Y.Val = HVC.subvector(Builder, Y, V * ChopLen, ChopLen);
1377     Results.push_back(processFxpMulChopped(Builder, In, ChopOp));
1378     if (Results.back() == nullptr)
1379       break;
1380   }
1381 
1382   if (Results.empty() || Results.back() == nullptr)
1383     return nullptr;
1384 
1385   Value *Cat = HVC.concat(Builder, Results);
1386   Value *Ext = SignX == Signed || SignY == Signed
1387                    ? Builder.CreateSExt(Cat, VecTy)
1388                    : Builder.CreateZExt(Cat, VecTy);
1389   return Ext;
1390 }
1391 
1392 auto HvxIdioms::processFxpMulChopped(IRBuilderBase &Builder, Instruction &In,
1393                                      const FxpOp &Op) const -> Value * {
1394   assert(Op.X.Val->getType() == Op.Y.Val->getType());
1395   auto *InpTy = cast<VectorType>(Op.X.Val->getType());
1396   unsigned Width = InpTy->getScalarSizeInBits();
1397   bool Rounding = Op.RoundAt.has_value();
1398 
1399   if (!Op.RoundAt || *Op.RoundAt == Op.Frac - 1) {
1400     // The fixed-point intrinsics do signed multiplication.
1401     if (Width == Op.Frac + 1 && Op.X.Sgn != Unsigned && Op.Y.Sgn != Unsigned) {
1402       Value *QMul = nullptr;
1403       if (Width == 16) {
1404         QMul = createMulQ15(Builder, Op.X, Op.Y, Rounding);
1405       } else if (Width == 32) {
1406         QMul = createMulQ31(Builder, Op.X, Op.Y, Rounding);
1407       }
1408       if (QMul != nullptr)
1409         return QMul;
1410     }
1411   }
1412 
1413   assert(Width >= 32 || isPowerOf2_32(Width)); // Width <= 32 => Width is 2^n
1414   assert(Width < 32 || Width % 32 == 0);       // Width > 32 => Width is 32*k
1415 
1416   // If Width < 32, then it should really be 16.
1417   if (Width < 32) {
1418     if (Width < 16)
1419       return nullptr;
1420     // Getting here with Op.Frac == 0 isn't wrong, but suboptimal: here we
1421     // generate a full precision products, which is unnecessary if there is
1422     // no shift.
1423     assert(Width == 16);
1424     assert(Op.Frac != 0 && "Unshifted mul should have been skipped");
1425     if (Op.Frac == 16) {
1426       // Multiply high
1427       if (Value *MulH = createMulH16(Builder, Op.X, Op.Y))
1428         return MulH;
1429     }
1430     // Do full-precision multiply and shift.
1431     Value *Prod32 = createMul16(Builder, Op.X, Op.Y);
1432     if (Rounding) {
1433       Value *RoundVal = HVC.getConstSplat(Prod32->getType(), 1 << *Op.RoundAt);
1434       Prod32 = Builder.CreateAdd(Prod32, RoundVal);
1435     }
1436 
1437     Value *ShiftAmt = HVC.getConstSplat(Prod32->getType(), Op.Frac);
1438     Value *Shifted = Op.X.Sgn == Signed || Op.Y.Sgn == Signed
1439                ? Builder.CreateAShr(Prod32, ShiftAmt)
1440                : Builder.CreateLShr(Prod32, ShiftAmt);
1441     return Builder.CreateTrunc(Shifted, InpTy);
1442   }
1443 
1444   // Width >= 32
1445 
1446   // Break up the arguments Op.X and Op.Y into vectors of smaller widths
1447   // in preparation of doing the multiplication by 32-bit parts.
1448   auto WordX = HVC.splitVectorElements(Builder, Op.X.Val, /*ToWidth=*/32);
1449   auto WordY = HVC.splitVectorElements(Builder, Op.Y.Val, /*ToWidth=*/32);
1450   auto WordP = createMulLong(Builder, WordX, Op.X.Sgn, WordY, Op.Y.Sgn);
1451 
1452   auto *HvxWordTy = cast<VectorType>(WordP.front()->getType());
1453 
1454   // Add the optional rounding to the proper word.
1455   if (Op.RoundAt.has_value()) {
1456     Value *Zero = HVC.getNullValue(WordX[0]->getType());
1457     SmallVector<Value *> RoundV(WordP.size(), Zero);
1458     RoundV[*Op.RoundAt / 32] =
1459         HVC.getConstSplat(HvxWordTy, 1 << (*Op.RoundAt % 32));
1460     WordP = createAddLong(Builder, WordP, RoundV);
1461   }
1462 
1463   // createRightShiftLong?
1464 
1465   // Shift all products right by Op.Frac.
1466   unsigned SkipWords = Op.Frac / 32;
1467   Constant *ShiftAmt = HVC.getConstSplat(HvxWordTy, Op.Frac % 32);
1468 
1469   for (int Dst = 0, End = WordP.size() - SkipWords; Dst != End; ++Dst) {
1470     int Src = Dst + SkipWords;
1471     Value *Lo = WordP[Src];
1472     if (Src + 1 < End) {
1473       Value *Hi = WordP[Src + 1];
1474       WordP[Dst] = Builder.CreateIntrinsic(HvxWordTy, Intrinsic::fshr,
1475                                            {Hi, Lo, ShiftAmt});
1476     } else {
1477       // The shift of the most significant word.
1478       WordP[Dst] = Builder.CreateAShr(Lo, ShiftAmt);
1479     }
1480   }
1481   if (SkipWords != 0)
1482     WordP.resize(WordP.size() - SkipWords);
1483 
1484   return HVC.joinVectorElements(Builder, WordP, InpTy);
1485 }
1486 
1487 auto HvxIdioms::createMulQ15(IRBuilderBase &Builder, SValue X, SValue Y,
1488                              bool Rounding) const -> Value * {
1489   assert(X.Val->getType() == Y.Val->getType());
1490   assert(X.Val->getType()->getScalarType() == HVC.getIntTy(16));
1491   assert(HVC.HST.isHVXVectorType(EVT::getEVT(X.Val->getType(), false)));
1492 
1493   // There is no non-rounding intrinsic for i16.
1494   if (!Rounding || X.Sgn == Unsigned || Y.Sgn == Unsigned)
1495     return nullptr;
1496 
1497   auto V6_vmpyhvsrs = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyhvsrs);
1498   return HVC.createHvxIntrinsic(Builder, V6_vmpyhvsrs, X.Val->getType(),
1499                                 {X.Val, Y.Val});
1500 }
1501 
1502 auto HvxIdioms::createMulQ31(IRBuilderBase &Builder, SValue X, SValue Y,
1503                              bool Rounding) const -> Value * {
1504   Type *InpTy = X.Val->getType();
1505   assert(InpTy == Y.Val->getType());
1506   assert(InpTy->getScalarType() == HVC.getIntTy(32));
1507   assert(HVC.HST.isHVXVectorType(EVT::getEVT(InpTy, false)));
1508 
1509   if (X.Sgn == Unsigned || Y.Sgn == Unsigned)
1510     return nullptr;
1511 
1512   auto V6_vmpyewuh = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyewuh);
1513   auto V6_vmpyo_acc = Rounding
1514                           ? HVC.HST.getIntrinsicId(Hexagon::V6_vmpyowh_rnd_sacc)
1515                           : HVC.HST.getIntrinsicId(Hexagon::V6_vmpyowh_sacc);
1516   Value *V1 =
1517       HVC.createHvxIntrinsic(Builder, V6_vmpyewuh, InpTy, {X.Val, Y.Val});
1518   return HVC.createHvxIntrinsic(Builder, V6_vmpyo_acc, InpTy,
1519                                 {V1, X.Val, Y.Val});
1520 }
1521 
1522 auto HvxIdioms::createAddCarry(IRBuilderBase &Builder, Value *X, Value *Y,
1523                                Value *CarryIn) const
1524     -> std::pair<Value *, Value *> {
1525   assert(X->getType() == Y->getType());
1526   auto VecTy = cast<VectorType>(X->getType());
1527   if (VecTy == HvxI32Ty && HVC.HST.useHVXV62Ops()) {
1528     SmallVector<Value *> Args = {X, Y};
1529     Intrinsic::ID AddCarry;
1530     if (CarryIn == nullptr && HVC.HST.useHVXV66Ops()) {
1531       AddCarry = HVC.HST.getIntrinsicId(Hexagon::V6_vaddcarryo);
1532     } else {
1533       AddCarry = HVC.HST.getIntrinsicId(Hexagon::V6_vaddcarry);
1534       if (CarryIn == nullptr)
1535         CarryIn = HVC.getNullValue(HVC.getBoolTy(HVC.length(VecTy)));
1536       Args.push_back(CarryIn);
1537     }
1538     Value *Ret = HVC.createHvxIntrinsic(Builder, AddCarry,
1539                                         /*RetTy=*/nullptr, Args);
1540     Value *Result = Builder.CreateExtractValue(Ret, {0});
1541     Value *CarryOut = Builder.CreateExtractValue(Ret, {1});
1542     return {Result, CarryOut};
1543   }
1544 
1545   // In other cases, do a regular add, and unsigned compare-less-than.
1546   // The carry-out can originate in two places: adding the carry-in or adding
1547   // the two input values.
1548   Value *Result1 = X; // Result1 = X + CarryIn
1549   if (CarryIn != nullptr) {
1550     unsigned Width = VecTy->getScalarSizeInBits();
1551     uint32_t Mask = 1;
1552     if (Width < 32) {
1553       for (unsigned i = 0, e = 32 / Width; i != e; ++i)
1554         Mask = (Mask << Width) | 1;
1555     }
1556     auto V6_vandqrt = HVC.HST.getIntrinsicId(Hexagon::V6_vandqrt);
1557     Value *ValueIn =
1558         HVC.createHvxIntrinsic(Builder, V6_vandqrt, /*RetTy=*/nullptr,
1559                                {CarryIn, HVC.getConstInt(Mask)});
1560     Result1 = Builder.CreateAdd(X, ValueIn);
1561   }
1562 
1563   Value *CarryOut1 = Builder.CreateCmp(CmpInst::ICMP_ULT, Result1, X);
1564   Value *Result2 = Builder.CreateAdd(Result1, Y);
1565   Value *CarryOut2 = Builder.CreateCmp(CmpInst::ICMP_ULT, Result2, Y);
1566   return {Result2, Builder.CreateOr(CarryOut1, CarryOut2)};
1567 }
1568 
1569 auto HvxIdioms::createMul16(IRBuilderBase &Builder, SValue X, SValue Y) const
1570     -> Value * {
1571   Intrinsic::ID V6_vmpyh = 0;
1572   std::tie(X, Y) = canonSgn(X, Y);
1573 
1574   if (X.Sgn == Signed) {
1575     V6_vmpyh = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyhv);
1576   } else if (Y.Sgn == Signed) {
1577     // In vmpyhus the second operand is unsigned
1578     V6_vmpyh = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyhus);
1579   } else {
1580     V6_vmpyh = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyuhv);
1581   }
1582 
1583   // i16*i16 -> i32 / interleaved
1584   Value *P =
1585       HVC.createHvxIntrinsic(Builder, V6_vmpyh, HvxP32Ty, {Y.Val, X.Val});
1586   // Deinterleave
1587   return HVC.vshuff(Builder, HVC.sublo(Builder, P), HVC.subhi(Builder, P));
1588 }
1589 
1590 auto HvxIdioms::createMulH16(IRBuilderBase &Builder, SValue X, SValue Y) const
1591     -> Value * {
1592   Type *HvxI16Ty = HVC.getHvxTy(HVC.getIntTy(16), /*Pair=*/false);
1593 
1594   if (HVC.HST.useHVXV69Ops()) {
1595     if (X.Sgn != Signed && Y.Sgn != Signed) {
1596       auto V6_vmpyuhvs = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyuhvs);
1597       return HVC.createHvxIntrinsic(Builder, V6_vmpyuhvs, HvxI16Ty,
1598                                     {X.Val, Y.Val});
1599     }
1600   }
1601 
1602   Type *HvxP16Ty = HVC.getHvxTy(HVC.getIntTy(16), /*Pair=*/true);
1603   Value *Pair16 = Builder.CreateBitCast(createMul16(Builder, X, Y), HvxP16Ty);
1604   unsigned Len = HVC.length(HvxP16Ty) / 2;
1605 
1606   SmallVector<int, 128> PickOdd(Len);
1607   for (int i = 0; i != static_cast<int>(Len); ++i)
1608     PickOdd[i] = 2 * i + 1;
1609 
1610   return Builder.CreateShuffleVector(HVC.sublo(Builder, Pair16),
1611                                      HVC.subhi(Builder, Pair16), PickOdd);
1612 }
1613 
1614 auto HvxIdioms::createMul32(IRBuilderBase &Builder, SValue X, SValue Y) const
1615     -> std::pair<Value *, Value *> {
1616   assert(X.Val->getType() == Y.Val->getType());
1617   assert(X.Val->getType() == HvxI32Ty);
1618 
1619   Intrinsic::ID V6_vmpy_parts;
1620   std::tie(X, Y) = canonSgn(X, Y);
1621 
1622   if (X.Sgn == Signed) {
1623     V6_vmpy_parts = Intrinsic::hexagon_V6_vmpyss_parts;
1624   } else if (Y.Sgn == Signed) {
1625     V6_vmpy_parts = Intrinsic::hexagon_V6_vmpyus_parts;
1626   } else {
1627     V6_vmpy_parts = Intrinsic::hexagon_V6_vmpyuu_parts;
1628   }
1629 
1630   Value *Parts = HVC.createHvxIntrinsic(Builder, V6_vmpy_parts, nullptr,
1631                                         {X.Val, Y.Val}, {HvxI32Ty});
1632   Value *Hi = Builder.CreateExtractValue(Parts, {0});
1633   Value *Lo = Builder.CreateExtractValue(Parts, {1});
1634   return {Lo, Hi};
1635 }
1636 
1637 auto HvxIdioms::createAddLong(IRBuilderBase &Builder, ArrayRef<Value *> WordX,
1638                               ArrayRef<Value *> WordY) const
1639     -> SmallVector<Value *> {
1640   assert(WordX.size() == WordY.size());
1641   unsigned Idx = 0, Length = WordX.size();
1642   SmallVector<Value *> Sum(Length);
1643 
1644   while (Idx != Length) {
1645     if (HVC.isZero(WordX[Idx]))
1646       Sum[Idx] = WordY[Idx];
1647     else if (HVC.isZero(WordY[Idx]))
1648       Sum[Idx] = WordX[Idx];
1649     else
1650       break;
1651     ++Idx;
1652   }
1653 
1654   Value *Carry = nullptr;
1655   for (; Idx != Length; ++Idx) {
1656     std::tie(Sum[Idx], Carry) =
1657         createAddCarry(Builder, WordX[Idx], WordY[Idx], Carry);
1658   }
1659 
1660   // This drops the final carry beyond the highest word.
1661   return Sum;
1662 }
1663 
1664 auto HvxIdioms::createMulLong(IRBuilderBase &Builder, ArrayRef<Value *> WordX,
1665                               Signedness SgnX, ArrayRef<Value *> WordY,
1666                               Signedness SgnY) const -> SmallVector<Value *> {
1667   SmallVector<SmallVector<Value *>> Products(WordX.size() + WordY.size());
1668 
1669   // WordX[i] * WordY[j] produces words i+j and i+j+1 of the results,
1670   // that is halves 2(i+j), 2(i+j)+1, 2(i+j)+2, 2(i+j)+3.
1671   for (int i = 0, e = WordX.size(); i != e; ++i) {
1672     for (int j = 0, f = WordY.size(); j != f; ++j) {
1673       // Check the 4 halves that this multiplication can generate.
1674       Signedness SX = (i + 1 == e) ? SgnX : Unsigned;
1675       Signedness SY = (j + 1 == f) ? SgnY : Unsigned;
1676       auto [Lo, Hi] = createMul32(Builder, {WordX[i], SX}, {WordY[j], SY});
1677       Products[i + j + 0].push_back(Lo);
1678       Products[i + j + 1].push_back(Hi);
1679     }
1680   }
1681 
1682   Value *Zero = HVC.getNullValue(WordX[0]->getType());
1683 
1684   auto pop_back_or_zero = [Zero](auto &Vector) -> Value * {
1685     if (Vector.empty())
1686       return Zero;
1687     auto Last = Vector.back();
1688     Vector.pop_back();
1689     return Last;
1690   };
1691 
1692   for (int i = 0, e = Products.size(); i != e; ++i) {
1693     while (Products[i].size() > 1) {
1694       Value *Carry = nullptr; // no carry-in
1695       for (int j = i; j != e; ++j) {
1696         auto &ProdJ = Products[j];
1697         auto [Sum, CarryOut] = createAddCarry(Builder, pop_back_or_zero(ProdJ),
1698                                               pop_back_or_zero(ProdJ), Carry);
1699         ProdJ.insert(ProdJ.begin(), Sum);
1700         Carry = CarryOut;
1701       }
1702     }
1703   }
1704 
1705   SmallVector<Value *> WordP;
1706   for (auto &P : Products) {
1707     assert(P.size() == 1 && "Should have been added together");
1708     WordP.push_back(P.front());
1709   }
1710 
1711   return WordP;
1712 }
1713 
1714 auto HvxIdioms::run() -> bool {
1715   bool Changed = false;
1716 
1717   for (BasicBlock &B : HVC.F) {
1718     for (auto It = B.rbegin(); It != B.rend(); ++It) {
1719       if (auto Fxm = matchFxpMul(*It)) {
1720         Value *New = processFxpMul(*It, *Fxm);
1721         // Always report "changed" for now.
1722         Changed = true;
1723         if (!New)
1724           continue;
1725         bool StartOver = !isa<Instruction>(New);
1726         It->replaceAllUsesWith(New);
1727         RecursivelyDeleteTriviallyDeadInstructions(&*It, &HVC.TLI);
1728         It = StartOver ? B.rbegin()
1729                        : cast<Instruction>(New)->getReverseIterator();
1730         Changed = true;
1731       }
1732     }
1733   }
1734 
1735   return Changed;
1736 }
1737 
1738 // --- End HvxIdioms
1739 
1740 auto HexagonVectorCombine::run() -> bool {
1741   if (!HST.useHVXOps())
1742     return false;
1743 
1744   bool Changed = false;
1745   Changed |= AlignVectors(*this).run();
1746   Changed |= HvxIdioms(*this).run();
1747 
1748   return Changed;
1749 }
1750 
1751 auto HexagonVectorCombine::getIntTy(unsigned Width) const -> IntegerType * {
1752   return IntegerType::get(F.getContext(), Width);
1753 }
1754 
1755 auto HexagonVectorCombine::getByteTy(int ElemCount) const -> Type * {
1756   assert(ElemCount >= 0);
1757   IntegerType *ByteTy = Type::getInt8Ty(F.getContext());
1758   if (ElemCount == 0)
1759     return ByteTy;
1760   return VectorType::get(ByteTy, ElemCount, /*Scalable=*/false);
1761 }
1762 
1763 auto HexagonVectorCombine::getBoolTy(int ElemCount) const -> Type * {
1764   assert(ElemCount >= 0);
1765   IntegerType *BoolTy = Type::getInt1Ty(F.getContext());
1766   if (ElemCount == 0)
1767     return BoolTy;
1768   return VectorType::get(BoolTy, ElemCount, /*Scalable=*/false);
1769 }
1770 
1771 auto HexagonVectorCombine::getConstInt(int Val, unsigned Width) const
1772     -> ConstantInt * {
1773   return ConstantInt::getSigned(getIntTy(Width), Val);
1774 }
1775 
1776 auto HexagonVectorCombine::isZero(const Value *Val) const -> bool {
1777   if (auto *C = dyn_cast<Constant>(Val))
1778     return C->isZeroValue();
1779   return false;
1780 }
1781 
1782 auto HexagonVectorCombine::getIntValue(const Value *Val) const
1783     -> std::optional<APInt> {
1784   if (auto *CI = dyn_cast<ConstantInt>(Val))
1785     return CI->getValue();
1786   return std::nullopt;
1787 }
1788 
1789 auto HexagonVectorCombine::isUndef(const Value *Val) const -> bool {
1790   return isa<UndefValue>(Val);
1791 }
1792 
1793 auto HexagonVectorCombine::getHvxTy(Type *ElemTy, bool Pair) const
1794     -> VectorType * {
1795   EVT ETy = EVT::getEVT(ElemTy, false);
1796   assert(ETy.isSimple() && "Invalid HVX element type");
1797   // Do not allow boolean types here: they don't have a fixed length.
1798   assert(HST.isHVXElementType(ETy.getSimpleVT(), /*IncludeBool=*/false) &&
1799          "Invalid HVX element type");
1800   unsigned HwLen = HST.getVectorLength();
1801   unsigned NumElems = (8 * HwLen) / ETy.getSizeInBits();
1802   return VectorType::get(ElemTy, Pair ? 2 * NumElems : NumElems,
1803                          /*Scalable=*/false);
1804 }
1805 
1806 auto HexagonVectorCombine::getSizeOf(const Value *Val, SizeKind Kind) const
1807     -> int {
1808   return getSizeOf(Val->getType(), Kind);
1809 }
1810 
1811 auto HexagonVectorCombine::getSizeOf(const Type *Ty, SizeKind Kind) const
1812     -> int {
1813   auto *NcTy = const_cast<Type *>(Ty);
1814   switch (Kind) {
1815   case Store:
1816     return DL.getTypeStoreSize(NcTy).getFixedValue();
1817   case Alloc:
1818     return DL.getTypeAllocSize(NcTy).getFixedValue();
1819   }
1820   llvm_unreachable("Unhandled SizeKind enum");
1821 }
1822 
1823 auto HexagonVectorCombine::getTypeAlignment(Type *Ty) const -> int {
1824   // The actual type may be shorter than the HVX vector, so determine
1825   // the alignment based on subtarget info.
1826   if (HST.isTypeForHVX(Ty))
1827     return HST.getVectorLength();
1828   return DL.getABITypeAlign(Ty).value();
1829 }
1830 
1831 auto HexagonVectorCombine::length(Value *Val) const -> size_t {
1832   return length(Val->getType());
1833 }
1834 
1835 auto HexagonVectorCombine::length(Type *Ty) const -> size_t {
1836   auto *VecTy = dyn_cast<VectorType>(Ty);
1837   assert(VecTy && "Must be a vector type");
1838   return VecTy->getElementCount().getFixedValue();
1839 }
1840 
1841 auto HexagonVectorCombine::getNullValue(Type *Ty) const -> Constant * {
1842   assert(Ty->isIntOrIntVectorTy());
1843   auto Zero = ConstantInt::get(Ty->getScalarType(), 0);
1844   if (auto *VecTy = dyn_cast<VectorType>(Ty))
1845     return ConstantVector::getSplat(VecTy->getElementCount(), Zero);
1846   return Zero;
1847 }
1848 
1849 auto HexagonVectorCombine::getFullValue(Type *Ty) const -> Constant * {
1850   assert(Ty->isIntOrIntVectorTy());
1851   auto Minus1 = ConstantInt::get(Ty->getScalarType(), -1);
1852   if (auto *VecTy = dyn_cast<VectorType>(Ty))
1853     return ConstantVector::getSplat(VecTy->getElementCount(), Minus1);
1854   return Minus1;
1855 }
1856 
1857 auto HexagonVectorCombine::getConstSplat(Type *Ty, int Val) const
1858     -> Constant * {
1859   assert(Ty->isVectorTy());
1860   auto VecTy = cast<VectorType>(Ty);
1861   Type *ElemTy = VecTy->getElementType();
1862   // Add support for floats if needed.
1863   auto *Splat = ConstantVector::getSplat(VecTy->getElementCount(),
1864                                          ConstantInt::get(ElemTy, Val));
1865   return Splat;
1866 }
1867 
1868 auto HexagonVectorCombine::simplify(Value *V) const -> Value * {
1869   if (auto *In = dyn_cast<Instruction>(V)) {
1870     SimplifyQuery Q(DL, &TLI, &DT, &AC, In);
1871     return simplifyInstruction(In, Q);
1872   }
1873   return nullptr;
1874 }
1875 
1876 // Insert bytes [Start..Start+Length) of Src into Dst at byte Where.
1877 auto HexagonVectorCombine::insertb(IRBuilderBase &Builder, Value *Dst,
1878                                    Value *Src, int Start, int Length,
1879                                    int Where) const -> Value * {
1880   assert(isByteVecTy(Dst->getType()) && isByteVecTy(Src->getType()));
1881   int SrcLen = getSizeOf(Src);
1882   int DstLen = getSizeOf(Dst);
1883   assert(0 <= Start && Start + Length <= SrcLen);
1884   assert(0 <= Where && Where + Length <= DstLen);
1885 
1886   int P2Len = PowerOf2Ceil(SrcLen | DstLen);
1887   auto *Undef = UndefValue::get(getByteTy());
1888   Value *P2Src = vresize(Builder, Src, P2Len, Undef);
1889   Value *P2Dst = vresize(Builder, Dst, P2Len, Undef);
1890 
1891   SmallVector<int, 256> SMask(P2Len);
1892   for (int i = 0; i != P2Len; ++i) {
1893     // If i is in [Where, Where+Length), pick Src[Start+(i-Where)].
1894     // Otherwise, pick Dst[i];
1895     SMask[i] =
1896         (Where <= i && i < Where + Length) ? P2Len + Start + (i - Where) : i;
1897   }
1898 
1899   Value *P2Insert = Builder.CreateShuffleVector(P2Dst, P2Src, SMask);
1900   return vresize(Builder, P2Insert, DstLen, Undef);
1901 }
1902 
1903 auto HexagonVectorCombine::vlalignb(IRBuilderBase &Builder, Value *Lo,
1904                                     Value *Hi, Value *Amt) const -> Value * {
1905   assert(Lo->getType() == Hi->getType() && "Argument type mismatch");
1906   if (isZero(Amt))
1907     return Hi;
1908   int VecLen = getSizeOf(Hi);
1909   if (auto IntAmt = getIntValue(Amt))
1910     return getElementRange(Builder, Lo, Hi, VecLen - IntAmt->getSExtValue(),
1911                            VecLen);
1912 
1913   if (HST.isTypeForHVX(Hi->getType())) {
1914     assert(static_cast<unsigned>(VecLen) == HST.getVectorLength() &&
1915            "Expecting an exact HVX type");
1916     return createHvxIntrinsic(Builder, HST.getIntrinsicId(Hexagon::V6_vlalignb),
1917                               Hi->getType(), {Hi, Lo, Amt});
1918   }
1919 
1920   if (VecLen == 4) {
1921     Value *Pair = concat(Builder, {Lo, Hi});
1922     Value *Shift = Builder.CreateLShr(Builder.CreateShl(Pair, Amt), 32);
1923     Value *Trunc = Builder.CreateTrunc(Shift, Type::getInt32Ty(F.getContext()));
1924     return Builder.CreateBitCast(Trunc, Hi->getType());
1925   }
1926   if (VecLen == 8) {
1927     Value *Sub = Builder.CreateSub(getConstInt(VecLen), Amt);
1928     return vralignb(Builder, Lo, Hi, Sub);
1929   }
1930   llvm_unreachable("Unexpected vector length");
1931 }
1932 
1933 auto HexagonVectorCombine::vralignb(IRBuilderBase &Builder, Value *Lo,
1934                                     Value *Hi, Value *Amt) const -> Value * {
1935   assert(Lo->getType() == Hi->getType() && "Argument type mismatch");
1936   if (isZero(Amt))
1937     return Lo;
1938   int VecLen = getSizeOf(Lo);
1939   if (auto IntAmt = getIntValue(Amt))
1940     return getElementRange(Builder, Lo, Hi, IntAmt->getSExtValue(), VecLen);
1941 
1942   if (HST.isTypeForHVX(Lo->getType())) {
1943     assert(static_cast<unsigned>(VecLen) == HST.getVectorLength() &&
1944            "Expecting an exact HVX type");
1945     return createHvxIntrinsic(Builder, HST.getIntrinsicId(Hexagon::V6_valignb),
1946                               Lo->getType(), {Hi, Lo, Amt});
1947   }
1948 
1949   if (VecLen == 4) {
1950     Value *Pair = concat(Builder, {Lo, Hi});
1951     Value *Shift = Builder.CreateLShr(Pair, Amt);
1952     Value *Trunc = Builder.CreateTrunc(Shift, Type::getInt32Ty(F.getContext()));
1953     return Builder.CreateBitCast(Trunc, Lo->getType());
1954   }
1955   if (VecLen == 8) {
1956     Type *Int64Ty = Type::getInt64Ty(F.getContext());
1957     Value *Lo64 = Builder.CreateBitCast(Lo, Int64Ty);
1958     Value *Hi64 = Builder.CreateBitCast(Hi, Int64Ty);
1959     Function *FI = Intrinsic::getDeclaration(F.getParent(),
1960                                              Intrinsic::hexagon_S2_valignrb);
1961     Value *Call = Builder.CreateCall(FI, {Hi64, Lo64, Amt});
1962     return Builder.CreateBitCast(Call, Lo->getType());
1963   }
1964   llvm_unreachable("Unexpected vector length");
1965 }
1966 
1967 // Concatenates a sequence of vectors of the same type.
1968 auto HexagonVectorCombine::concat(IRBuilderBase &Builder,
1969                                   ArrayRef<Value *> Vecs) const -> Value * {
1970   assert(!Vecs.empty());
1971   SmallVector<int, 256> SMask;
1972   std::vector<Value *> Work[2];
1973   int ThisW = 0, OtherW = 1;
1974 
1975   Work[ThisW].assign(Vecs.begin(), Vecs.end());
1976   while (Work[ThisW].size() > 1) {
1977     auto *Ty = cast<VectorType>(Work[ThisW].front()->getType());
1978     SMask.resize(length(Ty) * 2);
1979     std::iota(SMask.begin(), SMask.end(), 0);
1980 
1981     Work[OtherW].clear();
1982     if (Work[ThisW].size() % 2 != 0)
1983       Work[ThisW].push_back(UndefValue::get(Ty));
1984     for (int i = 0, e = Work[ThisW].size(); i < e; i += 2) {
1985       Value *Joined = Builder.CreateShuffleVector(Work[ThisW][i],
1986                                                   Work[ThisW][i + 1], SMask);
1987       Work[OtherW].push_back(Joined);
1988     }
1989     std::swap(ThisW, OtherW);
1990   }
1991 
1992   // Since there may have been some undefs appended to make shuffle operands
1993   // have the same type, perform the last shuffle to only pick the original
1994   // elements.
1995   SMask.resize(Vecs.size() * length(Vecs.front()->getType()));
1996   std::iota(SMask.begin(), SMask.end(), 0);
1997   Value *Total = Work[ThisW].front();
1998   return Builder.CreateShuffleVector(Total, SMask);
1999 }
2000 
2001 auto HexagonVectorCombine::vresize(IRBuilderBase &Builder, Value *Val,
2002                                    int NewSize, Value *Pad) const -> Value * {
2003   assert(isa<VectorType>(Val->getType()));
2004   auto *ValTy = cast<VectorType>(Val->getType());
2005   assert(ValTy->getElementType() == Pad->getType());
2006 
2007   int CurSize = length(ValTy);
2008   if (CurSize == NewSize)
2009     return Val;
2010   // Truncate?
2011   if (CurSize > NewSize)
2012     return getElementRange(Builder, Val, /*Ignored*/ Val, 0, NewSize);
2013   // Extend.
2014   SmallVector<int, 128> SMask(NewSize);
2015   std::iota(SMask.begin(), SMask.begin() + CurSize, 0);
2016   std::fill(SMask.begin() + CurSize, SMask.end(), CurSize);
2017   Value *PadVec = Builder.CreateVectorSplat(CurSize, Pad);
2018   return Builder.CreateShuffleVector(Val, PadVec, SMask);
2019 }
2020 
2021 auto HexagonVectorCombine::rescale(IRBuilderBase &Builder, Value *Mask,
2022                                    Type *FromTy, Type *ToTy) const -> Value * {
2023   // Mask is a vector <N x i1>, where each element corresponds to an
2024   // element of FromTy. Remap it so that each element will correspond
2025   // to an element of ToTy.
2026   assert(isa<VectorType>(Mask->getType()));
2027 
2028   Type *FromSTy = FromTy->getScalarType();
2029   Type *ToSTy = ToTy->getScalarType();
2030   if (FromSTy == ToSTy)
2031     return Mask;
2032 
2033   int FromSize = getSizeOf(FromSTy);
2034   int ToSize = getSizeOf(ToSTy);
2035   assert(FromSize % ToSize == 0 || ToSize % FromSize == 0);
2036 
2037   auto *MaskTy = cast<VectorType>(Mask->getType());
2038   int FromCount = length(MaskTy);
2039   int ToCount = (FromCount * FromSize) / ToSize;
2040   assert((FromCount * FromSize) % ToSize == 0);
2041 
2042   auto *FromITy = getIntTy(FromSize * 8);
2043   auto *ToITy = getIntTy(ToSize * 8);
2044 
2045   // Mask <N x i1> -> sext to <N x FromTy> -> bitcast to <M x ToTy> ->
2046   // -> trunc to <M x i1>.
2047   Value *Ext = Builder.CreateSExt(
2048       Mask, VectorType::get(FromITy, FromCount, /*Scalable=*/false));
2049   Value *Cast = Builder.CreateBitCast(
2050       Ext, VectorType::get(ToITy, ToCount, /*Scalable=*/false));
2051   return Builder.CreateTrunc(
2052       Cast, VectorType::get(getBoolTy(), ToCount, /*Scalable=*/false));
2053 }
2054 
2055 // Bitcast to bytes, and return least significant bits.
2056 auto HexagonVectorCombine::vlsb(IRBuilderBase &Builder, Value *Val) const
2057     -> Value * {
2058   Type *ScalarTy = Val->getType()->getScalarType();
2059   if (ScalarTy == getBoolTy())
2060     return Val;
2061 
2062   Value *Bytes = vbytes(Builder, Val);
2063   if (auto *VecTy = dyn_cast<VectorType>(Bytes->getType()))
2064     return Builder.CreateTrunc(Bytes, getBoolTy(getSizeOf(VecTy)));
2065   // If Bytes is a scalar (i.e. Val was a scalar byte), return i1, not
2066   // <1 x i1>.
2067   return Builder.CreateTrunc(Bytes, getBoolTy());
2068 }
2069 
2070 // Bitcast to bytes for non-bool. For bool, convert i1 -> i8.
2071 auto HexagonVectorCombine::vbytes(IRBuilderBase &Builder, Value *Val) const
2072     -> Value * {
2073   Type *ScalarTy = Val->getType()->getScalarType();
2074   if (ScalarTy == getByteTy())
2075     return Val;
2076 
2077   if (ScalarTy != getBoolTy())
2078     return Builder.CreateBitCast(Val, getByteTy(getSizeOf(Val)));
2079   // For bool, return a sext from i1 to i8.
2080   if (auto *VecTy = dyn_cast<VectorType>(Val->getType()))
2081     return Builder.CreateSExt(Val, VectorType::get(getByteTy(), VecTy));
2082   return Builder.CreateSExt(Val, getByteTy());
2083 }
2084 
2085 auto HexagonVectorCombine::subvector(IRBuilderBase &Builder, Value *Val,
2086                                      unsigned Start, unsigned Length) const
2087     -> Value * {
2088   assert(Start + Length <= length(Val));
2089   return getElementRange(Builder, Val, /*Ignored*/ Val, Start, Length);
2090 }
2091 
2092 auto HexagonVectorCombine::sublo(IRBuilderBase &Builder, Value *Val) const
2093     -> Value * {
2094   size_t Len = length(Val);
2095   assert(Len % 2 == 0 && "Length should be even");
2096   return subvector(Builder, Val, 0, Len / 2);
2097 }
2098 
2099 auto HexagonVectorCombine::subhi(IRBuilderBase &Builder, Value *Val) const
2100     -> Value * {
2101   size_t Len = length(Val);
2102   assert(Len % 2 == 0 && "Length should be even");
2103   return subvector(Builder, Val, Len / 2, Len / 2);
2104 }
2105 
2106 auto HexagonVectorCombine::vdeal(IRBuilderBase &Builder, Value *Val0,
2107                                  Value *Val1) const -> Value * {
2108   assert(Val0->getType() == Val1->getType());
2109   int Len = length(Val0);
2110   SmallVector<int, 128> Mask(2 * Len);
2111 
2112   for (int i = 0; i != Len; ++i) {
2113     Mask[i] = 2 * i;           // Even
2114     Mask[i + Len] = 2 * i + 1; // Odd
2115   }
2116   return Builder.CreateShuffleVector(Val0, Val1, Mask);
2117 }
2118 
2119 auto HexagonVectorCombine::vshuff(IRBuilderBase &Builder, Value *Val0,
2120                                   Value *Val1) const -> Value * { //
2121   assert(Val0->getType() == Val1->getType());
2122   int Len = length(Val0);
2123   SmallVector<int, 128> Mask(2 * Len);
2124 
2125   for (int i = 0; i != Len; ++i) {
2126     Mask[2 * i + 0] = i;       // Val0
2127     Mask[2 * i + 1] = i + Len; // Val1
2128   }
2129   return Builder.CreateShuffleVector(Val0, Val1, Mask);
2130 }
2131 
2132 auto HexagonVectorCombine::createHvxIntrinsic(IRBuilderBase &Builder,
2133                                               Intrinsic::ID IntID, Type *RetTy,
2134                                               ArrayRef<Value *> Args,
2135                                               ArrayRef<Type *> ArgTys) const
2136     -> Value * {
2137   auto getCast = [&](IRBuilderBase &Builder, Value *Val,
2138                      Type *DestTy) -> Value * {
2139     Type *SrcTy = Val->getType();
2140     if (SrcTy == DestTy)
2141       return Val;
2142 
2143     // Non-HVX type. It should be a scalar, and it should already have
2144     // a valid type.
2145     assert(HST.isTypeForHVX(SrcTy, /*IncludeBool=*/true));
2146 
2147     Type *BoolTy = Type::getInt1Ty(F.getContext());
2148     if (cast<VectorType>(SrcTy)->getElementType() != BoolTy)
2149       return Builder.CreateBitCast(Val, DestTy);
2150 
2151     // Predicate HVX vector.
2152     unsigned HwLen = HST.getVectorLength();
2153     Intrinsic::ID TC = HwLen == 64 ? Intrinsic::hexagon_V6_pred_typecast
2154                                    : Intrinsic::hexagon_V6_pred_typecast_128B;
2155     Function *FI =
2156         Intrinsic::getDeclaration(F.getParent(), TC, {DestTy, Val->getType()});
2157     return Builder.CreateCall(FI, {Val});
2158   };
2159 
2160   Function *IntrFn = Intrinsic::getDeclaration(F.getParent(), IntID, ArgTys);
2161   FunctionType *IntrTy = IntrFn->getFunctionType();
2162 
2163   SmallVector<Value *, 4> IntrArgs;
2164   for (int i = 0, e = Args.size(); i != e; ++i) {
2165     Value *A = Args[i];
2166     Type *T = IntrTy->getParamType(i);
2167     if (A->getType() != T) {
2168       IntrArgs.push_back(getCast(Builder, A, T));
2169     } else {
2170       IntrArgs.push_back(A);
2171     }
2172   }
2173   Value *Call = Builder.CreateCall(IntrFn, IntrArgs);
2174 
2175   Type *CallTy = Call->getType();
2176   if (RetTy == nullptr || CallTy == RetTy)
2177     return Call;
2178   // Scalar types should have RetTy matching the call return type.
2179   assert(HST.isTypeForHVX(CallTy, /*IncludeBool=*/true));
2180   return getCast(Builder, Call, RetTy);
2181 }
2182 
2183 auto HexagonVectorCombine::splitVectorElements(IRBuilderBase &Builder,
2184                                                Value *Vec,
2185                                                unsigned ToWidth) const
2186     -> SmallVector<Value *> {
2187   // Break a vector of wide elements into a series of vectors with narrow
2188   // elements:
2189   //   (...c0:b0:a0, ...c1:b1:a1, ...c2:b2:a2, ...)
2190   // -->
2191   //   (a0, a1, a2, ...)    // lowest "ToWidth" bits
2192   //   (b0, b1, b2, ...)    // the next lowest...
2193   //   (c0, c1, c2, ...)    // ...
2194   //   ...
2195   //
2196   // The number of elements in each resulting vector is the same as
2197   // in the original vector.
2198 
2199   auto *VecTy = cast<VectorType>(Vec->getType());
2200   assert(VecTy->getElementType()->isIntegerTy());
2201   unsigned FromWidth = VecTy->getScalarSizeInBits();
2202   assert(isPowerOf2_32(ToWidth) && isPowerOf2_32(FromWidth));
2203   assert(ToWidth <= FromWidth && "Breaking up into wider elements?");
2204   unsigned NumResults = FromWidth / ToWidth;
2205 
2206   SmallVector<Value *> Results(NumResults);
2207   Results[0] = Vec;
2208   unsigned Length = length(VecTy);
2209 
2210   // Do it by splitting in half, since those operations correspond to deal
2211   // instructions.
2212   auto splitInHalf = [&](unsigned Begin, unsigned End, auto splitFunc) -> void {
2213     // Take V = Results[Begin], split it in L, H.
2214     // Store Results[Begin] = L, Results[(Begin+End)/2] = H
2215     // Call itself recursively split(Begin, Half), split(Half+1, End)
2216     if (Begin + 1 == End)
2217       return;
2218 
2219     Value *Val = Results[Begin];
2220     unsigned Width = Val->getType()->getScalarSizeInBits();
2221 
2222     auto *VTy = VectorType::get(getIntTy(Width / 2), 2 * Length, false);
2223     Value *VVal = Builder.CreateBitCast(Val, VTy);
2224 
2225     Value *Res = vdeal(Builder, sublo(Builder, VVal), subhi(Builder, VVal));
2226 
2227     unsigned Half = (Begin + End) / 2;
2228     Results[Begin] = sublo(Builder, Res);
2229     Results[Half] = subhi(Builder, Res);
2230 
2231     splitFunc(Begin, Half, splitFunc);
2232     splitFunc(Half, End, splitFunc);
2233   };
2234 
2235   splitInHalf(0, NumResults, splitInHalf);
2236   return Results;
2237 }
2238 
2239 auto HexagonVectorCombine::joinVectorElements(IRBuilderBase &Builder,
2240                                               ArrayRef<Value *> Values,
2241                                               VectorType *ToType) const
2242     -> Value * {
2243   assert(ToType->getElementType()->isIntegerTy());
2244 
2245   // If the list of values does not have power-of-2 elements, append copies
2246   // of the sign bit to it, to make the size be 2^n.
2247   // The reason for this is that the values will be joined in pairs, because
2248   // otherwise the shuffles will result in convoluted code. With pairwise
2249   // joins, the shuffles will hopefully be folded into a perfect shuffle.
2250   // The output will need to be sign-extended to a type with element width
2251   // being a power-of-2 anyways.
2252   SmallVector<Value *> Inputs(Values.begin(), Values.end());
2253 
2254   unsigned ToWidth = ToType->getScalarSizeInBits();
2255   unsigned Width = Inputs.front()->getType()->getScalarSizeInBits();
2256   assert(Width <= ToWidth);
2257   assert(isPowerOf2_32(Width) && isPowerOf2_32(ToWidth));
2258   unsigned Length = length(Inputs.front()->getType());
2259 
2260   unsigned NeedInputs = ToWidth / Width;
2261   if (Inputs.size() != NeedInputs) {
2262     Value *Last = Inputs.back();
2263     Value *Sign =
2264         Builder.CreateAShr(Last, getConstSplat(Last->getType(), Width - 1));
2265     Inputs.resize(NeedInputs, Sign);
2266   }
2267 
2268   while (Inputs.size() > 1) {
2269     Width *= 2;
2270     auto *VTy = VectorType::get(getIntTy(Width), Length, false);
2271     for (int i = 0, e = Inputs.size(); i < e; i += 2) {
2272       Value *Res = vshuff(Builder, Inputs[i], Inputs[i + 1]);
2273       Inputs[i / 2] = Builder.CreateBitCast(Res, VTy);
2274     }
2275     Inputs.resize(Inputs.size() / 2);
2276   }
2277 
2278   assert(Inputs.front()->getType() == ToType);
2279   return Inputs.front();
2280 }
2281 
2282 auto HexagonVectorCombine::calculatePointerDifference(Value *Ptr0,
2283                                                       Value *Ptr1) const
2284     -> std::optional<int> {
2285   struct Builder : IRBuilder<> {
2286     Builder(BasicBlock *B) : IRBuilder<>(B->getTerminator()) {}
2287     ~Builder() {
2288       for (Instruction *I : llvm::reverse(ToErase))
2289         I->eraseFromParent();
2290     }
2291     SmallVector<Instruction *, 8> ToErase;
2292   };
2293 
2294 #define CallBuilder(B, F)                                                      \
2295   [&](auto &B_) {                                                              \
2296     Value *V = B_.F;                                                           \
2297     if (auto *I = dyn_cast<Instruction>(V))                                    \
2298       B_.ToErase.push_back(I);                                                 \
2299     return V;                                                                  \
2300   }(B)
2301 
2302   auto Simplify = [this](Value *V) {
2303     if (Value *S = simplify(V))
2304       return S;
2305     return V;
2306   };
2307 
2308   auto StripBitCast = [](Value *V) {
2309     while (auto *C = dyn_cast<BitCastInst>(V))
2310       V = C->getOperand(0);
2311     return V;
2312   };
2313 
2314   Ptr0 = StripBitCast(Ptr0);
2315   Ptr1 = StripBitCast(Ptr1);
2316   if (!isa<GetElementPtrInst>(Ptr0) || !isa<GetElementPtrInst>(Ptr1))
2317     return std::nullopt;
2318 
2319   auto *Gep0 = cast<GetElementPtrInst>(Ptr0);
2320   auto *Gep1 = cast<GetElementPtrInst>(Ptr1);
2321   if (Gep0->getPointerOperand() != Gep1->getPointerOperand())
2322     return std::nullopt;
2323   if (Gep0->getSourceElementType() != Gep1->getSourceElementType())
2324     return std::nullopt;
2325 
2326   Builder B(Gep0->getParent());
2327   int Scale = getSizeOf(Gep0->getSourceElementType(), Alloc);
2328 
2329   // FIXME: for now only check GEPs with a single index.
2330   if (Gep0->getNumOperands() != 2 || Gep1->getNumOperands() != 2)
2331     return std::nullopt;
2332 
2333   Value *Idx0 = Gep0->getOperand(1);
2334   Value *Idx1 = Gep1->getOperand(1);
2335 
2336   // First, try to simplify the subtraction directly.
2337   if (auto *Diff = dyn_cast<ConstantInt>(
2338           Simplify(CallBuilder(B, CreateSub(Idx0, Idx1)))))
2339     return Diff->getSExtValue() * Scale;
2340 
2341   KnownBits Known0 = getKnownBits(Idx0, Gep0);
2342   KnownBits Known1 = getKnownBits(Idx1, Gep1);
2343   APInt Unknown = ~(Known0.Zero | Known0.One) | ~(Known1.Zero | Known1.One);
2344   if (Unknown.isAllOnes())
2345     return std::nullopt;
2346 
2347   Value *MaskU = ConstantInt::get(Idx0->getType(), Unknown);
2348   Value *AndU0 = Simplify(CallBuilder(B, CreateAnd(Idx0, MaskU)));
2349   Value *AndU1 = Simplify(CallBuilder(B, CreateAnd(Idx1, MaskU)));
2350   Value *SubU = Simplify(CallBuilder(B, CreateSub(AndU0, AndU1)));
2351   int Diff0 = 0;
2352   if (auto *C = dyn_cast<ConstantInt>(SubU)) {
2353     Diff0 = C->getSExtValue();
2354   } else {
2355     return std::nullopt;
2356   }
2357 
2358   Value *MaskK = ConstantInt::get(MaskU->getType(), ~Unknown);
2359   Value *AndK0 = Simplify(CallBuilder(B, CreateAnd(Idx0, MaskK)));
2360   Value *AndK1 = Simplify(CallBuilder(B, CreateAnd(Idx1, MaskK)));
2361   Value *SubK = Simplify(CallBuilder(B, CreateSub(AndK0, AndK1)));
2362   int Diff1 = 0;
2363   if (auto *C = dyn_cast<ConstantInt>(SubK)) {
2364     Diff1 = C->getSExtValue();
2365   } else {
2366     return std::nullopt;
2367   }
2368 
2369   return (Diff0 + Diff1) * Scale;
2370 
2371 #undef CallBuilder
2372 }
2373 
2374 auto HexagonVectorCombine::getNumSignificantBits(const Value *V,
2375                                                  const Instruction *CtxI) const
2376     -> unsigned {
2377   return ComputeMaxSignificantBits(V, DL, /*Depth=*/0, &AC, CtxI, &DT);
2378 }
2379 
2380 auto HexagonVectorCombine::getKnownBits(const Value *V,
2381                                         const Instruction *CtxI) const
2382     -> KnownBits {
2383   return computeKnownBits(V, DL, /*Depth=*/0, &AC, CtxI, &DT, /*ORE=*/nullptr,
2384                           /*UseInstrInfo=*/true);
2385 }
2386 
2387 template <typename T>
2388 auto HexagonVectorCombine::isSafeToMoveBeforeInBB(const Instruction &In,
2389                                                   BasicBlock::const_iterator To,
2390                                                   const T &IgnoreInsts) const
2391     -> bool {
2392   auto getLocOrNone =
2393       [this](const Instruction &I) -> std::optional<MemoryLocation> {
2394     if (const auto *II = dyn_cast<IntrinsicInst>(&I)) {
2395       switch (II->getIntrinsicID()) {
2396       case Intrinsic::masked_load:
2397         return MemoryLocation::getForArgument(II, 0, TLI);
2398       case Intrinsic::masked_store:
2399         return MemoryLocation::getForArgument(II, 1, TLI);
2400       }
2401     }
2402     return MemoryLocation::getOrNone(&I);
2403   };
2404 
2405   // The source and the destination must be in the same basic block.
2406   const BasicBlock &Block = *In.getParent();
2407   assert(Block.begin() == To || Block.end() == To || To->getParent() == &Block);
2408   // No PHIs.
2409   if (isa<PHINode>(In) || (To != Block.end() && isa<PHINode>(*To)))
2410     return false;
2411 
2412   if (!mayHaveNonDefUseDependency(In))
2413     return true;
2414   bool MayWrite = In.mayWriteToMemory();
2415   auto MaybeLoc = getLocOrNone(In);
2416 
2417   auto From = In.getIterator();
2418   if (From == To)
2419     return true;
2420   bool MoveUp = (To != Block.end() && To->comesBefore(&In));
2421   auto Range =
2422       MoveUp ? std::make_pair(To, From) : std::make_pair(std::next(From), To);
2423   for (auto It = Range.first; It != Range.second; ++It) {
2424     const Instruction &I = *It;
2425     if (llvm::is_contained(IgnoreInsts, &I))
2426       continue;
2427     // assume intrinsic can be ignored
2428     if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
2429       if (II->getIntrinsicID() == Intrinsic::assume)
2430         continue;
2431     }
2432     // Parts based on isSafeToMoveBefore from CoveMoverUtils.cpp.
2433     if (I.mayThrow())
2434       return false;
2435     if (auto *CB = dyn_cast<CallBase>(&I)) {
2436       if (!CB->hasFnAttr(Attribute::WillReturn))
2437         return false;
2438       if (!CB->hasFnAttr(Attribute::NoSync))
2439         return false;
2440     }
2441     if (I.mayReadOrWriteMemory()) {
2442       auto MaybeLocI = getLocOrNone(I);
2443       if (MayWrite || I.mayWriteToMemory()) {
2444         if (!MaybeLoc || !MaybeLocI)
2445           return false;
2446         if (!AA.isNoAlias(*MaybeLoc, *MaybeLocI))
2447           return false;
2448       }
2449     }
2450   }
2451   return true;
2452 }
2453 
2454 auto HexagonVectorCombine::isByteVecTy(Type *Ty) const -> bool {
2455   if (auto *VecTy = dyn_cast<VectorType>(Ty))
2456     return VecTy->getElementType() == getByteTy();
2457   return false;
2458 }
2459 
2460 auto HexagonVectorCombine::getElementRange(IRBuilderBase &Builder, Value *Lo,
2461                                            Value *Hi, int Start,
2462                                            int Length) const -> Value * {
2463   assert(0 <= Start && size_t(Start + Length) < length(Lo) + length(Hi));
2464   SmallVector<int, 128> SMask(Length);
2465   std::iota(SMask.begin(), SMask.end(), Start);
2466   return Builder.CreateShuffleVector(Lo, Hi, SMask);
2467 }
2468 
2469 // Pass management.
2470 
2471 namespace llvm {
2472 void initializeHexagonVectorCombineLegacyPass(PassRegistry &);
2473 FunctionPass *createHexagonVectorCombineLegacyPass();
2474 } // namespace llvm
2475 
2476 namespace {
2477 class HexagonVectorCombineLegacy : public FunctionPass {
2478 public:
2479   static char ID;
2480 
2481   HexagonVectorCombineLegacy() : FunctionPass(ID) {}
2482 
2483   StringRef getPassName() const override { return "Hexagon Vector Combine"; }
2484 
2485   void getAnalysisUsage(AnalysisUsage &AU) const override {
2486     AU.setPreservesCFG();
2487     AU.addRequired<AAResultsWrapperPass>();
2488     AU.addRequired<AssumptionCacheTracker>();
2489     AU.addRequired<DominatorTreeWrapperPass>();
2490     AU.addRequired<TargetLibraryInfoWrapperPass>();
2491     AU.addRequired<TargetPassConfig>();
2492     FunctionPass::getAnalysisUsage(AU);
2493   }
2494 
2495   bool runOnFunction(Function &F) override {
2496     if (skipFunction(F))
2497       return false;
2498     AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2499     AssumptionCache &AC =
2500         getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2501     DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2502     TargetLibraryInfo &TLI =
2503         getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
2504     auto &TM = getAnalysis<TargetPassConfig>().getTM<HexagonTargetMachine>();
2505     HexagonVectorCombine HVC(F, AA, AC, DT, TLI, TM);
2506     return HVC.run();
2507   }
2508 };
2509 } // namespace
2510 
2511 char HexagonVectorCombineLegacy::ID = 0;
2512 
2513 INITIALIZE_PASS_BEGIN(HexagonVectorCombineLegacy, DEBUG_TYPE,
2514                       "Hexagon Vector Combine", false, false)
2515 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2516 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2517 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2518 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2519 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
2520 INITIALIZE_PASS_END(HexagonVectorCombineLegacy, DEBUG_TYPE,
2521                     "Hexagon Vector Combine", false, false)
2522 
2523 FunctionPass *llvm::createHexagonVectorCombineLegacyPass() {
2524   return new HexagonVectorCombineLegacy();
2525 }
2526