LLVM 24.0.0git
HexagonVectorCombine.cpp
Go to the documentation of this file.
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// HvxIdioms: recognize various opportunities to generate HVX intrinsic code.
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/MapVector.h"
19#include "llvm/ADT/STLExtras.h"
33#include "llvm/IR/Dominators.h"
34#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/IntrinsicsHexagon.h"
38#include "llvm/IR/Metadata.h"
41#include "llvm/Pass.h"
49
50#include "Hexagon.h"
51#include "HexagonSubtarget.h"
53
54#include <algorithm>
55#include <deque>
56#include <optional>
57#include <set>
58#include <utility>
59#include <vector>
60
61#define DEBUG_TYPE "hexagon-vc"
62
63// This is a const that represents default HVX VTCM page size.
64// It is boot time configurable, so we probably want an API to
65// read it, but for now assume 128KB
66#define DEFAULT_HVX_VTCM_PAGE_SIZE 131072
67
68using namespace llvm;
69
70namespace {
71cl::opt<bool> DumpModule("hvc-dump-module", cl::Hidden);
72cl::opt<bool> VAEnabled("hvc-va", cl::Hidden, cl::init(true)); // Align
73cl::opt<bool> VIEnabled("hvc-vi", cl::Hidden, cl::init(true)); // Idioms
74cl::opt<bool> VADoFullStores("hvc-va-full-stores", cl::Hidden);
75
76cl::opt<unsigned> VAGroupCountLimit("hvc-va-group-count-limit", cl::Hidden,
77 cl::init(~0));
78cl::opt<unsigned> VAGroupSizeLimit("hvc-va-group-size-limit", cl::Hidden,
79 cl::init(~0));
81 MinLoadGroupSizeForAlignment("hvc-ld-min-group-size-for-alignment",
83
84class HexagonVectorCombine {
85public:
86 HexagonVectorCombine(Function &F_, AliasAnalysis &AA_, AssumptionCache &AC_,
88 TargetLibraryInfo &TLI_, const TargetMachine &TM_,
90 : F(F_), DL(F.getDataLayout()), AA(AA_), AC(AC_), DT(DT_), SE(SE_),
91 TLI(TLI_),
92 HST(static_cast<const HexagonSubtarget &>(*TM_.getSubtargetImpl(F))),
93 ORE(ORE_) {}
94
95 bool run();
96
97 // Common integer type.
98 IntegerType *getIntTy(unsigned Width = 32) const;
99 // Byte type: either scalar (when Length = 0), or vector with given
100 // element count.
101 Type *getByteTy(int ElemCount = 0) const;
102 // Boolean type: either scalar (when Length = 0), or vector with given
103 // element count.
104 Type *getBoolTy(int ElemCount = 0) const;
105 // Create a ConstantInt of type returned by getIntTy with the value Val.
106 ConstantInt *getConstInt(int Val, unsigned Width = 32) const;
107 // Get the integer value of V, if it exists.
108 std::optional<APInt> getIntValue(const Value *Val) const;
109 // Is Val a constant 0, or a vector of 0s?
110 bool isZero(const Value *Val) const;
111 // Is Val an undef value?
112 bool isUndef(const Value *Val) const;
113 // Is Val a scalar (i1 true) or a vector of (i1 true)?
114 bool isTrue(const Value *Val) const;
115 // Is Val a scalar (i1 false) or a vector of (i1 false)?
116 bool isFalse(const Value *Val) const;
117
118 // Get HVX vector type with the given element type.
119 VectorType *getHvxTy(Type *ElemTy, bool Pair = false) const;
120
121 enum SizeKind {
122 Store, // Store size
123 Alloc, // Alloc size
124 };
125 int getSizeOf(const Value *Val, SizeKind Kind = Store) const;
126 int getSizeOf(const Type *Ty, SizeKind Kind = Store) const;
127 int getTypeAlignment(Type *Ty) const;
128 size_t length(Value *Val) const;
129 size_t length(Type *Ty) const;
130
131 Value *simplify(Value *Val) const;
132
133 Value *insertb(IRBuilderBase &Builder, Value *Dest, Value *Src, int Start,
134 int Length, int Where) const;
135 Value *vlalignb(IRBuilderBase &Builder, Value *Lo, Value *Hi,
136 Value *Amt) const;
137 Value *vralignb(IRBuilderBase &Builder, Value *Lo, Value *Hi,
138 Value *Amt) const;
139 Value *concat(IRBuilderBase &Builder, ArrayRef<Value *> Vecs) const;
140 Value *vresize(IRBuilderBase &Builder, Value *Val, int NewSize,
141 Value *Pad) const;
142 Value *rescale(IRBuilderBase &Builder, Value *Mask, Type *FromTy,
143 Type *ToTy) const;
144 Value *vlsb(IRBuilderBase &Builder, Value *Val) const;
145 Value *vbytes(IRBuilderBase &Builder, Value *Val) const;
146 Value *subvector(IRBuilderBase &Builder, Value *Val, unsigned Start,
147 unsigned Length) const;
148 Value *sublo(IRBuilderBase &Builder, Value *Val) const;
149 Value *subhi(IRBuilderBase &Builder, Value *Val) const;
150 Value *vdeal(IRBuilderBase &Builder, Value *Val0, Value *Val1) const;
151 Value *vshuff(IRBuilderBase &Builder, Value *Val0, Value *Val1) const;
152
153 Value *createHvxIntrinsic(IRBuilderBase &Builder, Intrinsic::ID IntID,
154 Type *RetTy, ArrayRef<Value *> Args,
155 ArrayRef<Type *> ArgTys = {},
156 ArrayRef<Value *> MDSources = {}) const;
157 SmallVector<Value *> splitVectorElements(IRBuilderBase &Builder, Value *Vec,
158 unsigned ToWidth) const;
159 Value *joinVectorElements(IRBuilderBase &Builder, ArrayRef<Value *> Values,
160 VectorType *ToType) const;
161
162 std::optional<int> calculatePointerDifference(Value *Ptr0, Value *Ptr1) const;
163
164 unsigned getNumSignificantBits(const Value *V,
165 const Instruction *CtxI = nullptr) const;
166 KnownBits getKnownBits(const Value *V,
167 const Instruction *CtxI = nullptr) const;
168
169 bool isSafeToClone(const Instruction &In) const;
170
171 template <typename T = std::vector<Instruction *>>
172 bool isSafeToMoveBeforeInBB(const Instruction &In,
174 const T &IgnoreInsts = {}) const;
175
176 // This function is only used for assertions at the moment.
177 [[maybe_unused]] bool isByteVecTy(Type *Ty) const;
178
179 Function &F;
180 const DataLayout &DL;
182 AssumptionCache &AC;
183 DominatorTree &DT;
184 ScalarEvolution &SE;
186 const HexagonSubtarget &HST;
188
189private:
190 Value *getElementRange(IRBuilderBase &Builder, Value *Lo, Value *Hi,
191 int Start, int Length) const;
192};
193
194class AlignVectors {
195 // This code tries to replace unaligned vector loads/stores with aligned
196 // ones.
197 // Consider unaligned load:
198 // %v = original_load %some_addr, align <bad>
199 // %user = %v
200 // It will generate
201 // = load ..., align <good>
202 // = load ..., align <good>
203 // = valign
204 // etc.
205 // %synthesize = combine/shuffle the loaded data so that it looks
206 // exactly like what "original_load" has loaded.
207 // %user = %synthesize
208 // Similarly for stores.
209public:
210 AlignVectors(const HexagonVectorCombine &HVC_) : HVC(HVC_) {}
211
212 bool run();
213
214private:
215 using InstList = std::vector<Instruction *>;
217
218 struct AddrInfo {
219 AddrInfo(const AddrInfo &) = default;
220 AddrInfo &operator=(const AddrInfo &) = default;
221 AddrInfo(const HexagonVectorCombine &HVC, Instruction *I, Value *A, Type *T,
222 Align H)
223 : Inst(I), Addr(A), ValTy(T), HaveAlign(H),
224 NeedAlign(HVC.getTypeAlignment(ValTy)) {}
225
226 // XXX: add Size member?
227 Instruction *Inst;
228 Value *Addr;
229 Type *ValTy;
230 Align HaveAlign;
231 Align NeedAlign;
232 int Offset = 0; // Offset (in bytes) from the first member of the
233 // containing AddrList.
234 };
235 using AddrList = std::vector<AddrInfo>;
236
237 struct InstrLess {
238 bool operator()(const Instruction *A, const Instruction *B) const {
239 return A->comesBefore(B);
240 }
241 };
242 using DepList = std::set<Instruction *, InstrLess>;
243
244 struct MoveGroup {
245 MoveGroup(const AddrInfo &AI, Instruction *B, bool Hvx, bool Load)
246 : Base(B), Main{AI.Inst}, Clones{}, IsHvx(Hvx), IsLoad(Load) {}
247 MoveGroup() = default;
248 Instruction *Base; // Base instruction of the parent address group.
249 InstList Main; // Main group of instructions.
250 InstList Deps; // List of dependencies.
251 InstMap Clones; // Map from original Deps to cloned ones.
252 bool IsHvx; // Is this group of HVX instructions?
253 bool IsLoad; // Is this a load group?
254 };
255 using MoveList = std::vector<MoveGroup>;
256
257 struct ByteSpan {
258 // A representation of "interesting" bytes within a given span of memory.
259 // These bytes are those that are loaded or stored, and they don't have
260 // to cover the entire span of memory.
261 //
262 // The representation works by picking a contiguous sequence of bytes
263 // from somewhere within a llvm::Value, and placing it at a given offset
264 // within the span.
265 //
266 // The sequence of bytes from llvm:Value is represented by Segment.
267 // Block is Segment, plus where it goes in the span.
268 //
269 // An important feature of ByteSpan is being able to make a "section",
270 // i.e. creating another ByteSpan corresponding to a range of offsets
271 // relative to the source span.
272
273 struct Segment {
274 // Segment of a Value: 'Len' bytes starting at byte 'Begin'.
275 Segment(Value *Val, int Begin, int Len)
276 : Val(Val), Start(Begin), Size(Len) {}
277 Segment(const Segment &Seg) = default;
278 Segment &operator=(const Segment &Seg) = default;
279 Value *Val; // Value representable as a sequence of bytes.
280 int Start; // First byte of the value that belongs to the segment.
281 int Size; // Number of bytes in the segment.
282 };
283
284 struct Block {
285 Block(Value *Val, int Len, int Pos) : Seg(Val, 0, Len), Pos(Pos) {}
286 Block(Value *Val, int Off, int Len, int Pos)
287 : Seg(Val, Off, Len), Pos(Pos) {}
288 Block(const Block &Blk) = default;
289 Block &operator=(const Block &Blk) = default;
290 Segment Seg; // Value segment.
291 int Pos; // Position (offset) of the block in the span.
292 };
293
294 int extent() const;
295 ByteSpan section(int Start, int Length) const;
296 ByteSpan &shift(int Offset);
297 SmallVector<Value *, 8> values() const;
298
299 int size() const { return Blocks.size(); }
300 Block &operator[](int i) { return Blocks[i]; }
301 const Block &operator[](int i) const { return Blocks[i]; }
302
303 std::vector<Block> Blocks;
304
305 using iterator = decltype(Blocks)::iterator;
306 iterator begin() { return Blocks.begin(); }
307 iterator end() { return Blocks.end(); }
308 using const_iterator = decltype(Blocks)::const_iterator;
309 const_iterator begin() const { return Blocks.begin(); }
310 const_iterator end() const { return Blocks.end(); }
311 };
312
313 std::optional<AddrInfo> getAddrInfo(Instruction &In) const;
314 bool isHvx(const AddrInfo &AI) const;
315 // This function is only used for assertions at the moment.
316 [[maybe_unused]] bool isSectorTy(Type *Ty) const;
317
318 Value *getPayload(Value *Val) const;
319 Value *getMask(Value *Val) const;
320 Value *getPassThrough(Value *Val) const;
321
322 Value *createAdjustedPointer(IRBuilderBase &Builder, Value *Ptr, Type *ValTy,
323 int Adjust,
324 const InstMap &CloneMap = InstMap()) const;
325 Value *createAlignedPointer(IRBuilderBase &Builder, Value *Ptr, Type *ValTy,
326 int Alignment,
327 const InstMap &CloneMap = InstMap()) const;
328
329 Value *createLoad(IRBuilderBase &Builder, Type *ValTy, Value *Ptr,
330 Value *Predicate, int Alignment, Value *Mask,
331 Value *PassThru, ArrayRef<Value *> MDSources = {}) const;
332 Value *createSimpleLoad(IRBuilderBase &Builder, Type *ValTy, Value *Ptr,
333 int Alignment,
334 ArrayRef<Value *> MDSources = {}) const;
335
336 Value *createStore(IRBuilderBase &Builder, Value *Val, Value *Ptr,
337 Value *Predicate, int Alignment, Value *Mask,
338 ArrayRef<Value *> MDSources = {}) const;
339 Value *createSimpleStore(IRBuilderBase &Builder, Value *Val, Value *Ptr,
340 int Alignment,
341 ArrayRef<Value *> MDSources = {}) const;
342
343 Value *createPredicatedLoad(IRBuilderBase &Builder, Type *ValTy, Value *Ptr,
344 Value *Predicate, int Alignment,
345 ArrayRef<Value *> MDSources = {}) const;
346 Value *createPredicatedStore(IRBuilderBase &Builder, Value *Val, Value *Ptr,
347 Value *Predicate, int Alignment,
348 ArrayRef<Value *> MDSources = {}) const;
349
350 DepList getUpwardDeps(Instruction *In, Instruction *Base) const;
351 bool createAddressGroups();
352 MoveList createLoadGroups(const AddrList &Group) const;
353 MoveList createStoreGroups(const AddrList &Group) const;
354 bool moveTogether(MoveGroup &Move) const;
355 template <typename T>
356 InstMap cloneBefore(BasicBlock::iterator To, T &&Insts) const;
357
358 void realignLoadGroup(IRBuilderBase &Builder, const ByteSpan &VSpan,
359 int ScLen, Value *AlignVal, Value *AlignAddr) const;
360 void realignStoreGroup(IRBuilderBase &Builder, const ByteSpan &VSpan,
361 int ScLen, Value *AlignVal, Value *AlignAddr) const;
362 bool realignGroup(const MoveGroup &Move);
363 Value *makeTestIfUnaligned(IRBuilderBase &Builder, Value *AlignVal,
364 int Alignment) const;
365
366 using AddrGroupMap = MapVector<Instruction *, AddrList>;
367 AddrGroupMap AddrGroups;
368
369 friend raw_ostream &operator<<(raw_ostream &OS, const AddrList &L);
370 friend raw_ostream &operator<<(raw_ostream &OS, const AddrInfo &AI);
371 friend raw_ostream &operator<<(raw_ostream &OS, const MoveGroup &MG);
372 friend raw_ostream &operator<<(raw_ostream &OS, const MoveList &L);
373 friend raw_ostream &operator<<(raw_ostream &OS, const ByteSpan::Block &B);
374 friend raw_ostream &operator<<(raw_ostream &OS, const ByteSpan &BS);
375 friend raw_ostream &operator<<(raw_ostream &OS, const AddrGroupMap &AG);
376 friend raw_ostream &operator<<(raw_ostream &OS, const AddrList &L);
377 friend raw_ostream &operator<<(raw_ostream &OS, const AddrInfo &AI);
378 friend raw_ostream &operator<<(raw_ostream &OS, const MoveGroup &MG);
379 friend raw_ostream &operator<<(raw_ostream &OS, const MoveList &L);
380 friend raw_ostream &operator<<(raw_ostream &OS, const ByteSpan::Block &B);
381 friend raw_ostream &operator<<(raw_ostream &OS, const ByteSpan &BS);
382 friend raw_ostream &operator<<(raw_ostream &OS, const AddrGroupMap &AG);
383
384 const HexagonVectorCombine &HVC;
385};
386
387[[maybe_unused]] raw_ostream &operator<<(raw_ostream &OS,
388 const AlignVectors::AddrGroupMap &AG) {
389 OS << "Printing AddrGroups:"
390 << "\n";
391 for (auto &It : AG) {
392 OS << "\n\tInstruction: ";
393 It.first->dump();
394 OS << "\n\tAddrInfo: ";
395 for (auto &AI : It.second)
396 OS << AI << "\n";
397 }
398 return OS;
399}
400
401[[maybe_unused]] raw_ostream &operator<<(raw_ostream &OS,
402 const AlignVectors::AddrList &AL) {
403 OS << "\n *** Addr List: ***\n";
404 for (auto &AG : AL) {
405 OS << "\n *** Addr Group: ***\n";
406 OS << AG;
407 OS << "\n";
408 }
409 return OS;
410}
411
412[[maybe_unused]] raw_ostream &operator<<(raw_ostream &OS,
413 const AlignVectors::AddrInfo &AI) {
414 OS << "Inst: " << AI.Inst << " " << *AI.Inst << '\n';
415 OS << "Addr: " << *AI.Addr << '\n';
416 OS << "Type: " << *AI.ValTy << '\n';
417 OS << "HaveAlign: " << AI.HaveAlign.value() << '\n';
418 OS << "NeedAlign: " << AI.NeedAlign.value() << '\n';
419 OS << "Offset: " << AI.Offset;
420 return OS;
421}
422
423[[maybe_unused]] raw_ostream &operator<<(raw_ostream &OS,
424 const AlignVectors::MoveList &ML) {
425 OS << "\n *** Move List: ***\n";
426 for (auto &MG : ML) {
427 OS << "\n *** Move Group: ***\n";
428 OS << MG;
429 OS << "\n";
430 }
431 return OS;
432}
433
434[[maybe_unused]] raw_ostream &operator<<(raw_ostream &OS,
435 const AlignVectors::MoveGroup &MG) {
436 OS << "IsLoad:" << (MG.IsLoad ? "yes" : "no");
437 OS << ", IsHvx:" << (MG.IsHvx ? "yes" : "no") << '\n';
438 OS << "Main\n";
439 for (Instruction *I : MG.Main)
440 OS << " " << *I << '\n';
441 OS << "Deps\n";
442 for (Instruction *I : MG.Deps)
443 OS << " " << *I << '\n';
444 OS << "Clones\n";
445 for (auto [K, V] : MG.Clones) {
446 OS << " ";
447 K->printAsOperand(OS, false);
448 OS << "\t-> " << *V << '\n';
449 }
450 return OS;
451}
452
453[[maybe_unused]] raw_ostream &
454operator<<(raw_ostream &OS, const AlignVectors::ByteSpan::Block &B) {
455 OS << " @" << B.Pos << " [" << B.Seg.Start << ',' << B.Seg.Size << "] ";
456 if (B.Seg.Val == reinterpret_cast<const Value *>(&B)) {
457 OS << "(self:" << B.Seg.Val << ')';
458 } else if (B.Seg.Val != nullptr) {
459 OS << *B.Seg.Val;
460 } else {
461 OS << "(null)";
462 }
463 return OS;
464}
465
466[[maybe_unused]] raw_ostream &operator<<(raw_ostream &OS,
467 const AlignVectors::ByteSpan &BS) {
468 OS << "ByteSpan[size=" << BS.size() << ", extent=" << BS.extent() << '\n';
469 for (const AlignVectors::ByteSpan::Block &B : BS)
470 OS << B << '\n';
471 OS << ']';
472 return OS;
473}
474
475class HvxIdioms {
476public:
477 enum DstQualifier {
478 Undefined = 0,
479 Arithmetic,
480 LdSt,
481 LLVM_Gather,
482 LLVM_Scatter,
483 HEX_Gather_Scatter,
484 HEX_Gather,
485 HEX_Scatter,
486 Call
487 };
488
489 HvxIdioms(const HexagonVectorCombine &HVC_) : HVC(HVC_) {
490 auto *Int32Ty = HVC.getIntTy(32);
491 HvxI32Ty = HVC.getHvxTy(Int32Ty, /*Pair=*/false);
492 HvxP32Ty = HVC.getHvxTy(Int32Ty, /*Pair=*/true);
493 }
494
495 bool run();
496
497private:
498 enum Signedness { Positive, Signed, Unsigned };
499
500 // Value + sign
501 // This is to keep track of whether the value should be treated as signed
502 // or unsigned, or is known to be positive.
503 struct SValue {
504 Value *Val;
505 Signedness Sgn;
506 };
507
508 struct FxpOp {
509 unsigned Opcode;
510 unsigned Frac; // Number of fraction bits
511 SValue X, Y;
512 // If present, add 1 << RoundAt before shift:
513 std::optional<unsigned> RoundAt;
514 VectorType *ResTy;
515 };
516
517 auto getNumSignificantBits(Value *V, Instruction *In) const
518 -> std::pair<unsigned, Signedness>;
519 auto canonSgn(SValue X, SValue Y) const -> std::pair<SValue, SValue>;
520
521 auto matchFxpMul(Instruction &In) const -> std::optional<FxpOp>;
522 auto processFxpMul(Instruction &In, const FxpOp &Op) const -> Value *;
523
524 auto processFxpMulChopped(IRBuilderBase &Builder, Instruction &In,
525 const FxpOp &Op) const -> Value *;
526 auto createMulQ15(IRBuilderBase &Builder, SValue X, SValue Y,
527 bool Rounding) const -> Value *;
528 auto createMulQ31(IRBuilderBase &Builder, SValue X, SValue Y,
529 bool Rounding) const -> Value *;
530 // Return {Result, Carry}, where Carry is a vector predicate.
531 auto createAddCarry(IRBuilderBase &Builder, Value *X, Value *Y,
532 Value *CarryIn = nullptr) const
533 -> std::pair<Value *, Value *>;
534 auto createMul16(IRBuilderBase &Builder, SValue X, SValue Y) const -> Value *;
535 auto createMulH16(IRBuilderBase &Builder, SValue X, SValue Y) const
536 -> Value *;
537 auto createMul32(IRBuilderBase &Builder, SValue X, SValue Y) const
538 -> std::pair<Value *, Value *>;
539 auto createAddLong(IRBuilderBase &Builder, ArrayRef<Value *> WordX,
541 auto createMulLong(IRBuilderBase &Builder, ArrayRef<Value *> WordX,
542 Signedness SgnX, ArrayRef<Value *> WordY,
543 Signedness SgnY) const -> SmallVector<Value *>;
544
545 bool matchMLoad(Instruction &In) const;
546 bool matchMStore(Instruction &In) const;
547 Value *processMLoad(Instruction &In) const;
548 Value *processMStore(Instruction &In) const;
549 std::optional<uint64_t> getAlignment(Instruction &In, Value *ptr) const;
550 std::optional<uint64_t>
551 getAlignmentImpl(Instruction &In, Value *ptr,
552 SmallPtrSet<Value *, 16> &Visited) const;
553 std::optional<uint64_t> getPHIBaseMinAlignment(Instruction &In,
554 PHINode *PN) const;
555
556 // Vector manipulations for Ripple
557 bool matchScatter(Instruction &In) const;
558 bool matchGather(Instruction &In) const;
559 Value *processVScatter(Instruction &In) const;
560 Value *processVGather(Instruction &In) const;
561
562 VectorType *HvxI32Ty;
563 VectorType *HvxP32Ty;
564 const HexagonVectorCombine &HVC;
565
566 friend raw_ostream &operator<<(raw_ostream &, const FxpOp &);
567};
568
569[[maybe_unused]] raw_ostream &operator<<(raw_ostream &OS,
570 const HvxIdioms::FxpOp &Op) {
571 static const char *SgnNames[] = {"Positive", "Signed", "Unsigned"};
572 OS << Instruction::getOpcodeName(Op.Opcode) << '.' << Op.Frac;
573 if (Op.RoundAt.has_value()) {
574 if (Op.Frac != 0 && *Op.RoundAt == Op.Frac - 1) {
575 OS << ":rnd";
576 } else {
577 OS << " + 1<<" << *Op.RoundAt;
578 }
579 }
580 OS << "\n X:(" << SgnNames[Op.X.Sgn] << ") " << *Op.X.Val << "\n"
581 << " Y:(" << SgnNames[Op.Y.Sgn] << ") " << *Op.Y.Val;
582 return OS;
583}
584
585} // namespace
586
587namespace {
588
589template <typename T> T *getIfUnordered(T *MaybeT) {
590 return MaybeT && MaybeT->isUnordered() ? MaybeT : nullptr;
591}
592template <typename T> T *isCandidate(Instruction *In) {
593 return dyn_cast<T>(In);
594}
596 return getIfUnordered(dyn_cast<LoadInst>(In));
597}
599 return getIfUnordered(dyn_cast<StoreInst>(In));
600}
601
602// Forward other erase_ifs to the LLVM implementations.
603template <typename Pred, typename T> void erase_if(T &&container, Pred p) {
604 llvm::erase_if(std::forward<T>(container), p);
605}
606
607} // namespace
608
609// --- Begin AlignVectors
610
611// For brevity, only consider loads. We identify a group of loads where we
612// know the relative differences between their addresses, so we know how they
613// are laid out in memory (relative to one another). These loads can overlap,
614// can be shorter or longer than the desired vector length.
615// Ultimately we want to generate a sequence of aligned loads that will load
616// every byte that the original loads loaded, and have the program use these
617// loaded values instead of the original loads.
618// We consider the contiguous memory area spanned by all these loads.
619//
620// Let's say that a single aligned vector load can load 16 bytes at a time.
621// If the program wanted to use a byte at offset 13 from the beginning of the
622// original span, it will be a byte at offset 13+x in the aligned data for
623// some x>=0. This may happen to be in the first aligned load, or in the load
624// following it. Since we generally don't know what the that alignment value
625// is at compile time, we proactively do valigns on the aligned loads, so that
626// byte that was at offset 13 is still at offset 13 after the valigns.
627//
628// This will be the starting point for making the rest of the program use the
629// data loaded by the new loads.
630// For each original load, and its users:
631// %v = load ...
632// ... = %v
633// ... = %v
634// we create
635// %new_v = extract/combine/shuffle data from loaded/valigned vectors so
636// it contains the same value as %v did before
637// then replace all users of %v with %new_v.
638// ... = %new_v
639// ... = %new_v
640
641auto AlignVectors::ByteSpan::extent() const -> int {
642 if (size() == 0)
643 return 0;
644 int Min = Blocks[0].Pos;
645 int Max = Blocks[0].Pos + Blocks[0].Seg.Size;
646 for (int i = 1, e = size(); i != e; ++i) {
647 Min = std::min(Min, Blocks[i].Pos);
648 Max = std::max(Max, Blocks[i].Pos + Blocks[i].Seg.Size);
649 }
650 return Max - Min;
651}
652
653auto AlignVectors::ByteSpan::section(int Start, int Length) const -> ByteSpan {
654 ByteSpan Section;
655 for (const ByteSpan::Block &B : Blocks) {
656 int L = std::max(B.Pos, Start); // Left end.
657 int R = std::min(B.Pos + B.Seg.Size, Start + Length); // Right end+1.
658 if (L < R) {
659 // How much to chop off the beginning of the segment:
660 int Off = L > B.Pos ? L - B.Pos : 0;
661 Section.Blocks.emplace_back(B.Seg.Val, B.Seg.Start + Off, R - L, L);
662 }
663 }
664 return Section;
665}
666
667auto AlignVectors::ByteSpan::shift(int Offset) -> ByteSpan & {
668 for (Block &B : Blocks)
669 B.Pos += Offset;
670 return *this;
671}
672
673auto AlignVectors::ByteSpan::values() const -> SmallVector<Value *, 8> {
674 SmallVector<Value *, 8> Values(Blocks.size());
675 for (int i = 0, e = Blocks.size(); i != e; ++i)
676 Values[i] = Blocks[i].Seg.Val;
677 return Values;
678}
679
680// Turn a requested integer alignment into the effective Align to use.
681// If Requested == 0 -> use ABI alignment of the value type (old semantics).
682// 0 means "ABI alignment" in old IR.
684 int Requested) {
685 if (Requested > 0)
686 return Align(static_cast<uint64_t>(Requested));
687 return Align(DL.getABITypeAlign(ValTy).value());
688}
689
690auto AlignVectors::getAddrInfo(Instruction &In) const
691 -> std::optional<AddrInfo> {
692 if (auto *L = isCandidate<LoadInst>(&In))
693 return AddrInfo(HVC, L, L->getPointerOperand(), L->getType(),
694 L->getAlign());
695 if (auto *S = isCandidate<StoreInst>(&In))
696 return AddrInfo(HVC, S, S->getPointerOperand(),
697 S->getValueOperand()->getType(), S->getAlign());
698 if (auto *II = isCandidate<IntrinsicInst>(&In)) {
699 Intrinsic::ID ID = II->getIntrinsicID();
700 switch (ID) {
701 case Intrinsic::masked_load:
702 return AddrInfo(HVC, II, II->getArgOperand(0), II->getType(),
703 II->getParamAlign(0).valueOrOne());
704 case Intrinsic::masked_store:
705 return AddrInfo(HVC, II, II->getArgOperand(1),
706 II->getArgOperand(0)->getType(),
707 II->getParamAlign(1).valueOrOne());
708 }
709 }
710 return std::nullopt;
711}
712
713auto AlignVectors::isHvx(const AddrInfo &AI) const -> bool {
714 return HVC.HST.isTypeForHVX(AI.ValTy);
715}
716
717auto AlignVectors::getPayload(Value *Val) const -> Value * {
718 if (auto *In = dyn_cast<Instruction>(Val)) {
719 Intrinsic::ID ID = 0;
720 if (auto *II = dyn_cast<IntrinsicInst>(In))
721 ID = II->getIntrinsicID();
722 if (isa<StoreInst>(In) || ID == Intrinsic::masked_store)
723 return In->getOperand(0);
724 }
725 return Val;
726}
727
728auto AlignVectors::getMask(Value *Val) const -> Value * {
729 if (auto *II = dyn_cast<IntrinsicInst>(Val)) {
730 switch (II->getIntrinsicID()) {
731 case Intrinsic::masked_load:
732 return II->getArgOperand(1);
733 case Intrinsic::masked_store:
734 return II->getArgOperand(2);
735 }
736 }
737
738 Type *ValTy = getPayload(Val)->getType();
739 if (auto *VecTy = dyn_cast<VectorType>(ValTy))
740 return Constant::getAllOnesValue(HVC.getBoolTy(HVC.length(VecTy)));
741 return Constant::getAllOnesValue(HVC.getBoolTy());
742}
743
744auto AlignVectors::getPassThrough(Value *Val) const -> Value * {
745 if (auto *II = dyn_cast<IntrinsicInst>(Val)) {
746 if (II->getIntrinsicID() == Intrinsic::masked_load)
747 return II->getArgOperand(2);
748 }
749 return UndefValue::get(getPayload(Val)->getType());
750}
751
752auto AlignVectors::createAdjustedPointer(IRBuilderBase &Builder, Value *Ptr,
753 Type *ValTy, int Adjust,
754 const InstMap &CloneMap) const
755 -> Value * {
756 if (auto *I = dyn_cast<Instruction>(Ptr))
757 if (Instruction *New = CloneMap.lookup(I))
758 Ptr = New;
759 return Builder.CreatePtrAddWithSignedOffset(Ptr, Adjust, "gep");
760}
761
762auto AlignVectors::createAlignedPointer(IRBuilderBase &Builder, Value *Ptr,
763 Type *ValTy, int Alignment,
764 const InstMap &CloneMap) const
765 -> Value * {
766 auto remap = [&](Value *V) -> Value * {
767 if (auto *I = dyn_cast<Instruction>(V)) {
768 for (auto [Old, New] : CloneMap)
769 I->replaceUsesOfWith(Old, New);
770 return I;
771 }
772 return V;
773 };
774 Value *AsInt = Builder.CreatePtrToInt(Ptr, HVC.getIntTy(), "pti");
775 Value *Mask = HVC.getConstInt(-Alignment);
776 Value *And = Builder.CreateAnd(remap(AsInt), Mask, "and");
777 return Builder.CreateIntToPtr(
778 And, PointerType::getUnqual(ValTy->getContext()), "itp");
779}
780
781auto AlignVectors::createLoad(IRBuilderBase &Builder, Type *ValTy, Value *Ptr,
782 Value *Predicate, int Alignment, Value *Mask,
783 Value *PassThru,
784 ArrayRef<Value *> MDSources) const -> Value * {
785 // Predicate is nullptr if not creating predicated load
786 if (Predicate) {
787 assert(!Predicate->getType()->isVectorTy() &&
788 "Expectning scalar predicate");
789 if (HVC.isFalse(Predicate))
790 return UndefValue::get(ValTy);
791 if (!HVC.isTrue(Predicate)) {
792 Value *Load = createPredicatedLoad(Builder, ValTy, Ptr, Predicate,
793 Alignment, MDSources);
794 return Builder.CreateSelect(Mask, Load, PassThru);
795 }
796 // Predicate == true here.
797 }
798 assert(!HVC.isUndef(Mask)); // Should this be allowed?
799 if (HVC.isZero(Mask))
800 return PassThru;
801
802 Align EffA = effectiveAlignForValueTy(HVC.DL, ValTy, Alignment);
803 if (HVC.isTrue(Mask))
804 return createSimpleLoad(Builder, ValTy, Ptr, EffA.value(), MDSources);
805
807 Builder.CreateMaskedLoad(ValTy, Ptr, EffA, Mask, PassThru, "mld");
808 LLVM_DEBUG(dbgs() << "\t[Creating masked Load:] "; Load->dump());
810 return Load;
811}
812
813auto AlignVectors::createSimpleLoad(IRBuilderBase &Builder, Type *ValTy,
814 Value *Ptr, int Alignment,
815 ArrayRef<Value *> MDSources) const
816 -> Value * {
817 Align EffA = effectiveAlignForValueTy(HVC.DL, ValTy, Alignment);
818 Instruction *Load = Builder.CreateAlignedLoad(ValTy, Ptr, EffA, "ald");
820 LLVM_DEBUG(dbgs() << "\t[Creating Load:] "; Load->dump());
821 return Load;
822}
823
824auto AlignVectors::createPredicatedLoad(IRBuilderBase &Builder, Type *ValTy,
825 Value *Ptr, Value *Predicate,
826 int Alignment,
827 ArrayRef<Value *> MDSources) const
828 -> Value * {
829 assert(HVC.HST.isTypeForHVX(ValTy) &&
830 "Predicates 'scalar' vector loads not yet supported");
831 assert(Predicate);
832 assert(!Predicate->getType()->isVectorTy() && "Expectning scalar predicate");
833 Align EffA = effectiveAlignForValueTy(HVC.DL, ValTy, Alignment);
834 assert(HVC.getSizeOf(ValTy, HVC.Alloc) % EffA.value() == 0);
835
836 if (HVC.isFalse(Predicate))
837 return UndefValue::get(ValTy);
838 if (HVC.isTrue(Predicate))
839 return createSimpleLoad(Builder, ValTy, Ptr, EffA.value(), MDSources);
840
841 auto V6_vL32b_pred_ai = HVC.HST.getIntrinsicId(Hexagon::V6_vL32b_pred_ai);
842 // FIXME: This may not put the offset from Ptr into the vmem offset.
843 return HVC.createHvxIntrinsic(Builder, V6_vL32b_pred_ai, ValTy,
844 {Predicate, Ptr, HVC.getConstInt(0)}, {},
845 MDSources);
846}
847
848auto AlignVectors::createStore(IRBuilderBase &Builder, Value *Val, Value *Ptr,
849 Value *Predicate, int Alignment, Value *Mask,
850 ArrayRef<Value *> MDSources) const -> Value * {
851 if (HVC.isZero(Mask) || HVC.isUndef(Val) || HVC.isUndef(Mask))
852 return UndefValue::get(Val->getType());
853 assert(!Predicate || (!Predicate->getType()->isVectorTy() &&
854 "Expectning scalar predicate"));
855 if (Predicate) {
856 if (HVC.isFalse(Predicate))
857 return UndefValue::get(Val->getType());
858 if (HVC.isTrue(Predicate))
859 Predicate = nullptr;
860 }
861 // Here both Predicate and Mask are true or unknown.
862
863 if (HVC.isTrue(Mask)) {
864 if (Predicate) { // Predicate unknown
865 return createPredicatedStore(Builder, Val, Ptr, Predicate, Alignment,
866 MDSources);
867 }
868 // Predicate is true:
869 return createSimpleStore(Builder, Val, Ptr, Alignment, MDSources);
870 }
871
872 // Mask is unknown
873 if (!Predicate) {
875 Builder.CreateMaskedStore(Val, Ptr, Align(Alignment), Mask);
877 return Store;
878 }
879
880 // Both Predicate and Mask are unknown.
881 // Emulate masked store with predicated-load + mux + predicated-store.
882 Value *PredLoad = createPredicatedLoad(Builder, Val->getType(), Ptr,
883 Predicate, Alignment, MDSources);
884 Value *Mux = Builder.CreateSelect(Mask, Val, PredLoad);
885 return createPredicatedStore(Builder, Mux, Ptr, Predicate, Alignment,
886 MDSources);
887}
888
889auto AlignVectors::createSimpleStore(IRBuilderBase &Builder, Value *Val,
890 Value *Ptr, int Alignment,
891 ArrayRef<Value *> MDSources) const
892 -> Value * {
893 Align EffA = effectiveAlignForValueTy(HVC.DL, Val->getType(), Alignment);
894 Instruction *Store = Builder.CreateAlignedStore(Val, Ptr, EffA);
895 LLVM_DEBUG(dbgs() << "\t[Creating store:] "; Store->dump());
897 return Store;
898}
899
900auto AlignVectors::createPredicatedStore(IRBuilderBase &Builder, Value *Val,
901 Value *Ptr, Value *Predicate,
902 int Alignment,
903 ArrayRef<Value *> MDSources) const
904 -> Value * {
905 Align EffA = effectiveAlignForValueTy(HVC.DL, Val->getType(), Alignment);
906 assert(HVC.HST.isTypeForHVX(Val->getType()) &&
907 "Predicates 'scalar' vector stores not yet supported");
908 assert(Predicate);
909 if (HVC.isFalse(Predicate))
910 return UndefValue::get(Val->getType());
911 if (HVC.isTrue(Predicate))
912 return createSimpleStore(Builder, Val, Ptr, EffA.value(), MDSources);
913
914 assert(HVC.getSizeOf(Val, HVC.Alloc) % EffA.value() == 0);
915 auto V6_vS32b_pred_ai = HVC.HST.getIntrinsicId(Hexagon::V6_vS32b_pred_ai);
916 // FIXME: This may not put the offset from Ptr into the vmem offset.
917 return HVC.createHvxIntrinsic(Builder, V6_vS32b_pred_ai, nullptr,
918 {Predicate, Ptr, HVC.getConstInt(0), Val}, {},
919 MDSources);
920}
921
922auto AlignVectors::getUpwardDeps(Instruction *In, Instruction *Base) const
923 -> DepList {
924 BasicBlock *Parent = Base->getParent();
925 assert(In->getParent() == Parent &&
926 "Base and In should be in the same block");
927 assert(Base->comesBefore(In) && "Base should come before In");
928
929 DepList Deps;
930 std::deque<Instruction *> WorkQ = {In};
931 while (!WorkQ.empty()) {
932 Instruction *D = WorkQ.front();
933 WorkQ.pop_front();
934 if (D != In)
935 Deps.insert(D);
936 for (Value *Op : D->operands()) {
937 if (auto *I = dyn_cast<Instruction>(Op)) {
938 if (I->getParent() == Parent && Base->comesBefore(I))
939 WorkQ.push_back(I);
940 }
941 }
942 }
943 return Deps;
944}
945
946auto AlignVectors::createAddressGroups() -> bool {
947 // An address group created here may contain instructions spanning
948 // multiple basic blocks.
949 AddrList WorkStack;
950
951 auto findBaseAndOffset = [&](AddrInfo &AI) -> std::pair<Instruction *, int> {
952 for (AddrInfo &W : WorkStack) {
953 if (auto D = HVC.calculatePointerDifference(AI.Addr, W.Addr))
954 return std::make_pair(W.Inst, *D);
955 }
956 return std::make_pair(nullptr, 0);
957 };
958
959 auto traverseBlock = [&](DomTreeNode *DomN, auto Visit) -> void {
960 BasicBlock &Block = *DomN->getBlock();
961 for (Instruction &I : Block) {
962 auto AI = this->getAddrInfo(I); // Use this-> for gcc6.
963 if (!AI)
964 continue;
965 auto F = findBaseAndOffset(*AI);
966 Instruction *GroupInst;
967 if (Instruction *BI = F.first) {
968 AI->Offset = F.second;
969 GroupInst = BI;
970 } else {
971 WorkStack.push_back(*AI);
972 GroupInst = AI->Inst;
973 }
974 AddrGroups[GroupInst].push_back(*AI);
975 }
976
977 for (DomTreeNode *C : DomN->children())
978 Visit(C, Visit);
979
980 while (!WorkStack.empty() && WorkStack.back().Inst->getParent() == &Block)
981 WorkStack.pop_back();
982 };
983
984 traverseBlock(HVC.DT.getRootNode(), traverseBlock);
985 assert(WorkStack.empty());
986
987 // AddrGroups are formed.
988 // Remove groups of size 1.
989 AddrGroups.remove_if([](auto &G) { return G.second.size() == 1; });
990 // Remove groups that don't use HVX types.
991 AddrGroups.remove_if([&](auto &G) {
992 return llvm::none_of(
993 G.second, [&](auto &I) { return HVC.HST.isTypeForHVX(I.ValTy); });
994 });
995
996 LLVM_DEBUG(dbgs() << AddrGroups);
997 return !AddrGroups.empty();
998}
999
1000auto AlignVectors::createLoadGroups(const AddrList &Group) const -> MoveList {
1001 // Form load groups.
1002 // To avoid complications with moving code across basic blocks, only form
1003 // groups that are contained within a single basic block.
1004 unsigned SizeLimit = VAGroupSizeLimit;
1005 if (SizeLimit == 0)
1006 return {};
1007
1008 auto tryAddTo = [&](const AddrInfo &Info, MoveGroup &Move) {
1009 assert(!Move.Main.empty() && "Move group should have non-empty Main");
1010 if (Move.Main.size() >= SizeLimit) {
1011 HVC.ORE.emit([&]() {
1012 return OptimizationRemarkMissed(DEBUG_TYPE, "GroupSizeLimitExceeded",
1013 Info.Inst->getDebugLoc(),
1014 Info.Inst->getParent())
1015 << "alignment group exceeds size limit";
1016 });
1017 return false;
1018 }
1019 // Don't mix HVX and non-HVX instructions.
1020 if (Move.IsHvx != isHvx(Info))
1021 return false;
1022 // Leading instruction in the load group.
1023 Instruction *Base = Move.Main.front();
1024 if (Base->getParent() != Info.Inst->getParent())
1025 return false;
1026 // Check if it's safe to move the load.
1027 if (!HVC.isSafeToMoveBeforeInBB(*Info.Inst, Base->getIterator())) {
1028 HVC.ORE.emit([&]() {
1029 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsafeToRelocate",
1030 Info.Inst->getDebugLoc(),
1031 Info.Inst->getParent())
1032 << "unsafe to relocate memory access for alignment";
1033 });
1034 return false;
1035 }
1036 // And if it's safe to clone the dependencies.
1037 auto isSafeToCopyAtBase = [&](const Instruction *I) {
1038 return HVC.isSafeToMoveBeforeInBB(*I, Base->getIterator()) &&
1039 HVC.isSafeToClone(*I);
1040 };
1041 DepList Deps = getUpwardDeps(Info.Inst, Base);
1042 if (!llvm::all_of(Deps, isSafeToCopyAtBase))
1043 return false;
1044
1045 Move.Main.push_back(Info.Inst);
1046 llvm::append_range(Move.Deps, Deps);
1047 return true;
1048 };
1049
1050 MoveList LoadGroups;
1051
1052 for (const AddrInfo &Info : Group) {
1053 if (!Info.Inst->mayReadFromMemory())
1054 continue;
1055 if (LoadGroups.empty() || !tryAddTo(Info, LoadGroups.back()))
1056 LoadGroups.emplace_back(Info, Group.front().Inst, isHvx(Info), true);
1057 }
1058
1059 // Erase groups smaller than the minimum load group size.
1060 unsigned LoadGroupSizeLimit = MinLoadGroupSizeForAlignment;
1061 erase_if(LoadGroups, [LoadGroupSizeLimit](const MoveGroup &G) {
1062 return G.Main.size() < LoadGroupSizeLimit;
1063 });
1064
1065 // Erase HVX groups on targets < HvxV62 (due to lack of predicated loads).
1066 if (!HVC.HST.useHVXV62Ops()) {
1067 bool HadHvx =
1068 llvm::any_of(LoadGroups, [](const MoveGroup &G) { return G.IsHvx; });
1069 erase_if(LoadGroups, [](const MoveGroup &G) { return G.IsHvx; });
1070 if (HadHvx) {
1071 HVC.ORE.emit([&]() {
1072 return OptimizationRemarkMissed(DEBUG_TYPE, "HvxVersionTooLow",
1073 HVC.F.getSubprogram(), &HVC.F.front())
1074 << "HVX version too low for predicated load operations";
1075 });
1076 }
1077 }
1078
1079 LLVM_DEBUG(dbgs() << "LoadGroups list: " << LoadGroups);
1080 return LoadGroups;
1081}
1082
1083auto AlignVectors::createStoreGroups(const AddrList &Group) const -> MoveList {
1084 // Form store groups.
1085 // To avoid complications with moving code across basic blocks, only form
1086 // groups that are contained within a single basic block.
1087 unsigned SizeLimit = VAGroupSizeLimit;
1088 if (SizeLimit == 0)
1089 return {};
1090
1091 auto tryAddTo = [&](const AddrInfo &Info, MoveGroup &Move) {
1092 assert(!Move.Main.empty() && "Move group should have non-empty Main");
1093 if (Move.Main.size() >= SizeLimit) {
1094 HVC.ORE.emit([&]() {
1095 return OptimizationRemarkMissed(DEBUG_TYPE, "GroupSizeLimitExceeded",
1096 Info.Inst->getDebugLoc(),
1097 Info.Inst->getParent())
1098 << "alignment group exceeds size limit";
1099 });
1100 return false;
1101 }
1102 // For stores with return values we'd have to collect downward dependencies.
1103 // There are no such stores that we handle at the moment, so omit that.
1104 assert(Info.Inst->getType()->isVoidTy() &&
1105 "Not handling stores with return values");
1106 // Don't mix HVX and non-HVX instructions.
1107 if (Move.IsHvx != isHvx(Info))
1108 return false;
1109 // For stores we need to be careful whether it's safe to move them.
1110 // Stores that are otherwise safe to move together may not appear safe
1111 // to move over one another (i.e. isSafeToMoveBefore may return false).
1112 Instruction *Base = Move.Main.front();
1113 if (Base->getParent() != Info.Inst->getParent())
1114 return false;
1115 if (!HVC.isSafeToMoveBeforeInBB(*Info.Inst, Base->getIterator(),
1116 Move.Main)) {
1117 HVC.ORE.emit([&]() {
1118 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsafeToRelocate",
1119 Info.Inst->getDebugLoc(),
1120 Info.Inst->getParent())
1121 << "unsafe to relocate memory access for alignment";
1122 });
1123 return false;
1124 }
1125 Move.Main.push_back(Info.Inst);
1126 return true;
1127 };
1128
1129 MoveList StoreGroups;
1130
1131 for (auto I = Group.rbegin(), E = Group.rend(); I != E; ++I) {
1132 const AddrInfo &Info = *I;
1133 if (!Info.Inst->mayWriteToMemory())
1134 continue;
1135 if (StoreGroups.empty() || !tryAddTo(Info, StoreGroups.back()))
1136 StoreGroups.emplace_back(Info, Group.front().Inst, isHvx(Info), false);
1137 }
1138
1139 // Erase singleton groups.
1140 erase_if(StoreGroups, [](const MoveGroup &G) { return G.Main.size() <= 1; });
1141
1142 // Erase HVX groups on targets < HvxV62 (due to lack of predicated loads).
1143 if (!HVC.HST.useHVXV62Ops()) {
1144 bool HadHvx =
1145 llvm::any_of(StoreGroups, [](const MoveGroup &G) { return G.IsHvx; });
1146 erase_if(StoreGroups, [](const MoveGroup &G) { return G.IsHvx; });
1147 if (HadHvx) {
1148 HVC.ORE.emit([&]() {
1149 return OptimizationRemarkMissed(DEBUG_TYPE, "HvxVersionTooLow",
1150 HVC.F.getSubprogram(), &HVC.F.front())
1151 << "HVX version too low for predicated store operations";
1152 });
1153 }
1154 }
1155
1156 // Erase groups where every store is a full HVX vector. The reason is that
1157 // aligning predicated stores generates complex code that may be less
1158 // efficient than a sequence of unaligned vector stores.
1159 if (!VADoFullStores) {
1160 erase_if(StoreGroups, [this](const MoveGroup &G) {
1161 return G.IsHvx && llvm::all_of(G.Main, [this](Instruction *S) {
1162 auto MaybeInfo = this->getAddrInfo(*S);
1163 assert(MaybeInfo.has_value());
1164 return HVC.HST.isHVXVectorType(
1165 EVT::getEVT(MaybeInfo->ValTy, false));
1166 });
1167 });
1168 }
1169
1170 return StoreGroups;
1171}
1172
1173auto AlignVectors::moveTogether(MoveGroup &Move) const -> bool {
1174 // Move all instructions to be adjacent.
1175 assert(!Move.Main.empty() && "Move group should have non-empty Main");
1176 Instruction *Where = Move.Main.front();
1177
1178 if (Move.IsLoad) {
1179 // Move all the loads (and dependencies) to where the first load is.
1180 // Clone all deps to before Where, keeping order.
1181 Move.Clones = cloneBefore(Where->getIterator(), Move.Deps);
1182 // Move all main instructions to after Where, keeping order.
1183 ArrayRef<Instruction *> Main(Move.Main);
1184 for (Instruction *M : Main) {
1185 if (M != Where)
1186 M->moveAfter(Where);
1187 for (auto [Old, New] : Move.Clones)
1188 M->replaceUsesOfWith(Old, New);
1189 Where = M;
1190 }
1191 // Replace Deps with the clones.
1192 for (int i = 0, e = Move.Deps.size(); i != e; ++i)
1193 Move.Deps[i] = Move.Clones[Move.Deps[i]];
1194 } else {
1195 // Move all the stores to where the last store is.
1196 // NOTE: Deps are empty for "store" groups. If they need to be
1197 // non-empty, decide on the order.
1198 assert(Move.Deps.empty());
1199 // Move all main instructions to before Where, inverting order.
1200 ArrayRef<Instruction *> Main(Move.Main);
1201 for (Instruction *M : Main.drop_front(1)) {
1202 M->moveBefore(Where->getIterator());
1203 Where = M;
1204 }
1205 }
1206
1207 return Move.Main.size() + Move.Deps.size() > 1;
1208}
1209
1210template <typename T>
1211auto AlignVectors::cloneBefore(BasicBlock::iterator To, T &&Insts) const
1212 -> InstMap {
1213 InstMap Map;
1214
1215 for (Instruction *I : Insts) {
1216 assert(HVC.isSafeToClone(*I));
1217 Instruction *C = I->clone();
1218 C->setName(Twine("c.") + I->getName() + ".");
1219 C->insertBefore(To);
1220
1221 for (auto [Old, New] : Map)
1222 C->replaceUsesOfWith(Old, New);
1223 Map.insert(std::make_pair(I, C));
1224 }
1225 return Map;
1226}
1227
1228auto AlignVectors::realignLoadGroup(IRBuilderBase &Builder,
1229 const ByteSpan &VSpan, int ScLen,
1230 Value *AlignVal, Value *AlignAddr) const
1231 -> void {
1232 LLVM_DEBUG(dbgs() << __func__ << "\n");
1233
1234 Type *SecTy = HVC.getByteTy(ScLen);
1235 int NumSectors = (VSpan.extent() + ScLen - 1) / ScLen;
1236 bool DoAlign = !HVC.isZero(AlignVal);
1237 BasicBlock::iterator BasePos = Builder.GetInsertPoint();
1238 BasicBlock *BaseBlock = Builder.GetInsertBlock();
1239
1240 ByteSpan ASpan;
1241 auto *True = Constant::getAllOnesValue(HVC.getBoolTy(ScLen));
1242 auto *Undef = UndefValue::get(SecTy);
1243
1244 // Created load does not have to be "Instruction" (e.g. "undef").
1245 SmallVector<Value *> Loads(NumSectors + DoAlign, nullptr);
1246
1247 // We could create all of the aligned loads, and generate the valigns
1248 // at the location of the first load, but for large load groups, this
1249 // could create highly suboptimal code (there have been groups of 140+
1250 // loads in real code).
1251 // Instead, place the loads/valigns as close to the users as possible.
1252 // In any case we need to have a mapping from the blocks of VSpan (the
1253 // span covered by the pre-existing loads) to ASpan (the span covered
1254 // by the aligned loads). There is a small problem, though: ASpan needs
1255 // to have pointers to the loads/valigns, but we don't have these loads
1256 // because we don't know where to put them yet. We find out by creating
1257 // a section of ASpan that corresponds to values (blocks) from VSpan,
1258 // and checking where the new load should be placed. We need to attach
1259 // this location information to each block in ASpan somehow, so we put
1260 // distincts values for Seg.Val in each ASpan.Blocks[i], and use a map
1261 // to store the location for each Seg.Val.
1262 // The distinct values happen to be Blocks[i].Seg.Val = &Blocks[i],
1263 // which helps with printing ByteSpans without crashing when printing
1264 // Segments with these temporary identifiers in place of Val.
1265
1266 // Populate the blocks first, to avoid reallocations of the vector
1267 // interfering with generating the placeholder addresses.
1268 for (int Index = 0; Index != NumSectors; ++Index)
1269 ASpan.Blocks.emplace_back(nullptr, ScLen, Index * ScLen);
1270 for (int Index = 0; Index != NumSectors; ++Index) {
1271 ASpan.Blocks[Index].Seg.Val =
1272 reinterpret_cast<Value *>(&ASpan.Blocks[Index]);
1273 }
1274
1275 // Multiple values from VSpan can map to the same value in ASpan. Since we
1276 // try to create loads lazily, we need to find the earliest use for each
1277 // value from ASpan.
1278 DenseMap<void *, Instruction *> EarliestUser;
1279 auto isEarlier = [](Instruction *A, Instruction *B) {
1280 if (B == nullptr)
1281 return true;
1282 if (A == nullptr)
1283 return false;
1284 assert(A->getParent() == B->getParent());
1285 return A->comesBefore(B);
1286 };
1287 auto earliestUser = [&](const auto &Uses) {
1288 Instruction *User = nullptr;
1289 for (const Use &U : Uses) {
1290 auto *I = dyn_cast<Instruction>(U.getUser());
1291 assert(I != nullptr && "Load used in a non-instruction?");
1292 // Make sure we only consider users in this block, but we need
1293 // to remember if there were users outside the block too. This is
1294 // because if no users are found, aligned loads will not be created.
1295 if (I->getParent() == BaseBlock) {
1296 if (!isa<PHINode>(I))
1297 User = std::min(User, I, isEarlier);
1298 } else {
1299 User = std::min(User, BaseBlock->getTerminator(), isEarlier);
1300 }
1301 }
1302 return User;
1303 };
1304
1305 for (const ByteSpan::Block &B : VSpan) {
1306 ByteSpan ASection = ASpan.section(B.Pos, B.Seg.Size);
1307 for (const ByteSpan::Block &S : ASection) {
1308 auto &EU = EarliestUser[S.Seg.Val];
1309 EU = std::min(EU, earliestUser(B.Seg.Val->uses()), isEarlier);
1310 }
1311 }
1312
1313 LLVM_DEBUG({
1314 dbgs() << "ASpan:\n" << ASpan << '\n';
1315 dbgs() << "Earliest users of ASpan:\n";
1316 for (auto &[Val, User] : EarliestUser) {
1317 dbgs() << Val << "\n ->" << *User << '\n';
1318 }
1319 });
1320
1321 auto createLoad = [&](IRBuilderBase &Builder, const ByteSpan &VSpan,
1322 int Index, bool MakePred) {
1323 Value *Ptr =
1324 createAdjustedPointer(Builder, AlignAddr, SecTy, Index * ScLen);
1325 Value *Predicate =
1326 MakePred ? makeTestIfUnaligned(Builder, AlignVal, ScLen) : nullptr;
1327
1328 // If vector shifting is potentially needed, accumulate metadata
1329 // from source sections of twice the load width.
1330 int Start = (Index - DoAlign) * ScLen;
1331 int Width = (1 + DoAlign) * ScLen;
1332 return this->createLoad(Builder, SecTy, Ptr, Predicate, ScLen, True, Undef,
1333 VSpan.section(Start, Width).values());
1334 };
1335
1336 auto moveBefore = [this](BasicBlock::iterator In, BasicBlock::iterator To) {
1337 // Move In and its upward dependencies to before To.
1338 assert(In->getParent() == To->getParent());
1339 DepList Deps = getUpwardDeps(&*In, &*To);
1340 In->moveBefore(To);
1341 // DepList is sorted with respect to positions in the basic block.
1342 InstMap Map = cloneBefore(In, Deps);
1343 for (auto [Old, New] : Map)
1344 In->replaceUsesOfWith(Old, New);
1345 };
1346
1347 // Generate necessary loads at appropriate locations.
1348 LLVM_DEBUG(dbgs() << "Creating loads for ASpan sectors\n");
1349 for (int Index = 0; Index != NumSectors + 1; ++Index) {
1350 // In ASpan, each block will be either a single aligned load, or a
1351 // valign of a pair of loads. In the latter case, an aligned load j
1352 // will belong to the current valign, and the one in the previous
1353 // block (for j > 0).
1354 // Place the load at a location which will dominate the valign, assuming
1355 // the valign will be placed right before the earliest user.
1356 Instruction *PrevAt =
1357 DoAlign && Index > 0 ? EarliestUser[&ASpan[Index - 1]] : nullptr;
1358 Instruction *ThisAt =
1359 Index < NumSectors ? EarliestUser[&ASpan[Index]] : nullptr;
1360 if (auto *Where = std::min(PrevAt, ThisAt, isEarlier)) {
1361 Builder.SetInsertPoint(Where);
1362 Loads[Index] =
1363 createLoad(Builder, VSpan, Index, DoAlign && Index == NumSectors);
1364 // We know it's safe to put the load at BasePos, but we'd prefer to put
1365 // it at "Where". To see if the load is safe to be placed at Where, put
1366 // it there first and then check if it's safe to move it to BasePos.
1367 // If not, then the load needs to be placed at BasePos.
1368 // We can't do this check proactively because we need the load to exist
1369 // in order to check legality.
1370 if (auto *Load = dyn_cast<Instruction>(Loads[Index])) {
1371 if (!HVC.isSafeToMoveBeforeInBB(*Load, BasePos))
1372 moveBefore(Load->getIterator(), BasePos);
1373 }
1374 LLVM_DEBUG(dbgs() << "Loads[" << Index << "]:" << *Loads[Index] << '\n');
1375 }
1376 }
1377
1378 // Generate valigns if needed, and fill in proper values in ASpan
1379 LLVM_DEBUG(dbgs() << "Creating values for ASpan sectors\n");
1380 for (int Index = 0; Index != NumSectors; ++Index) {
1381 ASpan[Index].Seg.Val = nullptr;
1382 if (auto *Where = EarliestUser[&ASpan[Index]]) {
1383 Builder.SetInsertPoint(Where);
1384 Value *Val = Loads[Index];
1385 assert(Val != nullptr);
1386 if (DoAlign) {
1387 Value *NextLoad = Loads[Index + 1];
1388 assert(NextLoad != nullptr);
1389 Val = HVC.vralignb(Builder, Val, NextLoad, AlignVal);
1390 }
1391 ASpan[Index].Seg.Val = Val;
1392 LLVM_DEBUG(dbgs() << "ASpan[" << Index << "]:" << *Val << '\n');
1393 }
1394 }
1395
1396 for (const ByteSpan::Block &B : VSpan) {
1397 ByteSpan ASection = ASpan.section(B.Pos, B.Seg.Size).shift(-B.Pos);
1398 Value *Accum = UndefValue::get(HVC.getByteTy(B.Seg.Size));
1399 Builder.SetInsertPoint(cast<Instruction>(B.Seg.Val));
1400
1401 // We're generating a reduction, where each instruction depends on
1402 // the previous one, so we need to order them according to the position
1403 // of their inputs in the code.
1404 std::vector<ByteSpan::Block *> ABlocks;
1405 for (ByteSpan::Block &S : ASection) {
1406 if (S.Seg.Val != nullptr)
1407 ABlocks.push_back(&S);
1408 }
1409 llvm::sort(ABlocks,
1410 [&](const ByteSpan::Block *A, const ByteSpan::Block *B) {
1411 return isEarlier(cast<Instruction>(A->Seg.Val),
1412 cast<Instruction>(B->Seg.Val));
1413 });
1414 for (ByteSpan::Block *S : ABlocks) {
1415 // The processing of the data loaded by the aligned loads
1416 // needs to be inserted after the data is available.
1417 Instruction *SegI = cast<Instruction>(S->Seg.Val);
1418 Builder.SetInsertPoint(&*std::next(SegI->getIterator()));
1419 Value *Pay = HVC.vbytes(Builder, getPayload(S->Seg.Val));
1420 Accum =
1421 HVC.insertb(Builder, Accum, Pay, S->Seg.Start, S->Seg.Size, S->Pos);
1422 }
1423 // Instead of casting everything to bytes for the vselect, cast to the
1424 // original value type. This will avoid complications with casting masks.
1425 // For example, in cases when the original mask applied to i32, it could
1426 // be converted to a mask applicable to i8 via pred_typecast intrinsic,
1427 // but if the mask is not exactly of HVX length, extra handling would be
1428 // needed to make it work.
1429 Type *ValTy = getPayload(B.Seg.Val)->getType();
1430 Value *Cast = Builder.CreateBitCast(Accum, ValTy, "cst");
1431 Value *Sel = Builder.CreateSelect(getMask(B.Seg.Val), Cast,
1432 getPassThrough(B.Seg.Val), "sel");
1433 B.Seg.Val->replaceAllUsesWith(Sel);
1434 }
1435}
1436
1437auto AlignVectors::realignStoreGroup(IRBuilderBase &Builder,
1438 const ByteSpan &VSpan, int ScLen,
1439 Value *AlignVal, Value *AlignAddr) const
1440 -> void {
1441 LLVM_DEBUG(dbgs() << __func__ << "\n");
1442
1443 Type *SecTy = HVC.getByteTy(ScLen);
1444 int NumSectors = (VSpan.extent() + ScLen - 1) / ScLen;
1445 bool DoAlign = !HVC.isZero(AlignVal);
1446
1447 // Stores.
1448 ByteSpan ASpanV, ASpanM;
1449
1450 // Return a vector value corresponding to the input value Val:
1451 // either <1 x Val> for scalar Val, or Val itself for vector Val.
1452 auto MakeVec = [](IRBuilderBase &Builder, Value *Val) -> Value * {
1453 Type *Ty = Val->getType();
1454 if (Ty->isVectorTy())
1455 return Val;
1456 auto *VecTy = VectorType::get(Ty, 1, /*Scalable=*/false);
1457 return Builder.CreateBitCast(Val, VecTy, "cst");
1458 };
1459
1460 // Create an extra "undef" sector at the beginning and at the end.
1461 // They will be used as the left/right filler in the vlalign step.
1462 for (int Index = (DoAlign ? -1 : 0); Index != NumSectors + DoAlign; ++Index) {
1463 // For stores, the size of each section is an aligned vector length.
1464 // Adjust the store offsets relative to the section start offset.
1465 ByteSpan VSection =
1466 VSpan.section(Index * ScLen, ScLen).shift(-Index * ScLen);
1467 Value *Undef = UndefValue::get(SecTy);
1469 Value *AccumV = Undef;
1470 Value *AccumM = Zero;
1471 for (ByteSpan::Block &S : VSection) {
1472 Value *Pay = getPayload(S.Seg.Val);
1473 Value *Mask = HVC.rescale(Builder, MakeVec(Builder, getMask(S.Seg.Val)),
1474 Pay->getType(), HVC.getByteTy());
1475 Value *PartM = HVC.insertb(Builder, Zero, HVC.vbytes(Builder, Mask),
1476 S.Seg.Start, S.Seg.Size, S.Pos);
1477 AccumM = Builder.CreateOr(AccumM, PartM);
1478
1479 Value *PartV = HVC.insertb(Builder, Undef, HVC.vbytes(Builder, Pay),
1480 S.Seg.Start, S.Seg.Size, S.Pos);
1481
1482 AccumV = Builder.CreateSelect(
1483 Builder.CreateICmp(CmpInst::ICMP_NE, PartM, Zero), PartV, AccumV);
1484 }
1485 ASpanV.Blocks.emplace_back(AccumV, ScLen, Index * ScLen);
1486 ASpanM.Blocks.emplace_back(AccumM, ScLen, Index * ScLen);
1487 }
1488
1489 LLVM_DEBUG({
1490 dbgs() << "ASpanV before vlalign:\n" << ASpanV << '\n';
1491 dbgs() << "ASpanM before vlalign:\n" << ASpanM << '\n';
1492 });
1493
1494 // vlalign
1495 if (DoAlign) {
1496 for (int Index = 1; Index != NumSectors + 2; ++Index) {
1497 Value *PrevV = ASpanV[Index - 1].Seg.Val, *ThisV = ASpanV[Index].Seg.Val;
1498 Value *PrevM = ASpanM[Index - 1].Seg.Val, *ThisM = ASpanM[Index].Seg.Val;
1499 assert(isSectorTy(PrevV->getType()) && isSectorTy(PrevM->getType()));
1500 ASpanV[Index - 1].Seg.Val = HVC.vlalignb(Builder, PrevV, ThisV, AlignVal);
1501 ASpanM[Index - 1].Seg.Val = HVC.vlalignb(Builder, PrevM, ThisM, AlignVal);
1502 }
1503 }
1504
1505 LLVM_DEBUG({
1506 dbgs() << "ASpanV after vlalign:\n" << ASpanV << '\n';
1507 dbgs() << "ASpanM after vlalign:\n" << ASpanM << '\n';
1508 });
1509
1510 auto createStore = [&](IRBuilderBase &Builder, const ByteSpan &ASpanV,
1511 const ByteSpan &ASpanM, int Index, bool MakePred) {
1512 Value *Val = ASpanV[Index].Seg.Val;
1513 Value *Mask = ASpanM[Index].Seg.Val; // bytes
1514 if (HVC.isUndef(Val) || HVC.isZero(Mask))
1515 return;
1516 Value *Ptr =
1517 createAdjustedPointer(Builder, AlignAddr, SecTy, Index * ScLen);
1518 Value *Predicate =
1519 MakePred ? makeTestIfUnaligned(Builder, AlignVal, ScLen) : nullptr;
1520
1521 // If vector shifting is potentially needed, accumulate metadata
1522 // from source sections of twice the store width.
1523 int Start = (Index - DoAlign) * ScLen;
1524 int Width = (1 + DoAlign) * ScLen;
1525 this->createStore(Builder, Val, Ptr, Predicate, ScLen,
1526 HVC.vlsb(Builder, Mask),
1527 VSpan.section(Start, Width).values());
1528 };
1529
1530 for (int Index = 0; Index != NumSectors + DoAlign; ++Index) {
1531 createStore(Builder, ASpanV, ASpanM, Index, DoAlign && Index == NumSectors);
1532 }
1533}
1534
1535auto AlignVectors::realignGroup(const MoveGroup &Move) -> bool {
1536 LLVM_DEBUG(dbgs() << "Realigning group:\n" << Move << '\n');
1537
1538 // TODO: Needs support for masked loads/stores of "scalar" vectors.
1539 if (!Move.IsHvx)
1540 return false;
1541
1542 // Return the element with the maximum alignment from Range,
1543 // where GetValue obtains the value to compare from an element.
1544 auto getMaxOf = [](auto Range, auto GetValue) {
1545 return *llvm::max_element(Range, [&GetValue](auto &A, auto &B) {
1546 return GetValue(A) < GetValue(B);
1547 });
1548 };
1549
1550 AddrList &BaseInfos = AddrGroups[Move.Base];
1551
1552 // Conceptually, there is a vector of N bytes covering the addresses
1553 // starting from the minimum offset (i.e. Base.Addr+Start). This vector
1554 // represents a contiguous memory region that spans all accessed memory
1555 // locations.
1556 // The correspondence between loaded or stored values will be expressed
1557 // in terms of this vector. For example, the 0th element of the vector
1558 // from the Base address info will start at byte Start from the beginning
1559 // of this conceptual vector.
1560 //
1561 // This vector will be loaded/stored starting at the nearest down-aligned
1562 // address and the amount of the down-alignment will be AlignVal:
1563 // valign(load_vector(align_down(Base+Start)), AlignVal)
1564
1565 std::set<Instruction *> TestSet(Move.Main.begin(), Move.Main.end());
1566 AddrList MoveInfos;
1567
1569 BaseInfos, std::back_inserter(MoveInfos),
1570 [&TestSet](const AddrInfo &AI) { return TestSet.count(AI.Inst); });
1571
1572 // Maximum alignment present in the whole address group.
1573 const AddrInfo &WithMaxAlign =
1574 getMaxOf(MoveInfos, [](const AddrInfo &AI) { return AI.HaveAlign; });
1575 Align MaxGiven = WithMaxAlign.HaveAlign;
1576
1577 // Minimum alignment present in the move address group.
1578 const AddrInfo &WithMinOffset =
1579 getMaxOf(MoveInfos, [](const AddrInfo &AI) { return -AI.Offset; });
1580
1581 const AddrInfo &WithMaxNeeded =
1582 getMaxOf(MoveInfos, [](const AddrInfo &AI) { return AI.NeedAlign; });
1583 Align MinNeeded = WithMaxNeeded.NeedAlign;
1584
1585 // Set the builder's insertion point right before the load group, or
1586 // immediately after the store group. (Instructions in a store group are
1587 // listed in reverse order.)
1588 Instruction *InsertAt = Move.Main.front();
1589 if (!Move.IsLoad) {
1590 // There should be a terminator (which store isn't, but check anyways).
1591 assert(InsertAt->getIterator() != InsertAt->getParent()->end());
1592 InsertAt = &*std::next(InsertAt->getIterator());
1593 }
1594
1595 IRBuilder Builder(InsertAt->getIterator(), InstSimplifyFolder(HVC.DL));
1596 Value *AlignAddr = nullptr; // Actual aligned address.
1597 Value *AlignVal = nullptr; // Right-shift amount (for valign).
1598
1599 if (MinNeeded <= MaxGiven) {
1600 int Start = WithMinOffset.Offset;
1601 int OffAtMax = WithMaxAlign.Offset;
1602 // Shift the offset of the maximally aligned instruction (OffAtMax)
1603 // back by just enough multiples of the required alignment to cover the
1604 // distance from Start to OffAtMax.
1605 // Calculate the address adjustment amount based on the address with the
1606 // maximum alignment. This is to allow a simple gep instruction instead
1607 // of potential bitcasts to i8*.
1608 int Adjust = -alignTo(OffAtMax - Start, MinNeeded.value());
1609 AlignAddr = createAdjustedPointer(Builder, WithMaxAlign.Addr,
1610 WithMaxAlign.ValTy, Adjust, Move.Clones);
1611 int Diff = Start - (OffAtMax + Adjust);
1612 AlignVal = HVC.getConstInt(Diff);
1613 assert(Diff >= 0);
1614 assert(static_cast<decltype(MinNeeded.value())>(Diff) < MinNeeded.value());
1615 } else {
1616 // WithMinOffset is the lowest address in the group,
1617 // WithMinOffset.Addr = Base+Start.
1618 // Align instructions for both HVX (V6_valign) and scalar (S2_valignrb)
1619 // mask off unnecessary bits, so it's ok to just the original pointer as
1620 // the alignment amount.
1621 // Do an explicit down-alignment of the address to avoid creating an
1622 // aligned instruction with an address that is not really aligned.
1623 AlignAddr =
1624 createAlignedPointer(Builder, WithMinOffset.Addr, WithMinOffset.ValTy,
1625 MinNeeded.value(), Move.Clones);
1626 AlignVal =
1627 Builder.CreatePtrToInt(WithMinOffset.Addr, HVC.getIntTy(), "pti");
1628 if (auto *I = dyn_cast<Instruction>(AlignVal)) {
1629 for (auto [Old, New] : Move.Clones)
1630 I->replaceUsesOfWith(Old, New);
1631 }
1632 }
1633
1634 ByteSpan VSpan;
1635 for (const AddrInfo &AI : MoveInfos) {
1636 VSpan.Blocks.emplace_back(AI.Inst, HVC.getSizeOf(AI.ValTy),
1637 AI.Offset - WithMinOffset.Offset);
1638 }
1639
1640 // The aligned loads/stores will use blocks that are either scalars,
1641 // or HVX vectors. Let "sector" be the unified term for such a block.
1642 // blend(scalar, vector) -> sector...
1643 int ScLen = Move.IsHvx ? HVC.HST.getVectorLength()
1644 : std::max<int>(MinNeeded.value(), 4);
1645 assert(!Move.IsHvx || ScLen == 64 || ScLen == 128);
1646 assert(Move.IsHvx || ScLen == 4 || ScLen == 8);
1647
1648 LLVM_DEBUG({
1649 dbgs() << "ScLen: " << ScLen << "\n";
1650 dbgs() << "AlignVal:" << *AlignVal << "\n";
1651 dbgs() << "AlignAddr:" << *AlignAddr << "\n";
1652 dbgs() << "VSpan:\n" << VSpan << '\n';
1653 });
1654
1655 if (Move.IsLoad)
1656 realignLoadGroup(Builder, VSpan, ScLen, AlignVal, AlignAddr);
1657 else
1658 realignStoreGroup(Builder, VSpan, ScLen, AlignVal, AlignAddr);
1659
1660 Instruction *Front = Move.Main.front();
1661 HVC.ORE.emit([&]() {
1662 return OptimizationRemark(DEBUG_TYPE, "VectorsAligned",
1663 Front->getDebugLoc(), Front->getParent())
1664 << "aligned vector memory operations";
1665 });
1666
1667 for (auto *Inst : Move.Main)
1668 Inst->eraseFromParent();
1669
1670 return true;
1671}
1672
1673auto AlignVectors::makeTestIfUnaligned(IRBuilderBase &Builder, Value *AlignVal,
1674 int Alignment) const -> Value * {
1675 auto *AlignTy = AlignVal->getType();
1676 Value *And = Builder.CreateAnd(
1677 AlignVal, ConstantInt::get(AlignTy, Alignment - 1), "and");
1678 Value *Zero = ConstantInt::get(AlignTy, 0);
1679 return Builder.CreateICmpNE(And, Zero, "isz");
1680}
1681
1682auto AlignVectors::isSectorTy(Type *Ty) const -> bool {
1683 if (!HVC.isByteVecTy(Ty))
1684 return false;
1685 int Size = HVC.getSizeOf(Ty);
1686 if (HVC.HST.isTypeForHVX(Ty))
1687 return Size == static_cast<int>(HVC.HST.getVectorLength());
1688 return Size == 4 || Size == 8;
1689}
1690
1691auto AlignVectors::run() -> bool {
1692 LLVM_DEBUG(dbgs() << "\nRunning HVC::AlignVectors on " << HVC.F.getName()
1693 << '\n');
1694 if (!createAddressGroups())
1695 return false;
1696
1697 LLVM_DEBUG({
1698 dbgs() << "Address groups(" << AddrGroups.size() << "):\n";
1699 for (auto &[In, AL] : AddrGroups) {
1700 for (const AddrInfo &AI : AL)
1701 dbgs() << "---\n" << AI << '\n';
1702 }
1703 });
1704
1705 bool Changed = false;
1706 MoveList LoadGroups, StoreGroups;
1707
1708 for (auto &G : AddrGroups) {
1709 llvm::append_range(LoadGroups, createLoadGroups(G.second));
1710 llvm::append_range(StoreGroups, createStoreGroups(G.second));
1711 }
1712
1713 LLVM_DEBUG({
1714 dbgs() << "\nLoad groups(" << LoadGroups.size() << "):\n";
1715 for (const MoveGroup &G : LoadGroups)
1716 dbgs() << G << "\n";
1717 dbgs() << "Store groups(" << StoreGroups.size() << "):\n";
1718 for (const MoveGroup &G : StoreGroups)
1719 dbgs() << G << "\n";
1720 });
1721
1722 // Cumulative limit on the number of groups.
1723 unsigned CountLimit = VAGroupCountLimit;
1724 if (CountLimit == 0)
1725 return false;
1726
1727 if (LoadGroups.size() > CountLimit) {
1728 LoadGroups.resize(CountLimit);
1729 StoreGroups.clear();
1730 } else {
1731 unsigned StoreLimit = CountLimit - LoadGroups.size();
1732 if (StoreGroups.size() > StoreLimit)
1733 StoreGroups.resize(StoreLimit);
1734 }
1735
1736 for (auto &M : LoadGroups)
1737 Changed |= moveTogether(M);
1738 for (auto &M : StoreGroups)
1739 Changed |= moveTogether(M);
1740
1741 LLVM_DEBUG(dbgs() << "After moveTogether:\n" << HVC.F);
1742
1743 for (auto &M : LoadGroups)
1744 Changed |= realignGroup(M);
1745 for (auto &M : StoreGroups)
1746 Changed |= realignGroup(M);
1747
1748 return Changed;
1749}
1750
1751// --- End AlignVectors
1752
1753// --- Begin HvxIdioms
1754
1755auto HvxIdioms::getNumSignificantBits(Value *V, Instruction *In) const
1756 -> std::pair<unsigned, Signedness> {
1757 unsigned Bits = HVC.getNumSignificantBits(V, In);
1758 // The significant bits are calculated including the sign bit. This may
1759 // add an extra bit for zero-extended values, e.g. (zext i32 to i64) may
1760 // result in 33 significant bits. To avoid extra words, skip the extra
1761 // sign bit, but keep information that the value is to be treated as
1762 // unsigned.
1763 KnownBits Known = HVC.getKnownBits(V, In);
1764 Signedness Sign = Signed;
1765 unsigned NumToTest = 0; // Number of bits used in test for unsignedness.
1766 if (isPowerOf2_32(Bits))
1767 NumToTest = Bits;
1768 else if (Bits > 1 && isPowerOf2_32(Bits - 1))
1769 NumToTest = Bits - 1;
1770
1771 if (NumToTest != 0 && Known.Zero.ashr(NumToTest).isAllOnes()) {
1772 Sign = Unsigned;
1773 Bits = NumToTest;
1774 }
1775
1776 // If the top bit of the nearest power-of-2 is zero, this value is
1777 // positive. It could be treated as either signed or unsigned.
1778 if (unsigned Pow2 = PowerOf2Ceil(Bits); Pow2 != Bits) {
1779 if (Known.Zero.ashr(Pow2 - 1).isAllOnes())
1780 Sign = Positive;
1781 }
1782 return {Bits, Sign};
1783}
1784
1785auto HvxIdioms::canonSgn(SValue X, SValue Y) const
1786 -> std::pair<SValue, SValue> {
1787 // Canonicalize the signedness of X and Y, so that the result is one of:
1788 // S, S
1789 // U/P, S
1790 // U/P, U/P
1791 if (X.Sgn == Signed && Y.Sgn != Signed)
1792 std::swap(X, Y);
1793 return {X, Y};
1794}
1795
1796// Match
1797// (X * Y) [>> N], or
1798// ((X * Y) + (1 << M)) >> N
1799auto HvxIdioms::matchFxpMul(Instruction &In) const -> std::optional<FxpOp> {
1800 using namespace PatternMatch;
1801 auto *Ty = In.getType();
1802
1803 if (!Ty->isVectorTy() || !Ty->getScalarType()->isIntegerTy())
1804 return std::nullopt;
1805
1806 unsigned Width = cast<IntegerType>(Ty->getScalarType())->getBitWidth();
1807
1808 FxpOp Op;
1809 Value *Exp = &In;
1810
1811 // Fixed-point multiplication is always shifted right (except when the
1812 // fraction is 0 bits).
1813 auto m_Shr = [](auto &&V, auto &&S) {
1814 return m_CombineOr(m_LShr(V, S), m_AShr(V, S));
1815 };
1816
1817 uint64_t Qn = 0;
1818 if (Value *T; match(Exp, m_Shr(m_Value(T), m_ConstantInt(Qn)))) {
1819 Op.Frac = Qn;
1820 Exp = T;
1821 } else {
1822 Op.Frac = 0;
1823 }
1824
1825 if (Op.Frac > Width)
1826 return std::nullopt;
1827
1828 // Check if there is rounding added.
1829 uint64_t CV;
1830 if (Value *T;
1831 Op.Frac > 0 && match(Exp, m_Add(m_Value(T), m_ConstantInt(CV)))) {
1832 if (CV != 0 && !isPowerOf2_64(CV))
1833 return std::nullopt;
1834 if (CV != 0)
1835 Op.RoundAt = Log2_64(CV);
1836 Exp = T;
1837 }
1838
1839 // Check if the rest is a multiplication.
1840 if (match(Exp, m_Mul(m_Value(Op.X.Val), m_Value(Op.Y.Val)))) {
1841 Op.Opcode = Instruction::Mul;
1842 // FIXME: The information below is recomputed.
1843 Op.X.Sgn = getNumSignificantBits(Op.X.Val, &In).second;
1844 Op.Y.Sgn = getNumSignificantBits(Op.Y.Val, &In).second;
1845 Op.ResTy = cast<VectorType>(Ty);
1846 return Op;
1847 }
1848
1849 return std::nullopt;
1850}
1851
1852auto HvxIdioms::processFxpMul(Instruction &In, const FxpOp &Op) const
1853 -> Value * {
1854 assert(Op.X.Val->getType() == Op.Y.Val->getType());
1855
1856 auto *VecTy = dyn_cast<VectorType>(Op.X.Val->getType());
1857 if (VecTy == nullptr)
1858 return nullptr;
1859 auto *ElemTy = cast<IntegerType>(VecTy->getElementType());
1860 unsigned ElemWidth = ElemTy->getBitWidth();
1861
1862 // TODO: This can be relaxed after legalization is done pre-isel.
1863 if ((HVC.length(VecTy) * ElemWidth) % (8 * HVC.HST.getVectorLength()) != 0)
1864 return nullptr;
1865
1866 // There are no special intrinsics that should be used for multiplying
1867 // signed 8-bit values, so just skip them. Normal codegen should handle
1868 // this just fine.
1869 if (ElemWidth <= 8)
1870 return nullptr;
1871 // Similarly, if this is just a multiplication that can be handled without
1872 // intervention, then leave it alone.
1873 if (ElemWidth <= 32 && Op.Frac == 0)
1874 return nullptr;
1875
1876 auto [BitsX, SignX] = getNumSignificantBits(Op.X.Val, &In);
1877 auto [BitsY, SignY] = getNumSignificantBits(Op.Y.Val, &In);
1878
1879 // TODO: Add multiplication of vectors by scalar registers (up to 4 bytes).
1880
1881 Value *X = Op.X.Val, *Y = Op.Y.Val;
1882 IRBuilder Builder(In.getIterator(), InstSimplifyFolder(HVC.DL));
1883
1884 auto roundUpWidth = [](unsigned Width) -> unsigned {
1885 if (Width <= 32 && !isPowerOf2_32(Width)) {
1886 // If the element width is not a power of 2, round it up
1887 // to the next one. Do this for widths not exceeding 32.
1888 return PowerOf2Ceil(Width);
1889 }
1890 if (Width > 32 && Width % 32 != 0) {
1891 // For wider elements, round it up to the multiple of 32.
1892 return alignTo(Width, 32u);
1893 }
1894 return Width;
1895 };
1896
1897 BitsX = roundUpWidth(BitsX);
1898 BitsY = roundUpWidth(BitsY);
1899
1900 // For elementwise multiplication vectors must have the same lengths, so
1901 // resize the elements of both inputs to the same width, the max of the
1902 // calculated significant bits.
1903 unsigned Width = std::max(BitsX, BitsY);
1904
1905 auto *ResizeTy = VectorType::get(HVC.getIntTy(Width), VecTy);
1906 if (Width < ElemWidth) {
1907 X = Builder.CreateTrunc(X, ResizeTy, "trn");
1908 Y = Builder.CreateTrunc(Y, ResizeTy, "trn");
1909 } else if (Width > ElemWidth) {
1910 X = SignX == Signed ? Builder.CreateSExt(X, ResizeTy, "sxt")
1911 : Builder.CreateZExt(X, ResizeTy, "zxt");
1912 Y = SignY == Signed ? Builder.CreateSExt(Y, ResizeTy, "sxt")
1913 : Builder.CreateZExt(Y, ResizeTy, "zxt");
1914 };
1915
1916 assert(X->getType() == Y->getType() && X->getType() == ResizeTy);
1917
1918 unsigned VecLen = HVC.length(ResizeTy);
1919 unsigned ChopLen = (8 * HVC.HST.getVectorLength()) / std::min(Width, 32u);
1920
1922 FxpOp ChopOp = Op;
1923 ChopOp.ResTy = VectorType::get(Op.ResTy->getElementType(), ChopLen, false);
1924
1925 for (unsigned V = 0; V != VecLen / ChopLen; ++V) {
1926 ChopOp.X.Val = HVC.subvector(Builder, X, V * ChopLen, ChopLen);
1927 ChopOp.Y.Val = HVC.subvector(Builder, Y, V * ChopLen, ChopLen);
1928 Results.push_back(processFxpMulChopped(Builder, In, ChopOp));
1929 if (Results.back() == nullptr)
1930 break;
1931 }
1932
1933 if (Results.empty() || Results.back() == nullptr)
1934 return nullptr;
1935
1936 Value *Cat = HVC.concat(Builder, Results);
1937 Value *Ext = SignX == Signed || SignY == Signed
1938 ? Builder.CreateSExt(Cat, VecTy, "sxt")
1939 : Builder.CreateZExt(Cat, VecTy, "zxt");
1940 return Ext;
1941}
1942
1943inline bool HvxIdioms::matchScatter(Instruction &In) const {
1944 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&In);
1945 if (!II)
1946 return false;
1947 return (II->getIntrinsicID() == Intrinsic::masked_scatter);
1948}
1949
1950inline bool HvxIdioms::matchGather(Instruction &In) const {
1951 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&In);
1952 if (!II)
1953 return false;
1954 return (II->getIntrinsicID() == Intrinsic::masked_gather);
1955}
1956
1957inline bool HvxIdioms::matchMLoad(Instruction &In) const {
1958 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&In);
1959 if (!II)
1960 return false;
1961 return (II->getIntrinsicID() == Intrinsic::masked_load);
1962}
1963
1964inline bool HvxIdioms::matchMStore(Instruction &In) const {
1965 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&In);
1966 if (!II)
1967 return false;
1968 return (II->getIntrinsicID() == Intrinsic::masked_store);
1969}
1970
1971Instruction *locateDestination(Instruction *In, HvxIdioms::DstQualifier &Qual);
1972
1973// Binary instructions we want to handle as users of gather/scatter.
1974inline bool isArithmetic(unsigned Opc) {
1975 switch (Opc) {
1976 case Instruction::Add:
1977 case Instruction::Sub:
1978 case Instruction::Mul:
1979 case Instruction::And:
1980 case Instruction::Or:
1981 case Instruction::Xor:
1982 case Instruction::AShr:
1983 case Instruction::LShr:
1984 case Instruction::Shl:
1985 case Instruction::UDiv:
1986 return true;
1987 }
1988 return false;
1989}
1990
1991// TODO: Maybe use MemoryLocation for this. See getLocOrNone above.
1992inline Value *getPointer(Value *Ptr) {
1993 assert(Ptr && "Unable to extract pointer");
1994 if (isa<AllocaInst>(Ptr) || isa<Argument>(Ptr) || isa<GlobalValue>(Ptr))
1995 return Ptr;
1996 if (isa<LoadInst>(Ptr) || isa<StoreInst>(Ptr))
1997 return getLoadStorePointerOperand(Ptr);
1999 if (II->getIntrinsicID() == Intrinsic::masked_store)
2000 return II->getOperand(1);
2001 }
2002 return nullptr;
2003}
2004
2006 HvxIdioms::DstQualifier &Qual) {
2007 Instruction *Destination = nullptr;
2008 if (!In)
2009 return Destination;
2010 if (isa<StoreInst>(In)) {
2011 Destination = In;
2012 Qual = HvxIdioms::LdSt;
2013 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(In)) {
2014 if (II->getIntrinsicID() == Intrinsic::masked_gather) {
2015 Destination = In;
2016 Qual = HvxIdioms::LLVM_Gather;
2017 } else if (II->getIntrinsicID() == Intrinsic::masked_scatter) {
2018 Destination = In;
2019 Qual = HvxIdioms::LLVM_Scatter;
2020 } else if (II->getIntrinsicID() == Intrinsic::masked_store) {
2021 Destination = In;
2022 Qual = HvxIdioms::LdSt;
2023 } else if (II->getIntrinsicID() ==
2024 Intrinsic::hexagon_V6_vgather_vscattermh) {
2025 Destination = In;
2026 Qual = HvxIdioms::HEX_Gather_Scatter;
2027 } else if (II->getIntrinsicID() == Intrinsic::hexagon_V6_vscattermh_128B) {
2028 Destination = In;
2029 Qual = HvxIdioms::HEX_Scatter;
2030 } else if (II->getIntrinsicID() == Intrinsic::hexagon_V6_vgathermh_128B) {
2031 Destination = In;
2032 Qual = HvxIdioms::HEX_Gather;
2033 }
2034 } else if (isa<ZExtInst>(In)) {
2035 return locateDestination(In, Qual);
2036 } else if (isa<CastInst>(In)) {
2037 return locateDestination(In, Qual);
2038 } else if (isa<CallInst>(In)) {
2039 Destination = In;
2040 Qual = HvxIdioms::Call;
2041 } else if (isa<GetElementPtrInst>(In)) {
2042 return locateDestination(In, Qual);
2043 } else if (isArithmetic(In->getOpcode())) {
2044 Destination = In;
2045 Qual = HvxIdioms::Arithmetic;
2046 } else {
2047 LLVM_DEBUG(dbgs() << "Unhandled destination : " << *In << "\n");
2048 }
2049 return Destination;
2050}
2051
2052// This method attempts to find destination (user) for a given intrinsic.
2053// Given that these are produced only by Ripple, the number of options is
2054// limited. Simplest case is explicit store which in fact is redundant (since
2055// HVX gater creates its own store during packetization). Nevertheless we need
2056// to figure address where we storing. Other cases are more complicated, but
2057// still few.
2058Instruction *locateDestination(Instruction *In, HvxIdioms::DstQualifier &Qual) {
2059 Instruction *Destination = nullptr;
2060 if (!In)
2061 return Destination;
2062 // Get all possible destinations
2064 // Iterate over the uses of the instruction
2065 for (Instruction *UI : In->users()) {
2066 Destination = selectDestination(UI, Qual);
2067 if (Destination)
2068 Users.push_back(Destination);
2069 }
2070 // Now see which of the users (if any) is a memory destination.
2071 for (auto *I : Users)
2072 if (getPointer(I))
2073 return I;
2074 return Destination;
2075}
2076
2077// The two intrinsics we handle here have GEP in a different position.
2079 assert(In && "Bad instruction");
2081 assert((IIn && (IIn->getIntrinsicID() == Intrinsic::masked_gather ||
2082 IIn->getIntrinsicID() == Intrinsic::masked_scatter)) &&
2083 "Not a gather Intrinsic");
2084 GetElementPtrInst *GEPIndex = nullptr;
2085 if (IIn->getIntrinsicID() == Intrinsic::masked_gather)
2086 GEPIndex = dyn_cast<GetElementPtrInst>(IIn->getOperand(0));
2087 else
2088 GEPIndex = dyn_cast<GetElementPtrInst>(IIn->getOperand(1));
2089 return GEPIndex;
2090}
2091
2092// Given the intrinsic find its GEP argument and extract base address it uses.
2093// The method relies on the way how Ripple typically forms the GEP for
2094// scatter/gather.
2097 if (!GEPIndex) {
2098 LLVM_DEBUG(dbgs() << " No GEP in intrinsic\n");
2099 return nullptr;
2100 }
2101 Value *BaseAddress = GEPIndex->getPointerOperand();
2102 auto *IndexLoad = dyn_cast<LoadInst>(BaseAddress);
2103 if (IndexLoad)
2104 return IndexLoad;
2105
2106 auto *IndexZEx = dyn_cast<ZExtInst>(BaseAddress);
2107 if (IndexZEx) {
2108 IndexLoad = dyn_cast<LoadInst>(IndexZEx->getOperand(0));
2109 if (IndexLoad)
2110 return IndexLoad;
2111 IntrinsicInst *II = dyn_cast<IntrinsicInst>(IndexZEx->getOperand(0));
2112 if (II && II->getIntrinsicID() == Intrinsic::masked_gather)
2114 }
2115 auto *BaseShuffle = dyn_cast<ShuffleVectorInst>(BaseAddress);
2116 if (BaseShuffle) {
2117 IndexLoad = dyn_cast<LoadInst>(BaseShuffle->getOperand(0));
2118 if (IndexLoad)
2119 return IndexLoad;
2120 auto *IE = dyn_cast<InsertElementInst>(BaseShuffle->getOperand(0));
2121 if (IE) {
2122 auto *Src = IE->getOperand(1);
2123 IndexLoad = dyn_cast<LoadInst>(Src);
2124 if (IndexLoad)
2125 return IndexLoad;
2126 auto *Alloca = dyn_cast<AllocaInst>(Src);
2127 if (Alloca)
2128 return Alloca;
2129 if (isa<Argument>(Src)) {
2130 return Src;
2131 }
2132 if (isa<GlobalValue>(Src)) {
2133 return Src;
2134 }
2135 }
2136 }
2137 LLVM_DEBUG(dbgs() << " Unable to locate Address from intrinsic\n");
2138 return nullptr;
2139}
2140
2142 if (!In)
2143 return nullptr;
2144
2145 if (isa<LoadInst>(In) || isa<StoreInst>(In))
2146 return getLoadStoreType(In);
2147
2149 if (II->getIntrinsicID() == Intrinsic::masked_load)
2150 return II->getType();
2151 if (II->getIntrinsicID() == Intrinsic::masked_store)
2152 return II->getOperand(0)->getType();
2153 }
2154 return In->getType();
2155}
2156
2158 if (!In)
2159 return nullptr;
2160 if (isa<LoadInst>(In))
2161 return In;
2163 if (II->getIntrinsicID() == Intrinsic::masked_load)
2164 return In;
2165 if (II->getIntrinsicID() == Intrinsic::masked_gather)
2166 return In;
2167 }
2168 if (auto *IndexZEx = dyn_cast<ZExtInst>(In))
2169 return locateIndexesFromGEP(IndexZEx->getOperand(0));
2170 if (auto *IndexSEx = dyn_cast<SExtInst>(In))
2171 return locateIndexesFromGEP(IndexSEx->getOperand(0));
2172 if (auto *BaseShuffle = dyn_cast<ShuffleVectorInst>(In))
2173 return locateIndexesFromGEP(BaseShuffle->getOperand(0));
2174 if (auto *IE = dyn_cast<InsertElementInst>(In))
2175 return locateIndexesFromGEP(IE->getOperand(1));
2176 if (auto *cstDataVector = dyn_cast<ConstantDataVector>(In))
2177 return cstDataVector;
2178 if (auto *GEPIndex = dyn_cast<GetElementPtrInst>(In))
2179 return GEPIndex->getOperand(0);
2180 return nullptr;
2181}
2182
2183// Given the intrinsic find its GEP argument and extract offsetts from the base
2184// address it uses.
2187 if (!GEPIndex) {
2188 LLVM_DEBUG(dbgs() << " No GEP in intrinsic\n");
2189 return nullptr;
2190 }
2191 Value *Indexes = GEPIndex->getOperand(1);
2192 if (auto *IndexLoad = locateIndexesFromGEP(Indexes))
2193 return IndexLoad;
2194
2195 LLVM_DEBUG(dbgs() << " Unable to locate Index from intrinsic\n");
2196 return nullptr;
2197}
2198
2199// Because of aukward definition of many Hex intrinsics we often have to
2200// reinterprete HVX native <64 x i16> as <32 x i32> which in practice is a NOP
2201// for all use cases, so this only exist to make IR builder happy.
2202inline Value *getReinterpretiveCast_i16_to_i32(const HexagonVectorCombine &HVC,
2203 IRBuilderBase &Builder,
2204 LLVMContext &Ctx, Value *I) {
2205 assert(I && "Unable to reinterprete cast");
2206 Type *NT = HVC.getHvxTy(HVC.getIntTy(32), false);
2207 std::vector<unsigned> shuffleMask;
2208 for (unsigned i = 0; i < 64; ++i)
2209 shuffleMask.push_back(i);
2210 Constant *Mask = llvm::ConstantDataVector::get(Ctx, shuffleMask);
2211 Value *CastShuffle =
2212 Builder.CreateShuffleVector(I, I, Mask, "identity_shuffle");
2213 return Builder.CreateBitCast(CastShuffle, NT, "cst64_i16_to_32_i32");
2214}
2215
2216// Recast <128 x i8> as <32 x i32>
2217inline Value *getReinterpretiveCast_i8_to_i32(const HexagonVectorCombine &HVC,
2218 IRBuilderBase &Builder,
2219 LLVMContext &Ctx, Value *I) {
2220 assert(I && "Unable to reinterprete cast");
2221 Type *NT = HVC.getHvxTy(HVC.getIntTy(32), false);
2222 std::vector<unsigned> shuffleMask;
2223 for (unsigned i = 0; i < 128; ++i)
2224 shuffleMask.push_back(i);
2225 Constant *Mask = llvm::ConstantDataVector::get(Ctx, shuffleMask);
2226 Value *CastShuffle =
2227 Builder.CreateShuffleVector(I, I, Mask, "identity_shuffle");
2228 return Builder.CreateBitCast(CastShuffle, NT, "cst128_i8_to_32_i32");
2229}
2230
2231// Create <32 x i32> mask reinterpreted as <128 x i1> with a given pattern
2232inline Value *get_i32_Mask(const HexagonVectorCombine &HVC,
2233 IRBuilderBase &Builder, LLVMContext &Ctx,
2234 unsigned int pattern) {
2235 std::vector<unsigned int> byteMask;
2236 for (unsigned i = 0; i < 32; ++i)
2237 byteMask.push_back(pattern);
2238
2239 return Builder.CreateIntrinsic(
2240 HVC.getBoolTy(128), HVC.HST.getIntrinsicId(Hexagon::V6_vandvrt),
2241 {llvm::ConstantDataVector::get(Ctx, byteMask), HVC.getConstInt(~0)},
2242 nullptr);
2243}
2244
2245Value *HvxIdioms::processVScatter(Instruction &In) const {
2246 auto *InpTy = dyn_cast<VectorType>(In.getOperand(0)->getType());
2247 assert(InpTy && "Cannot handle no vector type for llvm.scatter/gather");
2248 unsigned InpSize = HVC.getSizeOf(InpTy);
2249 auto *F = In.getFunction();
2250 LLVMContext &Ctx = F->getContext();
2251 auto *ElemTy = dyn_cast<IntegerType>(InpTy->getElementType());
2252 assert(ElemTy && "llvm.scatter needs integer type argument");
2253 unsigned ElemWidth = HVC.DL.getTypeAllocSize(ElemTy);
2254 LLVM_DEBUG({
2255 unsigned Elements = HVC.length(InpTy);
2256 dbgs() << "\n[Process scatter](" << In << ")\n" << *In.getParent() << "\n";
2257 dbgs() << " Input type(" << *InpTy << ") elements(" << Elements
2258 << ") VecLen(" << InpSize << ") type(" << *ElemTy << ") ElemWidth("
2259 << ElemWidth << ")\n";
2260 });
2261
2262 IRBuilder Builder(In.getIterator(), InstSimplifyFolder(HVC.DL));
2263
2264 auto *ValueToScatter = In.getOperand(0);
2265 LLVM_DEBUG(dbgs() << " ValueToScatter : " << *ValueToScatter << "\n");
2266
2267 if (HVC.HST.getVectorLength() != InpSize) {
2268 LLVM_DEBUG(dbgs() << "Unhandled vector size(" << InpSize
2269 << ") for vscatter\n");
2270 return nullptr;
2271 }
2272
2273 // Base address of indexes.
2274 auto *IndexLoad = locateAddressFromIntrinsic(&In);
2275 if (!IndexLoad)
2276 return nullptr;
2277 LLVM_DEBUG(dbgs() << " IndexLoad : " << *IndexLoad << "\n");
2278
2279 // Address of destination. Must be in VTCM.
2280 auto *Ptr = getPointer(IndexLoad);
2281 if (!Ptr)
2282 return nullptr;
2283 LLVM_DEBUG(dbgs() << " Ptr : " << *Ptr << "\n");
2284 // Indexes/offsets
2285 auto *Indexes = locateIndexesFromIntrinsic(&In);
2286 if (!Indexes)
2287 return nullptr;
2288 LLVM_DEBUG(dbgs() << " Indexes : " << *Indexes << "\n");
2289 Value *CastedDst = Builder.CreateBitOrPointerCast(Ptr, Type::getInt32Ty(Ctx),
2290 "cst_ptr_to_i32");
2291 LLVM_DEBUG(dbgs() << " CastedDst : " << *CastedDst << "\n");
2292 // Adjust Indexes
2293 auto *cstDataVector = dyn_cast<ConstantDataVector>(Indexes);
2294 Value *CastIndex = nullptr;
2295 if (cstDataVector) {
2296 // Our indexes are represented as a constant. We need it in a reg.
2297 Type *IndexVectorType = HVC.getHvxTy(HVC.getIntTy(32), false);
2298 AllocaInst *IndexesAlloca = Builder.CreateAlloca(IndexVectorType);
2299 [[maybe_unused]] auto *StoreIndexes =
2300 Builder.CreateStore(cstDataVector, IndexesAlloca);
2301 LLVM_DEBUG(dbgs() << " StoreIndexes : " << *StoreIndexes << "\n");
2302 CastIndex =
2303 Builder.CreateLoad(IndexVectorType, IndexesAlloca, "reload_index");
2304 } else {
2305 if (ElemWidth == 2)
2306 CastIndex = getReinterpretiveCast_i16_to_i32(HVC, Builder, Ctx, Indexes);
2307 else
2308 CastIndex = Indexes;
2309 }
2310 LLVM_DEBUG(dbgs() << " Cast index : " << *CastIndex << ")\n");
2311
2312 if (ElemWidth == 1) {
2313 // v128i8 There is no native instruction for this.
2314 // Do this as two Hi/Lo gathers with masking.
2315 Type *NT = HVC.getHvxTy(HVC.getIntTy(32), false);
2316 // Extend indexes. We assume that indexes are in 128i8 format - need to
2317 // expand them to Hi/Lo 64i16
2318 Value *CastIndexes = Builder.CreateBitCast(CastIndex, NT, "cast_to_32i32");
2319 auto V6_vunpack = HVC.HST.getIntrinsicId(Hexagon::V6_vunpackub);
2320 auto *UnpackedIndexes = Builder.CreateIntrinsic(
2321 HVC.getHvxTy(HVC.getIntTy(32), true), V6_vunpack, CastIndexes, nullptr);
2322 LLVM_DEBUG(dbgs() << " UnpackedIndexes : " << *UnpackedIndexes << ")\n");
2323
2324 auto V6_hi = HVC.HST.getIntrinsicId(Hexagon::V6_hi);
2325 auto V6_lo = HVC.HST.getIntrinsicId(Hexagon::V6_lo);
2326 [[maybe_unused]] Value *IndexHi =
2327 HVC.createHvxIntrinsic(Builder, V6_hi, NT, UnpackedIndexes);
2328 [[maybe_unused]] Value *IndexLo =
2329 HVC.createHvxIntrinsic(Builder, V6_lo, NT, UnpackedIndexes);
2330 LLVM_DEBUG(dbgs() << " UnpackedIndHi : " << *IndexHi << ")\n");
2331 LLVM_DEBUG(dbgs() << " UnpackedIndLo : " << *IndexLo << ")\n");
2332 // Now unpack values to scatter
2333 Value *CastSrc =
2334 getReinterpretiveCast_i8_to_i32(HVC, Builder, Ctx, ValueToScatter);
2335 LLVM_DEBUG(dbgs() << " CastSrc : " << *CastSrc << ")\n");
2336 auto *UnpackedValueToScatter = Builder.CreateIntrinsic(
2337 HVC.getHvxTy(HVC.getIntTy(32), true), V6_vunpack, CastSrc, nullptr);
2338 LLVM_DEBUG(dbgs() << " UnpackedValToScat: " << *UnpackedValueToScatter
2339 << ")\n");
2340
2341 [[maybe_unused]] Value *UVSHi =
2342 HVC.createHvxIntrinsic(Builder, V6_hi, NT, UnpackedValueToScatter);
2343 [[maybe_unused]] Value *UVSLo =
2344 HVC.createHvxIntrinsic(Builder, V6_lo, NT, UnpackedValueToScatter);
2345 LLVM_DEBUG(dbgs() << " UVSHi : " << *UVSHi << ")\n");
2346 LLVM_DEBUG(dbgs() << " UVSLo : " << *UVSLo << ")\n");
2347
2348 // Create the mask for individual bytes
2349 auto *QByteMask = get_i32_Mask(HVC, Builder, Ctx, 0x00ff00ff);
2350 LLVM_DEBUG(dbgs() << " QByteMask : " << *QByteMask << "\n");
2351 [[maybe_unused]] auto *ResHi = Builder.CreateIntrinsic(
2352 Type::getVoidTy(Ctx), Intrinsic::hexagon_V6_vscattermhq_128B,
2353 {QByteMask, CastedDst, HVC.getConstInt(DEFAULT_HVX_VTCM_PAGE_SIZE),
2354 IndexHi, UVSHi},
2355 nullptr);
2356 LLVM_DEBUG(dbgs() << " ResHi : " << *ResHi << ")\n");
2357 return Builder.CreateIntrinsic(
2358 Type::getVoidTy(Ctx), Intrinsic::hexagon_V6_vscattermhq_128B,
2359 {QByteMask, CastedDst, HVC.getConstInt(DEFAULT_HVX_VTCM_PAGE_SIZE),
2360 IndexLo, UVSLo},
2361 nullptr);
2362 } else if (ElemWidth == 2) {
2363 Value *CastSrc =
2364 getReinterpretiveCast_i16_to_i32(HVC, Builder, Ctx, ValueToScatter);
2365 LLVM_DEBUG(dbgs() << " CastSrc : " << *CastSrc << ")\n");
2366 return Builder.CreateIntrinsic(
2367 Type::getVoidTy(Ctx), Intrinsic::hexagon_V6_vscattermh_128B,
2368 {CastedDst, HVC.getConstInt(DEFAULT_HVX_VTCM_PAGE_SIZE), CastIndex,
2369 CastSrc},
2370 nullptr);
2371 } else if (ElemWidth == 4) {
2372 return Builder.CreateIntrinsic(
2373 Type::getVoidTy(Ctx), Intrinsic::hexagon_V6_vscattermw_128B,
2374 {CastedDst, HVC.getConstInt(DEFAULT_HVX_VTCM_PAGE_SIZE), CastIndex,
2375 ValueToScatter},
2376 nullptr);
2377 } else {
2378 LLVM_DEBUG(dbgs() << "Unhandled element type for vscatter\n");
2379 return nullptr;
2380 }
2381}
2382
2383Value *HvxIdioms::processVGather(Instruction &In) const {
2384 [[maybe_unused]] auto *InpTy =
2385 dyn_cast<VectorType>(In.getOperand(0)->getType());
2386 assert(InpTy && "Cannot handle no vector type for llvm.gather");
2387 [[maybe_unused]] auto *ElemTy =
2388 dyn_cast<PointerType>(InpTy->getElementType());
2389 assert(ElemTy && "llvm.gather needs vector of ptr argument");
2390 auto *F = In.getFunction();
2391 LLVMContext &Ctx = F->getContext();
2392 LLVM_DEBUG(dbgs() << "\n[Process gather](" << In << ")\n"
2393 << *In.getParent() << "\n");
2394 LLVM_DEBUG(dbgs() << " Input type(" << *InpTy << ") elements("
2395 << HVC.length(InpTy) << ") VecLen(" << HVC.getSizeOf(InpTy)
2396 << ") type(" << *ElemTy << ") Access alignment("
2397 << *In.getOperand(1) << ") AddressSpace("
2398 << ElemTy->getAddressSpace() << ")\n");
2399
2400 // TODO: Handle masking of elements.
2401 assert(dyn_cast<VectorType>(In.getOperand(2)->getType()) &&
2402 "llvm.gather needs vector for mask");
2403 IRBuilder Builder(In.getIterator(), InstSimplifyFolder(HVC.DL));
2404
2405 // See who is using the result. The difference between LLVM and HVX vgather
2406 // Intrinsic makes it impossible to handle all cases with temp storage. Alloca
2407 // in VTCM is not yet supported, so for now we just bail out for those cases.
2408 HvxIdioms::DstQualifier Qual = HvxIdioms::Undefined;
2409 Instruction *Dst = locateDestination(&In, Qual);
2410 if (!Dst) {
2411 LLVM_DEBUG(dbgs() << " Unable to locate vgather destination\n");
2412 return nullptr;
2413 }
2414 LLVM_DEBUG(dbgs() << " Destination : " << *Dst << " Qual(" << Qual
2415 << ")\n");
2416
2417 // Address of destination. Must be in VTCM.
2418 auto *Ptr = getPointer(Dst);
2419 if (!Ptr) {
2420 LLVM_DEBUG(dbgs() << "Could not locate vgather destination ptr\n");
2421 return nullptr;
2422 }
2423
2424 // Result type. Assume it is a vector type.
2425 auto *DstType = cast<VectorType>(getIndexType(Dst));
2426 assert(DstType && "Cannot handle non vector dst type for llvm.gather");
2427
2428 // Base address for sources to be loaded
2429 auto *IndexLoad = locateAddressFromIntrinsic(&In);
2430 if (!IndexLoad)
2431 return nullptr;
2432 LLVM_DEBUG(dbgs() << " IndexLoad : " << *IndexLoad << "\n");
2433
2434 // Gather indexes/offsets
2435 auto *Indexes = locateIndexesFromIntrinsic(&In);
2436 if (!Indexes)
2437 return nullptr;
2438 LLVM_DEBUG(dbgs() << " Indexes : " << *Indexes << "\n");
2439
2440 Value *Gather = nullptr;
2441 Type *NT = HVC.getHvxTy(HVC.getIntTy(32), false);
2442 if (Qual == HvxIdioms::LdSt || Qual == HvxIdioms::Arithmetic) {
2443 // We fully assume the address space is in VTCM. We also assume that all
2444 // pointers in Operand(0) have the same base(!).
2445 // This is the most basic case of all the above.
2446 unsigned OutputSize = HVC.getSizeOf(DstType);
2447 auto *DstElemTy = cast<IntegerType>(DstType->getElementType());
2448 unsigned ElemWidth = HVC.DL.getTypeAllocSize(DstElemTy);
2449 LLVM_DEBUG(dbgs() << " Buffer type : " << *Ptr->getType()
2450 << " Address space ("
2451 << Ptr->getType()->getPointerAddressSpace() << ")\n"
2452 << " Result type : " << *DstType
2453 << "\n Size in bytes : " << OutputSize
2454 << " element type(" << *DstElemTy
2455 << ")\n ElemWidth : " << ElemWidth << " bytes\n");
2456
2457 auto *IndexType = cast<VectorType>(getIndexType(Indexes));
2458 assert(IndexType && "Cannot handle non vector index type for llvm.gather");
2459 unsigned IndexWidth = HVC.DL.getTypeAllocSize(IndexType->getElementType());
2460 LLVM_DEBUG(dbgs() << " IndexWidth(" << IndexWidth << ")\n");
2461
2462 // Intrinsic takes i32 instead of pointer so cast.
2463 Value *CastedPtr = Builder.CreateBitOrPointerCast(
2464 IndexLoad, Type::getInt32Ty(Ctx), "cst_ptr_to_i32");
2465 // [llvm_ptr_ty, llvm_i32_ty, llvm_i32_ty, ...]
2466 // int_hexagon_V6_vgathermh [... , llvm_v16i32_ty]
2467 // int_hexagon_V6_vgathermh_128B [... , llvm_v32i32_ty]
2468 // int_hexagon_V6_vgathermhw [... , llvm_v32i32_ty]
2469 // int_hexagon_V6_vgathermhw_128B [... , llvm_v64i32_ty]
2470 // int_hexagon_V6_vgathermw [... , llvm_v16i32_ty]
2471 // int_hexagon_V6_vgathermw_128B [... , llvm_v32i32_ty]
2472 if (HVC.HST.getVectorLength() == OutputSize) {
2473 if (ElemWidth == 1) {
2474 // v128i8 There is no native instruction for this.
2475 // Do this as two Hi/Lo gathers with masking.
2476 // Unpack indexes. We assume that indexes are in 128i8 format - need to
2477 // expand them to Hi/Lo 64i16
2478 Value *CastIndexes =
2479 Builder.CreateBitCast(Indexes, NT, "cast_to_32i32");
2480 auto V6_vunpack = HVC.HST.getIntrinsicId(Hexagon::V6_vunpackub);
2481 auto *UnpackedIndexes =
2482 Builder.CreateIntrinsic(HVC.getHvxTy(HVC.getIntTy(32), true),
2483 V6_vunpack, CastIndexes, nullptr);
2484 LLVM_DEBUG(dbgs() << " UnpackedIndexes : " << *UnpackedIndexes
2485 << ")\n");
2486
2487 auto V6_hi = HVC.HST.getIntrinsicId(Hexagon::V6_hi);
2488 auto V6_lo = HVC.HST.getIntrinsicId(Hexagon::V6_lo);
2489 [[maybe_unused]] Value *IndexHi =
2490 HVC.createHvxIntrinsic(Builder, V6_hi, NT, UnpackedIndexes);
2491 [[maybe_unused]] Value *IndexLo =
2492 HVC.createHvxIntrinsic(Builder, V6_lo, NT, UnpackedIndexes);
2493 LLVM_DEBUG(dbgs() << " UnpackedIndHi : " << *IndexHi << ")\n");
2494 LLVM_DEBUG(dbgs() << " UnpackedIndLo : " << *IndexLo << ")\n");
2495 // Create the mask for individual bytes
2496 auto *QByteMask = get_i32_Mask(HVC, Builder, Ctx, 0x00ff00ff);
2497 LLVM_DEBUG(dbgs() << " QByteMask : " << *QByteMask << "\n");
2498 // We use our destination allocation as a temp storage
2499 // This is unlikely to work properly for masked gather.
2500 auto V6_vgather = HVC.HST.getIntrinsicId(Hexagon::V6_vgathermhq);
2501 [[maybe_unused]] auto GatherHi = Builder.CreateIntrinsic(
2502 Type::getVoidTy(Ctx), V6_vgather,
2503 {Ptr, QByteMask, CastedPtr,
2504 HVC.getConstInt(DEFAULT_HVX_VTCM_PAGE_SIZE), IndexHi},
2505 nullptr);
2506 LLVM_DEBUG(dbgs() << " GatherHi : " << *GatherHi << ")\n");
2507 // Rematerialize the result
2508 [[maybe_unused]] Value *LoadedResultHi = Builder.CreateLoad(
2509 HVC.getHvxTy(HVC.getIntTy(32), false), Ptr, "temp_result_hi");
2510 LLVM_DEBUG(dbgs() << " LoadedResultHi : " << *LoadedResultHi << "\n");
2511 // Same for the low part. Here we use Gather to return non-NULL result
2512 // from this function and continue to iterate. We also are deleting Dst
2513 // store below.
2514 Gather = Builder.CreateIntrinsic(
2515 Type::getVoidTy(Ctx), V6_vgather,
2516 {Ptr, QByteMask, CastedPtr,
2517 HVC.getConstInt(DEFAULT_HVX_VTCM_PAGE_SIZE), IndexLo},
2518 nullptr);
2519 LLVM_DEBUG(dbgs() << " GatherLo : " << *Gather << ")\n");
2520 Value *LoadedResultLo = Builder.CreateLoad(
2521 HVC.getHvxTy(HVC.getIntTy(32), false), Ptr, "temp_result_lo");
2522 LLVM_DEBUG(dbgs() << " LoadedResultLo : " << *LoadedResultLo << "\n");
2523 // Now we have properly sized bytes in every other position
2524 // B b A a c a A b B c f F g G h H is presented as
2525 // B . b . A . a . c . a . A . b . B . c . f . F . g . G . h . H
2526 // Use vpack to gather them
2527 auto V6_vpackeb = HVC.HST.getIntrinsicId(Hexagon::V6_vpackeb);
2528 [[maybe_unused]] auto Res = Builder.CreateIntrinsic(
2529 NT, V6_vpackeb, {LoadedResultHi, LoadedResultLo}, nullptr);
2530 LLVM_DEBUG(dbgs() << " ScaledRes : " << *Res << "\n");
2531 [[maybe_unused]] auto *StoreRes = Builder.CreateStore(Res, Ptr);
2532 LLVM_DEBUG(dbgs() << " StoreRes : " << *StoreRes << "\n");
2533 } else if (ElemWidth == 2) {
2534 // v32i16
2535 if (IndexWidth == 2) {
2536 // Reinterprete 64i16 as 32i32. Only needed for syntactic IR match.
2537 Value *CastIndex =
2538 getReinterpretiveCast_i16_to_i32(HVC, Builder, Ctx, Indexes);
2539 LLVM_DEBUG(dbgs() << " Cast index: " << *CastIndex << ")\n");
2540 // shift all i16 left by 1 to match short addressing mode instead of
2541 // byte.
2542 auto V6_vaslh = HVC.HST.getIntrinsicId(Hexagon::V6_vaslh);
2543 Value *AdjustedIndex = HVC.createHvxIntrinsic(
2544 Builder, V6_vaslh, NT, {CastIndex, HVC.getConstInt(1)});
2546 << " Shifted half index: " << *AdjustedIndex << ")\n");
2547
2548 auto V6_vgather = HVC.HST.getIntrinsicId(Hexagon::V6_vgathermh);
2549 // The 3rd argument is the size of the region to gather from. Probably
2550 // want to set it to max VTCM size.
2551 Gather = Builder.CreateIntrinsic(
2552 Type::getVoidTy(Ctx), V6_vgather,
2553 {Ptr, CastedPtr, HVC.getConstInt(DEFAULT_HVX_VTCM_PAGE_SIZE),
2554 AdjustedIndex},
2555 nullptr);
2556 for (Instruction *UI : Dst->users())
2557 dbgs() << " dst used by: " << *UI << "\n";
2558 for (Instruction *UI : In.users())
2559 dbgs() << " In used by : " << *UI << "\n";
2560 // Create temp load from result in case the result is used by any
2561 // other instruction.
2562 Value *LoadedResult = Builder.CreateLoad(
2563 HVC.getHvxTy(HVC.getIntTy(16), false), Ptr, "temp_result");
2564 LLVM_DEBUG(dbgs() << " LoadedResult : " << *LoadedResult << "\n");
2565 In.replaceAllUsesWith(LoadedResult);
2566 } else {
2567 dbgs() << " Unhandled index type for vgather\n";
2568 return nullptr;
2569 }
2570 } else if (ElemWidth == 4) {
2571 if (IndexWidth == 4) {
2572 // v32i32
2573 auto V6_vaslh = HVC.HST.getIntrinsicId(Hexagon::V6_vaslh);
2574 Value *AdjustedIndex = HVC.createHvxIntrinsic(
2575 Builder, V6_vaslh, NT, {Indexes, HVC.getConstInt(2)});
2577 << " Shifted word index: " << *AdjustedIndex << ")\n");
2578 Gather = Builder.CreateIntrinsic(
2579 Type::getVoidTy(Ctx), Intrinsic::hexagon_V6_vgathermw_128B,
2580 {Ptr, CastedPtr, HVC.getConstInt(DEFAULT_HVX_VTCM_PAGE_SIZE),
2581 AdjustedIndex},
2582 nullptr);
2583 } else {
2584 LLVM_DEBUG(dbgs() << " Unhandled index type for vgather\n");
2585 return nullptr;
2586 }
2587 } else {
2588 LLVM_DEBUG(dbgs() << " Unhandled element type for vgather\n");
2589 return nullptr;
2590 }
2591 } else if (HVC.HST.getVectorLength() == OutputSize * 2) {
2592 // This is half of the reg width, duplicate low in high
2593 LLVM_DEBUG(dbgs() << " Unhandled half of register size\n");
2594 return nullptr;
2595 } else if (HVC.HST.getVectorLength() * 2 == OutputSize) {
2596 LLVM_DEBUG(dbgs() << " Unhandle twice the register size\n");
2597 return nullptr;
2598 }
2599 // Erase the original intrinsic and store that consumes it.
2600 // HVX will create a pseudo for gather that is expanded to gather + store
2601 // during packetization.
2602 Dst->eraseFromParent();
2603 } else if (Qual == HvxIdioms::LLVM_Scatter) {
2604 // Gather feeds directly into scatter.
2605 LLVM_DEBUG({
2606 auto *DstInpTy = cast<VectorType>(Dst->getOperand(1)->getType());
2607 assert(DstInpTy && "Cannot handle no vector type for llvm.scatter");
2608 unsigned DstInpSize = HVC.getSizeOf(DstInpTy);
2609 unsigned DstElements = HVC.length(DstInpTy);
2610 auto *DstElemTy = cast<PointerType>(DstInpTy->getElementType());
2611 assert(DstElemTy && "llvm.scatter needs vector of ptr argument");
2612 dbgs() << " Gather feeds into scatter\n Values to scatter : "
2613 << *Dst->getOperand(0) << "\n";
2614 dbgs() << " Dst type(" << *DstInpTy << ") elements(" << DstElements
2615 << ") VecLen(" << DstInpSize << ") type(" << *DstElemTy
2616 << ") Access alignment(" << *Dst->getOperand(2) << ")\n";
2617 });
2618 // Address of source
2619 auto *Src = getPointer(IndexLoad);
2620 if (!Src)
2621 return nullptr;
2622 LLVM_DEBUG(dbgs() << " Src : " << *Src << "\n");
2623
2624 if (!isa<PointerType>(Src->getType())) {
2625 LLVM_DEBUG(dbgs() << " Source is not a pointer type...\n");
2626 return nullptr;
2627 }
2628
2629 Value *CastedSrc = Builder.CreateBitOrPointerCast(
2630 Src, Type::getInt32Ty(Ctx), "cst_ptr_to_i32");
2631 LLVM_DEBUG(dbgs() << " CastedSrc: " << *CastedSrc << "\n");
2632
2633 auto *DstLoad = locateAddressFromIntrinsic(Dst);
2634 if (!DstLoad) {
2635 LLVM_DEBUG(dbgs() << " Unable to locate DstLoad\n");
2636 return nullptr;
2637 }
2638 LLVM_DEBUG(dbgs() << " DstLoad : " << *DstLoad << "\n");
2639
2640 Value *Ptr = getPointer(DstLoad);
2641 if (!Ptr)
2642 return nullptr;
2643 LLVM_DEBUG(dbgs() << " Ptr : " << *Ptr << "\n");
2644 Value *CastIndex =
2645 getReinterpretiveCast_i16_to_i32(HVC, Builder, Ctx, IndexLoad);
2646 LLVM_DEBUG(dbgs() << " Cast index: " << *CastIndex << ")\n");
2647 // Shift all i16 left by 1 to match short addressing mode instead of
2648 // byte.
2649 auto V6_vaslh = HVC.HST.getIntrinsicId(Hexagon::V6_vaslh);
2650 Value *AdjustedIndex = HVC.createHvxIntrinsic(
2651 Builder, V6_vaslh, NT, {CastIndex, HVC.getConstInt(1)});
2652 LLVM_DEBUG(dbgs() << " Shifted half index: " << *AdjustedIndex << ")\n");
2653
2654 return Builder.CreateIntrinsic(
2655 Type::getVoidTy(Ctx), Intrinsic::hexagon_V6_vgathermh_128B,
2656 {Ptr, CastedSrc, HVC.getConstInt(DEFAULT_HVX_VTCM_PAGE_SIZE),
2657 AdjustedIndex},
2658 nullptr);
2659 } else if (Qual == HvxIdioms::HEX_Gather_Scatter) {
2660 // Gather feeds into previously inserted pseudo intrinsic.
2661 // These could not be in the same packet, so we need to generate another
2662 // pseudo that is expanded to .tmp + store V6_vgathermh_pseudo
2663 // V6_vgathermh_pseudo (ins IntRegs:$_dst_, s4_0Imm:$Ii, IntRegs:$Rt,
2664 // ModRegs:$Mu, HvxVR:$Vv)
2665 if (isa<AllocaInst>(IndexLoad)) {
2666 auto *cstDataVector = dyn_cast<ConstantDataVector>(Indexes);
2667 if (cstDataVector) {
2668 // Our indexes are represented as a constant. We need THEM in a reg.
2669 // This most likely will not work properly since alloca gives us DDR
2670 // stack location. This will be fixed once we teach compiler about VTCM.
2671 AllocaInst *IndexesAlloca = Builder.CreateAlloca(NT);
2672 [[maybe_unused]] auto *StoreIndexes =
2673 Builder.CreateStore(cstDataVector, IndexesAlloca);
2674 LLVM_DEBUG(dbgs() << " StoreIndexes : " << *StoreIndexes << "\n");
2675 Value *LoadedIndex =
2676 Builder.CreateLoad(NT, IndexesAlloca, "reload_index");
2677 AllocaInst *ResultAlloca = Builder.CreateAlloca(NT);
2678 LLVM_DEBUG(dbgs() << " ResultAlloca : " << *ResultAlloca << "\n");
2679
2680 Value *CastedSrc = Builder.CreateBitOrPointerCast(
2681 IndexLoad, Type::getInt32Ty(Ctx), "cst_ptr_to_i32");
2682 LLVM_DEBUG(dbgs() << " CastedSrc : " << *CastedSrc << "\n");
2683
2684 Gather = Builder.CreateIntrinsic(
2685 Type::getVoidTy(Ctx), Intrinsic::hexagon_V6_vgathermh_128B,
2686 {ResultAlloca, CastedSrc,
2687 HVC.getConstInt(DEFAULT_HVX_VTCM_PAGE_SIZE), LoadedIndex},
2688 nullptr);
2689 Value *LoadedResult = Builder.CreateLoad(
2690 HVC.getHvxTy(HVC.getIntTy(16), false), ResultAlloca, "temp_result");
2691 LLVM_DEBUG(dbgs() << " LoadedResult : " << *LoadedResult << "\n");
2692 LLVM_DEBUG(dbgs() << " Gather : " << *Gather << "\n");
2693 In.replaceAllUsesWith(LoadedResult);
2694 }
2695 } else {
2696 // Address of source
2697 auto *Src = getPointer(IndexLoad);
2698 if (!Src)
2699 return nullptr;
2700 LLVM_DEBUG(dbgs() << " Src : " << *Src << "\n");
2701
2702 Value *CastedSrc = Builder.CreateBitOrPointerCast(
2703 Src, Type::getInt32Ty(Ctx), "cst_ptr_to_i32");
2704 LLVM_DEBUG(dbgs() << " CastedSrc: " << *CastedSrc << "\n");
2705
2706 auto *DstLoad = locateAddressFromIntrinsic(Dst);
2707 if (!DstLoad)
2708 return nullptr;
2709 LLVM_DEBUG(dbgs() << " DstLoad : " << *DstLoad << "\n");
2710 auto *Ptr = getPointer(DstLoad);
2711 if (!Ptr)
2712 return nullptr;
2713 LLVM_DEBUG(dbgs() << " Ptr : " << *Ptr << "\n");
2714
2715 Gather = Builder.CreateIntrinsic(
2716 Type::getVoidTy(Ctx), Intrinsic::hexagon_V6_vgather_vscattermh,
2717 {Ptr, CastedSrc, HVC.getConstInt(DEFAULT_HVX_VTCM_PAGE_SIZE),
2718 Indexes},
2719 nullptr);
2720 }
2721 return Gather;
2722 } else if (Qual == HvxIdioms::HEX_Scatter) {
2723 // This is the case when result of a gather is used as an argument to
2724 // Intrinsic::hexagon_V6_vscattermh_128B. Most likely we just inserted it
2725 // ourselves. We have to create alloca, store to it, and replace all uses
2726 // with that.
2727 AllocaInst *ResultAlloca = Builder.CreateAlloca(NT);
2728 Value *CastedSrc = Builder.CreateBitOrPointerCast(
2729 IndexLoad, Type::getInt32Ty(Ctx), "cst_ptr_to_i32");
2730 LLVM_DEBUG(dbgs() << " CastedSrc : " << *CastedSrc << "\n");
2731 Value *CastIndex =
2732 getReinterpretiveCast_i16_to_i32(HVC, Builder, Ctx, Indexes);
2733 LLVM_DEBUG(dbgs() << " Cast index : " << *CastIndex << ")\n");
2734
2735 Gather = Builder.CreateIntrinsic(
2736 Type::getVoidTy(Ctx), Intrinsic::hexagon_V6_vgathermh_128B,
2737 {ResultAlloca, CastedSrc, HVC.getConstInt(DEFAULT_HVX_VTCM_PAGE_SIZE),
2738 CastIndex},
2739 nullptr);
2740 Value *LoadedResult = Builder.CreateLoad(
2741 HVC.getHvxTy(HVC.getIntTy(16), false), ResultAlloca, "temp_result");
2742 LLVM_DEBUG(dbgs() << " LoadedResult : " << *LoadedResult << "\n");
2743 In.replaceAllUsesWith(LoadedResult);
2744 } else if (Qual == HvxIdioms::HEX_Gather) {
2745 // Gather feeds to another gather but already replaced with
2746 // hexagon_V6_vgathermh_128B
2747 if (isa<AllocaInst>(IndexLoad)) {
2748 auto *cstDataVector = dyn_cast<ConstantDataVector>(Indexes);
2749 if (cstDataVector) {
2750 // Our indexes are represented as a constant. We need it in a reg.
2751 AllocaInst *IndexesAlloca = Builder.CreateAlloca(NT);
2752
2753 [[maybe_unused]] auto *StoreIndexes =
2754 Builder.CreateStore(cstDataVector, IndexesAlloca);
2755 LLVM_DEBUG(dbgs() << " StoreIndexes : " << *StoreIndexes << "\n");
2756 Value *LoadedIndex =
2757 Builder.CreateLoad(NT, IndexesAlloca, "reload_index");
2758 AllocaInst *ResultAlloca = Builder.CreateAlloca(NT);
2759 LLVM_DEBUG(dbgs() << " ResultAlloca : " << *ResultAlloca
2760 << "\n AddressSpace: "
2761 << ResultAlloca->getAddressSpace() << "\n";);
2762
2763 Value *CastedSrc = Builder.CreateBitOrPointerCast(
2764 IndexLoad, Type::getInt32Ty(Ctx), "cst_ptr_to_i32");
2765 LLVM_DEBUG(dbgs() << " CastedSrc : " << *CastedSrc << "\n");
2766
2767 Gather = Builder.CreateIntrinsic(
2768 Type::getVoidTy(Ctx), Intrinsic::hexagon_V6_vgathermh_128B,
2769 {ResultAlloca, CastedSrc,
2770 HVC.getConstInt(DEFAULT_HVX_VTCM_PAGE_SIZE), LoadedIndex},
2771 nullptr);
2772 Value *LoadedResult = Builder.CreateLoad(
2773 HVC.getHvxTy(HVC.getIntTy(16), false), ResultAlloca, "temp_result");
2774 LLVM_DEBUG(dbgs() << " LoadedResult : " << *LoadedResult << "\n");
2775 LLVM_DEBUG(dbgs() << " Gather : " << *Gather << "\n");
2776 In.replaceAllUsesWith(LoadedResult);
2777 }
2778 }
2779 } else if (Qual == HvxIdioms::LLVM_Gather) {
2780 // Gather feeds into another gather
2781 errs() << " Underimplemented vgather to vgather sequence\n";
2782 return nullptr;
2783 } else
2784 llvm_unreachable("Unhandled Qual enum");
2785
2786 return Gather;
2787}
2788
2789// Go through all PHI incomming values and find minimal alignment for non GEP
2790// members.
2791std::optional<uint64_t> HvxIdioms::getPHIBaseMinAlignment(Instruction &In,
2792 PHINode *PN) const {
2793 if (!PN)
2794 return std::nullopt;
2795
2796 SmallVector<Value *, 16> Worklist;
2797 SmallPtrSet<Value *, 16> Visited;
2798 uint64_t minPHIAlignment = Value::MaximumAlignment;
2799 Worklist.push_back(PN);
2800
2801 while (!Worklist.empty()) {
2802 Value *V = Worklist.back();
2803 Worklist.pop_back();
2804 if (!Visited.insert(V).second)
2805 continue;
2806
2807 if (PHINode *PN = dyn_cast<PHINode>(V)) {
2808 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
2809 Worklist.push_back(PN->getIncomingValue(i));
2810 }
2811 } else if (isa<GetElementPtrInst>(V)) {
2812 // Ignore geps for now.
2813 continue;
2814 } else {
2815 Align KnownAlign = getKnownAlignment(V, HVC.DL, &In, &HVC.AC, &HVC.DT);
2816 if (KnownAlign.value() < minPHIAlignment)
2817 minPHIAlignment = KnownAlign.value();
2818 }
2819 }
2820 if (minPHIAlignment != Value::MaximumAlignment)
2821 return minPHIAlignment;
2822 return std::nullopt;
2823}
2824
2825// Helper function to discover alignment for a ptr.
2826std::optional<uint64_t> HvxIdioms::getAlignment(Instruction &In,
2827 Value *ptr) const {
2828 SmallPtrSet<Value *, 16> Visited;
2829 return getAlignmentImpl(In, ptr, Visited);
2830}
2831
2832std::optional<uint64_t>
2833HvxIdioms::getAlignmentImpl(Instruction &In, Value *ptr,
2834 SmallPtrSet<Value *, 16> &Visited) const {
2835 LLVM_DEBUG(dbgs() << "[getAlignment] for : " << *ptr << "\n");
2836 // Prevent infinite recursion
2837 if (!Visited.insert(ptr).second)
2838 return std::nullopt;
2839 // Try AssumptionCache.
2840 Align KnownAlign = getKnownAlignment(ptr, HVC.DL, &In, &HVC.AC, &HVC.DT);
2841 // This is the most formal and reliable source of information.
2842 if (KnownAlign.value() > 1) {
2843 LLVM_DEBUG(dbgs() << " VC align(" << KnownAlign.value() << ")\n");
2844 return KnownAlign.value();
2845 }
2846
2847 // If it is a PHI try to iterate through inputs
2848 if (PHINode *PN = dyn_cast<PHINode>(ptr)) {
2849 // See if we have a common base to which we know alignment.
2850 auto baseAlignmentOpt = getPHIBaseMinAlignment(In, PN);
2851 if (!baseAlignmentOpt)
2852 return std::nullopt;
2853
2854 uint64_t minBaseAlignment = *baseAlignmentOpt;
2855 // If it is 1, there is no point to keep on looking.
2856 if (minBaseAlignment == 1)
2857 return 1;
2858 // No see if all other incomming phi nodes are just loop carried constants.
2859 uint64_t minPHIAlignment = minBaseAlignment;
2860 LLVM_DEBUG(dbgs() << " It is a PHI with(" << PN->getNumIncomingValues()
2861 << ")nodes and min base aligned to (" << minBaseAlignment
2862 << ")\n");
2863 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
2864 Value *IV = PN->getIncomingValue(i);
2865 // We have already looked at all other values.
2867 continue;
2868 uint64_t MemberAlignment = Value::MaximumAlignment;
2869 if (auto res = getAlignment(*PN, IV))
2870 MemberAlignment = *res;
2871 else
2872 return std::nullopt;
2873 // Adjust total PHI alignment.
2874 if (minPHIAlignment > MemberAlignment)
2875 minPHIAlignment = MemberAlignment;
2876 }
2877 LLVM_DEBUG(dbgs() << " total PHI alignment(" << minPHIAlignment << ")\n");
2878 return minPHIAlignment;
2879 }
2880
2881 if (auto *GEP = dyn_cast<GetElementPtrInst>(ptr)) {
2882 auto *GEPPtr = GEP->getPointerOperand();
2883 // Only if this is the induction variable with const offset
2884 // Implicit assumption is that induction variable itself is a PHI
2885 if (&In == GEPPtr) {
2886 APInt Offset(HVC.DL.getPointerSizeInBits(
2887 GEPPtr->getType()->getPointerAddressSpace()),
2888 0);
2889 if (GEP->accumulateConstantOffset(HVC.DL, Offset)) {
2890 LLVM_DEBUG(dbgs() << " Induction GEP with const step of ("
2891 << Offset.getZExtValue() << ")\n");
2892 return Offset.getZExtValue();
2893 }
2894 }
2895 }
2896
2897 return std::nullopt;
2898}
2899
2900Value *HvxIdioms::processMStore(Instruction &In) const {
2901 [[maybe_unused]] auto *InpTy =
2902 dyn_cast<VectorType>(In.getOperand(0)->getType());
2903 assert(InpTy && "Cannot handle no vector type for llvm.masked.store");
2904
2905 LLVM_DEBUG(dbgs() << "\n[Process mstore](" << In << ")\n"
2906 << *In.getParent() << "\n");
2907 LLVM_DEBUG(dbgs() << " Input type(" << *InpTy << ") elements("
2908 << HVC.length(InpTy) << ") VecLen(" << HVC.getSizeOf(InpTy)
2909 << ") type(" << *InpTy->getElementType() << ") of size("
2910 << InpTy->getScalarSizeInBits() << ")bits\n");
2911 auto *CI = dyn_cast<CallBase>(&In);
2912 assert(CI && "Expected llvm.masked.store to be a call");
2913 Align HaveAlign = CI->getParamAlign(1).valueOrOne();
2914
2915 uint64_t KA = 1;
2916 if (auto res = getAlignment(In, In.getOperand(1))) // ptr operand
2917 KA = *res;
2918 LLVM_DEBUG(dbgs() << " HaveAlign(" << HaveAlign.value() << ") KnownAlign("
2919 << KA << ")\n");
2920 // Normalize 0 -> ABI alignment of the stored value type (operand 0).
2921 Type *ValTy = In.getOperand(0)->getType();
2922 Align EffA =
2923 (KA > 0) ? Align(KA) : Align(HVC.DL.getABITypeAlign(ValTy).value());
2924
2925 if (EffA < HaveAlign)
2926 return nullptr;
2927
2928 // Attach/replace the param attribute on pointer param #1.
2929 AttrBuilder AttrB(CI->getContext());
2930 AttrB.addAlignmentAttr(EffA);
2931 CI->setAttributes(
2932 CI->getAttributes().addParamAttributes(CI->getContext(), 1, AttrB));
2933 return CI;
2934}
2935
2936Value *HvxIdioms::processMLoad(Instruction &In) const {
2937 [[maybe_unused]] auto *InpTy = dyn_cast<VectorType>(In.getType());
2938 assert(InpTy && "Cannot handle non vector type for llvm.masked.store");
2939 LLVM_DEBUG(dbgs() << "\n[Process mload](" << In << ")\n"
2940 << *In.getParent() << "\n");
2941 LLVM_DEBUG(dbgs() << " Input type(" << *InpTy << ") elements("
2942 << HVC.length(InpTy) << ") VecLen(" << HVC.getSizeOf(InpTy)
2943 << ") type(" << *InpTy->getElementType() << ") of size("
2944 << InpTy->getScalarSizeInBits() << ")bits\n");
2945 auto *CI = dyn_cast<CallBase>(&In);
2946 assert(CI && "Expected to be a call to llvm.masked.load");
2947 // The pointer is operand #0, and its param attribute index is also 0.
2948 Align HaveAlign = CI->getParamAlign(0).valueOrOne();
2949
2950 // Compute best-known alignment KA from analysis.
2951 uint64_t KA = 1;
2952 if (auto res = getAlignment(In, In.getOperand(0))) // ptr operand
2953 KA = *res;
2954
2955 // Normalize 0 → ABI alignment of the loaded value type.
2956 Type *ValTy = In.getType();
2957 Align EffA =
2958 (KA > 0) ? Align(KA) : Align(HVC.DL.getABITypeAlign(ValTy).value());
2959 if (EffA < HaveAlign)
2960 return nullptr;
2961 LLVM_DEBUG(dbgs() << " HaveAlign(" << HaveAlign.value() << ") KnownAlign("
2962 << KA << ")\n");
2963
2964 // Attach/replace the param attribute on pointer param #0.
2965 AttrBuilder AttrB(CI->getContext());
2966 AttrB.addAlignmentAttr(EffA);
2967 CI->setAttributes(
2968 CI->getAttributes().addParamAttributes(CI->getContext(), 0, AttrB));
2969 return CI;
2970}
2971
2972auto HvxIdioms::processFxpMulChopped(IRBuilderBase &Builder, Instruction &In,
2973 const FxpOp &Op) const -> Value * {
2974 assert(Op.X.Val->getType() == Op.Y.Val->getType());
2975 auto *InpTy = cast<VectorType>(Op.X.Val->getType());
2976 unsigned Width = InpTy->getScalarSizeInBits();
2977 bool Rounding = Op.RoundAt.has_value();
2978
2979 if (!Op.RoundAt || *Op.RoundAt == Op.Frac - 1) {
2980 // The fixed-point intrinsics do signed multiplication.
2981 if (Width == Op.Frac + 1 && Op.X.Sgn != Unsigned && Op.Y.Sgn != Unsigned) {
2982 Value *QMul = nullptr;
2983 if (Width == 16) {
2984 QMul = createMulQ15(Builder, Op.X, Op.Y, Rounding);
2985 } else if (Width == 32) {
2986 QMul = createMulQ31(Builder, Op.X, Op.Y, Rounding);
2987 }
2988 if (QMul != nullptr)
2989 return QMul;
2990 }
2991 }
2992
2993 assert(Width >= 32 || isPowerOf2_32(Width)); // Width <= 32 => Width is 2^n
2994 assert(Width < 32 || Width % 32 == 0); // Width > 32 => Width is 32*k
2995
2996 // If Width < 32, then it should really be 16.
2997 if (Width < 32) {
2998 if (Width < 16)
2999 return nullptr;
3000 // Getting here with Op.Frac == 0 isn't wrong, but suboptimal: here we
3001 // generate a full precision products, which is unnecessary if there is
3002 // no shift.
3003 assert(Width == 16);
3004 assert(Op.Frac != 0 && "Unshifted mul should have been skipped");
3005 if (Op.Frac == 16) {
3006 // Multiply high
3007 if (Value *MulH = createMulH16(Builder, Op.X, Op.Y))
3008 return MulH;
3009 }
3010 // Do full-precision multiply and shift.
3011 Value *Prod32 = createMul16(Builder, Op.X, Op.Y);
3012 if (Rounding) {
3013 Value *RoundVal =
3014 ConstantInt::get(Prod32->getType(), 1ull << *Op.RoundAt);
3015 Prod32 = Builder.CreateAdd(Prod32, RoundVal, "add");
3016 }
3017
3018 Value *ShiftAmt = ConstantInt::get(Prod32->getType(), Op.Frac);
3019 Value *Shifted = Op.X.Sgn == Signed || Op.Y.Sgn == Signed
3020 ? Builder.CreateAShr(Prod32, ShiftAmt, "asr")
3021 : Builder.CreateLShr(Prod32, ShiftAmt, "lsr");
3022 return Builder.CreateTrunc(Shifted, InpTy, "trn");
3023 }
3024
3025 // Width >= 32
3026
3027 // Break up the arguments Op.X and Op.Y into vectors of smaller widths
3028 // in preparation of doing the multiplication by 32-bit parts.
3029 auto WordX = HVC.splitVectorElements(Builder, Op.X.Val, /*ToWidth=*/32);
3030 auto WordY = HVC.splitVectorElements(Builder, Op.Y.Val, /*ToWidth=*/32);
3031 auto WordP = createMulLong(Builder, WordX, Op.X.Sgn, WordY, Op.Y.Sgn);
3032
3033 auto *HvxWordTy = cast<VectorType>(WordP.front()->getType());
3034
3035 // Add the optional rounding to the proper word.
3036 if (Op.RoundAt.has_value()) {
3037 Value *Zero = Constant::getNullValue(WordX[0]->getType());
3038 SmallVector<Value *> RoundV(WordP.size(), Zero);
3039 RoundV[*Op.RoundAt / 32] =
3040 ConstantInt::get(HvxWordTy, 1ull << (*Op.RoundAt % 32));
3041 WordP = createAddLong(Builder, WordP, RoundV);
3042 }
3043
3044 // createRightShiftLong?
3045
3046 // Shift all products right by Op.Frac.
3047 unsigned SkipWords = Op.Frac / 32;
3048 Constant *ShiftAmt = ConstantInt::get(HvxWordTy, Op.Frac % 32);
3049
3050 for (int Dst = 0, End = WordP.size() - SkipWords; Dst != End; ++Dst) {
3051 int Src = Dst + SkipWords;
3052 Value *Lo = WordP[Src];
3053 if (Src + 1 < End) {
3054 Value *Hi = WordP[Src + 1];
3055 WordP[Dst] = Builder.CreateIntrinsic(HvxWordTy, Intrinsic::fshr,
3056 {Hi, Lo, ShiftAmt},
3057 /*FMFSource*/ nullptr, "int");
3058 } else {
3059 // The shift of the most significant word.
3060 WordP[Dst] = Builder.CreateAShr(Lo, ShiftAmt, "asr");
3061 }
3062 }
3063 if (SkipWords != 0)
3064 WordP.resize(WordP.size() - SkipWords);
3065
3066 return HVC.joinVectorElements(Builder, WordP, Op.ResTy);
3067}
3068
3069auto HvxIdioms::createMulQ15(IRBuilderBase &Builder, SValue X, SValue Y,
3070 bool Rounding) const -> Value * {
3071 assert(X.Val->getType() == Y.Val->getType());
3072 assert(X.Val->getType()->getScalarType() == HVC.getIntTy(16));
3073 assert(HVC.HST.isHVXVectorType(EVT::getEVT(X.Val->getType(), false)));
3074
3075 // There is no non-rounding intrinsic for i16.
3076 if (!Rounding || X.Sgn == Unsigned || Y.Sgn == Unsigned)
3077 return nullptr;
3078
3079 auto V6_vmpyhvsrs = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyhvsrs);
3080 return HVC.createHvxIntrinsic(Builder, V6_vmpyhvsrs, X.Val->getType(),
3081 {X.Val, Y.Val});
3082}
3083
3084auto HvxIdioms::createMulQ31(IRBuilderBase &Builder, SValue X, SValue Y,
3085 bool Rounding) const -> Value * {
3086 Type *InpTy = X.Val->getType();
3087 assert(InpTy == Y.Val->getType());
3088 assert(InpTy->getScalarType() == HVC.getIntTy(32));
3089 assert(HVC.HST.isHVXVectorType(EVT::getEVT(InpTy, false)));
3090
3091 if (X.Sgn == Unsigned || Y.Sgn == Unsigned)
3092 return nullptr;
3093
3094 auto V6_vmpyewuh = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyewuh);
3095 auto V6_vmpyo_acc = Rounding
3096 ? HVC.HST.getIntrinsicId(Hexagon::V6_vmpyowh_rnd_sacc)
3097 : HVC.HST.getIntrinsicId(Hexagon::V6_vmpyowh_sacc);
3098 Value *V1 =
3099 HVC.createHvxIntrinsic(Builder, V6_vmpyewuh, InpTy, {X.Val, Y.Val});
3100 return HVC.createHvxIntrinsic(Builder, V6_vmpyo_acc, InpTy,
3101 {V1, X.Val, Y.Val});
3102}
3103
3104auto HvxIdioms::createAddCarry(IRBuilderBase &Builder, Value *X, Value *Y,
3105 Value *CarryIn) const
3106 -> std::pair<Value *, Value *> {
3107 assert(X->getType() == Y->getType());
3108 auto VecTy = cast<VectorType>(X->getType());
3109 if (VecTy == HvxI32Ty && HVC.HST.useHVXV62Ops()) {
3111 Intrinsic::ID AddCarry;
3112 if (CarryIn == nullptr && HVC.HST.useHVXV66Ops()) {
3113 AddCarry = HVC.HST.getIntrinsicId(Hexagon::V6_vaddcarryo);
3114 } else {
3115 AddCarry = HVC.HST.getIntrinsicId(Hexagon::V6_vaddcarry);
3116 if (CarryIn == nullptr)
3117 CarryIn = Constant::getNullValue(HVC.getBoolTy(HVC.length(VecTy)));
3118 Args.push_back(CarryIn);
3119 }
3120 Value *Ret = HVC.createHvxIntrinsic(Builder, AddCarry,
3121 /*RetTy=*/nullptr, Args);
3122 Value *Result = Builder.CreateExtractValue(Ret, {0}, "ext");
3123 Value *CarryOut = Builder.CreateExtractValue(Ret, {1}, "ext");
3124 return {Result, CarryOut};
3125 }
3126
3127 // In other cases, do a regular add, and unsigned compare-less-than.
3128 // The carry-out can originate in two places: adding the carry-in or adding
3129 // the two input values.
3130 Value *Result1 = X; // Result1 = X + CarryIn
3131 if (CarryIn != nullptr) {
3132 unsigned Width = VecTy->getScalarSizeInBits();
3133 uint32_t Mask = 1;
3134 if (Width < 32) {
3135 for (unsigned i = 0, e = 32 / Width; i != e; ++i)
3136 Mask = (Mask << Width) | 1;
3137 }
3138 auto V6_vandqrt = HVC.HST.getIntrinsicId(Hexagon::V6_vandqrt);
3139 Value *ValueIn =
3140 HVC.createHvxIntrinsic(Builder, V6_vandqrt, /*RetTy=*/nullptr,
3141 {CarryIn, HVC.getConstInt(Mask)});
3142 Result1 = Builder.CreateAdd(X, ValueIn, "add");
3143 }
3144
3145 Value *CarryOut1 = Builder.CreateCmp(CmpInst::ICMP_ULT, Result1, X, "cmp");
3146 Value *Result2 = Builder.CreateAdd(Result1, Y, "add");
3147 Value *CarryOut2 = Builder.CreateCmp(CmpInst::ICMP_ULT, Result2, Y, "cmp");
3148 return {Result2, Builder.CreateOr(CarryOut1, CarryOut2, "orb")};
3149}
3150
3151auto HvxIdioms::createMul16(IRBuilderBase &Builder, SValue X, SValue Y) const
3152 -> Value * {
3153 Intrinsic::ID V6_vmpyh = 0;
3154 std::tie(X, Y) = canonSgn(X, Y);
3155
3156 if (X.Sgn == Signed) {
3157 V6_vmpyh = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyhv);
3158 } else if (Y.Sgn == Signed) {
3159 // In vmpyhus the second operand is unsigned
3160 V6_vmpyh = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyhus);
3161 } else {
3162 V6_vmpyh = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyuhv);
3163 }
3164
3165 // i16*i16 -> i32 / interleaved
3166 Value *P =
3167 HVC.createHvxIntrinsic(Builder, V6_vmpyh, HvxP32Ty, {Y.Val, X.Val});
3168 // Deinterleave
3169 return HVC.vshuff(Builder, HVC.sublo(Builder, P), HVC.subhi(Builder, P));
3170}
3171
3172auto HvxIdioms::createMulH16(IRBuilderBase &Builder, SValue X, SValue Y) const
3173 -> Value * {
3174 Type *HvxI16Ty = HVC.getHvxTy(HVC.getIntTy(16), /*Pair=*/false);
3175
3176 if (HVC.HST.useHVXV69Ops()) {
3177 if (X.Sgn != Signed && Y.Sgn != Signed) {
3178 auto V6_vmpyuhvs = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyuhvs);
3179 return HVC.createHvxIntrinsic(Builder, V6_vmpyuhvs, HvxI16Ty,
3180 {X.Val, Y.Val});
3181 }
3182 }
3183
3184 Type *HvxP16Ty = HVC.getHvxTy(HVC.getIntTy(16), /*Pair=*/true);
3185 Value *Pair16 =
3186 Builder.CreateBitCast(createMul16(Builder, X, Y), HvxP16Ty, "cst");
3187 unsigned Len = HVC.length(HvxP16Ty) / 2;
3188
3189 SmallVector<int, 128> PickOdd(Len);
3190 for (int i = 0; i != static_cast<int>(Len); ++i)
3191 PickOdd[i] = 2 * i + 1;
3192
3193 return Builder.CreateShuffleVector(
3194 HVC.sublo(Builder, Pair16), HVC.subhi(Builder, Pair16), PickOdd, "shf");
3195}
3196
3197auto HvxIdioms::createMul32(IRBuilderBase &Builder, SValue X, SValue Y) const
3198 -> std::pair<Value *, Value *> {
3199 assert(X.Val->getType() == Y.Val->getType());
3200 assert(X.Val->getType() == HvxI32Ty);
3201
3202 Intrinsic::ID V6_vmpy_parts;
3203 std::tie(X, Y) = canonSgn(X, Y);
3204
3205 if (X.Sgn == Signed) {
3206 V6_vmpy_parts = Intrinsic::hexagon_V6_vmpyss_parts;
3207 } else if (Y.Sgn == Signed) {
3208 V6_vmpy_parts = Intrinsic::hexagon_V6_vmpyus_parts;
3209 } else {
3210 V6_vmpy_parts = Intrinsic::hexagon_V6_vmpyuu_parts;
3211 }
3212
3213 Value *Parts = HVC.createHvxIntrinsic(Builder, V6_vmpy_parts, nullptr,
3214 {X.Val, Y.Val}, {HvxI32Ty});
3215 Value *Hi = Builder.CreateExtractValue(Parts, {0}, "ext");
3216 Value *Lo = Builder.CreateExtractValue(Parts, {1}, "ext");
3217 return {Lo, Hi};
3218}
3219
3220auto HvxIdioms::createAddLong(IRBuilderBase &Builder, ArrayRef<Value *> WordX,
3221 ArrayRef<Value *> WordY) const
3223 assert(WordX.size() == WordY.size());
3224 unsigned Idx = 0, Length = WordX.size();
3226
3227 while (Idx != Length) {
3228 if (HVC.isZero(WordX[Idx]))
3229 Sum[Idx] = WordY[Idx];
3230 else if (HVC.isZero(WordY[Idx]))
3231 Sum[Idx] = WordX[Idx];
3232 else
3233 break;
3234 ++Idx;
3235 }
3236
3237 Value *Carry = nullptr;
3238 for (; Idx != Length; ++Idx) {
3239 std::tie(Sum[Idx], Carry) =
3240 createAddCarry(Builder, WordX[Idx], WordY[Idx], Carry);
3241 }
3242
3243 // This drops the final carry beyond the highest word.
3244 return Sum;
3245}
3246
3247auto HvxIdioms::createMulLong(IRBuilderBase &Builder, ArrayRef<Value *> WordX,
3248 Signedness SgnX, ArrayRef<Value *> WordY,
3249 Signedness SgnY) const -> SmallVector<Value *> {
3250 SmallVector<SmallVector<Value *>> Products(WordX.size() + WordY.size());
3251
3252 // WordX[i] * WordY[j] produces words i+j and i+j+1 of the results,
3253 // that is halves 2(i+j), 2(i+j)+1, 2(i+j)+2, 2(i+j)+3.
3254 for (int i = 0, e = WordX.size(); i != e; ++i) {
3255 for (int j = 0, f = WordY.size(); j != f; ++j) {
3256 // Check the 4 halves that this multiplication can generate.
3257 Signedness SX = (i + 1 == e) ? SgnX : Unsigned;
3258 Signedness SY = (j + 1 == f) ? SgnY : Unsigned;
3259 auto [Lo, Hi] = createMul32(Builder, {WordX[i], SX}, {WordY[j], SY});
3260 Products[i + j + 0].push_back(Lo);
3261 Products[i + j + 1].push_back(Hi);
3262 }
3263 }
3264
3265 Value *Zero = Constant::getNullValue(WordX[0]->getType());
3266
3267 auto pop_back_or_zero = [Zero](auto &Vector) -> Value * {
3268 if (Vector.empty())
3269 return Zero;
3270 auto Last = Vector.back();
3271 Vector.pop_back();
3272 return Last;
3273 };
3274
3275 for (int i = 0, e = Products.size(); i != e; ++i) {
3276 while (Products[i].size() > 1) {
3277 Value *Carry = nullptr; // no carry-in
3278 for (int j = i; j != e; ++j) {
3279 auto &ProdJ = Products[j];
3280 auto [Sum, CarryOut] = createAddCarry(Builder, pop_back_or_zero(ProdJ),
3281 pop_back_or_zero(ProdJ), Carry);
3282 ProdJ.insert(ProdJ.begin(), Sum);
3283 Carry = CarryOut;
3284 }
3285 }
3286 }
3287
3289 for (auto &P : Products) {
3290 assert(P.size() == 1 && "Should have been added together");
3291 WordP.push_back(P.front());
3292 }
3293
3294 return WordP;
3295}
3296
3297auto HvxIdioms::run() -> bool {
3298 bool Changed = false;
3299
3300 for (BasicBlock &B : HVC.F) {
3301 for (auto It = B.rbegin(); It != B.rend(); ++It) {
3302 if (auto Fxm = matchFxpMul(*It)) {
3303 Value *New = processFxpMul(*It, *Fxm);
3304 // Always report "changed" for now.
3305 Changed = true;
3306 if (!New)
3307 continue;
3308 bool StartOver = !isa<Instruction>(New);
3309 It->replaceAllUsesWith(New);
3311 It = StartOver ? B.rbegin()
3312 : cast<Instruction>(New)->getReverseIterator();
3313 Changed = true;
3314 } else if (matchGather(*It)) {
3315 Value *New = processVGather(*It);
3316 if (!New)
3317 continue;
3318 LLVM_DEBUG(dbgs() << " Gather : " << *New << "\n");
3319 // We replace original intrinsic with a new pseudo call.
3320 It->eraseFromParent();
3321 It = cast<Instruction>(New)->getReverseIterator();
3323 Changed = true;
3324 } else if (matchScatter(*It)) {
3325 Value *New = processVScatter(*It);
3326 if (!New)
3327 continue;
3328 LLVM_DEBUG(dbgs() << " Scatter : " << *New << "\n");
3329 // We replace original intrinsic with a new pseudo call.
3330 It->eraseFromParent();
3331 It = cast<Instruction>(New)->getReverseIterator();
3333 Changed = true;
3334 } else if (matchMLoad(*It)) {
3335 Value *New = processMLoad(*It);
3336 if (!New)
3337 continue;
3338 LLVM_DEBUG(dbgs() << " MLoad : " << *New << "\n");
3339 Changed = true;
3340 } else if (matchMStore(*It)) {
3341 Value *New = processMStore(*It);
3342 if (!New)
3343 continue;
3344 LLVM_DEBUG(dbgs() << " MStore : " << *New << "\n");
3345 Changed = true;
3346 }
3347 }
3348 }
3349
3350 return Changed;
3351}
3352
3353// --- End HvxIdioms
3354
3355auto HexagonVectorCombine::run() -> bool {
3356 if (DumpModule)
3357 dbgs() << "Module before HexagonVectorCombine\n" << *F.getParent();
3358
3359 bool Changed = false;
3360 if (HST.useHVXOps()) {
3361 if (VAEnabled)
3362 Changed |= AlignVectors(*this).run();
3363 if (VIEnabled)
3364 Changed |= HvxIdioms(*this).run();
3365 }
3366
3367 if (DumpModule) {
3368 dbgs() << "Module " << (Changed ? "(modified)" : "(unchanged)")
3369 << " after HexagonVectorCombine\n"
3370 << *F.getParent();
3371 }
3372 return Changed;
3373}
3374
3375auto HexagonVectorCombine::getIntTy(unsigned Width) const -> IntegerType * {
3376 return IntegerType::get(F.getContext(), Width);
3377}
3378
3379auto HexagonVectorCombine::getByteTy(int ElemCount) const -> Type * {
3380 assert(ElemCount >= 0);
3381 IntegerType *ByteTy = Type::getInt8Ty(F.getContext());
3382 if (ElemCount == 0)
3383 return ByteTy;
3384 return VectorType::get(ByteTy, ElemCount, /*Scalable=*/false);
3385}
3386
3387auto HexagonVectorCombine::getBoolTy(int ElemCount) const -> Type * {
3388 assert(ElemCount >= 0);
3389 IntegerType *BoolTy = Type::getInt1Ty(F.getContext());
3390 if (ElemCount == 0)
3391 return BoolTy;
3392 return VectorType::get(BoolTy, ElemCount, /*Scalable=*/false);
3393}
3394
3395auto HexagonVectorCombine::getConstInt(int Val, unsigned Width) const
3396 -> ConstantInt * {
3397 return ConstantInt::getSigned(getIntTy(Width), Val);
3398}
3399
3400auto HexagonVectorCombine::isZero(const Value *Val) const -> bool {
3401 if (auto *C = dyn_cast<Constant>(Val))
3402 return C->isNullValue();
3403 return false;
3404}
3405
3406auto HexagonVectorCombine::getIntValue(const Value *Val) const
3407 -> std::optional<APInt> {
3408 if (auto *CI = dyn_cast<ConstantInt>(Val))
3409 return CI->getValue();
3410 return std::nullopt;
3411}
3412
3413auto HexagonVectorCombine::isUndef(const Value *Val) const -> bool {
3414 return isa<UndefValue>(Val);
3415}
3416
3417auto HexagonVectorCombine::isTrue(const Value *Val) const -> bool {
3418 return Val == ConstantInt::getTrue(Val->getType());
3419}
3420
3421auto HexagonVectorCombine::isFalse(const Value *Val) const -> bool {
3422 return isZero(Val);
3423}
3424
3425auto HexagonVectorCombine::getHvxTy(Type *ElemTy, bool Pair) const
3426 -> VectorType * {
3427 EVT ETy = EVT::getEVT(ElemTy, false);
3428 assert(ETy.isSimple() && "Invalid HVX element type");
3429 // Do not allow boolean types here: they don't have a fixed length.
3430 assert(HST.isHVXElementType(ETy.getSimpleVT(), /*IncludeBool=*/false) &&
3431 "Invalid HVX element type");
3432 unsigned HwLen = HST.getVectorLength();
3433 unsigned NumElems = (8 * HwLen) / ETy.getSizeInBits();
3434 return VectorType::get(ElemTy, Pair ? 2 * NumElems : NumElems,
3435 /*Scalable=*/false);
3436}
3437
3438auto HexagonVectorCombine::getSizeOf(const Value *Val, SizeKind Kind) const
3439 -> int {
3440 return getSizeOf(Val->getType(), Kind);
3441}
3442
3443auto HexagonVectorCombine::getSizeOf(const Type *Ty, SizeKind Kind) const
3444 -> int {
3445 auto *NcTy = const_cast<Type *>(Ty);
3446 switch (Kind) {
3447 case Store:
3448 return DL.getTypeStoreSize(NcTy).getFixedValue();
3449 case Alloc:
3450 return DL.getTypeAllocSize(NcTy).getFixedValue();
3451 }
3452 llvm_unreachable("Unhandled SizeKind enum");
3453}
3454
3455auto HexagonVectorCombine::getTypeAlignment(Type *Ty) const -> int {
3456 // The actual type may be shorter than the HVX vector, so determine
3457 // the alignment based on subtarget info.
3458 if (HST.isTypeForHVX(Ty))
3459 return HST.getVectorLength();
3460 return DL.getABITypeAlign(Ty).value();
3461}
3462
3463auto HexagonVectorCombine::length(Value *Val) const -> size_t {
3464 return length(Val->getType());
3465}
3466
3467auto HexagonVectorCombine::length(Type *Ty) const -> size_t {
3468 auto *VecTy = dyn_cast<VectorType>(Ty);
3469 assert(VecTy && "Must be a vector type");
3470 return VecTy->getElementCount().getFixedValue();
3471}
3472
3473auto HexagonVectorCombine::simplify(Value *V) const -> Value * {
3474 if (auto *In = dyn_cast<Instruction>(V)) {
3475 SimplifyQuery Q(DL, &TLI, &DT, &AC, In);
3476 return simplifyInstruction(In, Q);
3477 }
3478 return nullptr;
3479}
3480
3481// Insert bytes [Start..Start+Length) of Src into Dst at byte Where.
3482auto HexagonVectorCombine::insertb(IRBuilderBase &Builder, Value *Dst,
3483 Value *Src, int Start, int Length,
3484 int Where) const -> Value * {
3485 assert(isByteVecTy(Dst->getType()) && isByteVecTy(Src->getType()));
3486 int SrcLen = getSizeOf(Src);
3487 int DstLen = getSizeOf(Dst);
3488 assert(0 <= Start && Start + Length <= SrcLen);
3489 assert(0 <= Where && Where + Length <= DstLen);
3490
3491 int P2Len = PowerOf2Ceil(SrcLen | DstLen);
3492 auto *Poison = PoisonValue::get(getByteTy());
3493 Value *P2Src = vresize(Builder, Src, P2Len, Poison);
3494 Value *P2Dst = vresize(Builder, Dst, P2Len, Poison);
3495
3496 SmallVector<int, 256> SMask(P2Len);
3497 for (int i = 0; i != P2Len; ++i) {
3498 // If i is in [Where, Where+Length), pick Src[Start+(i-Where)].
3499 // Otherwise, pick Dst[i];
3500 SMask[i] =
3501 (Where <= i && i < Where + Length) ? P2Len + Start + (i - Where) : i;
3502 }
3503
3504 Value *P2Insert = Builder.CreateShuffleVector(P2Dst, P2Src, SMask, "shf");
3505 return vresize(Builder, P2Insert, DstLen, Poison);
3506}
3507
3508auto HexagonVectorCombine::vlalignb(IRBuilderBase &Builder, Value *Lo,
3509 Value *Hi, Value *Amt) const -> Value * {
3510 assert(Lo->getType() == Hi->getType() && "Argument type mismatch");
3511 if (isZero(Amt))
3512 return Hi;
3513 int VecLen = getSizeOf(Hi);
3514 if (auto IntAmt = getIntValue(Amt))
3515 return getElementRange(Builder, Lo, Hi, VecLen - IntAmt->getSExtValue(),
3516 VecLen);
3517
3518 if (HST.isTypeForHVX(Hi->getType())) {
3519 assert(static_cast<unsigned>(VecLen) == HST.getVectorLength() &&
3520 "Expecting an exact HVX type");
3521 return createHvxIntrinsic(Builder, HST.getIntrinsicId(Hexagon::V6_vlalignb),
3522 Hi->getType(), {Hi, Lo, Amt});
3523 }
3524
3525 if (VecLen == 4) {
3526 Value *Pair = concat(Builder, {Lo, Hi});
3527 Value *Shift =
3528 Builder.CreateLShr(Builder.CreateShl(Pair, Amt, "shl"), 32, "lsr");
3529 Value *Trunc =
3530 Builder.CreateTrunc(Shift, Type::getInt32Ty(F.getContext()), "trn");
3531 return Builder.CreateBitCast(Trunc, Hi->getType(), "cst");
3532 }
3533 if (VecLen == 8) {
3534 Value *Sub = Builder.CreateSub(getConstInt(VecLen), Amt, "sub");
3535 return vralignb(Builder, Lo, Hi, Sub);
3536 }
3537 llvm_unreachable("Unexpected vector length");
3538}
3539
3540auto HexagonVectorCombine::vralignb(IRBuilderBase &Builder, Value *Lo,
3541 Value *Hi, Value *Amt) const -> Value * {
3542 assert(Lo->getType() == Hi->getType() && "Argument type mismatch");
3543 if (isZero(Amt))
3544 return Lo;
3545 int VecLen = getSizeOf(Lo);
3546 if (auto IntAmt = getIntValue(Amt))
3547 return getElementRange(Builder, Lo, Hi, IntAmt->getSExtValue(), VecLen);
3548
3549 if (HST.isTypeForHVX(Lo->getType())) {
3550 assert(static_cast<unsigned>(VecLen) == HST.getVectorLength() &&
3551 "Expecting an exact HVX type");
3552 return createHvxIntrinsic(Builder, HST.getIntrinsicId(Hexagon::V6_valignb),
3553 Lo->getType(), {Hi, Lo, Amt});
3554 }
3555
3556 if (VecLen == 4) {
3557 Value *Pair = concat(Builder, {Lo, Hi});
3558 Value *Shift = Builder.CreateLShr(Pair, Amt, "lsr");
3559 Value *Trunc =
3560 Builder.CreateTrunc(Shift, Type::getInt32Ty(F.getContext()), "trn");
3561 return Builder.CreateBitCast(Trunc, Lo->getType(), "cst");
3562 }
3563 if (VecLen == 8) {
3564 Type *Int64Ty = Type::getInt64Ty(F.getContext());
3565 Value *Lo64 = Builder.CreateBitCast(Lo, Int64Ty, "cst");
3566 Value *Hi64 = Builder.CreateBitCast(Hi, Int64Ty, "cst");
3567 Value *Call = Builder.CreateIntrinsic(Intrinsic::hexagon_S2_valignrb,
3568 {Hi64, Lo64, Amt},
3569 /*FMFSource=*/nullptr, "cup");
3570 return Builder.CreateBitCast(Call, Lo->getType(), "cst");
3571 }
3572 llvm_unreachable("Unexpected vector length");
3573}
3574
3575// Concatenates a sequence of vectors of the same type.
3576auto HexagonVectorCombine::concat(IRBuilderBase &Builder,
3577 ArrayRef<Value *> Vecs) const -> Value * {
3578 assert(!Vecs.empty());
3580 std::vector<Value *> Work[2];
3581 int ThisW = 0, OtherW = 1;
3582
3583 Work[ThisW].assign(Vecs.begin(), Vecs.end());
3584 while (Work[ThisW].size() > 1) {
3585 auto *Ty = cast<VectorType>(Work[ThisW].front()->getType());
3586 SMask.resize(length(Ty) * 2);
3587 std::iota(SMask.begin(), SMask.end(), 0);
3588
3589 Work[OtherW].clear();
3590 if (Work[ThisW].size() % 2 != 0)
3591 Work[ThisW].push_back(UndefValue::get(Ty));
3592 for (int i = 0, e = Work[ThisW].size(); i < e; i += 2) {
3593 Value *Joined = Builder.CreateShuffleVector(
3594 Work[ThisW][i], Work[ThisW][i + 1], SMask, "shf");
3595 Work[OtherW].push_back(Joined);
3596 }
3597 std::swap(ThisW, OtherW);
3598 }
3599
3600 // Since there may have been some undefs appended to make shuffle operands
3601 // have the same type, perform the last shuffle to only pick the original
3602 // elements.
3603 SMask.resize(Vecs.size() * length(Vecs.front()->getType()));
3604 std::iota(SMask.begin(), SMask.end(), 0);
3605 Value *Total = Work[ThisW].front();
3606 return Builder.CreateShuffleVector(Total, SMask, "shf");
3607}
3608
3609auto HexagonVectorCombine::vresize(IRBuilderBase &Builder, Value *Val,
3610 int NewSize, Value *Pad) const -> Value * {
3612 auto *ValTy = cast<VectorType>(Val->getType());
3613 assert(ValTy->getElementType() == Pad->getType());
3614
3615 int CurSize = length(ValTy);
3616 if (CurSize == NewSize)
3617 return Val;
3618 // Truncate?
3619 if (CurSize > NewSize)
3620 return getElementRange(Builder, Val, /*Ignored*/ Val, 0, NewSize);
3621 // Extend.
3622 SmallVector<int, 128> SMask(NewSize);
3623 std::iota(SMask.begin(), SMask.begin() + CurSize, 0);
3624 std::fill(SMask.begin() + CurSize, SMask.end(), CurSize);
3625 Value *PadVec = Builder.CreateVectorSplat(CurSize, Pad, "spt");
3626 return Builder.CreateShuffleVector(Val, PadVec, SMask, "shf");
3627}
3628
3629auto HexagonVectorCombine::rescale(IRBuilderBase &Builder, Value *Mask,
3630 Type *FromTy, Type *ToTy) const -> Value * {
3631 // Mask is a vector <N x i1>, where each element corresponds to an
3632 // element of FromTy. Remap it so that each element will correspond
3633 // to an element of ToTy.
3634 assert(isa<VectorType>(Mask->getType()));
3635
3636 Type *FromSTy = FromTy->getScalarType();
3637 Type *ToSTy = ToTy->getScalarType();
3638 if (FromSTy == ToSTy)
3639 return Mask;
3640
3641 int FromSize = getSizeOf(FromSTy);
3642 int ToSize = getSizeOf(ToSTy);
3643 assert(FromSize % ToSize == 0 || ToSize % FromSize == 0);
3644
3645 auto *MaskTy = cast<VectorType>(Mask->getType());
3646 int FromCount = length(MaskTy);
3647 int ToCount = (FromCount * FromSize) / ToSize;
3648 assert((FromCount * FromSize) % ToSize == 0);
3649
3650 auto *FromITy = getIntTy(FromSize * 8);
3651 auto *ToITy = getIntTy(ToSize * 8);
3652
3653 // Mask <N x i1> -> sext to <N x FromTy> -> bitcast to <M x ToTy> ->
3654 // -> trunc to <M x i1>.
3655 Value *Ext = Builder.CreateSExt(
3656 Mask, VectorType::get(FromITy, FromCount, /*Scalable=*/false), "sxt");
3657 Value *Cast = Builder.CreateBitCast(
3658 Ext, VectorType::get(ToITy, ToCount, /*Scalable=*/false), "cst");
3659 return Builder.CreateTrunc(
3660 Cast, VectorType::get(getBoolTy(), ToCount, /*Scalable=*/false), "trn");
3661}
3662
3663// Bitcast to bytes, and return least significant bits.
3664auto HexagonVectorCombine::vlsb(IRBuilderBase &Builder, Value *Val) const
3665 -> Value * {
3666 Type *ScalarTy = Val->getType()->getScalarType();
3667 if (ScalarTy == getBoolTy())
3668 return Val;
3669
3670 Value *Bytes = vbytes(Builder, Val);
3671 if (auto *VecTy = dyn_cast<VectorType>(Bytes->getType()))
3672 return Builder.CreateTrunc(Bytes, getBoolTy(getSizeOf(VecTy)), "trn");
3673 // If Bytes is a scalar (i.e. Val was a scalar byte), return i1, not
3674 // <1 x i1>.
3675 return Builder.CreateTrunc(Bytes, getBoolTy(), "trn");
3676}
3677
3678// Bitcast to bytes for non-bool. For bool, convert i1 -> i8.
3679auto HexagonVectorCombine::vbytes(IRBuilderBase &Builder, Value *Val) const
3680 -> Value * {
3681 Type *ScalarTy = Val->getType()->getScalarType();
3682 if (ScalarTy == getByteTy())
3683 return Val;
3684
3685 if (ScalarTy != getBoolTy())
3686 return Builder.CreateBitCast(Val, getByteTy(getSizeOf(Val)), "cst");
3687 // For bool, return a sext from i1 to i8.
3688 if (auto *VecTy = dyn_cast<VectorType>(Val->getType()))
3689 return Builder.CreateSExt(Val, VectorType::get(getByteTy(), VecTy), "sxt");
3690 return Builder.CreateSExt(Val, getByteTy(), "sxt");
3691}
3692
3693auto HexagonVectorCombine::subvector(IRBuilderBase &Builder, Value *Val,
3694 unsigned Start, unsigned Length) const
3695 -> Value * {
3696 assert(Start + Length <= length(Val));
3697 return getElementRange(Builder, Val, /*Ignored*/ Val, Start, Length);
3698}
3699
3700auto HexagonVectorCombine::sublo(IRBuilderBase &Builder, Value *Val) const
3701 -> Value * {
3702 size_t Len = length(Val);
3703 assert(Len % 2 == 0 && "Length should be even");
3704 return subvector(Builder, Val, 0, Len / 2);
3705}
3706
3707auto HexagonVectorCombine::subhi(IRBuilderBase &Builder, Value *Val) const
3708 -> Value * {
3709 size_t Len = length(Val);
3710 assert(Len % 2 == 0 && "Length should be even");
3711 return subvector(Builder, Val, Len / 2, Len / 2);
3712}
3713
3714auto HexagonVectorCombine::vdeal(IRBuilderBase &Builder, Value *Val0,
3715 Value *Val1) const -> Value * {
3716 assert(Val0->getType() == Val1->getType());
3717 int Len = length(Val0);
3718 SmallVector<int, 128> Mask(2 * Len);
3719
3720 for (int i = 0; i != Len; ++i) {
3721 Mask[i] = 2 * i; // Even
3722 Mask[i + Len] = 2 * i + 1; // Odd
3723 }
3724 return Builder.CreateShuffleVector(Val0, Val1, Mask, "shf");
3725}
3726
3727auto HexagonVectorCombine::vshuff(IRBuilderBase &Builder, Value *Val0,
3728 Value *Val1) const -> Value * { //
3729 assert(Val0->getType() == Val1->getType());
3730 int Len = length(Val0);
3731 SmallVector<int, 128> Mask(2 * Len);
3732
3733 for (int i = 0; i != Len; ++i) {
3734 Mask[2 * i + 0] = i; // Val0
3735 Mask[2 * i + 1] = i + Len; // Val1
3736 }
3737 return Builder.CreateShuffleVector(Val0, Val1, Mask, "shf");
3738}
3739
3740auto HexagonVectorCombine::createHvxIntrinsic(IRBuilderBase &Builder,
3741 Intrinsic::ID IntID, Type *RetTy,
3742 ArrayRef<Value *> Args,
3743 ArrayRef<Type *> ArgTys,
3744 ArrayRef<Value *> MDSources) const
3745 -> Value * {
3746 auto getCast = [&](IRBuilderBase &Builder, Value *Val,
3747 Type *DestTy) -> Value * {
3748 Type *SrcTy = Val->getType();
3749 if (SrcTy == DestTy)
3750 return Val;
3751
3752 // Non-HVX type. It should be a scalar, and it should already have
3753 // a valid type.
3754 assert(HST.isTypeForHVX(SrcTy, /*IncludeBool=*/true));
3755
3756 Type *BoolTy = Type::getInt1Ty(F.getContext());
3757 if (cast<VectorType>(SrcTy)->getElementType() != BoolTy)
3758 return Builder.CreateBitCast(Val, DestTy, "cst");
3759
3760 // Predicate HVX vector.
3761 unsigned HwLen = HST.getVectorLength();
3762 Intrinsic::ID TC = HwLen == 64 ? Intrinsic::hexagon_V6_pred_typecast
3763 : Intrinsic::hexagon_V6_pred_typecast_128B;
3764 return Builder.CreateIntrinsic(TC, {DestTy, Val->getType()}, {Val},
3765 /*FMFSource=*/nullptr, "cup");
3766 };
3767
3768 Function *IntrFn =
3769 Intrinsic::getOrInsertDeclaration(F.getParent(), IntID, ArgTys);
3770 FunctionType *IntrTy = IntrFn->getFunctionType();
3771
3772 SmallVector<Value *, 4> IntrArgs;
3773 for (int i = 0, e = Args.size(); i != e; ++i) {
3774 Value *A = Args[i];
3775 Type *T = IntrTy->getParamType(i);
3776 if (A->getType() != T) {
3777 IntrArgs.push_back(getCast(Builder, A, T));
3778 } else {
3779 IntrArgs.push_back(A);
3780 }
3781 }
3782 StringRef MaybeName = !IntrTy->getReturnType()->isVoidTy() ? "cup" : "";
3783 CallInst *Call = Builder.CreateCall(IntrFn, IntrArgs, MaybeName);
3784
3785 MemoryEffects ME = Call->getAttributes().getMemoryEffects();
3788
3789 Type *CallTy = Call->getType();
3790 if (RetTy == nullptr || CallTy == RetTy)
3791 return Call;
3792 // Scalar types should have RetTy matching the call return type.
3793 assert(HST.isTypeForHVX(CallTy, /*IncludeBool=*/true));
3794 return getCast(Builder, Call, RetTy);
3795}
3796
3797auto HexagonVectorCombine::splitVectorElements(IRBuilderBase &Builder,
3798 Value *Vec,
3799 unsigned ToWidth) const
3801 // Break a vector of wide elements into a series of vectors with narrow
3802 // elements:
3803 // (...c0:b0:a0, ...c1:b1:a1, ...c2:b2:a2, ...)
3804 // -->
3805 // (a0, a1, a2, ...) // lowest "ToWidth" bits
3806 // (b0, b1, b2, ...) // the next lowest...
3807 // (c0, c1, c2, ...) // ...
3808 // ...
3809 //
3810 // The number of elements in each resulting vector is the same as
3811 // in the original vector.
3812
3813 auto *VecTy = cast<VectorType>(Vec->getType());
3814 assert(VecTy->getElementType()->isIntegerTy());
3815 unsigned FromWidth = VecTy->getScalarSizeInBits();
3816 assert(isPowerOf2_32(ToWidth) && isPowerOf2_32(FromWidth));
3817 assert(ToWidth <= FromWidth && "Breaking up into wider elements?");
3818 unsigned NumResults = FromWidth / ToWidth;
3819
3820 SmallVector<Value *> Results(NumResults);
3821 Results[0] = Vec;
3822 unsigned Length = length(VecTy);
3823
3824 // Do it by splitting in half, since those operations correspond to deal
3825 // instructions.
3826 auto splitInHalf = [&](unsigned Begin, unsigned End, auto splitFunc) -> void {
3827 // Take V = Results[Begin], split it in L, H.
3828 // Store Results[Begin] = L, Results[(Begin+End)/2] = H
3829 // Call itself recursively split(Begin, Half), split(Half+1, End)
3830 if (Begin + 1 == End)
3831 return;
3832
3833 Value *Val = Results[Begin];
3834 unsigned Width = Val->getType()->getScalarSizeInBits();
3835
3836 auto *VTy = VectorType::get(getIntTy(Width / 2), 2 * Length, false);
3837 Value *VVal = Builder.CreateBitCast(Val, VTy, "cst");
3838
3839 Value *Res = vdeal(Builder, sublo(Builder, VVal), subhi(Builder, VVal));
3840
3841 unsigned Half = (Begin + End) / 2;
3842 Results[Begin] = sublo(Builder, Res);
3843 Results[Half] = subhi(Builder, Res);
3844
3845 splitFunc(Begin, Half, splitFunc);
3846 splitFunc(Half, End, splitFunc);
3847 };
3848
3849 splitInHalf(0, NumResults, splitInHalf);
3850 return Results;
3851}
3852
3853auto HexagonVectorCombine::joinVectorElements(IRBuilderBase &Builder,
3855 VectorType *ToType) const
3856 -> Value * {
3857 assert(ToType->getElementType()->isIntegerTy());
3858
3859 // If the list of values does not have power-of-2 elements, append copies
3860 // of the sign bit to it, to make the size be 2^n.
3861 // The reason for this is that the values will be joined in pairs, because
3862 // otherwise the shuffles will result in convoluted code. With pairwise
3863 // joins, the shuffles will hopefully be folded into a perfect shuffle.
3864 // The output will need to be sign-extended to a type with element width
3865 // being a power-of-2 anyways.
3867
3868 unsigned ToWidth = ToType->getScalarSizeInBits();
3869 unsigned Width = Inputs.front()->getType()->getScalarSizeInBits();
3870 assert(Width <= ToWidth);
3871 assert(isPowerOf2_32(Width) && isPowerOf2_32(ToWidth));
3872 unsigned Length = length(Inputs.front()->getType());
3873
3874 unsigned NeedInputs = ToWidth / Width;
3875 if (Inputs.size() != NeedInputs) {
3876 // Having too many inputs is ok: drop the high bits (usual wrap-around).
3877 // If there are too few, fill them with the sign bit.
3878 Value *Last = Inputs.back();
3879 Value *Sign = Builder.CreateAShr(
3880 Last, ConstantInt::get(Last->getType(), Width - 1), "asr");
3881 Inputs.resize(NeedInputs, Sign);
3882 }
3883
3884 while (Inputs.size() > 1) {
3885 Width *= 2;
3886 auto *VTy = VectorType::get(getIntTy(Width), Length, false);
3887 for (int i = 0, e = Inputs.size(); i < e; i += 2) {
3888 Value *Res = vshuff(Builder, Inputs[i], Inputs[i + 1]);
3889 Inputs[i / 2] = Builder.CreateBitCast(Res, VTy, "cst");
3890 }
3891 Inputs.resize(Inputs.size() / 2);
3892 }
3893
3894 assert(Inputs.front()->getType() == ToType);
3895 return Inputs.front();
3896}
3897
3898auto HexagonVectorCombine::calculatePointerDifference(Value *Ptr0,
3899 Value *Ptr1) const
3900 -> std::optional<int> {
3901 // Try SCEV first.
3902 const SCEV *Scev0 = SE.getSCEV(Ptr0);
3903 const SCEV *Scev1 = SE.getSCEV(Ptr1);
3904 const SCEV *ScevDiff = SE.getMinusSCEV(Scev0, Scev1);
3905 if (auto *Const = dyn_cast<SCEVConstant>(ScevDiff)) {
3906 APInt V = Const->getAPInt();
3907 if (V.isSignedIntN(8 * sizeof(int)))
3908 return static_cast<int>(V.getSExtValue());
3909 }
3910
3911 struct Builder : IRBuilder<> {
3912 Builder(BasicBlock *B) : IRBuilder<>(B->getTerminator()) {}
3913 ~Builder() {
3914 for (Instruction *I : llvm::reverse(ToErase))
3915 I->eraseFromParent();
3916 }
3917 SmallVector<Instruction *, 8> ToErase;
3918 };
3919
3920#define CallBuilder(B, F) \
3921 [&](auto &B_) { \
3922 Value *V = B_.F; \
3923 if (auto *I = dyn_cast<Instruction>(V)) \
3924 B_.ToErase.push_back(I); \
3925 return V; \
3926 }(B)
3927
3928 auto Simplify = [this](Value *V) {
3929 if (Value *S = simplify(V))
3930 return S;
3931 return V;
3932 };
3933
3934 auto StripBitCast = [](Value *V) {
3935 while (auto *C = dyn_cast<BitCastInst>(V))
3936 V = C->getOperand(0);
3937 return V;
3938 };
3939
3940 Ptr0 = StripBitCast(Ptr0);
3941 Ptr1 = StripBitCast(Ptr1);
3943 return std::nullopt;
3944
3945 auto *Gep0 = cast<GetElementPtrInst>(Ptr0);
3946 auto *Gep1 = cast<GetElementPtrInst>(Ptr1);
3947 if (Gep0->getPointerOperand() != Gep1->getPointerOperand())
3948 return std::nullopt;
3949 if (Gep0->getSourceElementType() != Gep1->getSourceElementType())
3950 return std::nullopt;
3951
3952 Builder B(Gep0->getParent());
3953 int Scale = getSizeOf(Gep0->getSourceElementType(), Alloc);
3954
3955 // FIXME: for now only check GEPs with a single index.
3956 if (Gep0->getNumOperands() != 2 || Gep1->getNumOperands() != 2)
3957 return std::nullopt;
3958
3959 // Only indices already in the pointer's index type are subtracted. Other
3960 // widths can assert (mixed types) or wrap (narrow types), so give up.
3961 Type *IdxTy = DL.getIndexType(Gep0->getType());
3962 if (Gep0->getOperand(1)->getType() != IdxTy ||
3963 Gep1->getOperand(1)->getType() != IdxTy)
3964 return std::nullopt;
3965
3966 Value *Idx0 = Gep0->getOperand(1);
3967 Value *Idx1 = Gep1->getOperand(1);
3968
3969 // First, try to simplify the subtraction directly.
3970 if (auto *Diff = dyn_cast<ConstantInt>(
3971 Simplify(CallBuilder(B, CreateSub(Idx0, Idx1)))))
3972 return Diff->getSExtValue() * Scale;
3973
3974 KnownBits Known0 = getKnownBits(Idx0, Gep0);
3975 KnownBits Known1 = getKnownBits(Idx1, Gep1);
3976 APInt Unknown = ~(Known0.Zero | Known0.One) | ~(Known1.Zero | Known1.One);
3977 if (Unknown.isAllOnes())
3978 return std::nullopt;
3979
3980 Value *MaskU = ConstantInt::get(Idx0->getType(), Unknown);
3981 Value *AndU0 = Simplify(CallBuilder(B, CreateAnd(Idx0, MaskU)));
3982 Value *AndU1 = Simplify(CallBuilder(B, CreateAnd(Idx1, MaskU)));
3983 Value *SubU = Simplify(CallBuilder(B, CreateSub(AndU0, AndU1)));
3984 int Diff0 = 0;
3985 if (auto *C = dyn_cast<ConstantInt>(SubU)) {
3986 Diff0 = C->getSExtValue();
3987 } else {
3988 return std::nullopt;
3989 }
3990
3991 Value *MaskK = ConstantInt::get(MaskU->getType(), ~Unknown);
3992 Value *AndK0 = Simplify(CallBuilder(B, CreateAnd(Idx0, MaskK)));
3993 Value *AndK1 = Simplify(CallBuilder(B, CreateAnd(Idx1, MaskK)));
3994 Value *SubK = Simplify(CallBuilder(B, CreateSub(AndK0, AndK1)));
3995 int Diff1 = 0;
3996 if (auto *C = dyn_cast<ConstantInt>(SubK)) {
3997 Diff1 = C->getSExtValue();
3998 } else {
3999 return std::nullopt;
4000 }
4001
4002 return (Diff0 + Diff1) * Scale;
4003
4004#undef CallBuilder
4005}
4006
4007auto HexagonVectorCombine::getNumSignificantBits(const Value *V,
4008 const Instruction *CtxI) const
4009 -> unsigned {
4010 return ComputeMaxSignificantBits(V, DL, &AC, CtxI, &DT);
4011}
4012
4013auto HexagonVectorCombine::getKnownBits(const Value *V,
4014 const Instruction *CtxI) const
4015 -> KnownBits {
4016 return computeKnownBits(V, DL, &AC, CtxI, &DT);
4017}
4018
4019auto HexagonVectorCombine::isSafeToClone(const Instruction &In) const -> bool {
4020 if (In.mayHaveSideEffects() || In.isAtomic() || In.isVolatile() ||
4021 In.isFenceLike() || In.mayReadOrWriteMemory()) {
4022 return false;
4023 }
4024 if (isa<CallBase>(In) || isa<AllocaInst>(In))
4025 return false;
4026 return true;
4027}
4028
4029template <typename T>
4030auto HexagonVectorCombine::isSafeToMoveBeforeInBB(const Instruction &In,
4032 const T &IgnoreInsts) const
4033 -> bool {
4034 auto getLocOrNone =
4035 [this](const Instruction &I) -> std::optional<MemoryLocation> {
4036 if (const auto *II = dyn_cast<IntrinsicInst>(&I)) {
4037 switch (II->getIntrinsicID()) {
4038 case Intrinsic::masked_load:
4040 case Intrinsic::masked_store:
4042 }
4043 }
4045 };
4046
4047 // The source and the destination must be in the same basic block.
4048 const BasicBlock &Block = *In.getParent();
4049 assert(Block.begin() == To || Block.end() == To || To->getParent() == &Block);
4050 // No PHIs.
4051 if (isa<PHINode>(In) || (To != Block.end() && isa<PHINode>(*To)))
4052 return false;
4053
4055 return true;
4056 bool MayWrite = In.mayWriteToMemory();
4057 auto MaybeLoc = getLocOrNone(In);
4058
4059 auto From = In.getIterator();
4060 if (From == To)
4061 return true;
4062 bool MoveUp = (To != Block.end() && To->comesBefore(&In));
4063 auto Range =
4064 MoveUp ? std::make_pair(To, From) : std::make_pair(std::next(From), To);
4065 for (auto It = Range.first; It != Range.second; ++It) {
4066 const Instruction &I = *It;
4067 if (llvm::is_contained(IgnoreInsts, &I))
4068 continue;
4069 // assume intrinsic can be ignored
4070 if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
4071 if (II->getIntrinsicID() == Intrinsic::assume)
4072 continue;
4073 }
4074 // Parts based on isSafeToMoveBefore from CoveMoverUtils.cpp.
4075 if (I.mayThrow())
4076 return false;
4077 if (auto *CB = dyn_cast<CallBase>(&I)) {
4078 if (!CB->hasFnAttr(Attribute::WillReturn))
4079 return false;
4080 if (!CB->hasFnAttr(Attribute::NoSync))
4081 return false;
4082 }
4083 if (I.mayReadOrWriteMemory()) {
4084 auto MaybeLocI = getLocOrNone(I);
4085 if (MayWrite || I.mayWriteToMemory()) {
4086 if (!MaybeLoc || !MaybeLocI)
4087 return false;
4088 if (!AA.isNoAlias(*MaybeLoc, *MaybeLocI))
4089 return false;
4090 }
4091 }
4092 }
4093 return true;
4094}
4095
4096auto HexagonVectorCombine::isByteVecTy(Type *Ty) const -> bool {
4097 if (auto *VecTy = dyn_cast<VectorType>(Ty))
4098 return VecTy->getElementType() == getByteTy();
4099 return false;
4100}
4101
4102auto HexagonVectorCombine::getElementRange(IRBuilderBase &Builder, Value *Lo,
4103 Value *Hi, int Start,
4104 int Length) const -> Value * {
4105 assert(0 <= Start && size_t(Start + Length) < length(Lo) + length(Hi));
4106 SmallVector<int, 128> SMask(Length);
4107 std::iota(SMask.begin(), SMask.end(), Start);
4108 return Builder.CreateShuffleVector(Lo, Hi, SMask, "shf");
4109}
4110
4111// Pass management.
4112
4113namespace {
4114class HexagonVectorCombineLegacy : public FunctionPass {
4115public:
4116 static char ID;
4117
4118 HexagonVectorCombineLegacy() : FunctionPass(ID) {}
4119
4120 StringRef getPassName() const override { return "Hexagon Vector Combine"; }
4121
4122 void getAnalysisUsage(AnalysisUsage &AU) const override {
4123 AU.setPreservesCFG();
4124 AU.addRequired<AAResultsWrapperPass>();
4125 AU.addRequired<AssumptionCacheTracker>();
4126 AU.addRequired<DominatorTreeWrapperPass>();
4127 AU.addRequired<ScalarEvolutionWrapperPass>();
4128 AU.addRequired<TargetLibraryInfoWrapperPass>();
4129 AU.addRequired<TargetPassConfig>();
4130 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
4131 FunctionPass::getAnalysisUsage(AU);
4132 }
4133
4134 bool runOnFunction(Function &F) override {
4135 if (skipFunction(F))
4136 return false;
4137 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4138 AssumptionCache &AC =
4139 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4140 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4141 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4142 TargetLibraryInfo &TLI =
4143 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
4144 auto &TM = getAnalysis<TargetPassConfig>().getTM<HexagonTargetMachine>();
4145 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
4146 HexagonVectorCombine HVC(F, AA, AC, DT, SE, TLI, TM, ORE);
4147 return HVC.run();
4148 }
4149};
4150} // namespace
4151
4152char HexagonVectorCombineLegacy::ID = 0;
4153
4154INITIALIZE_PASS_BEGIN(HexagonVectorCombineLegacy, DEBUG_TYPE,
4155 "Hexagon Vector Combine", false, false)
4163INITIALIZE_PASS_END(HexagonVectorCombineLegacy, DEBUG_TYPE,
4164 "Hexagon Vector Combine", false, false)
4165
4167 return new HexagonVectorCombineLegacy();
4168}
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static IntegerType * getIntTy(IRBuilderBase &B, const TargetLibraryInfo *TLI)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
hexagon bit simplify
Hexagon Common GEP
static Value * locateIndexesFromIntrinsic(Instruction *In)
Instruction * locateDestination(Instruction *In, HvxIdioms::DstQualifier &Qual)
Value * getReinterpretiveCast_i8_to_i32(const HexagonVectorCombine &HVC, IRBuilderBase &Builder, LLVMContext &Ctx, Value *I)
static Value * locateIndexesFromGEP(Value *In)
#define CallBuilder(B, F)
Value * getPointer(Value *Ptr)
#define DEFAULT_HVX_VTCM_PAGE_SIZE
static Value * locateAddressFromIntrinsic(Instruction *In)
static Instruction * selectDestination(Instruction *In, HvxIdioms::DstQualifier &Qual)
Value * get_i32_Mask(const HexagonVectorCombine &HVC, IRBuilderBase &Builder, LLVMContext &Ctx, unsigned int pattern)
bool isArithmetic(unsigned Opc)
static Type * getIndexType(Value *In)
GetElementPtrInst * locateGepFromIntrinsic(Instruction *In)
Value * getReinterpretiveCast_i16_to_i32(const HexagonVectorCombine &HVC, IRBuilderBase &Builder, LLVMContext &Ctx, Value *I)
static Align effectiveAlignForValueTy(const DataLayout &DL, Type *ValTy, int Requested)
iv Induction Variable Users
Definition IVUsers.cpp:48
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:550
if(!TBB||Cond.size()< 1) return false
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
static bool isCandidate(const MachineInstr *MI, Register &DefedReg, Register FrameReg)
static bool isUndef(const MachineInstr &MI)
This file implements a map that provides insertion order iteration.
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineInstr *& Lo
Remove Loads Into Fake Uses
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Target-Independent Code Generator Pass Configuration Options pass.
static uint32_t getAlignment(const MCSectionCOFF &Sec)
static const uint32_t IV[8]
Definition blake3_impl.h:83
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
unsigned getAddressSpace() const
Return the address space for the allocation.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:170
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
AttributeList getAttributes() const
Return the attributes for this call.
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
static LLVM_ABI Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
unsigned getPointerSizeInBits(unsigned AS=0) const
The size in bits of the pointer representation in a given address space.
Definition DataLayout.h:503
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
iterator_range< iterator > children()
NodeT * getBlock() const
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool empty() const
Definition Function.h:853
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
const BasicBlock & front() const
Definition Function.h:854
const BasicBlock & back() const
Definition Function.h:856
DISubprogram * getSubprogram() const
Get the attached subprogram.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
bool isHVXVectorType(EVT VecTy, bool IncludeBool=false) const
unsigned getVectorLength() const
bool isTypeForHVX(Type *VecTy, bool IncludeBool=false) const
Intrinsic::ID getIntrinsicId(unsigned Opc) const
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition IRBuilder.h:1886
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2795
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2209
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1534
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", bool HasSameSign=false)
Definition IRBuilder.h:2568
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2462
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2408
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2595
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1441
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2319
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1913
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1513
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2197
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition IRBuilder.h:2770
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1572
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1931
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1424
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2309
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2640
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2183
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1553
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1594
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
const char * getOpcodeName() const
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
bool empty() const
Definition MapVector.h:80
void remove_if(Predicate Pred)
Remove the elements that match the predicate.
size_type size() const
Definition MapVector.h:59
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
bool onlyAccessesInaccessibleMem() const
Whether this function only (at most) accesses inaccessible memory.
Definition ModRef.h:265
static LLVM_ABI std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
static LLVM_ABI MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
OptimizationRemarkEmitter legacy analysis pass.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
The main scalar evolution driver.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void resize(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Provides information about what library functions are available for the current target.
Primary interface to the complete machine description for the target machine.
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
Target-Independent Code Generator Pass Configuration Options.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
Rounding
Possible values of current rounding mode, which is specified in bits 23:22 of FPCR.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
initializer< Ty > init(const Ty &Val)
constexpr double e
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI Instruction * getTerminator() const
LLVM_ABI Instruction & front() const
This is an optimization pass for GlobalISel generic memory operations.
FunctionPass * createHexagonVectorCombineLegacyPass()
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:523
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q, SmallVectorImpl< Instruction * > *DropAnnotations=nullptr)
See if we can compute a simplified version of this instruction.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
@ Undef
Value of the register doesn't matter.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1807
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1167
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
LLVM_ABI Instruction * propagateMetadataForVectorization(Instruction *I, ArrayRef< Value * > VL)
Propagate metadata that can be preserved after vectorization from VL to I, retaining only information...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
@ Off
Use window algorithm after SMS algorithm fails.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:241
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
MaskT vshuff(ArrayRef< int > Vu, ArrayRef< int > Vv, unsigned Size, bool TakeOdd)
MaskT vdeal(ArrayRef< int > Vu, ArrayRef< int > Vv, unsigned Size, bool TakeOdd)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354