LLVM 24.0.0git
VecUtils.cpp
Go to the documentation of this file.
1//===- VecUtils.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
10
11#include "llvm/ADT/DenseMap.h"
12#include "llvm/ADT/Sequence.h"
18
19namespace llvm::sandboxir {
20
22 "sbvec-max-users-to-consider", cl::init(16), cl::Hidden,
23 cl::desc("Limit the number of a seed's users that getNextUserBundles() "
24 "will examine as candidates for a matching bundle, to cap "
25 "compilation time."));
26
29 for (unsigned Idx : seq<unsigned>(U->getNumOperands()))
30 if (U->getOperand(Idx) == Op)
31 OpIdxVec.push_back(Idx);
32 return OpIdxVec;
33}
34
35static std::optional<BundleTy>
37 Instruction *SeedUserInst,
39 SmallVector<unsigned, 2> OpIdxVec0 =
40 getOperandIndicesInUser(SeedUserInst, Seed);
41 assert(!OpIdxVec0.empty() && "U0 does not use Seed!");
42 BundleTy NextUserBndl;
43 NextUserBndl.push_back(SeedUserInst);
44 Claimed.insert(SeedUserInst);
45 for (Value *V : drop_begin(Bndl)) {
46 Instruction *Match = nullptr;
47 for (User *U : V->users()) {
48 auto *UI = dyn_cast<Instruction>(U);
49 if (!UI || IMaps.isVectorized(UI) || Claimed.contains(UI) ||
50 UI->getOpcode() != SeedUserInst->getOpcode() ||
51 UI->getType() != SeedUserInst->getType() ||
52 UI->getParent() != SeedUserInst->getParent() ||
53 getOperandIndicesInUser(UI, V) != OpIdxVec0)
54 continue;
55
56 Match = UI;
57 break;
58 }
59 if (!Match)
60 return std::nullopt;
61 NextUserBndl.push_back(Match);
62 }
63
64 for (auto *I : NextUserBndl)
65 Claimed.insert(cast<Instruction>(I));
66 return NextUserBndl;
67}
68
73 if (Bndl.empty())
74 return Bundles;
75
76 Value *V0 = Bndl[0];
77 DenseSet<User *> SeenUsers;
78 // For each user U0 of lane 0, try to form a bundle of matching users across
79 // all lanes. Cap the number of users considered to bound compilation time,
80 // since each one may trigger an O(Bndl.size()) search across the other
81 // lanes' users.
82 for (User *U0 : V0->users()) {
83 if (SeenUsers.size() >= MaxUsersToConsider)
84 break;
85 if (!SeenUsers.insert(U0).second)
86 continue;
87 auto *UI0 = dyn_cast<Instruction>(U0);
88 if (!UI0 || IMaps.isVectorized(UI0) || Claimed.contains(UI0))
89 continue;
90 std::optional<BundleTy> NextUserBndl =
91 getMatchingBundle(Bndl, IMaps, V0, UI0, Claimed);
92 if (NextUserBndl)
93 Bundles.emplace_back(std::move(*NextUserBndl));
94 }
95 return Bundles;
96}
97
98unsigned VecUtils::getFloorPowerOf2(unsigned Num) {
99 if (Num == 0)
100 return Num;
101 unsigned Mask = Num;
102 Mask >>= 1;
103 for (unsigned ShiftBy = 1; ShiftBy < sizeof(Num) * 8; ShiftBy <<= 1)
104 Mask |= Mask >> ShiftBy;
105 return Num & ~Mask;
106}
107
108template <typename T>
110 ArrayRef<T *> Bndl) {
111 for (T *V : Bndl) {
112 assert(isa<Instruction>(V) && "Only works with instructions");
113 DeadInstrCandidates.insert(cast<Instruction>(V));
114 }
115 // Also collect the GEPs of vectorized loads and stores.
116 auto Opcode = cast<Instruction>(Bndl[0])->getOpcode();
117 switch (Opcode) {
118 case Instruction::Opcode::Load: {
119 for (T *V : drop_begin(Bndl))
120 if (auto *Ptr =
122 DeadInstrCandidates.insert(Ptr);
123 break;
124 }
125 case Instruction::Opcode::Store: {
126 for (T *V : drop_begin(Bndl))
127 if (auto *Ptr =
129 DeadInstrCandidates.insert(Ptr);
130 break;
131 }
132 default:
133 break;
134 }
135}
136
137template void
140template void
143
145 DenseMap<BasicBlock *, SmallVector<Instruction *>> SortedDeadInstrCandidates;
146 // The dead instrs could span BBs, so we need to collect and sort them per BB.
147 for (auto *V : DeadInstrCandidates) {
148 auto *DeadI = cast<Instruction>(V);
149 SortedDeadInstrCandidates[DeadI->getParent()].push_back(DeadI);
150 }
151 for (auto &Pair : SortedDeadInstrCandidates)
152 sort(Pair.second,
153 [](Instruction *I1, Instruction *I2) { return I1->comesBefore(I2); });
154 for (const auto &Pair : SortedDeadInstrCandidates) {
155 for (Instruction *I : reverse(Pair.second)) {
156 if (I->hasNUses(0)) {
157 // Erase the dead instructions bottom-to-top.
158 LLVM_DEBUG(dbgs() << DEBUG_PREFIX << "Erase dead: " << *I << "\n");
159 I->eraseFromParent();
160 }
161 }
162 }
163 DeadInstrCandidates.clear();
164}
165
166#ifndef NDEBUG
167template <typename T> static void dumpImpl(ArrayRef<T *> Bndl) {
168 for (auto [Idx, V] : enumerate(Bndl))
169 dbgs() << Idx << "." << *V << "\n";
170}
173
174template <typename T> void BndlRef<T>::dump() const {
175 print(dbgs());
176 dbgs() << "\n";
177}
178// Explicit instantiation for commonly used types.
179template class BndlRef<Instruction *>;
180template class BndlRef<Value *>;
181
182#endif // NDEBUG
183
184} // namespace llvm::sandboxir
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the DenseMap class.
#define I(x, y, z)
Definition MD5.cpp:57
#define T
static ManagedStatic< cl::opt< uint64_t >, CreateSeed > Seed
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
#define DEBUG_PREFIX
Definition Debug.h:19
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type size() const
Definition DenseSet.h:84
An ArrayRef of Values or Instructions that we can print/dump for debugging.
Definition VecUtils.h:459
LLVM_DUMP_METHOD void dump() const
Definition VecUtils.cpp:174
Maps the original instructions to the vectorized instrs and the reverse.
Definition InstrMaps.h:50
bool isVectorized(Value *Orig) const
\Returns true if Orig was vectorized
Definition InstrMaps.h:65
A sandboxir::User with operands, opcode and linked with previous/next instructions in an instruction ...
Definition Instruction.h:43
Opcode getOpcode() const
\Returns this Instruction's opcode.
LLVM_ABI BasicBlock * getParent() const
\Returns the BasicBlock containing this Instruction, or null if it is detached.
A sandboxir::User has operands.
Definition User.h:59
A SandboxIR Value has users. This is the base class.
Definition Value.h:72
LLVM_ABI Type * getType() const
Definition Value.cpp:46
iterator_range< user_iterator > users()
Definition Value.h:253
LLVM_ABI void tryEraseDeadInstrs()
Erase candidates recorded by collectPotentiallyDeadInstrs() that now have no uses,...
Definition VecUtils.cpp:144
void collectPotentiallyDeadInstrs(ArrayRef< T * > Bndl)
Record instructions in Bndl that may be dead after vectorization.
Definition VecUtils.cpp:109
static LLVM_DUMP_METHOD void dump(ArrayRef< Value * > Bndl)
Helper dump function for debugging.
Definition VecUtils.cpp:171
static LLVM_ABI unsigned getFloorPowerOf2(unsigned Num)
\Returns the first integer power of 2 that is <= Num.
Definition VecUtils.cpp:98
static LLVM_ABI SmallVector< BundleTy > getNextUserBundles(ArrayRef< Value * > Bndl, const InstrMaps &IMaps, SmallPtrSet< Instruction *, 4 > &Claimed)
For each user of lane 0 in Bndl, try to form a bundle of matching users for all lanes.
Definition VecUtils.cpp:70
initializer< Ty > init(const Ty &Val)
static cl::opt< unsigned > MaxUsersToConsider("sbvec-max-users-to-consider", cl::init(16), cl::Hidden, cl::desc("Limit the number of a seed's users that getNextUserBundles() " "will examine as candidates for a matching bundle, to cap " "compilation time."))
static SmallVector< unsigned, 2 > getOperandIndicesInUser(User *U, Value *Op)
Definition VecUtils.cpp:27
static void dumpImpl(ArrayRef< T * > Bndl)
Definition VecUtils.cpp:167
SmallVector< Value *, 4 > BundleTy
Definition VecUtils.h:39
static std::optional< BundleTy > getMatchingBundle(ArrayRef< Value * > Bndl, const InstrMaps &IMaps, Value *Seed, Instruction *SeedUserInst, SmallPtrSet< Instruction *, 4 > &Claimed)
Definition VecUtils.cpp:36
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
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 * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
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 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
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341