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