49 #define DEBUG_TYPE "scalarizer" 59 using ScatterMap = std::map<Value *, ValueVector>;
69 Scatterer() =
default;
75 ValueVector *cachePtr =
nullptr);
78 Value *operator[](
unsigned I);
81 unsigned size()
const {
return Size; }
87 ValueVector *CachePtr;
96 FCmpSplitter(
FCmpInst &fci) : FCI(fci) {}
108 struct ICmpSplitter {
109 ICmpSplitter(
ICmpInst &ici) : ICI(ici) {}
121 struct BinarySplitter {
137 uint64_t getElemAlign(
unsigned I) {
138 return MinAlign(VecAlign, I * ElemSize);
145 Type *ElemTy =
nullptr;
148 uint64_t VecAlign = 0;
151 uint64_t ElemSize = 0;
163 bool doInitialization(
Module &M)
override;
177 bool visitPHINode(
PHINode &PHI);
182 static void registerOptions() {
187 &Scalarizer::ScalarizeLoadStore>(
188 "scalarize-load-store",
189 "Allow the scalarizer pass to scalarize loads and store",
false);
195 bool canTransferMetadata(
unsigned Kind);
196 void transferMetadata(
Instruction *Op,
const ValueVector &CV);
201 template<
typename T>
bool splitBinary(
Instruction &,
const T &);
205 ScatterMap Scattered;
207 unsigned ParallelLoopAccessMDKind;
208 bool ScalarizeLoadStore;
216 "Scalarize vector operations",
false,
false)
219 ValueVector *cachePtr)
220 : BB(bb), BBI(bbi), V(v), CachePtr(cachePtr) {
221 Type *Ty = V->getType();
224 Ty = PtrTy->getElementType();
227 Tmp.resize(
Size,
nullptr);
228 else if (CachePtr->empty())
229 CachePtr->resize(
Size,
nullptr);
231 assert(
Size == CachePtr->size() &&
"Inconsistent vector sizes");
235 Value *Scatterer::operator[](
unsigned I) {
236 ValueVector &CV = (CachePtr ? *CachePtr : Tmp);
245 PtrTy->getAddressSpace());
250 V->getName() +
".i" +
Twine(I));
280 bool Scalarizer::doInitialization(
Module &M) {
281 ParallelLoopAccessMDKind =
291 assert(Gathered.empty() && Scattered.empty());
295 bool Done = visit(I);
307 if (
Argument *VArg = dyn_cast<Argument>(V)) {
312 return Scatterer(BB, BB->
begin(), V, &Scattered[V]);
330 void Scalarizer::gather(
Instruction *
Op,
const ValueVector &CV) {
336 transferMetadata(Op, CV);
340 ValueVector &SV = Scattered[
Op];
342 for (
unsigned I = 0,
E = SV.size(); I !=
E; ++
I) {
354 Gathered.
push_back(GatherList::value_type(Op, &SV));
359 bool Scalarizer::canTransferMetadata(
unsigned Tag) {
366 || Tag == ParallelLoopAccessMDKind);
371 void Scalarizer::transferMetadata(
Instruction *Op,
const ValueVector &CV) {
374 for (
unsigned I = 0,
E = CV.size(); I !=
E; ++
I) {
375 if (
Instruction *New = dyn_cast<Instruction>(CV[I])) {
376 for (
const auto &MD : MDs)
377 if (canTransferMetadata(MD.first))
378 New->setMetadata(MD.first, MD.second);
387 bool Scalarizer::getVectorLayout(
Type *Ty,
unsigned Alignment,
395 Layout.ElemTy = Layout.VecTy->getElementType();
401 Layout.VecAlign = Alignment;
410 template<
typename Splitter>
420 assert(Op0.size() == NumElems &&
"Mismatched binary operation");
421 assert(Op1.size() == NumElems &&
"Mismatched binary operation");
423 Res.resize(NumElems);
424 for (
unsigned Elem = 0; Elem < NumElems; ++Elem)
425 Res[Elem] =
Split(Builder, Op0[Elem], Op1[Elem],
444 bool Scalarizer::splitCall(
CallInst &CI) {
460 ValueVector ScalarOperands(NumArgs);
463 Scattered.
resize(NumArgs);
467 for (
unsigned I = 0; I != NumArgs; ++
I) {
470 Scattered[
I] = scatter(&CI, OpI);
471 assert(Scattered[I].
size() == NumElems &&
"mismatched call operands");
473 ScalarOperands[
I] = OpI;
477 ValueVector Res(NumElems);
478 ValueVector ScalarCallOps(NumArgs);
484 for (
unsigned Elem = 0; Elem < NumElems; ++Elem) {
485 ScalarCallOps.clear();
487 for (
unsigned J = 0; J != NumArgs; ++J) {
489 ScalarCallOps.push_back(ScalarOperands[J]);
491 ScalarCallOps.push_back(Scattered[J][Elem]);
494 Res[Elem] = Builder.CreateCall(NewIntrin, ScalarCallOps,
509 Scatterer Op1 = scatter(&SI, SI.
getOperand(1));
510 Scatterer Op2 = scatter(&SI, SI.
getOperand(2));
511 assert(Op1.size() == NumElems &&
"Mismatched select");
512 assert(Op2.size() == NumElems &&
"Mismatched select");
514 Res.resize(NumElems);
517 Scatterer Op0 = scatter(&SI, SI.
getOperand(0));
518 assert(Op0.size() == NumElems &&
"Mismatched select");
519 for (
unsigned I = 0; I < NumElems; ++
I)
524 for (
unsigned I = 0; I < NumElems; ++
I)
532 bool Scalarizer::visitICmpInst(
ICmpInst &ICI) {
533 return splitBinary(ICI, ICmpSplitter(ICI));
536 bool Scalarizer::visitFCmpInst(
FCmpInst &FCI) {
537 return splitBinary(FCI, FCmpSplitter(FCI));
541 return splitBinary(BO, BinarySplitter(BO));
558 Scatterer
Base = scatter(&GEPI, Op0);
562 for (
unsigned I = 0; I < NumIndices; ++
I) {
570 Ops[
I] = scatter(&GEPI, Op);
574 Res.resize(NumElems);
575 for (
unsigned I = 0; I < NumElems; ++
I) {
577 Indices.
resize(NumIndices);
578 for (
unsigned J = 0; J < NumIndices; ++J)
579 Indices[J] = Ops[J][I];
584 NewGEPI->setIsInBounds();
590 bool Scalarizer::visitCastInst(
CastInst &CI) {
597 Scatterer Op0 = scatter(&CI, CI.
getOperand(0));
598 assert(Op0.size() == NumElems &&
"Mismatched cast");
600 Res.resize(NumElems);
601 for (
unsigned I = 0; I < NumElems; ++
I)
608 bool Scalarizer::visitBitCastInst(
BitCastInst &BCI) {
611 if (!DstVT || !SrcVT)
615 unsigned SrcNumElems = SrcVT->getNumElements();
617 Scatterer Op0 = scatter(&BCI, BCI.
getOperand(0));
619 Res.resize(DstNumElems);
621 if (DstNumElems == SrcNumElems) {
622 for (
unsigned I = 0; I < DstNumElems; ++
I)
625 }
else if (DstNumElems > SrcNumElems) {
628 unsigned FanOut = DstNumElems / SrcNumElems;
631 for (
unsigned Op0I = 0; Op0I < SrcNumElems; ++Op0I) {
632 Value *V = Op0[Op0I];
636 while ((VI = dyn_cast<Instruction>(V)) &&
640 Scatterer Mid = scatter(&BCI, V);
641 for (
unsigned MidI = 0; MidI < FanOut; ++MidI)
642 Res[ResI++] = Mid[MidI];
646 unsigned FanIn = SrcNumElems / DstNumElems;
649 for (
unsigned ResI = 0; ResI < DstNumElems; ++ResI) {
651 for (
unsigned MidI = 0; MidI < FanIn; ++MidI)
654 +
".upto" +
Twine(MidI));
669 Scatterer Op0 = scatter(&SVI, SVI.
getOperand(0));
670 Scatterer Op1 = scatter(&SVI, SVI.
getOperand(1));
672 Res.resize(NumElems);
674 for (
unsigned I = 0; I < NumElems; ++
I) {
678 else if (
unsigned(Selector) < Op0.size())
679 Res[I] = Op0[Selector];
681 Res[
I] = Op1[Selector - Op0.size()];
687 bool Scalarizer::visitPHINode(
PHINode &PHI) {
695 Res.resize(NumElems);
698 for (
unsigned I = 0; I < NumElems; ++
I)
702 for (
unsigned I = 0; I < NumOps; ++
I) {
705 for (
unsigned J = 0; J < NumElems; ++J)
706 cast<PHINode>(Res[J])->addIncoming(Op[J], IncomingBlock);
712 bool Scalarizer::visitLoadInst(
LoadInst &LI) {
713 if (!ScalarizeLoadStore)
723 unsigned NumElems = Layout.VecTy->getNumElements();
727 Res.resize(NumElems);
729 for (
unsigned I = 0; I < NumElems; ++
I)
736 bool Scalarizer::visitStoreInst(
StoreInst &SI) {
737 if (!ScalarizeLoadStore)
748 unsigned NumElems = Layout.VecTy->getNumElements();
751 Scatterer Val = scatter(&SI, FullValue);
754 Stores.resize(NumElems);
755 for (
unsigned I = 0; I < NumElems; ++
I) {
756 unsigned Align = Layout.getElemAlign(I);
759 transferMetadata(&SI, Stores);
763 bool Scalarizer::visitCallInst(
CallInst &CI) {
764 return splitCall(CI);
769 bool Scalarizer::finish() {
772 if (Gathered.empty() && Scattered.empty())
774 for (
const auto &GMI : Gathered) {
776 ValueVector &CV = *GMI.second;
785 if (isa<PHINode>(Op))
787 for (
unsigned I = 0; I < Count; ++
I)
801 return new Scalarizer();
void getAllMetadataOtherThanDebugLoc(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
This does the same thing as getAllMetadata, except that it filters out the debug location.
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name="")
Type * getSrcTy() const
Return the source type, as a convenience.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
This class represents an incoming formal argument to a Function.
Base class for instruction visitors.
Compute iterated dominance frontiers using a linear time algorithm.
A Module instance is used to store all the information related to an LLVM module. ...
This class represents a function call, abstracting a target machine's calling convention.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
This instruction constructs a fixed permutation of two input vectors.
An instruction for reading from memory.
bool isVectorTy() const
True if this is an instance of VectorType.
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align, bool isVolatile=false)
iterator begin()
Instruction iterator methods.
unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
This is the base class for all instructions that perform data casts.
LLVMContext & getContext() const
Get the global data context.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
uint64_t getNumElements() const
Type * getSourceElementType() const
unsigned getNumIndices() const
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
This instruction compares its operands according to the predicate given to the constructor.
This class represents a no-op cast from one type to another.
Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
INITIALIZE_PASS_WITH_OPTIONS(Scalarizer, "scalarizer", "Scalarize vector operations", false, false) Scatterer
void takeName(Value *V)
Transfer the name from V to this value.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Value * getOperand(unsigned i) const
Class to represent pointers.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Value * getOperand(unsigned i_nocapture) const
Value * CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
bool isVoidTy() const
Return true if this is 'void'.
const BasicBlock & getEntryBlock() const
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static bool runOnFunction(Function &F, bool PostInlining)
This instruction inserts a single (scalar) element into a VectorType value.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
static Function * getScalarIntrinsicDeclaration(Module *M, Intrinsic::ID ID, VectorType *Ty)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
static bool isTriviallyScalariable(Intrinsic::ID ID)
This instruction compares its operands according to the predicate given to the constructor.
FunctionPass class - This class is used to implement most global optimizations.
Value * getPointerOperand()
self_iterator getIterator()
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static int getMaskValue(const Constant *Mask, unsigned Elt)
Return the shuffle mask value for the specified element of the mask.
ValT getOption() const
Query for a debug option's value.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
This is the shared class of boolean and integer constants.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Module.h This file contains the declarations for the Module class.
Value * CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx, const Twine &Name="")
This file declares helper objects for defining debug options that can be configured via the command l...
void initializeScalarizerPass(PassRegistry &)
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Type * getDestTy() const
Return the destination type, as a convenience.
bool hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, unsigned ScalarOpdIdx)
Identifies if the intrinsic has a scalar operand.
static void registerOption(StringRef ArgStr, StringRef Desc, const ValT &InitValue)
Registers an option with the OptionRegistry singleton.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
void setOperand(unsigned i, Value *Val)
unsigned getVectorNumElements() const
Class to represent vector types.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
void push_back(pointer val)
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
unsigned getNumArgOperands() const
Return the number of call arguments.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LoadInst * CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name)
Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")' correctly, instead of converting the strin...
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
FunctionPass * createScalarizerPass()
static void Split(std::vector< std::string > &V, StringRef S)
Splits a string of comma separated items in to a vector of strings.
VectorType * getType() const
Overload to return most specific vector type.
Value * getPointerOperand()
const BasicBlock * getParent() const
bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.