26#define DEBUG_PREFIX_LOCAL DEBUG_PREFIX "LoadStoreVec: "
47void LoadStoreVec::saveIR(Region &R) {
50 CostBefore = SB.getAfterCost() - SB.getBeforeCost();
54bool LoadStoreVec::acceptOrRevert() {
59 <<
" (After=" << CostAfter <<
" Before=" << CostBefore
62 if (CostGain > Opts.sbvec_cost_threshold) {
74 assert(!
ElemTy->isVectorTy() &&
"Expected a scalar element type!");
78template <
typename TypeRangeT>
79bool LoadStoreVec::canUnpack(
FixedVectorType *FromTy, TypeRangeT ToTypes) {
81 return all_of(ToTypes, [
this, VecElemTy](
Type *ToTy) {
93 Value *NewVal =
nullptr;
94 for (
auto It =
V->use_begin(),
E =
V->use_end(); It !=
E;) {
97 if (!ShouldReplace(U))
99 if (NewVal ==
nullptr)
100 NewVal = NewValBuilder();
105void LoadStoreVec::unpackIfNeeded(
LoadInst *VecLoad,
116 auto CreateUnpack = [&, Lane]() ->
Value * {
132 [&SkipUsers](
const Use &U) {
157 Context &Ctx = Ty->getContext();
167SameSizeReinterpret::getCastChain(Type *SrcTy, Type *DestTy,
168 const DataLayout &
DL) {
170 "Cannot reinterpret a non-integral pointer!");
172 "Expected types of the same size!");
177 if (Ty->getScalarType()->isPointerTy()) {
178 Ty = getIntTypeFor(Ty,
DL);
179 Chain.emplace_back(Instruction::Opcode::PtrToInt, Ty);
181 bool DestIsPtr = DestTy->getScalarType()->isPointerTy();
182 Type *BitCastTy = DestIsPtr ? getIntTypeFor(DestTy,
DL) : DestTy;
184 Chain.emplace_back(Instruction::Opcode::BitCast, BitCastTy);
186 Chain.emplace_back(Instruction::Opcode::IntToPtr, DestTy);
189 assert(Chain.size() <= 3 &&
"Unexpected reinterpret cast chain!");
200 for (
auto [
Opc, Ty] : getCastChain(
V->getType(), DestTy,
DL))
210 for (
auto [
Opc, Ty] : getCastChain(
C->getType(), DestTy,
DL)) {
212 case Instruction::Opcode::PtrToInt:
215 case Instruction::Opcode::BitCast:
218 case Instruction::Opcode::IntToPtr:
231 auto *LaneTy = VecTy->getScalarType();
237 "Chain contains a constant which cannot be converted or split");
247 for (
Value *Elm : AggrCOp->operands())
251 ConstantElements.push_back(SeqCOp->getElementAsConstant(ElmIdx));
253 auto *ZeroElm =
Zero->getSequentialElement();
254 for ([[maybe_unused]]
auto Cnt :
256 ConstantElements.push_back(ZeroElm);
259 for ([[maybe_unused]]
auto Cnt :
263 ConstantElements.push_back(Elm);
266 for ([[maybe_unused]]
auto Cnt :
270 ConstantElements.push_back(Elm);
274 for ([[maybe_unused]]
auto Cnt :
278 ConstantElements.push_back(Elm);
283 ConstantElements.push_back(COp);
294 LaneTyConstants.
reserve(ConstantElements.size());
295 for (Constant *
C : ConstantElements) {
297 if (Bits == LaneBits) {
301 LaneTyConstants.push_back(Lane);
302 }
else if (Bits > LaneBits) {
311 Val = CI->getValue();
313 Val = CFP->getValue().bitcastToAPInt();
316 unsigned NumSlices =
Bits / LaneBits;
318 unsigned EndianAwareSlice =
319 DL->isLittleEndian() ? SliceIdx : NumSlices - 1 - SliceIdx;
323 *Ctx, Val.extractBits(LaneBits, EndianAwareSlice * LaneBits));
326 if (SliceC ==
nullptr)
328 LaneTyConstants.push_back(SliceC);
338 if (!canVectorize(Stores))
342 for (
auto *
I : Stores) {
351 return LI && LI->getParent() == BB;
355 if (!AllLoadsInSameBB && !AllConstants)
361 Value *VecOp =
nullptr;
362 SmallVector<Instruction *, 8> Loads;
364 if (AllLoadsInSameBB) {
369 TypeVec.push_back(
Op->getType());
372 std::optional<Type *> LoadsVecTy = canVectorize(Loads);
385 VecOp = createVectorLoad(Loads);
386 assert(VecOp !=
nullptr &&
"Expected vector value!");
387 }
else if (AllConstants) {
392 VecOp = createConstantVector(Constants);
393 if (VecOp ==
nullptr) {
406 if (AllLoadsInSameBB) {
410 DeadInstrMorgue.collectPotentiallyDeadInstrs<
Instruction>(Loads);
412 DeadInstrMorgue.collectPotentiallyDeadInstrs(Stores);
413 DeadInstrMorgue.tryEraseDeadInstrs();
415 return acceptOrRevert();
420 auto VecTy = canVectorize(Loads);
432 auto *
VecLoad = createVectorLoad(Loads);
433 assert(VecLoad !=
nullptr &&
"Expected vector load");
434 unpackIfNeeded(VecLoad, Loads);
436 DeadInstrMorgue.collectPotentiallyDeadInstrs(Loads);
437 DeadInstrMorgue.tryEraseDeadInstrs();
439 if (!acceptOrRevert())
448 Function &
F = *Bndl[0]->getParent()->getParent();
449 DL = &
F.getParent()->getDataLayout();
450 Ctx = &
F.getContext();
453 auto Opc = Bndl[0]->getOpcode();
456 "Expected a homogeneous seed slice!");
460 case Instruction::Opcode::Load:
463 case Instruction::Opcode::Store:
471 F.getParent()->getDataLayout(), A->getTTI(),
472 F.getContext(), IMaps, Dir);
480 case Instruction::Opcode::Load:
481 Changed = vectorizeLoads(Bndl, Rgn) !=
nullptr;
483 case Instruction::Opcode::Store:
484 Changed = vectorizeStores(Bndl, Rgn);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
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
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
InstListType::iterator iterator
Instruction iterators...
This is an important base class in LLVM.
A parsed version of the target data layout string in and methods for querying it.
Class to represent fixed width SIMD vectors.
An instruction for reading from memory.
void reserve(size_type N)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM Value Representation.
Type * getElementType() const
An efficient, type-erasing, non-owning reference to a callable.
An ArrayRef of Values or Instructions that we can print/dump for debugging.
static LLVM_ABI Value * create(Type *DestTy, Opcode Op, Value *Operand, InsertPosition Pos, Context &Ctx, const Twine &Name="")
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty)
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty)
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...
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.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
void save()
Convenience function for getTracker().save()
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Maps the original instructions to the vectorized instrs and the reverse.
A sandboxir::User with operands, opcode and linked with previous/next instructions in an instruction ...
static LLVM_ABI IntegerType * get(Context &C, unsigned NumBits)
Performs the legality analysis and returns a LegalityResult object.
LLVM_ABI const LegalityResult & canVectorizeLSV(BndlRef< Instruction * > Bndl)
Similar to canVectorize() but specific to LoadStoreVec.
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 PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Context & getContext() const
static LLVM_ABI Constant * reinterpretConstant(Constant *C, Type *DestTy, const DataLayout &DL)
Reinterprets constant C as DestTy, e.g., float 1.0 to i32 0x3f800000, or a null pointer to i64 0.
static LLVM_ABI Value * reinterpretValue(Value *V, Type *DestTy, BasicBlock::iterator WhereIt, Context &Ctx, const DataLayout &DL)
Reinterprets V as DestTy, which must have the same size in DL, inserting casts before WhereIt.
static LLVM_ABI bool canReinterpret(Type *SrcTy, Type *DestTy, const DataLayout &DL)
static LLVM_ABI StoreInst * create(Value *V, Value *Ptr, MaybeAlign Align, InsertPosition Pos, bool IsVolatile, Context &Ctx)
Just like llvm::Type these are immutable, unique, never get freed and can only be created via static ...
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isPointerTy() const
True if this is an instance of PointerType.
Represents a Def-use/Use-def edge in SandboxIR.
static unsigned getNumBits(Type *Ty, const DataLayout &DL)
\Returns the number of bits of Ty.
static void propagateMetadataForVectorization(Instruction *I, const ValueRangeT &VL)
A SandboxIR Value has users. This is the base class.
static Instruction * getLowest(ArrayRef< Instruction * > Instrs)
\Returns the instruction in Instrs that is lowest in the BB.
static unsigned getNumLanes(Type *Ty)
\Returns the number of vector lanes of Ty or 1 if not a vector.
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.
static LLVM_DUMP_METHOD void dump(ArrayRef< Value * > Bndl)
Helper dump function for debugging.
static Align getVecAlignment(AlignRangeT AlignRange, TypeRangeT TypeRange)
Given the alignments of the instructions before vectorization, this returns the alignment of the vect...
static Type * getCombinedVectorTypeFor(BndlRef< T * > Bndl, const DataLayout &DL)
\Returns the combined vector type for Bndl, even when the element types differ.
#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 >
static void lazyRAUWIf(Value *V, function_ref< bool(const Use &)> ShouldReplace, function_ref< Value *()> NewValBuilder)
Replaces the uses of V for which ShouldReplace returns true with the value returned by NewValBuilder.
BasicBlock(llvm::BasicBlock *BB, Context &SBCtx)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
static bool isNonIntegralPtr(Type *Ty, const DataLayout &DL)
static Type * getWidenedType(Type *ElemTy, unsigned N)
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.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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...
DWARFExpression::Operation Op
const VectorizeOptions & getVectorizeOptions(const LLVMContext &C)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.