38 #define DEBUG_TYPE "lower-matrix-intrinsics" 45 cl::desc(
"Allow the use of FMAs if available and profitable. This may " 46 "result in different results, due to less rounding error."));
86 unsigned NumRows,
Type *EltType,
89 assert((!isa<ConstantInt>(Stride) ||
90 cast<ConstantInt>(Stride)->getZExtValue() >= NumRows) &&
91 "Stride must be >= the number of rows.");
92 unsigned AS = cast<PointerType>(BasePtr->
getType())->getAddressSpace();
99 if (isa<ConstantInt>(ColumnStart) && cast<ConstantInt>(ColumnStart)->
isZero())
100 ColumnStart = BasePtr;
102 ColumnStart = Builder.
CreateGEP(EltType, BasePtr, ColumnStart,
"col.gep");
133 class LowerMatrixIntrinsics {
140 class ColumnMatrixTy {
144 ColumnMatrixTy() : Columns() {}
146 : Columns(Cols.
begin(), Cols.
end()) {}
148 Value *getColumn(
unsigned i)
const {
return Columns[i]; }
150 void setColumn(
unsigned i,
Value *V) { Columns[i] = V; }
152 size_t getNumColumns()
const {
return Columns.
size(); }
153 size_t getNumRows()
const {
154 assert(Columns.
size() > 0 &&
"Cannot call getNumRows without columns");
155 return cast<VectorType>(Columns[0]->getType())->getNumElements();
171 return Columns.
size() == 1 ? Columns[0]
180 ShapeInfo(
unsigned NumRows = 0,
unsigned NumColumns = 0)
181 : NumRows(NumRows), NumColumns(NumColumns) {}
188 return NumRows == other.NumRows && NumColumns == other.NumColumns;
190 bool operator!=(
const ShapeInfo &other) {
return !(*
this == other); }
194 operator bool()
const {
195 assert(NumRows == 0 || NumColumns != 0);
218 : Func(F), DL(F.
getParent()->getDataLayout()), TTI(TTI) {}
225 ColumnMatrixTy getMatrix(
Value *MatrixVal,
const ShapeInfo &
SI,
228 assert(VType &&
"MatrixVal must be a vector type");
230 "The vector size must match the number of matrix elements");
236 auto Found = Inst2ColumnMatrix.
find(MatrixVal);
237 if (Found != Inst2ColumnMatrix.
end()) {
238 ColumnMatrixTy &M = Found->second;
241 if (SI.NumRows == M.getNumRows() && SI.NumColumns == M.getNumColumns())
244 MatrixVal = M.embedInVector(Builder);
251 MaskStart += SI.NumRows) {
262 bool setShapeInfo(
Value *V, ShapeInfo Shape) {
263 assert(Shape &&
"Shape not set");
264 if (isa<UndefValue>(V) || !supportsShapeInfo(V))
267 auto SIter = ShapeMap.
find(V);
268 if (SIter != ShapeMap.
end()) {
270 << SIter->second.NumRows <<
" " 271 << SIter->second.NumColumns <<
" for " << *V <<
"\n");
275 ShapeMap.
insert({V, Shape});
276 LLVM_DEBUG(
dbgs() <<
" " << Shape.NumRows <<
" x " << Shape.NumColumns
277 <<
" for " << *V <<
"\n");
281 bool isUniformShape(
Value *V) {
287 case Instruction::FAdd:
288 case Instruction::FSub:
289 case Instruction::FMul:
291 case Instruction::Mul:
292 case Instruction::Sub:
301 bool supportsShapeInfo(
Value *V) {
309 case Intrinsic::matrix_multiply:
310 case Intrinsic::matrix_transpose:
311 case Intrinsic::matrix_columnwise_load:
312 case Intrinsic::matrix_columnwise_store:
317 return isUniformShape(V) || isa<StoreInst>(V) || isa<LoadInst>(V);
331 while (!WorkList.
empty()) {
336 bool Propagate =
false;
343 if (
match(Inst, m_Intrinsic<Intrinsic::matrix_multiply>(
346 Propagate = setShapeInfo(Inst, {M, K});
347 }
else if (
match(Inst, m_Intrinsic<Intrinsic::matrix_transpose>(
350 Propagate = setShapeInfo(Inst, {
N, M});
351 }
else if (
match(Inst, m_Intrinsic<Intrinsic::matrix_columnwise_store>(
354 Propagate = setShapeInfo(Inst, {
N, M});
355 }
else if (
match(Inst,
356 m_Intrinsic<Intrinsic::matrix_columnwise_load>(
358 Propagate = setShapeInfo(Inst, {M, N});
360 auto OpShape = ShapeMap.
find(MatrixA);
361 if (OpShape != ShapeMap.
end())
362 setShapeInfo(Inst, OpShape->second);
364 }
else if (isUniformShape(Inst)) {
367 auto OpShape = ShapeMap.
find(
Op.get());
368 if (OpShape != ShapeMap.
end()) {
369 Propagate |= setShapeInfo(Inst, OpShape->second);
392 auto pushInstruction = [](
Value *V,
402 while (!WorkList.
empty()) {
406 size_t BeforeProcessingV = WorkList.
size();
407 if (!isa<Instruction>(V))
415 if (
match(V, m_Intrinsic<Intrinsic::matrix_multiply>(
418 if (setShapeInfo(MatrixA, {M, N}))
419 pushInstruction(MatrixA, WorkList);
421 if (setShapeInfo(MatrixB, {
N, K}))
422 pushInstruction(MatrixB, WorkList);
424 }
else if (
match(V, m_Intrinsic<Intrinsic::matrix_transpose>(
427 if (setShapeInfo(MatrixA, {M, N}))
428 pushInstruction(MatrixA, WorkList);
429 }
else if (
match(V, m_Intrinsic<Intrinsic::matrix_columnwise_store>(
432 if (setShapeInfo(MatrixA, {M, N})) {
433 pushInstruction(MatrixA, WorkList);
435 }
else if (isa<LoadInst>(V) ||
436 match(V, m_Intrinsic<Intrinsic::matrix_columnwise_load>())) {
438 }
else if (isa<StoreInst>(V)) {
441 }
else if (isUniformShape(V)) {
443 ShapeInfo Shape = ShapeMap[V];
444 for (
Use &U : cast<Instruction>(V)->operands()) {
445 if (setShapeInfo(U.get(), Shape))
446 pushInstruction(U.get(), WorkList);
452 for (
size_t I = BeforeProcessingV; I != WorkList.
size(); I++)
454 if (isa<Instruction>(U) && V != U)
455 NewWorkList.
push_back(cast<Instruction>(U));
473 case Intrinsic::matrix_multiply:
474 case Intrinsic::matrix_transpose:
475 case Intrinsic::matrix_columnwise_load:
476 case Intrinsic::matrix_columnwise_store:
484 while (!WorkList.
empty()) {
485 WorkList = propagateShapeForward(WorkList);
486 WorkList = propagateShapeBackward(WorkList);
491 bool Changed =
false;
492 for (
auto *BB : RPOT) {
496 if (
CallInst *CInst = dyn_cast<CallInst>(&Inst))
497 Changed |= VisitCallInst(CInst);
501 if (
auto *BinOp = dyn_cast<BinaryOperator>(&Inst))
502 Changed |= VisitBinaryOperator(BinOp);
504 Changed |= VisitLoad(&Inst, Op1, Builder);
506 Changed |= VisitStore(&Inst, Op1, Op2, Builder);
531 unsigned AS = cast<PointerType>(BasePtr->
getType())->getAddressSpace();
537 bool VisitCallInst(
CallInst *Inst) {
542 case Intrinsic::matrix_multiply:
545 case Intrinsic::matrix_transpose:
546 LowerTranspose(Inst);
548 case Intrinsic::matrix_columnwise_load:
549 LowerColumnwiseLoad(Inst);
551 case Intrinsic::matrix_columnwise_store:
552 LowerColumnwiseStore(Inst);
563 auto VType = cast<VectorType>(Inst->
getType());
565 ColumnMatrixTy Result;
567 for (
unsigned C = 0,
E = Shape.NumColumns;
C <
E; ++
C) {
569 computeColumnAddr(EltPtr, Builder.
getInt32(
C), Stride, Shape.NumRows,
572 Result.addColumn(Column);
575 finalizeLowering(Inst, Result, Builder);
581 void LowerColumnwiseLoad(
CallInst *Inst) {
591 auto VType = cast<VectorType>(Matrix->
getType());
593 auto LM = getMatrix(Matrix, Shape, Builder);
596 computeColumnAddr(EltPtr, Builder.
getInt32(
C.index()), Stride,
607 void LowerColumnwiseStore(
CallInst *Inst) {
619 Value *Col = LM.getColumn(J);
630 unsigned BlockNumElts =
631 cast<VectorType>(Block->
getType())->getNumElements();
632 unsigned NumElts = cast<VectorType>(Col->
getType())->getNumElements();
633 assert(NumElts >= BlockNumElts &&
"Too few elements for current block");
644 for (i = 0; i <
I; i++)
647 unsigned VecNumElts = cast<VectorType>(Col->
getType())->getNumElements();
648 for (; i < I + BlockNumElts; i++)
651 for (; i < VecNumElts; i++)
666 if (AllowContraction) {
670 Func.getParent(), Intrinsic::fmuladd, A->
getType());
686 void finalizeLowering(
Instruction *Inst, ColumnMatrixTy Matrix,
688 Inst2ColumnMatrix.
insert(std::make_pair(Inst, Matrix));
691 Value *Flattened =
nullptr;
696 Flattened = Matrix.embedInVector(Builder);
703 void LowerMultiply(
CallInst *MatMul) {
705 auto *EltType = cast<VectorType>(MatMul->
getType())->getElementType();
709 const ColumnMatrixTy &Lhs =
711 const ColumnMatrixTy &Rhs =
714 const unsigned R = LShape.NumRows;
715 const unsigned M = LShape.NumColumns;
716 const unsigned C = RShape.NumColumns;
717 assert(M == RShape.NumRows);
720 ColumnMatrixTy Result;
721 for (
unsigned J = 0; J <
C; ++J)
733 for (
unsigned J = 0; J <
C; ++J) {
735 for (
unsigned I = 0; I < R; I +=
BlockSize) {
737 while (I + BlockSize > R)
740 Value *Sum =
nullptr;
741 for (
unsigned K = 0; K < M; ++K) {
748 Result.setColumn(J,
insertVector(Result.getColumn(J),
I, Sum, Builder));
751 finalizeLowering(MatMul, Result, Builder);
755 void LowerTranspose(
CallInst *Inst) {
756 ColumnMatrixTy Result;
761 ColumnMatrixTy InputMatrix = getMatrix(InputVal, ArgShape, Builder);
763 for (
unsigned Row = 0; Row < ArgShape.NumRows; ++Row) {
770 for (
auto C :
enumerate(InputMatrix.columns())) {
777 Result.addColumn(ResultColumn);
780 finalizeLowering(Inst, Result, Builder);
785 auto I = ShapeMap.
find(Inst);
786 if (I == ShapeMap.
end())
795 auto I = ShapeMap.
find(StoredVal);
796 if (I == ShapeMap.
end())
805 auto I = ShapeMap.
find(Inst);
806 if (I == ShapeMap.
end())
813 ShapeInfo &Shape = I->second;
815 ColumnMatrixTy LoweredLhs = getMatrix(Lhs, Shape, Builder);
816 ColumnMatrixTy LoweredRhs = getMatrix(Rhs, Shape, Builder);
819 ColumnMatrixTy Result;
820 auto BuildColumnOp = [&Builder, Inst](
Value *LHS,
Value *RHS) {
824 case Instruction::Mul:
826 case Instruction::Sub:
828 case Instruction::FAdd:
830 case Instruction::FMul:
832 case Instruction::FSub:
838 for (
unsigned C = 0; C < Shape.NumColumns; ++
C)
840 BuildColumnOp(LoweredLhs.getColumn(C), LoweredRhs.getColumn(C)));
842 finalizeLowering(Inst, Result, Builder);
851 LowerMatrixIntrinsics LMT(F, TTI);
862 class LowerMatrixIntrinsicsLegacyPass :
public FunctionPass {
872 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
873 LowerMatrixIntrinsics LMT(F, *TTI);
874 bool C = LMT.Visit();
885 static const char pass_name[] =
"Lower the matrix intrinsics";
893 return new LowerMatrixIntrinsicsLegacyPass();
Pass interface - Implemented by all 'passes'.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
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. ...
const_iterator end(StringRef path)
Get end iterator over path.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
BinaryOps getOpcode() const
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, unsigned Align, const char *Name)
Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")' correctly, instead of converting the strin...
void push_back(const T &Elt)
This class represents a function call, abstracting a target machine's calling convention.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Analysis pass providing the TargetTransformInfo.
An instruction for reading from memory.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align, bool isVolatile=false)
bool hasAllowContract() const
Determine whether the allow-contract flag is set.
Value * getArgOperand(unsigned i) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget, SelectionDAG &DAG)
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
INITIALIZE_PASS_BEGIN(LowerMatrixIntrinsicsLegacyPass, DEBUG_TYPE, pass_name, false, false) INITIALIZE_PASS_END(LowerMatrixIntrinsicsLegacyPass
A Use represents the edge between a Value definition and its users.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Constant * createSequentialMask(IRBuilder<> &Builder, unsigned Start, unsigned NumInts, unsigned NumUndefs)
Create a sequential shuffle mask.
Type * getType() const
All values are typed, get the type of this value.
Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
An instruction for storing to memory.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type cast(const Y &Val)
Value * getOperand(unsigned i) const
iterator find(const_arg_type_t< KeyT > Val)
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
A set of analyses that are preserved following a run of a transformation pass.
Value * concatenateVectors(IRBuilder<> &Builder, ArrayRef< Value *> Vecs)
Concatenate a list of vectors.
LLVM Basic Block Representation.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
The instances of the Type class are immutable: once they are created, they are never changed...
TwoOps_match< ValueOpTy, PointerOpTy, Instruction::Store > m_Store(const ValueOpTy &ValueOp, const PointerOpTy &PointerOp)
Matches StoreInst.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Represent the analysis usage information of a pass.
void initializeLowerMatrixIntrinsicsLegacyPassPass(PassRegistry &)
FunctionPass class - This class is used to implement most global optimizations.
static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget, SelectionDAG &DAG)
static cl::opt< bool > AllowContractEnabled("matrix-allow-contract", cl::init(false), cl::Hidden, cl::desc("Allow the use of FMAs if available and profitable. This may " "result in different results, due to less rounding error."))
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
This struct is a compact representation of a valid (non-zero power of two) alignment.
static const int BlockSize
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
This is the shared class of boolean and integer constants.
Align max(MaybeAlign Lhs, Align Rhs)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Value * CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx, const Twine &Name="")
static Value * insertVector(IRBuilderTy &IRB, Value *Old, Value *V, unsigned BeginIndex, const Twine &Name)
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.
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
A range adaptor for a pair of iterators.
Class to represent vector types.
iterator_range< user_iterator > users()
Represents analyses that only rely on functions' control flow.
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
bool operator!=(uint64_t V1, const APInt &V2)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
static cl::opt< bool > EnableShapePropagation("matrix-propagate-shape", cl::init(true))
static const char pass_name[]
LLVM_NODISCARD bool empty() const
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
void preserveSet()
Mark an analysis set as preserved.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
Value * CreateFSub(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
static Value * extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex, unsigned EndIndex, const Twine &Name)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Value * CreateFAdd(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Pass * createLowerMatrixIntrinsicsPass()
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
static const Function * getParent(const Value *V)
Type * getElementType() const
A container for analyses that lazily runs them and caches their results.
bool operator==(uint64_t V1, const APInt &V2)
static Constant * get(ArrayRef< Constant *> V)
detail::enumerator< R > enumerate(R &&TheRange)
Given an input range, returns a new range whose values are are pair (A,B) such that A is the 0-based ...
A wrapper class for inspecting calls to intrinsic functions.