59#define DEBUG_TYPE "lower-matrix-intrinsics"
61STATISTIC(FlattenedMatrices,
"Number of matrix flattenings");
62STATISTIC(ReshapedMatrices,
"Number of matrix reshapes");
81 return SV->isZeroEltSplat();
86template <
typename LTy,
typename RTy>
87static auto m_AnyMul(
const LTy &L,
const RTy &R) {
92template <
typename LTy,
typename RTy>
93static auto m_AnyAdd(
const LTy &L,
const RTy &R) {
138 unsigned NumElements,
Type *EltType,
143 "Stride must be >= the number of elements in the result vector.");
146 Value *VecStart = Builder.CreateMul(VecIdx, Stride,
"vec.start");
153 VecStart = Builder.CreateInBoundsGEP(EltType, BasePtr, VecStart,
"vec.gep");
165 ShapeInfo(
unsigned NumRows = 0,
unsigned NumColumns = 0)
166 : NumRows(NumRows), NumColumns(NumColumns),
167 IsColumnMajor(ScalarOptions::
Global.matrix_default_layout ==
171 : ShapeInfo(
cast<ConstantInt>(NumRows)->getZExtValue(),
172 cast<ConstantInt>(NumColumns)->getZExtValue()) {}
175 return NumRows == other.NumRows && NumColumns == other.NumColumns;
177 bool operator!=(
const ShapeInfo &other) {
return !(*
this == other); }
181 operator bool()
const {
182 assert(NumRows == 0 || NumColumns != 0);
186 unsigned getStride()
const {
192 unsigned getNumVectors()
const {
199 ShapeInfo t()
const {
return ShapeInfo(NumColumns, NumRows); }
201 friend raw_ostream &
operator<<(raw_ostream &OS, ShapeInfo SI);
207 return OS <<
SI.NumRows <<
'x' <<
SI.NumColumns;
224 switch (Cast->getOpcode()) {
225 case llvm::Instruction::Trunc:
226 case llvm::Instruction::ZExt:
227 case llvm::Instruction::SExt:
228 case llvm::Instruction::FPToUI:
229 case llvm::Instruction::FPToSI:
230 case llvm::Instruction::UIToFP:
231 case llvm::Instruction::SIToFP:
232 case llvm::Instruction::FPTrunc:
233 case llvm::Instruction::FPExt:
235 case llvm::Instruction::AddrSpaceCast:
236 case CastInst::PtrToAddr:
237 case CastInst::PtrToInt:
238 case CastInst::IntToPtr:
240 case CastInst::BitCast: {
243 return SrcVTy->getNumElements() == DestVTy->getNumElements();
246 case llvm::Instruction::CastOpsEnd:
253 switch (
II->getIntrinsicID()) {
255 case Intrinsic::fabs:
261 switch (
I->getOpcode()) {
262 case Instruction::PHI:
263 case Instruction::FNeg:
274 "Can't retrieve shaped operands for an instruction that does not "
275 "preserve shape information");
276 auto Ops =
I->operands();
281static std::optional<ShapeInfo>
289 return ShapeInfo(M,
K);
293 return ShapeInfo(
N, M);
298 return ShapeInfo(
N, M);
301 return ShapeInfo(M,
N);
304 auto OpShape = ShapeMap.
find(MatrixA);
305 if (OpShape != ShapeMap.
end())
306 return OpShape->second;
312 for (
auto &
Op : ShapedOps) {
313 auto OpShape = ShapeMap.
find(
Op.get());
314 if (OpShape != ShapeMap.
end())
315 return OpShape->second;
346class LowerMatrixIntrinsics {
347 const ScalarOptions &Opts;
349 const DataLayout &DL;
350 const TargetTransformInfo &TTI;
353 DominatorTree *DT =
nullptr;
354 LoopInfo *LI =
nullptr;
355 OptimizationRemarkEmitter *ORE =
nullptr;
361 unsigned NumStores = 0;
363 unsigned NumLoads = 0;
365 unsigned NumComputeOps = 0;
369 unsigned NumExposedTransposes = 0;
372 NumStores +=
RHS.NumStores;
373 NumLoads +=
RHS.NumLoads;
374 NumComputeOps +=
RHS.NumComputeOps;
375 NumExposedTransposes +=
RHS.NumExposedTransposes;
383 SmallVector<Value *, 16> Vectors;
387 bool IsColumnMajor = ScalarOptions::Global.matrix_default_layout ==
388 MatrixLayoutTy::ColumnMajor;
391 MatrixTy() =
default;
393 MatrixTy(
unsigned NumRows,
unsigned NumColumns,
Type *EltTy) {
395 unsigned D = isColumnMajor() ? NumColumns : NumRows;
396 for (
unsigned J = 0; J <
D; ++J)
398 EltTy, isColumnMajor() ? NumRows : NumColumns)));
401 Value *getVector(
unsigned i)
const {
return Vectors[i]; }
402 Value *getColumn(
unsigned i)
const {
403 assert(isColumnMajor() &&
"only supported for column-major matrixes");
406 Value *getRow(
unsigned i)
const {
407 assert(!isColumnMajor() &&
"only supported for row-major matrixes");
411 void setVector(
unsigned i,
Value *V) { Vectors[i] =
V; }
413 Type *getElementType()
const {
return getVectorTy()->getElementType(); }
415 unsigned getNumVectors()
const {
417 return getNumColumns();
421 unsigned getNumColumns()
const {
423 return Vectors.size();
425 assert(Vectors.size() > 0 &&
"Cannot call getNumRows without columns");
426 return getVectorTy()->getNumElements();
429 unsigned getNumRows()
const {
430 if (isColumnMajor()) {
431 assert(Vectors.size() > 0 &&
"Cannot call getNumRows without columns");
432 return getVectorTy()->getNumElements();
434 return Vectors.size();
437 void addVector(
Value *V) { Vectors.push_back(V); }
438 FixedVectorType *getColumnTy() {
439 assert(isColumnMajor() &&
"only supported for column-major matrixes");
440 return getVectorTy();
443 FixedVectorType *getVectorTy()
const {
447 iterator_range<SmallVector<Value *, 8>::iterator> columns() {
449 "columns() only supported for column-major matrixes");
450 return make_range(Vectors.begin(), Vectors.end());
453 iterator_range<SmallVector<Value *, 8>::iterator>
vectors() {
454 return make_range(Vectors.begin(), Vectors.end());
460 return Vectors.size() == 1 ? Vectors[0]
464 MatrixTy &addNumLoads(
unsigned N) {
465 OpInfo.NumLoads +=
N;
469 void setNumLoads(
unsigned N) { OpInfo.NumLoads =
N; }
471 MatrixTy &addNumStores(
unsigned N) {
472 OpInfo.NumStores +=
N;
476 MatrixTy &addNumExposedTransposes(
unsigned N) {
477 OpInfo.NumExposedTransposes +=
N;
481 MatrixTy &addNumComputeOps(
unsigned N) {
482 OpInfo.NumComputeOps +=
N;
486 unsigned getNumStores()
const {
return OpInfo.NumStores; }
487 unsigned getNumLoads()
const {
return OpInfo.NumLoads; }
488 unsigned getNumComputeOps()
const {
return OpInfo.NumComputeOps; }
490 const OpInfoTy &getOpInfo()
const {
return OpInfo; }
492 bool isColumnMajor()
const {
return IsColumnMajor; }
494 unsigned getStride()
const {
497 return getNumColumns();
500 ShapeInfo shape()
const {
return {getNumRows(), getNumColumns()}; }
507 Value *Vec = isColumnMajor() ? getColumn(J) : getRow(
I);
510 "Extracted vector will contain poison values");
531 DenseMap<Value *, ShapeInfo> ShapeMap;
536 SmallVector<Instruction *, 16> ToRemove;
539 MapVector<Value *, MatrixTy> Inst2ColumnMatrix;
554 LowerMatrixIntrinsics(
Function &
F, TargetTransformInfo &TTI,
556 : Opts(ScalarOptions::
Global), Func(
F), DL(
F.getDataLayout()), TTI(TTI),
559 unsigned getNumOps(
Type *VT) {
566 bool isMinimal()
const {
572 unsigned getNumOps(
Type *ST,
unsigned N) {
573 return std::ceil((
ST->getPrimitiveSizeInBits() *
N).getFixedValue() /
574 double(TTI.getRegisterBitWidth(
588 unsigned getNumNativeVectorOps(
Type *EltType,
unsigned R,
unsigned M,
590 unsigned NumFMAs =
C * getNumOps(EltType, R) *
M;
591 unsigned NumALoads = getNumOps(EltType, R) *
M;
592 unsigned NumBLoads = getNumOps(EltType, M) *
C;
593 unsigned NumStores = getNumOps(EltType, R) *
C;
594 return NumFMAs + NumALoads + NumBLoads + NumStores;
602 MatrixTy getMatrix(
Value *MatrixVal,
const ShapeInfo &SI,
606 "The vector size must match the number of matrix elements");
612 auto Found = Inst2ColumnMatrix.find(MatrixVal);
613 if (Found != Inst2ColumnMatrix.end()) {
614 MatrixTy &
M = Found->second;
617 if (
SI.NumRows ==
M.getNumRows() &&
SI.NumColumns ==
M.getNumColumns())
620 MatrixVal =
M.embedInVector(Builder);
624 SmallVector<Value *, 16> SplitVecs;
626 MaskStart +=
SI.getStride()) {
634 if (Found != Inst2ColumnMatrix.end()) {
637 LLVM_DEBUG(
dbgs() <<
"matrix reshape from " << Found->second.shape()
638 <<
" to " << SI <<
" using at least "
639 << SplitVecs.
size() <<
" shuffles on behalf of:\n"
642 }
else if (!ShapeMap.contains(MatrixVal)) {
645 <<
"splitting a " << SI <<
" matrix with " << SplitVecs.
size()
646 <<
" shuffles beacuse we do not have a shape-aware lowering for "
663 bool setShapeInfo(
Value *V, ShapeInfo Shape) {
664 assert(Shape &&
"Shape not set");
668 auto SIter = ShapeMap.find(V);
669 if (SIter != ShapeMap.end()) {
670 if (Opts.verify_matrix_shapes &&
671 (SIter->second.NumRows != Shape.NumRows ||
672 SIter->second.NumColumns != Shape.NumColumns)) {
673 errs() <<
"Conflicting shapes (" << SIter->second.NumRows <<
"x"
674 << SIter->second.NumColumns <<
" vs " << Shape.NumRows <<
"x"
675 << Shape.NumColumns <<
") for " << *
V <<
"\n";
677 "Matrix shape verification failed, compilation aborted!");
681 << SIter->second.NumRows <<
" "
682 << SIter->second.NumColumns <<
" for " << *V <<
"\n");
686 ShapeMap.insert({
V, Shape});
687 LLVM_DEBUG(
dbgs() <<
" " << Shape.NumRows <<
" x " << Shape.NumColumns
688 <<
" for " << *V <<
"\n");
694 bool supportsShapeInfo(
Value *V) {
701 switch (
II->getIntrinsicID()) {
702 case Intrinsic::matrix_multiply:
703 case Intrinsic::matrix_transpose:
704 case Intrinsic::matrix_column_major_load:
705 case Intrinsic::matrix_column_major_store:
718 propagateShapeForward(SmallVectorImpl<Instruction *> &WorkList) {
724 while (!WorkList.
empty()) {
728 bool Propagate =
false;
730 Propagate = setShapeInfo(Inst, *SI);
734 for (
auto *User : Inst->
users())
735 if (ShapeMap.count(User) == 0)
746 propagateShapeBackward(SmallVectorImpl<Instruction *> &WorkList) {
749 auto pushInstruction = [](
Value *
V,
750 SmallVectorImpl<Instruction *> &WorkList) {
759 while (!WorkList.
empty()) {
762 size_t BeforeProcessingV = WorkList.
size();
774 if (setShapeInfo(MatrixA, {
M,
N}))
775 pushInstruction(MatrixA, WorkList);
777 if (setShapeInfo(MatrixB, {
N,
K}))
778 pushInstruction(MatrixB, WorkList);
783 if (setShapeInfo(MatrixA, {
M,
N}))
784 pushInstruction(MatrixA, WorkList);
788 if (setShapeInfo(MatrixA, {
M,
N})) {
789 pushInstruction(MatrixA, WorkList);
800 ShapeInfo Shape = ShapeMap[
V];
801 for (Use &U : ShapedOps) {
802 if (setShapeInfo(
U.get(), Shape))
803 pushInstruction(
U.get(), WorkList);
809 for (
size_t I = BeforeProcessingV;
I != WorkList.
size();
I++)
810 for (User *U : WorkList[
I]->
users())
821 Value *Op0, ShapeInfo Shape0,
Value *Op1, ShapeInfo Shape1,
822 MatrixBuilder &Builder,
823 function_ref<Instruction *(
Value *, ShapeInfo,
Value *, ShapeInfo)>
826 Op0, Shape0.NumRows, Shape0.NumColumns, Op0->
getName() +
"_t");
829 setShapeInfo(T0, Shape0.t());
831 Op1, Shape1.NumRows, Shape1.NumColumns, Op1->
getName() +
"_t");
832 setShapeInfo(
T1, Shape1.t());
838 void eraseFromParentAndRemoveFromShapeMap(Instruction *Inst) {
839 ShapeMap.erase(Inst);
851 if (
II != BB.
rend() && Inst == &*
II)
853 eraseFromParentAndRemoveFromShapeMap(Inst);
858 void updateShapeAndReplaceAllUsesWith(Instruction &Old,
Value *New) {
862 auto S = ShapeMap.find(&Old);
863 if (S != ShapeMap.end()) {
864 ShapeInfo Shape = S->second;
866 if (supportsShapeInfo(New))
867 ShapeMap.insert({
New, Shape});
880 MatrixBuilder Builder(IB);
883 ConstantInt *
R, *
K, *
C;
892 updateShapeAndReplaceAllUsesWith(
I, TATA);
893 eraseFromParentAndMove(&
I,
II, BB);
894 eraseFromParentAndMove(TA,
II, BB);
901 updateShapeAndReplaceAllUsesWith(
I, TA);
902 eraseFromParentAndMove(&
I,
II, BB);
912 auto NewInst = distributeTransposes(
913 TAMB, {
K,
C}, TAMA, {
R,
K}, Builder,
914 [&](
Value *T0, ShapeInfo Shape0,
Value *
T1, ShapeInfo Shape1) {
917 Shape1.NumColumns,
"mmul");
919 updateShapeAndReplaceAllUsesWith(
I, NewInst);
920 eraseFromParentAndMove(&
I,
II, BB);
921 eraseFromParentAndMove(TA,
II, BB);
935 auto NewInst = distributeTransposes(
936 TAMA, {
R,
C}, TAMB, {
R,
C}, Builder,
937 [&](
Value *T0, ShapeInfo Shape0,
Value *
T1, ShapeInfo Shape1) {
938 bool IsFP =
I.getType()->isFPOrFPVectorTy();
939 auto *
Mul = IsFP ? LocalBuilder.CreateFMul(T0,
T1,
"mmul")
940 : LocalBuilder.CreateMul(T0,
T1,
"mmul");
942 setShapeInfo(Result, Shape0);
945 updateShapeAndReplaceAllUsesWith(
I, NewInst);
946 eraseFromParentAndMove(&
I,
II, BB);
947 eraseFromParentAndMove(TA,
II, BB);
956 auto NewInst = distributeTransposes(
957 TAMA, {
R,
C}, TAMB, {
R,
C}, Builder,
958 [&](
Value *T0, ShapeInfo Shape0,
Value *
T1, ShapeInfo Shape1) {
959 bool IsFP =
I.getType()->isFPOrFPVectorTy();
960 auto *
Add = IsFP ? LocalBuilder.CreateFAdd(T0,
T1,
"madd")
961 : LocalBuilder.CreateAdd(T0,
T1,
"madd");
964 setShapeInfo(Result, Shape0);
967 updateShapeAndReplaceAllUsesWith(
I, NewInst);
968 eraseFromParentAndMove(&
I,
II, BB);
969 eraseFromParentAndMove(TA,
II, BB);
977 bool liftTranspose(Instruction &
I) {
981 eraseFromParentAndRemoveFromShapeMap(&
T);
984 if (
A !=
B &&
B->use_empty())
989 ConstantInt *
R, *
K, *
C;
997 MatrixBuilder Builder(IB);
999 BT, AT,
C->getZExtValue(),
K->getZExtValue(),
R->getZExtValue());
1000 setShapeInfo(M, {
C,
R});
1003 updateShapeAndReplaceAllUsesWith(
I, NewInst);
1004 CleanupBinOp(
I,
A,
B);
1016 auto *
Add = Builder.CreateFAdd(AT,
BT,
"mfadd");
1017 MatrixBuilder MBuilder(Builder);
1018 Instruction *NewInst = MBuilder.CreateMatrixTranspose(
1019 Add,
R->getZExtValue(),
C->getZExtValue(),
"mfadd_t");
1020 updateShapeAndReplaceAllUsesWith(
I, NewInst);
1023 "Shape of new instruction doesn't match original shape.");
1024 CleanupBinOp(
I,
A,
B);
1026 setShapeInfo(AddI, {
R,
C});
1030 "Shape of updated addition doesn't match cached shape.");
1038 bool optimizeTransposes() {
1042 for (BasicBlock &BB :
reverse(Func)) {
1047 if (Instruction *NewInst = sinkTranspose(
I,
II,
Changed))
1054 for (BasicBlock &BB : Func) {
1067 for (BasicBlock &BB : Func)
1068 for (Instruction &Inst : BB) {
1073 switch (
II->getIntrinsicID()) {
1074 case Intrinsic::matrix_multiply:
1075 case Intrinsic::matrix_transpose:
1076 case Intrinsic::matrix_column_major_load:
1077 case Intrinsic::matrix_column_major_store:
1086 if (WorkList.
empty())
1090 ORE = &AM->getResult<OptimizationRemarkEmitterAnalysis>(Func);
1091 AA = &AM->getResult<AAManager>(Func);
1092 DT = &AM->getResult<DominatorTreeAnalysis>(Func);
1093 LI = &AM->getResult<LoopAnalysis>(Func);
1097 while (!WorkList.
empty()) {
1098 WorkList = propagateShapeForward(WorkList);
1099 WorkList = propagateShapeBackward(WorkList);
1104 Changed |= optimizeTransposes();
1105 if (Opts.matrix_print_after_transpose_opt) {
1106 dbgs() <<
"Dump after matrix transpose optimization:\n";
1112 SmallVector<Instruction *, 16> MatrixInsts;
1117 ReversePostOrderTraversal<Function *> RPOT(&Func);
1118 for (
auto *BB : RPOT)
1119 for (Instruction &
I : *BB) {
1122 if (!ShapeMap.contains(&
I))
1130 SmallPtrSet<Instruction *, 16> FusedInsts;
1131 for (CallInst *CI : MaybeFusableInsts)
1135 for (CallInst *CI : MaybeFusableInsts)
1137 LowerMatrixMultiplyFused(CI, FusedInsts, LifetimeEnds);
1143 for (Instruction *Inst : MatrixInsts) {
1144 if (FusedInsts.
count(Inst))
1151 const ShapeInfo &
SI = ShapeMap.at(Inst);
1153 MatrixTy PhiM(
SI.NumRows,
SI.NumColumns, EltTy);
1156 for (
unsigned VI = 0, VE = PhiM.getNumVectors(); VI != VE; ++VI)
1157 PhiM.setVector(VI, Builder.CreatePHI(PhiM.getVectorTy(),
1158 PHI->getNumIncomingValues(),
1160 assert(!Inst2ColumnMatrix.contains(
PHI) &&
"map already contains phi?");
1161 Inst2ColumnMatrix[
PHI] = PhiM;
1165 for (Instruction *Inst : MatrixInsts) {
1166 if (FusedInsts.
count(Inst))
1169 const ShapeInfo &
SI = ShapeMap.at(Inst);
1176 Result = VisitBinaryOperator(BinOp, SI, Builder);
1178 Result = VisitCastInstruction(Cast, SI, Builder);
1180 Result = VisitUnaryOperator(UnOp, SI, Builder);
1182 Result = VisitIntrinsicInst(Intr, SI, Builder);
1194 finalizeLowering(Inst, Result, Builder);
1199 RemarkGenerator RemarkGen(Inst2ColumnMatrix, *ORE, Func);
1200 RemarkGen.emitRemarks();
1212 SmallPtrSet<Instruction *, 16> PoisonedInsts;
1213 for (
auto *Inst :
reverse(ToRemove)) {
1216 PoisonedInsts.
insert(Poisoned);
1220 PoisonedInsts.
erase(Inst);
1222 if (!PoisonedInsts.
empty()) {
1224 dbgs() <<
"Poisoned but present instructions:\n";
1225 for (
auto *
I : PoisonedInsts)
1226 dbgs() << *
I <<
"\n";
1234 MatrixTy VisitIntrinsicInst(IntrinsicInst *Inst,
const ShapeInfo &SI,
1240 case Intrinsic::matrix_multiply:
1241 return LowerMultiply(Inst, Builder);
1242 case Intrinsic::matrix_transpose:
1243 return LowerTranspose(Inst, Builder);
1244 case Intrinsic::matrix_column_major_load:
1245 return LowerColumnMajorLoad(Inst, Builder);
1246 case Intrinsic::matrix_column_major_store:
1247 return LowerColumnMajorStore(Inst, Builder);
1248 case Intrinsic::abs:
1249 case Intrinsic::fabs: {
1251 MatrixTy
M = getMatrix(Inst->
getOperand(0), SI, Builder);
1254 for (
auto *
Vector :
M.vectors()) {
1256 case Intrinsic::abs:
1260 case Intrinsic::fabs:
1269 return Result.addNumComputeOps(getNumOps(
Result.getVectorTy()) *
1276 "only intrinsics supporting shape info should be seen here");
1284 Align getAlignForIndex(
unsigned Idx,
Value *Stride,
Type *ElementTy,
1285 MaybeAlign
A)
const {
1286 Align InitialAlign = DL.getValueOrABITypeAlignment(
A, ElementTy);
1288 return InitialAlign;
1290 TypeSize ElementSizeInBits = DL.getTypeSizeInBits(ElementTy);
1293 ConstStride->getZExtValue() * ElementSizeInBits / 8;
1309 "Attempted to cast non-integral type to integer index");
1314 V->getName() +
".cast");
1319 MatrixTy loadMatrix(
Type *Ty,
Value *Ptr, MaybeAlign MAlign,
Value *Stride,
1320 bool IsVolatile, ShapeInfo Shape,
IRBuilder<> &Builder) {
1324 Value *EltPtr = Ptr;
1326 Stride = castToIndexType(Ptr, Stride, Builder);
1327 for (
unsigned I = 0,
E = Shape.getNumVectors();
I <
E; ++
I) {
1330 Stride, Shape.getStride(), EltTy, Builder);
1332 VecTy,
GEP, getAlignForIndex(
I, Stride, EltTy, MAlign),
1333 IsVolatile,
"col.load");
1337 return Result.addNumLoads(getNumOps(
Result.getVectorTy()) *
1343 MatrixTy loadMatrix(
Value *MatrixPtr, MaybeAlign Align,
bool IsVolatile,
1345 ShapeInfo ResultShape,
Type *EltTy,
1348 Builder.
CreateMul(J, getIndex(MatrixPtr, MatrixShape.getStride())),
I);
1352 ResultShape.NumColumns);
1354 return loadMatrix(TileTy, TileStart, Align,
1355 getIndex(MatrixPtr, MatrixShape.getStride()), IsVolatile,
1356 ResultShape, Builder);
1360 MatrixTy
LowerLoad(Instruction *Inst,
Value *Ptr, MaybeAlign Align,
1361 Value *Stride,
bool IsVolatile, ShapeInfo Shape,
1363 return loadMatrix(Inst->
getType(), Ptr, Align, Stride, IsVolatile, Shape,
1370 MatrixTy LowerColumnMajorLoad(CallInst *Inst,
IRBuilder<> &Builder) {
1371 assert(Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor &&
1372 "Intrinsic only supports column-major layout!");
1377 {Inst->getArgOperand(3), Inst->getArgOperand(4)}, Builder);
1382 void storeMatrix(
const MatrixTy &StoreVal,
Value *MatrixPtr,
1383 MaybeAlign MAlign,
bool IsVolatile, ShapeInfo MatrixShape,
1386 Builder.
CreateMul(J, getIndex(MatrixPtr, MatrixShape.getStride())),
I);
1390 StoreVal.getNumColumns());
1392 storeMatrix(TileTy, StoreVal, TileStart, MAlign,
1393 getIndex(MatrixPtr, MatrixShape.getStride()), IsVolatile,
1399 MatrixTy storeMatrix(
Type *Ty, MatrixTy StoreVal,
Value *Ptr,
1400 MaybeAlign MAlign,
Value *Stride,
bool IsVolatile,
1403 Value *EltPtr = Ptr;
1404 Stride = castToIndexType(Ptr, Stride, Builder);
1405 for (
auto Vec :
enumerate(StoreVal.vectors())) {
1412 getAlignForIndex(Vec.index(), Stride,
1417 return MatrixTy().addNumStores(getNumOps(StoreVal.getVectorTy()) *
1418 StoreVal.getNumVectors());
1423 MaybeAlign
A,
Value *Stride,
bool IsVolatile,
1425 auto StoreVal = getMatrix(
Matrix, Shape, Builder);
1426 return storeMatrix(
Matrix->getType(), StoreVal, Ptr,
A, Stride, IsVolatile,
1433 MatrixTy LowerColumnMajorStore(CallInst *Inst,
IRBuilder<> &Builder) {
1434 assert(Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor &&
1435 "Intrinsic only supports column-major layout!");
1441 {Inst->getArgOperand(4), Inst->getArgOperand(5)},
1450 unsigned BlockNumElts =
1453 assert(NumElts >= BlockNumElts &&
"Too few elements for current block");
1460 SmallVector<int, 16>
Mask;
1462 for (i = 0; i <
I; i++)
1465 unsigned VecNumElts =
1467 for (; i <
I + BlockNumElts; i++)
1468 Mask.push_back(i -
I + VecNumElts);
1470 for (; i < VecNumElts; i++)
1478 unsigned &NumComputeOps) {
1479 NumComputeOps += getNumOps(
A->getType());
1484 if (AllowContraction) {
1490 NumComputeOps += getNumOps(
A->getType());
1495 NumComputeOps += getNumOps(
A->getType());
1505 void finalizeLowering(Instruction *Inst, MatrixTy
Matrix,
1507 auto inserted = Inst2ColumnMatrix.insert(std::make_pair(Inst,
Matrix));
1510 "multiple matrix lowering mapping");
1512 ToRemove.push_back(Inst);
1513 Value *Flattened =
nullptr;
1515 if (ShapeMap.contains(
U.getUser()))
1519 Flattened =
Matrix.embedInVector(Builder);
1522 <<
"flattening a " <<
Matrix.shape() <<
" matrix:\n"
1524 <<
"\nbecause we do not have a shape-aware lowering for its "
1527 FlattenedMatrices++;
1536 void lowerDotProduct(CallInst *MatMul,
1537 SmallPtrSet<Instruction *, 16> &FusedInsts,
1538 FastMathFlags FMF) {
1540 Opts.matrix_default_layout != MatrixLayoutTy::ColumnMajor)
1545 if (LShape.NumRows != 1 || RShape.NumColumns != 1)
1560 auto CanBeFlattened = [](
Value *
Op) {
1575 if (!ShapeMap.contains(
Op))
1576 return InstructionCost::getInvalid();
1584 if (!CanBeFlattened(
Op)) {
1587 for (
unsigned I = 1;
I <
N; ++
I)
1601 return NewCost - OriginalCost;
1609 for (
unsigned I = 1;
I <
N; ++
I)
1620 return TTI.getMemoryOpCost(Instruction::Load, VecTy,
Align(1), 0,
1622 N * TTI.getMemoryOpCost(Instruction::Load, EltTy,
Align(1), 0,
1629 SmallPtrSet<Value *, 4> Seen;
1634 while (!WorkList.
empty()) {
1640 if (OpCost + LHSCost >= LHSCost)
1646 WorkList.
append(
I->op_begin(),
I->op_end());
1650 int AddOpCode = IsIntVec ? Instruction::Add : Instruction::FAdd;
1651 int MulOpCode = IsIntVec ? Instruction::Mul : Instruction::FMul;
1653 TTI.getArithmeticReductionCost(
1655 IsIntVec ? std::nullopt : std::optional(FMF),
CostKind) +
1658 TTI.getArithmeticInstrCost(AddOpCode, ElementType,
CostKind) *
1659 (LShape.NumColumns - 1) +
1660 TTI.getArithmeticInstrCost(MulOpCode, ElementType,
CostKind) *
1661 (LShape.NumColumns);
1662 if ((LHSCost + ReductionCost - SequentialAddCost) >
InstructionCost(0))
1665 FusedInsts.
insert(MatMul);
1667 auto FlattenArg = [&Builder, &FusedInsts, &CanBeFlattened,
1672 if (!CanBeFlattened(
Op))
1676 auto It = ShapeMap.find(
Op);
1677 if (It != ShapeMap.end()) {
1678 It->second = It->second.t();
1692 0, MatLoad->getArgOperand(1),
1694 MatLoad->getParamAlign(0));
1697 Op->replaceAllUsesWith(NewLoad);
1703 Op->replaceAllUsesWith(Arg);
1708 for (
auto *V : ToFlatten)
1732 FusedInsts.insert(MatMul);
1733 ToRemove.push_back(MatMul);
1739 unsigned capBlockSize(
unsigned BlockSize,
unsigned Remainder,
Type *EltType) {
1745 if (TTI.isTypeLegal(VecTy))
1751 Opts.matrix_split_matmul_remainder_over_threshold)
1769 void emitMatrixMultiply(MatrixTy &Result,
const MatrixTy &
A,
1771 bool IsScalarMatrixTransposed, FastMathFlags FMF) {
1772 const unsigned VF = std::max<unsigned>(
1775 Result.getElementType()->getPrimitiveSizeInBits().getFixedValue(),
1777 unsigned R =
Result.getNumRows();
1778 unsigned C =
Result.getNumColumns();
1779 unsigned M =
A.getNumColumns();
1781 bool IsFP =
Result.getElementType()->isFloatingPointTy();
1782 assert(
A.isColumnMajor() ==
B.isColumnMajor() &&
1783 Result.isColumnMajor() ==
A.isColumnMajor() &&
1784 "operands must agree on matrix layout");
1785 unsigned NumComputeOps = 0;
1789 if (
A.isColumnMajor()) {
1793 for (
unsigned J = 0; J <
C; ++J) {
1803 for (
unsigned K = 0;
K <
M; ++
K) {
1806 B.getColumn(IsScalarMatrixTransposed ? K : J),
1807 IsScalarMatrixTransposed ? J : K);
1810 createMulAdd(isSumZero && K == 0 ?
nullptr : Sum, L,
Splat,
1821 for (
unsigned I = 0;
I <
R; ++
I) {
1824 for (
unsigned J = 0; J <
C; J +=
BlockSize) {
1828 Value *Sum =
nullptr;
1829 for (
unsigned K = 0;
K <
M; ++
K) {
1832 A.getVector(IsScalarMatrixTransposed ? K :
I),
1833 IsScalarMatrixTransposed ?
I : K);
1836 createMulAdd(isSumZero && K == 0 ?
nullptr : Sum,
Splat, R,
1844 Result.addNumComputeOps(NumComputeOps);
1850 std::pair<Value *, AllocaInst *>
1851 getNonAliasingPointer(LoadInst *
Load, StoreInst *
Store, CallInst *MatMul) {
1856 if (AA->isNoAlias(LoadLoc, StoreLoc))
1857 return {
Load->getPointerOperand(),
nullptr};
1861 IRBuilder<> AllocaBuilder(&Func.getEntryBlock().front());
1862 if (
Load->getPointerAddressSpace() !=
Store->getPointerAddressSpace()) {
1865 ArrayType::get(VT->getElementType(), VT->getNumElements());
1866 AllocaInst *Alloca =
1867 AllocaBuilder.CreateAlloca(ArrayTy,
Load->getPointerAddressSpace());
1871 Load->getPointerOperand(),
Load->getAlign(),
1873 return {Alloca, Alloca};
1886 DTUpdates.
push_back({DT->Delete, Check0, Succ});
1890 nullptr,
"alias_cont");
1896 nullptr,
"no_alias");
1904 Type *AddrTy = DL.getAddressType(
Store->getPointerOperand()->getType());
1905 Value *StoreBegin =
Store->getPointerOperand();
1907 StoreBegin, ConstantInt::get(AddrTy, StoreLoc.
Size.
getValue()),
1910 Value *LoadBegin =
Load->getPointerOperand();
1912 Builder.
CreateICmpULT(LoadBegin, StoreEnd), Check1, Fusion);
1924 auto *ArrayTy = ArrayType::get(VT->getElementType(), VT->getNumElements());
1925 AllocaInst *Alloca =
1926 AllocaBuilder.CreateAlloca(ArrayTy,
Load->getPointerAddressSpace());
1930 LoadBegin, ConstantInt::get(AddrTy, LoadLoc.
Size.
getValue()),
1944 PHI->addIncoming(
Load->getPointerOperand(), Check1);
1945 PHI->addIncoming(Alloca, Copy);
1948 DTUpdates.
push_back({DT->Insert, Check0, Check1});
1949 DTUpdates.
push_back({DT->Insert, Check0, Fusion});
1951 DTUpdates.
push_back({DT->Insert, Check1, Fusion});
1952 DT->applyUpdates(DTUpdates);
1953 return {
PHI, Alloca};
1956 bool isFusionProfitable(CallInst *MatMul) {
1957 if (Opts.force_fuse_matrix)
1963 const unsigned R = LShape.NumRows;
1964 const unsigned C = RShape.NumColumns;
1965 const unsigned M = LShape.NumColumns;
1968 const unsigned VF = std::max<unsigned>(
1980 if (R <= VF &&
C == 1)
1986 unsigned Op0Regs = (
R + VF - 1) / VF * M;
1987 unsigned Op1Regs = (
M + VF - 1) / VF *
C;
1988 return Op0Regs + Op1Regs >
1989 TTI.getNumberOfRegisters(TTI.getRegisterClassForType(
true));
1992 MatrixTy getZeroMatrix(
Type *EltType,
unsigned R,
unsigned C) {
1995 for (
unsigned I = 0;
I <
C; ++
I)
2000 void createTiledLoops(CallInst *MatMul,
Value *LPtr, ShapeInfo LShape,
2001 Value *RPtr, ShapeInfo RShape, StoreInst *
Store) {
2005 TileInfo TI(LShape.NumRows, RShape.NumColumns, LShape.NumColumns,
2006 Opts.fuse_matrix_tile_size);
2007 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
2013 BasicBlock *InnerBody = TI.CreateTiledLoops(Start,
End, Builder, DTU, *LI);
2016 Opts.fuse_matrix_tile_size);
2017 MatrixTy TileResult;
2022 for (
unsigned I = 0;
I < Opts.fuse_matrix_tile_size;
I++) {
2023 auto *
Phi = Builder.
CreatePHI(TileVecTy, 2,
"result.vec." + Twine(
I));
2025 TI.RowLoop.Header->getSingleSuccessor());
2026 TileResult.addVector(Phi);
2035 loadMatrix(LPtr, {},
false, LShape, TI.RowLoop.Index, TI.KLoop.Index,
2036 {Opts.fuse_matrix_tile_size, Opts.fuse_matrix_tile_size},
2039 loadMatrix(RPtr, {},
false, RShape, TI.KLoop.Index, TI.ColumnLoop.Index,
2040 {Opts.fuse_matrix_tile_size, Opts.fuse_matrix_tile_size},
2042 emitMatrixMultiply(TileResult,
A,
B, Builder,
true,
false,
2046 storeMatrix(TileResult,
Store->getPointerOperand(),
Store->getAlign(),
2047 Store->isVolatile(), {LShape.NumRows, RShape.NumColumns},
2048 TI.RowLoop.Index, TI.ColumnLoop.Index, EltType, Builder);
2050 for (
unsigned I = 0;
I < TileResult.getNumVectors();
I++)
2051 ColumnPhis[
I]->addIncoming(TileResult.getVector(
I), TI.KLoop.Latch);
2057 unsigned InnerLoopUnrollCount =
2058 std::min(10u, LShape.NumColumns / Opts.fuse_matrix_tile_size);
2060 "llvm.loop.unroll.count", InnerLoopUnrollCount);
2063 void emitSIMDTiling(CallInst *MatMul, LoadInst *LoadOp0, LoadInst *LoadOp1,
2065 SmallPtrSetImpl<Instruction *> &FusedInsts) {
2066 assert(Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor &&
2067 "Tiling only supported for column-major matrixes at the moment!");
2068 if (!isFusionProfitable(MatMul))
2074 const unsigned R = LShape.NumRows;
2075 const unsigned C = RShape.NumColumns;
2076 const unsigned M = LShape.NumColumns;
2079 auto [APtr, AAlloca] = getNonAliasingPointer(LoadOp0,
Store, MatMul);
2080 auto [BPtr, BAlloca] = getNonAliasingPointer(LoadOp1,
Store, MatMul);
2085 unsigned NumOps = getNumNativeVectorOps(EltType, R, M,
C);
2086 bool UseLoops = (
NumOps > Opts.fuse_matrix_loops_threshold) &&
2087 R % Opts.fuse_matrix_tile_size == 0 &&
2088 C % Opts.fuse_matrix_tile_size == 0;
2090 createTiledLoops(MatMul, APtr, LShape, BPtr, RShape,
Store);
2093 for (
unsigned J = 0; J <
C; J += Opts.fuse_matrix_tile_size)
2094 for (
unsigned I = 0;
I <
R;
I += Opts.fuse_matrix_tile_size) {
2095 const unsigned TileR = std::min(R -
I, Opts.fuse_matrix_tile_size);
2096 const unsigned TileC = std::min(
C - J, Opts.fuse_matrix_tile_size);
2097 MatrixTy Res = getZeroMatrix(EltType, TileR, TileC);
2099 for (
unsigned K = 0;
K <
M;
K += Opts.fuse_matrix_tile_size) {
2100 const unsigned TileM = std::min(M - K, Opts.fuse_matrix_tile_size);
2103 LShape, getIndex(APtr,
I), getIndex(APtr, K),
2104 {TileR, TileM}, EltType, Builder);
2107 RShape, getIndex(BPtr, K), getIndex(BPtr, J),
2108 {TileM, TileC}, EltType, Builder);
2109 emitMatrixMultiply(Res,
A,
B, Builder,
true,
false,
2112 storeMatrix(Res, CPtr,
Store->getAlign(),
Store->isVolatile(), {R, M},
2113 getIndex(CPtr,
I), getIndex(CPtr, J), EltType, Builder);
2128 FusedInsts.
insert(MatMul);
2129 eraseFromParentAndRemoveFromShapeMap(
Store);
2130 eraseFromParentAndRemoveFromShapeMap(MatMul);
2132 FusedInsts.
insert(LoadOp0);
2133 eraseFromParentAndRemoveFromShapeMap(LoadOp0);
2135 if (LoadOp1 != LoadOp0 && LoadOp1->
use_empty()) {
2136 FusedInsts.
insert(LoadOp1);
2137 eraseFromParentAndRemoveFromShapeMap(LoadOp1);
2146 LowerMatrixMultiplyFused(CallInst *MatMul,
2147 SmallPtrSetImpl<Instruction *> &FusedInsts,
2149 if (!Opts.fuse_matrix || !DT || Opts.fuse_matrix_tile_size == 0)
2152 assert(AA && LI &&
"Analyses should be available");
2159 if (Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor
2167 const unsigned R = LShape.NumRows;
2168 const unsigned M = LShape.NumColumns;
2169 const unsigned C = RShape.NumColumns;
2175 if (Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor) {
2176 MA = getMatrix(
A, ShapeInfo(R, M), Builder);
2177 MB = getMatrix(
T, ShapeInfo(
C, M), Builder);
2180 MA = getMatrix(
T, ShapeInfo(R, M), Builder);
2181 MB = getMatrix(
B, ShapeInfo(
C, M), Builder);
2186 MatrixTy
Result(R,
C, EltType);
2188 emitMatrixMultiply(Result, MA, MB, Builder,
false,
true,
2191 FusedInsts.
insert(MatMul);
2197 Inst2ColumnMatrix[Transpose] = MatrixTy(M,
C, EltType);
2199 finalizeLowering(MatMul, Result, Builder);
2204 Opts.matrix_default_layout != MatrixLayoutTy::ColumnMajor)
2212 if (LoadOp0 && LoadOp1 &&
Store) {
2215 SetVector<Value *> WorkList;
2217 SmallVector<Instruction *> ToHoist;
2218 for (
unsigned I = 0;
I != WorkList.
size(); ++
I) {
2219 Value *Current = WorkList[
I];
2225 if (DT->dominates(CurrI, MatMul))
2227 if (CurrI->mayHaveSideEffects() || CurrI->mayReadFromMemory())
2233 sort(ToHoist, [
this](Instruction *
A, Instruction *
B) {
2234 return DT->dominates(
A,
B);
2236 for (Instruction *
I : ToHoist)
2249 bool FusableOpsInSameBlock = LoadOp0->
getParent() == StoreParent &&
2251 for (
unsigned Idx = 0;
Idx != LifetimeEnds.
size();) {
2252 IntrinsicInst *
End = LifetimeEnds[
Idx];
2256 if (DT->dominates(
End, LoadOp0) && DT->dominates(
End, LoadOp1))
2262 if (FusableOpsInSameBlock &&
End->getParent() != StoreParent)
2270 if (AA->isNoAlias(Load0Loc, EndLoc) && AA->isNoAlias(Load1Loc, EndLoc))
2276 if (
End->getParent() == StoreParent) {
2282 ToRemove.push_back(
End);
2288 emitSIMDTiling(MatMul, LoadOp0, LoadOp1,
Store, FusedInsts);
2294 MatrixTy LowerMultiply(CallInst *MatMul,
IRBuilder<> &Builder) {
2299 const MatrixTy &Lhs = getMatrix(MatMul->
getArgOperand(0), LShape, Builder);
2300 const MatrixTy &Rhs = getMatrix(MatMul->
getArgOperand(1), RShape, Builder);
2301 assert(Lhs.getElementType() == Rhs.getElementType() &&
2302 "Matrix multiply argument element types do not match.");
2304 const unsigned R = LShape.NumRows;
2305 const unsigned C = RShape.NumColumns;
2306 assert(LShape.NumColumns == RShape.NumRows);
2309 MatrixTy
Result(R,
C, EltType);
2310 assert(Lhs.getElementType() ==
Result.getElementType() &&
2311 "Matrix multiply result element type does not match arguments.");
2313 emitMatrixMultiply(Result, Lhs, Rhs, Builder,
false,
false,
2319 MatrixTy LowerTranspose(CallInst *Inst,
IRBuilder<> &Builder) {
2324 MatrixTy InputMatrix = getMatrix(InputVal, ArgShape, Builder);
2326 const unsigned NewNumVecs =
2327 InputMatrix.isColumnMajor() ? ArgShape.NumRows : ArgShape.NumColumns;
2328 const unsigned NewNumElts =
2329 InputMatrix.isColumnMajor() ? ArgShape.NumColumns : ArgShape.NumRows;
2331 for (
unsigned I = 0;
I < NewNumVecs; ++
I) {
2336 for (
auto J :
enumerate(InputMatrix.vectors())) {
2342 Result.addVector(ResultVector);
2348 return Result.addNumComputeOps(2 * ArgShape.NumRows * ArgShape.NumColumns)
2349 .addNumExposedTransposes(1);
2353 MatrixTy VisitLoad(LoadInst *Inst,
const ShapeInfo &SI,
Value *Ptr,
2359 MatrixTy VisitStore(StoreInst *Inst,
const ShapeInfo &SI,
Value *StoredVal,
2366 MatrixTy VisitPHI(PHINode *Inst,
const ShapeInfo &SI,
IRBuilder<> &Builder) {
2367 auto BlockIP = Inst->
getParent()->getFirstInsertionPt();
2369 MatrixTy PhiM = getMatrix(Inst, SI, Builder);
2373 SmallDenseMap<BasicBlock *, MatrixTy> ReshapedIncoming;
2374 for (
auto [IncomingV, IncomingB] :
2381 if (
auto MaybeIP = IncomingInst->getInsertionPointAfterDef())
2386 It->second = getMatrix(IncomingV, SI, Builder);
2387 const MatrixTy &OpM = It->second;
2389 for (
unsigned VI = 0, VE = PhiM.getNumVectors(); VI != VE; ++VI) {
2391 NewPHI->
addIncoming(OpM.getVector(VI), IncomingB);
2402 MatrixTy VisitBinaryOperator(BinaryOperator *Inst,
const ShapeInfo &SI,
2408 MatrixTy
A = getMatrix(Lhs, SI, Builder);
2409 MatrixTy
B = getMatrix(Rhs, SI, Builder);
2410 assert(
A.isColumnMajor() ==
B.isColumnMajor() &&
2411 Result.isColumnMajor() ==
A.isColumnMajor() &&
2412 "operands must agree on matrix layout");
2419 return Result.addNumComputeOps(getNumOps(
Result.getVectorTy()) *
2424 MatrixTy VisitUnaryOperator(UnaryOperator *Inst,
const ShapeInfo &SI,
2429 MatrixTy
M = getMatrix(
Op, SI, Builder);
2434 auto BuildVectorOp = [&Builder, Inst](
Value *
Op) {
2436 case Instruction::FNeg:
2443 for (
auto *
Vector :
M.vectors())
2446 return Result.addNumComputeOps(getNumOps(
Result.getVectorTy()) *
2451 MatrixTy VisitCastInstruction(CastInst *Inst,
const ShapeInfo &Shape,
2456 MatrixTy
M = getMatrix(
Op, Shape, Builder);
2461 auto *NewVTy = VectorType::get(OrigVTy->getElementType(),
2464 for (
auto *
Vector :
M.vectors())
2467 return Result.addNumComputeOps(getNumOps(
Result.getVectorTy()) *
2472 MatrixTy VisitSelectInst(SelectInst *Inst,
const ShapeInfo &Shape,
2479 MatrixTy
A = getMatrix(OpA, Shape, Builder);
2480 MatrixTy
B = getMatrix(OpB, Shape, Builder);
2485 MatrixTy
C = getMatrix(
Cond, Shape, Builder);
2486 llvm::copy(
C.vectors(), std::back_inserter(CondV));
2488 CondV.
resize(
A.getNumVectors());
2496 "If we have a vector conditional, we should be propagating "
2497 "profile information.");
2501 return Result.addNumComputeOps(getNumOps(
Result.getVectorTy()) *
2508 struct ExprLinearizer {
2509 unsigned LengthToBreak = 100;
2511 raw_string_ostream Stream;
2512 unsigned LineLength = 0;
2513 const DataLayout &DL;
2517 const MapVector<Value *, MatrixTy> &Inst2Matrix;
2521 const DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared;
2524 const SmallSetVector<Value *, 32> &ExprsInSubprogram;
2531 SmallPtrSet<Value *, 8> ReusedExprs;
2533 ExprLinearizer(
const DataLayout &DL,
2534 const MapVector<Value *, MatrixTy> &Inst2Matrix,
2535 const DenseMap<
Value *, SmallPtrSet<Value *, 2>> &Shared,
2536 const SmallSetVector<Value *, 32> &ExprsInSubprogram,
2538 : Stream(Str), DL(DL), Inst2Matrix(Inst2Matrix), Shared(Shared),
2539 ExprsInSubprogram(ExprsInSubprogram), Leaf(Leaf) {}
2541 void indent(
unsigned N) {
2543 for (
unsigned i = 0; i <
N; i++)
2552 void maybeIndent(
unsigned Indent) {
2553 if (LineLength >= LengthToBreak)
2556 if (LineLength == 0)
2560 void write(StringRef S) {
2561 LineLength += S.
size();
2565 Value *getUnderlyingObjectThroughLoads(
Value *V) {
2567 return getUnderlyingObjectThroughLoads(Ptr);
2568 else if (
V->getType()->isPointerTy())
2574 bool isMatrix(
Value *V)
const {
return ExprsInSubprogram.count(V); }
2578 void prettyPrintMatrixType(
Value *V, raw_string_ostream &SS) {
2579 auto M = Inst2Matrix.find(V);
2580 if (M == Inst2Matrix.end())
2583 SS <<
M->second.getNumRows();
2585 SS <<
M->second.getNumColumns();
2592 void writeFnName(CallInst *CI) {
2594 write(
"<no called fn>");
2597 if (!
Name.starts_with(
"llvm.matrix")) {
2606 raw_string_ostream
SS(Tmp);
2608 switch (
II->getIntrinsicID()) {
2609 case Intrinsic::matrix_multiply:
2610 prettyPrintMatrixType(
II->getOperand(0), SS);
2612 prettyPrintMatrixType(
II->getOperand(1), SS);
2613 SS <<
"." << *
II->getType()->getScalarType();
2615 case Intrinsic::matrix_transpose:
2616 prettyPrintMatrixType(
II->getOperand(0), SS);
2617 SS <<
"." << *
II->getType()->getScalarType();
2619 case Intrinsic::matrix_column_major_load:
2620 prettyPrintMatrixType(
II, SS);
2621 SS <<
"." << *
II->getType()->getScalarType();
2623 case Intrinsic::matrix_column_major_store:
2624 prettyPrintMatrixType(
II->getOperand(0), SS);
2625 SS <<
"." << *
II->getOperand(0)->getType()->getScalarType();
2634 unsigned getNumShapeArgs(CallInst *CI)
const {
2636 switch (
II->getIntrinsicID()) {
2637 case Intrinsic::matrix_multiply:
2639 case Intrinsic::matrix_transpose:
2641 case Intrinsic::matrix_column_major_load:
2642 case Intrinsic::matrix_column_major_store:
2655 V = getUnderlyingObjectThroughLoads(V);
2656 if (
V->getType()->isPointerTy()) {
2658 Stream <<
"stack addr";
2659 LineLength += StringRef(
"stack addr").size();
2662 LineLength += StringRef(
"addr").size();
2664 if (!
V->getName().empty()) {
2665 Stream <<
" %" <<
V->getName() <<
"";
2666 LineLength +=
V->getName().size() + 2;
2672 raw_string_ostream TmpStream(Tmp);
2675 TmpStream << CI->getValue();
2677 TmpStream <<
"constant";
2680 TmpStream <<
"matrix";
2682 TmpStream <<
"scalar";
2684 Tmp = std::string(StringRef(Tmp).trim());
2685 LineLength += Tmp.size();
2692 void linearizeExpr(
Value *Expr,
unsigned Indent,
bool ParentReused,
2693 bool ParentShared) {
2695 maybeIndent(Indent);
2696 SmallVector<Value *, 8>
Ops;
2699 bool ExprShared =
false;
2702 if (!ParentShared) {
2703 auto SI = Shared.find(Expr);
2704 assert(SI != Shared.end() &&
SI->second.count(Leaf));
2710 write(
"shared with remark at line " + std::to_string(DL.getLine()) +
2711 " column " + std::to_string(DL.getCol()) +
" (");
2713 ExprShared =
SI->second.size() > 1;
2716 bool Reused = !ReusedExprs.insert(Expr).second;
2717 if (Reused && !ParentReused)
2730 Ops.append(
I->value_op_begin(),
I->value_op_end());
2731 write(
I->getOpcodeName());
2736 unsigned NumOpsToBreak = 1;
2741 if (
Ops.size() > NumOpsToBreak)
2744 maybeIndent(Indent + 1);
2746 linearizeExpr(
Op, Indent + 1, Reused, ExprShared);
2749 if (
Op !=
Ops.back())
2756 const std::string &getResult() {
2774 struct RemarkGenerator {
2775 const MapVector<Value *, MatrixTy> &Inst2Matrix;
2776 OptimizationRemarkEmitter &ORE;
2778 const DataLayout &DL;
2780 RemarkGenerator(
const MapVector<Value *, MatrixTy> &Inst2Matrix,
2781 OptimizationRemarkEmitter &ORE,
Function &Func)
2782 : Inst2Matrix(Inst2Matrix), ORE(ORE), Func(Func),
2783 DL(Func.getDataLayout()) {}
2788 SmallVector<Value *, 4>
2789 getExpressionLeaves(
const SmallSetVector<Value *, 32> &ExprsInSubprogram) {
2790 SmallVector<Value *, 4> Leaves;
2791 for (
auto *Expr : ExprsInSubprogram)
2793 !
any_of(Expr->
users(), [&ExprsInSubprogram](User *U) {
2794 return ExprsInSubprogram.count(U);
2803 void collectSharedInfo(
Value *Leaf,
Value *V,
2804 const SmallSetVector<Value *, 32> &ExprsInSubprogram,
2805 DenseMap<
Value *, SmallPtrSet<Value *, 2>> &Shared) {
2807 if (!ExprsInSubprogram.
count(V))
2813 collectSharedInfo(Leaf,
Op, ExprsInSubprogram, Shared);
2819 std::pair<OpInfoTy, OpInfoTy>
2820 sumOpInfos(
Value *Root, SmallPtrSetImpl<Value *> &ReusedExprs,
2821 const SmallSetVector<Value *, 32> &ExprsInSubprogram,
2822 DenseMap<
Value *, SmallPtrSet<Value *, 2>> &Shared)
const {
2823 if (!ExprsInSubprogram.
count(Root))
2827 if (!ReusedExprs.
insert(Root).second)
2830 OpInfoTy SharedCount;
2834 auto CM = Inst2Matrix.find(Root);
2835 if (
I->second.size() == 1)
2836 Count = CM->second.getOpInfo();
2838 SharedCount = CM->second.getOpInfo();
2841 auto C = sumOpInfos(
Op, ReusedExprs, ExprsInSubprogram, Shared);
2843 SharedCount +=
C.second;
2845 return {
Count, SharedCount};
2848 void emitRemarks() {
2855 MapVector<DISubprogram *, SmallVector<Value *, 8>> Subprog2Exprs;
2856 for (
const auto &KV : Inst2Matrix) {
2857 if (Func.getSubprogram()) {
2859 DILocation *
Context =
I->getDebugLoc();
2866 Subprog2Exprs[
nullptr].push_back(KV.first);
2869 for (
auto &KV : Subprog2Exprs) {
2870 SmallSetVector<Value *, 32> ExprsInSubprogram(KV.second.begin(),
2872 auto Leaves = getExpressionLeaves(ExprsInSubprogram);
2874 DenseMap<Value *, SmallPtrSet<Value *, 2>>
Shared;
2875 for (
Value *Leaf : Leaves)
2876 collectSharedInfo(Leaf, Leaf, ExprsInSubprogram, Shared);
2879 for (
auto *L : Leaves) {
2891 SmallPtrSet<Value *, 8> ReusedExprs;
2892 OpInfoTy Counts, SharedCounts;
2893 std::tie(Counts, SharedCounts) =
2894 sumOpInfos(L, ReusedExprs, ExprsInSubprogram, Shared);
2896 OptimizationRemark Rem(
DEBUG_TYPE,
"matrix-lowered", Loc,
2899 Rem <<
"Lowered with ";
2900 Rem <<
ore::NV(
"NumStores", Counts.NumStores) <<
" stores, "
2901 <<
ore::NV(
"NumLoads", Counts.NumLoads) <<
" loads, "
2902 <<
ore::NV(
"NumComputeOps", Counts.NumComputeOps)
2904 <<
ore::NV(
"NumExposedTransposes", Counts.NumExposedTransposes)
2905 <<
" exposed transposes";
2907 if (SharedCounts.NumStores > 0 || SharedCounts.NumLoads > 0 ||
2908 SharedCounts.NumComputeOps > 0) {
2909 Rem <<
",\nadditionally "
2910 <<
ore::NV(
"NumStores", SharedCounts.NumStores) <<
" stores, "
2911 <<
ore::NV(
"NumLoads", SharedCounts.NumLoads) <<
" loads, "
2912 <<
ore::NV(
"NumFPOps", SharedCounts.NumComputeOps)
2914 <<
" are shared with other expressions";
2917 Rem << (
"\n" + linearize(L, Shared, ExprsInSubprogram, DL));
2925 const DenseMap<
Value *, SmallPtrSet<Value *, 2>> &Shared,
2926 const SmallSetVector<Value *, 32> &ExprsInSubprogram,
2927 const DataLayout &DL) {
2928 ExprLinearizer Lin(DL, Inst2Matrix, Shared, ExprsInSubprogram, L);
2929 Lin.linearizeExpr(L, 0,
false,
false);
2930 return Lin.getResult();
2940 LowerMatrixIntrinsics LMT(
F,
TTI, Minimal ?
nullptr : &AM);
2954 static_cast<PassInfoMixin<LowerMatrixIntrinsicsPass> *
>(
this)->
printPipeline(
2955 OS, MapClassName2PassName);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
static Type * getIndexType(Value *In)
hexagon Hexagon specific predictive commoning for HVX vectors
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
static DISubprogram * getSubprogram(DIScope *Scope)
Helper function to either return Scope, if it is a subprogram or the attached subprogram for a local ...
static auto m_AnyAdd(const LTy &L, const RTy &R)
Match any add operation (fp or integer).
static bool isShapePreserving(Value *V)
static auto m_AnyMul(const LTy &L, const RTy &R)
Match any mul operation (fp or integer).
static bool isSplat(Value *V)
Return true if V is a splat of a value (which is used when multiplying a matrix with a scalar).
static std::optional< ShapeInfo > computeShapeInfoForInst(Instruction *I, const DenseMap< Value *, ShapeInfo > &ShapeMap)
Return the ShapeInfo for the result of I, it it can be determined.
static iterator_range< Use * > getShapedOperandsForInst(Instruction *I)
Return an iterator over the operands of I that should share shape information with I.
static Value * computeVectorAddr(Value *BasePtr, Value *VecIdx, Value *Stride, unsigned NumElements, Type *EltType, IRBuilder<> &Builder)
uint64_t IntrinsicInst * II
PowerPC Reduce CR logical Operation
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static unsigned getFastMathFlags(const MachineInstr &I, const SPIRVSubtarget &ST)
static Value * extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex, unsigned EndIndex, const Twine &Name)
static Value * insertVector(IRBuilderTy &IRB, Value *Old, Value *V, unsigned BeginIndex, const Twine &Name)
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static SymbolRef::Type getType(const Symbol *Sym)
static const int BlockSize
static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget, SelectionDAG &DAG)
static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget, SelectionDAG &DAG)
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
iterator begin()
Instruction iterator methods.
const Function * getParent() const
Return the enclosing method, or null if none.
reverse_iterator rbegin()
InstListType::reverse_iterator reverse_iterator
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
BinaryOps getOpcode() const
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Analysis pass which computes a DominatorTree.
static constexpr ElementCount getFixed(ScalarTy MinVal)
void setAllowContract(bool B=true)
bool allowReassoc() const
Flag queries.
bool allowContract() const
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
LLVM_ABI CallInst * CreateLifetimeStart(Value *Ptr)
Create a lifetime.start intrinsic.
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
LLVM_ABI CallInst * CreateLifetimeEnd(Value *Ptr)
Create a lifetime.end intrinsic.
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
CallInst * CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert a memcpy between the specified pointers.
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Value * CreateFAdd(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
LLVM_ABI Value * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
LLVM_ABI Value * CreateAddReduce(Value *Src)
Create a vector int add reduction intrinsic of the source vector.
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended from a 64-bit value.
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
LLVM_ABI Value * CreateFAddReduce(Value *Acc, Value *Src)
Create a sequential vector fadd reduction intrinsic of the source vector.
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
iterator_range< user_iterator > users()
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
user_iterator user_begin()
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
Align getAlign() const
Return the alignment of the access that is being performed.
TypeSize getValue() const
Analysis pass that exposes the LoopInfo for a function.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
CallInst * CreateMatrixTranspose(Value *Matrix, unsigned Rows, unsigned Columns, const Twine &Name="")
Create a llvm.matrix.transpose call, transposing Matrix with Rows rows and Columns columns.
CallInst * CreateMatrixMultiply(Value *LHS, Value *RHS, unsigned LHSRows, unsigned LHSColumns, unsigned RHSColumns, const Twine &Name="")
Create a llvm.matrix.multiply call, multiplying matrixes LHS and RHS.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
const Value * Ptr
The address of the start of the location.
static LLVM_ABI MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
size_type size() const
Determine the number of elements in the SetVector.
void insert_range(Range &&R)
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
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
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
bool isVolatile() const
Return true if this is a store to a volatile memory location.
Represent a constant reference to a string, i.e.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
constexpr size_t size() const
Get the string size.
Analysis pass providing the TargetTransformInfo.
The instances of the Type class are immutable: once they are created, they are never changed.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isVoidTy() const
Return true if this is 'void'.
UnaryOps getOpcode() const
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
TwoOps_match< ValueOpTy, PointerOpTy, Instruction::Store > m_Store(const ValueOpTy &ValueOp, const PointerOpTy &PointerOp)
Matches StoreInst.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
ElementType
The element type of an SRV or UAV resource.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< PhiNode * > Phi
friend class Instruction
Iterator for Instructions in a `BasicBlock.
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
scope_exit(Callable) -> scope_exit< Callable >
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
bool operator!=(uint64_t V1, const APInt &V2)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt & operator+=(DynamicAPInt &A, int64_t B)
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...
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI void addStringMetadataToLoop(Loop *TheLoop, const char *MDString, unsigned V=0)
Set input string into loop metadata by keeping other values intact.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
auto reverse(ContainerTy &&C)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Global
Append to llvm.global_dtors.
@ Mul
Product of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ End
Run the machine verifier once, at the end of the pipeline.
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
LLVM_ABI llvm::SmallVector< int, 16 > createSequentialMask(unsigned Start, unsigned NumInts, unsigned NumUndefs)
Create a sequential shuffle mask.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.