LLVM 24.0.0git
LoadStoreVec.cpp
Go to the documentation of this file.
1//===- LoadStoreVec.cpp - Vectorizer pass short load-store chains ---------===//
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#include "llvm/ADT/DenseSet.h"
21
22namespace llvm {
23
24extern cl::opt<int> CostThreshold; // Defined in TransactionAcceptOrRevert.cpp
25
26namespace sandboxir {
27
28#define DEBUG_PREFIX_LOCAL DEBUG_PREFIX "LoadStoreVec: "
29
30std::optional<Type *> LoadStoreVec::canVectorize(BndlRef<Instruction *> Bndl) {
31 // Check if in the same BB.
33 return std::nullopt;
34
35 // Check if instructions repeat.
37 return std::nullopt;
38
39 // Check scheduling.
40 if (!Sched->trySchedule(Bndl))
41 return std::nullopt;
42
44}
45
46void LoadStoreVec::saveIR(Region &R) {
47 Rgn = &R;
48 const auto &SB = cast<RegionWithScore>(Rgn)->getScoreboard();
49 CostBefore = SB.getAfterCost() - SB.getBeforeCost();
50 Rgn->getContext().save();
51}
52
53bool LoadStoreVec::acceptOrRevert() {
54 const auto &SB = cast<RegionWithScore>(*Rgn).getScoreboard();
55 InstructionCost CostAfter = SB.getAfterCost() - SB.getBeforeCost();
56 InstructionCost CostGain = CostAfter - CostBefore;
57 LLVM_DEBUG(dbgs() << DEBUG_PREFIX_LOCAL << "CostGain=" << CostGain
58 << " (After=" << CostAfter << " Before=" << CostBefore
59 << ")\n");
60 if (CostGain > CostThreshold) {
61 LLVM_DEBUG(dbgs() << DEBUG_PREFIX_LOCAL << "Not profitable, reverting.\n");
62 Ctx->revert();
63 return false;
64 }
65 LLVM_DEBUG(dbgs() << DEBUG_PREFIX_LOCAL << "Profitable accepting.\n");
66 Ctx->accept();
67 return true;
68}
69
70LoadInst *LoadStoreVec::createVectorLoad(BndlRef<Instruction *> Loads) {
72 Loads, A->getScalarEvolution(), *DL))
73 return nullptr;
74 if (!canVectorize(Loads))
75 return nullptr;
76
78 Value *LdPtr = cast<LoadInst>(Loads[0])->getPointerOperand();
79 // TODO: Compute alignment.
80 Align LdAlign(1);
81 auto LdWhereIt = std::next(VecUtils::getLowest(Loads)->getIterator());
82 return LoadInst::create(Ty, LdPtr, LdAlign, LdWhereIt, *Ctx, "VecIinitL");
83}
84
85Constant *LoadStoreVec::createConstantVector(BndlRef<Constant *> Operands) {
87 Constants.reserve(Operands.size());
88 for (Constant *COp : Operands) {
89 if (auto *AggrCOp = dyn_cast<ConstantAggregate>(COp)) {
90 // If the operand is a constant aggregate, then append all its elements.
91 for (Value *Elm : AggrCOp->operands())
92 Constants.push_back(cast<Constant>(Elm));
93 } else if (auto *SeqCOp = dyn_cast<ConstantDataSequential>(COp)) {
94 for (auto ElmIdx : seq<unsigned>(SeqCOp->getNumElements()))
95 Constants.push_back(SeqCOp->getElementAsConstant(ElmIdx));
96 } else if (auto *Zero = dyn_cast<ConstantAggregateZero>(COp)) {
97 auto *ZeroElm = Zero->getSequentialElement();
98 for ([[maybe_unused]] auto Cnt :
99 seq<unsigned>(Zero->getElementCount().getFixedValue()))
100 Constants.push_back(ZeroElm);
101 } else if (isa<ConstantInt>(COp) && isa<VectorType>(COp->getType())) {
102 auto *Elm = ConstantInt::get(*Ctx, cast<ConstantInt>(COp)->getValue());
103 for ([[maybe_unused]] auto Cnt :
104 seq<unsigned>(cast<VectorType>(COp->getType())
105 ->getElementCount()
106 .getFixedValue()))
107 Constants.push_back(Elm);
108 } else if (isa<ConstantFP>(COp) && isa<VectorType>(COp->getType())) {
109 auto *Elm = ConstantFP::get(cast<ConstantFP>(COp)->getValue(), *Ctx);
110 for ([[maybe_unused]] auto Cnt :
111 seq<unsigned>(cast<VectorType>(COp->getType())
112 ->getElementCount()
113 .getFixedValue()))
114 Constants.push_back(Elm);
115 } else {
116 Constants.push_back(COp);
117 }
118 }
119 return ConstantVector::get(Constants);
120}
121
122bool LoadStoreVec::vectorizeStores(BndlRef<Instruction *> Stores, Region &Rgn) {
124 Stores, A->getScalarEvolution(), *DL))
125 return false;
126 if (!canVectorize(Stores))
127 return false;
128 SmallVector<Value *, 4> Operands;
129 Operands.reserve(Stores.size());
130 for (auto *I : Stores) {
131 auto *Op = cast<StoreInst>(I)->getValueOperand();
132 Operands.push_back(Op);
133 }
134 BasicBlock *BB = Stores[0]->getParent();
135 // TODO: For now we only support load operands.
136 // TODO: For now we don't cross BBs.
137 // TODO: For now don't vectorize if the loads have external uses.
138 bool AllLoads = all_of(Operands, [BB](Value *V) {
139 auto *LI = dyn_cast<LoadInst>(V);
140 if (LI == nullptr)
141 return false;
142 // TODO: For now we don't cross BBs.
143 if (LI->getParent() != BB)
144 return false;
145 if (LI->hasNUsesOrMore(2))
146 return false;
147 return true;
148 });
149 bool AllConstants =
150 all_of(Operands, [](Value *V) { return isa<Constant>(V); });
151 if (!AllLoads && !AllConstants)
152 return false;
153
154 // Vectorizing mixed floats and integers with external uses may not be
155 // profitable on some targets, so save state here.
156 saveIR(Rgn);
157 Value *VecOp = nullptr;
158 SmallVector<Instruction *, 8> Loads;
159 if (AllLoads) {
160 Loads.reserve(Operands.size());
161 for (Value *Op : Operands)
162 Loads.push_back(cast<Instruction>(Op));
163 VecOp = createVectorLoad(Loads);
164 if (VecOp == nullptr) {
165 Ctx->accept();
166 return false;
167 }
168 } else if (AllConstants) {
170 Constants.reserve(Operands.size());
171 for (Value *Op : Operands)
172 Constants.push_back(cast<Constant>(Op));
173 VecOp = createConstantVector(Constants);
174 }
175
176 // Generate vector store.
177 Value *StPtr = cast<StoreInst>(Stores[0])->getPointerOperand();
178 // TODO: Compute alignment.
179 Align StAlign(1);
180 auto StWhereIt = std::next(VecUtils::getLowest(Stores)->getIterator());
181 StoreInst::create(VecOp, StPtr, StAlign, StWhereIt, *Ctx);
182
183 DeadInstrMorgue.collectPotentiallyDeadInstrs(Stores);
184 if (AllLoads)
185 DeadInstrMorgue.collectPotentiallyDeadInstrs<Instruction>(Loads);
186 DeadInstrMorgue.tryEraseDeadInstrs();
187
188 return acceptOrRevert();
189}
190
191LoadInst *LoadStoreVec::vectorizeLoads(BndlRef<Instruction *> Loads,
192 Region &Rgn) {
194 Loads, A->getScalarEvolution(), *DL))
195 return nullptr;
196 auto VecTy = canVectorize(Loads);
197 if (!VecTy)
198 return nullptr;
199
200 // TODO: Support mixed-type top-level load chains.
201 Type *VecElemTy = cast<FixedVectorType>(*VecTy)->getElementType();
202 if (!all_of(Loads, [VecElemTy](Instruction *I) {
203 return VecUtils::getElementType(I->getType()) == VecElemTy;
204 }))
205 return nullptr;
206
207 saveIR(Rgn);
208
209 auto *VecLoad = createVectorLoad(Loads);
210 if (VecLoad == nullptr) {
211 Ctx->accept();
212 return nullptr;
213 }
214
215 BasicBlock::iterator WhereIt = std::next(VecLoad->getIterator());
216 for (auto [Lane, OrigV] : VecUtils::enumerateLanes(Loads)) {
217 auto *OrigLoad = cast<LoadInst>(OrigV);
218 if (OrigLoad->hasNUses(0))
219 continue;
220 Value *Unpacked =
221 VecUtils::unpack(VecLoad, OrigLoad->getType(), Lane, WhereIt);
222 OrigLoad->replaceAllUsesWith(Unpacked);
223 }
224
225 DeadInstrMorgue.collectPotentiallyDeadInstrs(Loads);
226 DeadInstrMorgue.tryEraseDeadInstrs();
227
228 if (!acceptOrRevert())
229 return nullptr;
230 return VecLoad;
231}
232
233bool LoadStoreVec::runOnRegion(Region &Rgn, const Analyses &RegionAnalyses) {
234 SmallVector<Instruction *, 8> Bndl(Rgn.getAux().begin(), Rgn.getAux().end());
235 if (Bndl.size() < 2)
236 return false;
237 Function &F = *Bndl[0]->getParent()->getParent();
238 DL = &F.getParent()->getDataLayout();
239 Ctx = &F.getContext();
240 A = &RegionAnalyses;
241 Sched =
242 std::make_unique<Scheduler>(A->getAA(), *Ctx, SchedDirection::BottomUp);
243
244 auto Opc = Bndl[0]->getOpcode();
245 assert(
246 all_of(Bndl, [Opc](Instruction *I) { return I->getOpcode() == Opc; }) &&
247 "Expected a homogeneous seed slice!");
248
249 bool Changed = false;
250 switch (Opc) {
251 case Instruction::Opcode::Load:
252 Changed = vectorizeLoads(Bndl, Rgn) != nullptr;
253 break;
254 case Instruction::Opcode::Store:
255 Changed = vectorizeStores(Bndl, Rgn);
256 break;
257 default:
258 llvm_unreachable("Expected Load or Store");
259 }
260 Sched.reset();
261 return Changed;
262}
263
264} // namespace sandboxir
265
266} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the DenseSet and SmallDenseSet classes.
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
static constexpr Value * getValue(Ty &ValueOrUse)
#define DEBUG_PREFIX_LOCAL
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
SI Fold Operands
#define LLVM_DEBUG(...)
Definition Debug.h:119
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An ArrayRef of Values or Instructions that we can print/dump for debugging.
Definition VecUtils.h:39
static LLVM_ABI Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
Definition Constant.cpp:90
static LLVM_ABI Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition Constant.cpp:48
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
Definition Constant.cpp:176
A sandboxir::User with operands, opcode and linked with previous/next instructions in an instruction ...
Definition Instruction.h:43
static bool areUnique(BndlRef< ValueT * > Values)
Definition Legality.h:358
static bool differentBlock(BndlRef< ValueT * > Instrs)
Definition Legality.h:350
static LLVM_ABI LoadInst * create(Type *Ty, Value *Ptr, MaybeAlign Align, InsertPosition Pos, bool IsVolatile, Context &Ctx, const Twine &Name="")
bool runOnRegion(Region &Rgn, const Analyses &A) final
\Returns true if it modifies R.
static LLVM_ABI StoreInst * create(Value *V, Value *Ptr, MaybeAlign Align, InsertPosition Pos, bool IsVolatile, Context &Ctx)
static Instruction * getLowest(ArrayRef< Instruction * > Instrs)
\Returns the instruction in Instrs that is lowest in the BB.
Definition VecUtils.h:195
static Value * unpack(Value *FromVec, Type *ExtrTy, unsigned Lane, BasicBlock::iterator WhereIt)
Emits the necessary instruction sequence to extract element of type ExtrTy at Lane from FromVec.
Definition VecUtils.h:373
static auto enumerateLanes(const ValueContainerT &Range)
Helper for creating LaneValueEnumerator ranges.
Definition VecUtils.h:491
static bool areConsecutive(LoadOrStoreT *I1, LoadOrStoreT *I2, ScalarEvolution &SE, const DataLayout &DL)
\Returns true if I1 and I2 are load/stores accessing consecutive memory addresses.
Definition VecUtils.h:101
static Type * getElementType(Type *Ty)
Returns Ty if scalar or its element type if vector.
Definition VecUtils.h:94
static Type * getCombinedVectorTypeFor(BndlRef< T * > Bndl, const DataLayout &DL)
\Returns the combined vector type for Bndl, even when the element types differ.
Definition VecUtils.h:169
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
BndlRef(const T &OneElt) -> BndlRef< T >
BasicBlock(llvm::BasicBlock *BB, Context &SBCtx)
Definition BasicBlock.h:75
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
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
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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
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
static cl::opt< unsigned > CostThreshold("dfa-cost-threshold", cl::desc("Maximum cost accepted for the transformation"), cl::Hidden, cl::init(50))