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