LLVM 24.0.0git
LowerMatrixIntrinsics.cpp
Go to the documentation of this file.
1//===- LowerMatrixIntrinsics.cpp - Lower matrix intrinsics -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Lower matrix intrinsics to vector operations.
10//
11// TODO:
12// * Improve fusion:
13// * Support more cases, e.g. multiply-add, multiply-sub, operands/results
14// transposed.
15// * Improve cost-modeling, e.g. choose different number of rows/columns
16// columns for tiles, consider cost of copies on alias.
17//
18//===----------------------------------------------------------------------===//
19
21#include "ScalarOptions.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/ScopeExit.h"
26#include "llvm/ADT/Statistic.h"
34#include "llvm/IR/CFG.h"
35#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/Function.h"
39#include "llvm/IR/IRBuilder.h"
40#include "llvm/IR/InstrTypes.h"
49#include "llvm/Support/Debug.h"
53
54#include <cmath>
55
56using namespace llvm;
57using namespace PatternMatch;
58
59#define DEBUG_TYPE "lower-matrix-intrinsics"
60
61STATISTIC(FlattenedMatrices, "Number of matrix flattenings");
62STATISTIC(ReshapedMatrices, "Number of matrix reshapes");
63STATISTIC(SplitMatrices, "Number of matrix splits");
64
65namespace llvm {
67} // end namespace llvm
68
69/// Helper function to either return Scope, if it is a subprogram or the
70/// attached subprogram for a local scope.
72 if (auto *Subprogram = dyn_cast<DISubprogram>(Scope))
73 return Subprogram;
74 return cast<DILocalScope>(Scope)->getSubprogram();
75}
76
77/// Return true if V is a splat of a value (which is used when multiplying a
78/// matrix with a scalar).
79static bool isSplat(Value *V) {
80 if (auto *SV = dyn_cast<ShuffleVectorInst>(V))
81 return SV->isZeroEltSplat();
82 return false;
83}
84
85/// Match any mul operation (fp or integer).
86template <typename LTy, typename RTy>
87static auto m_AnyMul(const LTy &L, const RTy &R) {
88 return m_CombineOr(m_Mul(L, R), m_FMul(L, R));
89}
90
91/// Match any add operation (fp or integer).
92template <typename LTy, typename RTy>
93static auto m_AnyAdd(const LTy &L, const RTy &R) {
94 return m_CombineOr(m_Add(L, R), m_FAdd(L, R));
95}
96
97// Given an element pointer \p BasePtr to the start of a (sub) matrix, compute
98// the start address of vector \p VecIdx with type (\p EltType x \p NumElements)
99// assuming \p Stride elements between start two consecutive vectors.
100// \p Stride must be >= \p NumElements.
101// For column-major matrixes, the function computes the address of a column
102// vectors and \p NumElements must be set to the number of elements in a column
103// (= number of rows of the matrix). For row-major matrixes, the function
104// computes the address of a row vector and \p NumElements must be set to the
105// number of elements in a column (= number of columns of the matrix).
106//
107// Consider a 4x4 matrix in column-mjaor layout like below
108//
109// 0 1 2 3
110// 0 v_0_0 v_0_1 v_0_2 v_0_3
111// 1 v_1_0 v_1_1 v_1_2 v_1_3
112// 2 v_2_0 v_2_1 v_2_2 v_2_3
113// 3 v_3_0 v_3_1 v_3_2 v_3_3
114
115// To compute the column addresses for a 2x3 sub-matrix at row 1 and column 1,
116// we need a pointer to the first element of the submatrix as base pointer.
117// Then we can use computeVectorAddr to compute the addresses for the columns
118// of the sub-matrix.
119//
120// Column 0: computeVectorAddr(Base, 0 (column), 4 (stride), 2 (num rows), ..)
121// -> just returns Base
122// Column 1: computeVectorAddr(Base, 1 (column), 4 (stride), 2 (num rows), ..)
123// -> returns Base + (1 * 4)
124// Column 2: computeVectorAddr(Base, 2 (column), 4 (stride), 2 (num rows), ..)
125// -> returns Base + (2 * 4)
126//
127// The graphic below illustrates the number of elements in a column (marked
128// with |) and the number of skipped elements (marked with }).
129//
130// v_0_0 v_0_1 {v_0_2 {v_0_3
131// Base Col 1 Col 2
132// | | |
133// v_1_0 |v_1_1 |v_1_2 |v_1_3
134// v_2_0 |v_2_1 |v_2_2 |v_2_3
135// v_3_0 {v_3_1 {v_3_2 v_3_3
136//
137static Value *computeVectorAddr(Value *BasePtr, Value *VecIdx, Value *Stride,
138 unsigned NumElements, Type *EltType,
139 IRBuilder<> &Builder) {
140
141 assert((!isa<ConstantInt>(Stride) ||
142 cast<ConstantInt>(Stride)->getZExtValue() >= NumElements) &&
143 "Stride must be >= the number of elements in the result vector.");
144
145 // Compute the start of the vector with index VecIdx as VecIdx * Stride.
146 Value *VecStart = Builder.CreateMul(VecIdx, Stride, "vec.start");
147
148 // Get pointer to the start of the selected vector. Skip GEP creation,
149 // if we select vector 0.
150 if (isa<ConstantInt>(VecStart) && cast<ConstantInt>(VecStart)->isZero())
151 VecStart = BasePtr;
152 else
153 VecStart = Builder.CreateInBoundsGEP(EltType, BasePtr, VecStart, "vec.gep");
154
155 return VecStart;
156}
157
158namespace {
159struct ShapeInfo {
160 unsigned NumRows;
161 unsigned NumColumns;
162
163 ShapeInfo(unsigned NumRows = 0, unsigned NumColumns = 0)
164 : NumRows(NumRows), NumColumns(NumColumns) {}
165
166 ShapeInfo(Value *NumRows, Value *NumColumns)
167 : ShapeInfo(cast<ConstantInt>(NumRows)->getZExtValue(),
168 cast<ConstantInt>(NumColumns)->getZExtValue()) {}
169
170 bool operator==(const ShapeInfo &other) {
171 return NumRows == other.NumRows && NumColumns == other.NumColumns;
172 }
173 bool operator!=(const ShapeInfo &other) { return !(*this == other); }
174
175 /// Returns true if shape-information is defined, meaning both dimensions
176 /// are != 0.
177 operator bool() const {
178 assert(NumRows == 0 || NumColumns != 0);
179 return NumRows != 0;
180 }
181
182 /// Returns the transposed shape.
183 ShapeInfo t() const { return ShapeInfo(NumColumns, NumRows); }
184
185 friend raw_ostream &operator<<(raw_ostream &OS, ShapeInfo SI);
186
187 LLVM_DUMP_METHOD void dump() const { dbgs() << *this << '\n'; }
188};
189
190raw_ostream &operator<<(raw_ostream &OS, ShapeInfo SI) {
191 return OS << SI.NumRows << 'x' << SI.NumColumns;
192}
193
194} // namespace
195
196static bool isShapePreserving(Value *V) {
198 if (!I)
199 return true;
200
201 if (isa<SelectInst>(I))
202 return true;
203
204 if (I->isBinaryOp())
205 return true;
206
207 if (auto *Cast = dyn_cast<CastInst>(V)) {
208 switch (Cast->getOpcode()) {
209 case llvm::Instruction::Trunc:
210 case llvm::Instruction::ZExt:
211 case llvm::Instruction::SExt:
212 case llvm::Instruction::FPToUI:
213 case llvm::Instruction::FPToSI:
214 case llvm::Instruction::UIToFP:
215 case llvm::Instruction::SIToFP:
216 case llvm::Instruction::FPTrunc:
217 case llvm::Instruction::FPExt:
218 return true;
219 case llvm::Instruction::AddrSpaceCast:
220 case CastInst::PtrToAddr:
221 case CastInst::PtrToInt:
222 case CastInst::IntToPtr:
223 return false;
224 case CastInst::BitCast: {
225 if (auto *SrcVTy = dyn_cast<FixedVectorType>(Cast->getSrcTy()))
226 if (auto *DestVTy = dyn_cast<FixedVectorType>(Cast->getDestTy()))
227 return SrcVTy->getNumElements() == DestVTy->getNumElements();
228 return false;
229 }
230 case llvm::Instruction::CastOpsEnd:
231 llvm_unreachable("not an actual cast op");
232 }
233 llvm_unreachable("unhandled cast opcode");
234 }
235
236 if (auto *II = dyn_cast<IntrinsicInst>(V))
237 switch (II->getIntrinsicID()) {
238 case Intrinsic::abs:
239 case Intrinsic::fabs:
240 return true;
241 default:
242 return false;
243 }
244
245 switch (I->getOpcode()) {
246 case Instruction::PHI:
247 case Instruction::FNeg:
248 return true;
249 default:
250 return false;
251 }
252}
253
254/// Return an iterator over the operands of \p I that should share shape
255/// information with \p I.
258 "Can't retrieve shaped operands for an instruction that does not "
259 "preserve shape information");
260 auto Ops = I->operands();
261 return isa<SelectInst>(I) ? drop_begin(Ops) : Ops;
262}
263
264/// Return the ShapeInfo for the result of \p I, it it can be determined.
265static std::optional<ShapeInfo>
267 const DenseMap<Value *, ShapeInfo> &ShapeMap) {
268 Value *M;
269 Value *N;
270 Value *K;
272 m_Value(), m_Value(), m_Value(M), m_Value(N), m_Value(K))))
273 return ShapeInfo(M, K);
275 m_Value(N)))) {
276 // Flip dimensions.
277 return ShapeInfo(N, M);
278 }
280 m_Value(), m_Value(), m_Value(), m_Value(), m_Value(M),
281 m_Value(N))))
282 return ShapeInfo(N, M);
284 m_Value(), m_Value(), m_Value(), m_Value(M), m_Value(N))))
285 return ShapeInfo(M, N);
286 Value *MatrixA;
287 if (match(I, m_Store(m_Value(MatrixA), m_Value()))) {
288 auto OpShape = ShapeMap.find(MatrixA);
289 if (OpShape != ShapeMap.end())
290 return OpShape->second;
291 }
292
293 if (isShapePreserving(I)) {
294 auto ShapedOps = getShapedOperandsForInst(I);
295 // Find the first operand that has a known shape and use that.
296 for (auto &Op : ShapedOps) {
297 auto OpShape = ShapeMap.find(Op.get());
298 if (OpShape != ShapeMap.end())
299 return OpShape->second;
300 }
301 }
302 return std::nullopt;
303}
304
305namespace {
306
307/// LowerMatrixIntrinsics contains the methods used to lower matrix intrinsics.
308///
309/// Currently, the lowering for each matrix intrinsic is done as follows:
310/// 1. Propagate the shape information from intrinsics to connected
311/// instructions.
312/// 2. Lower instructions with shape information (assuming column-major layout).
313/// The lowering works similarly using row-major layout.
314/// 2.1. Get column vectors for each argument. If we already lowered the
315/// definition of an argument, use the produced column vectors directly.
316/// If not, split the operand vector containing an embedded matrix into
317/// a set of column vectors,
318/// 2.2. Lower the instruction in terms of column major operations, which
319/// yields a set of column vectors containing result matrix. Note that we
320/// lower all instructions that have shape information. Besides the
321/// intrinsics, this includes stores for example.
322/// 2.3. Update uses of the lowered instruction. If we have shape information
323/// for a user, there is nothing to do, as we will look up the result
324/// column matrix when lowering the user. For other uses, we embed the
325/// result matrix in a flat vector and update the use.
326/// 2.4. Cache the result column matrix for the instruction we lowered
327/// 3. After we lowered all instructions in a function, remove the now
328/// obsolete instructions.
329///
330class LowerMatrixIntrinsics {
331 const ScalarOptions &Opts;
332 Function &Func;
333 const DataLayout &DL;
334 const TargetTransformInfo &TTI;
336 AliasAnalysis *AA = nullptr;
337 DominatorTree *DT = nullptr;
338 LoopInfo *LI = nullptr;
339 OptimizationRemarkEmitter *ORE = nullptr;
340
341 /// Contains estimates of the number of operations (loads, stores, compute)
342 /// required to lower a matrix operation.
343 struct OpInfoTy {
344 /// Number of stores emitted to generate this matrix.
345 unsigned NumStores = 0;
346 /// Number of loads emitted to generate this matrix.
347 unsigned NumLoads = 0;
348 /// Number of compute operations emitted to generate this matrix.
349 unsigned NumComputeOps = 0;
350 /// Most of the time transposes can be fused with matrix multiplies or can
351 /// be folded away via algebraic simplifications. This is the number of
352 /// transposes that we failed to make "free" via such optimizations.
353 unsigned NumExposedTransposes = 0;
354
355 OpInfoTy &operator+=(const OpInfoTy &RHS) {
356 NumStores += RHS.NumStores;
357 NumLoads += RHS.NumLoads;
358 NumComputeOps += RHS.NumComputeOps;
359 NumExposedTransposes += RHS.NumExposedTransposes;
360 return *this;
361 }
362 };
363
364 /// Wrapper class representing a matrix as a set of vectors, either in row or
365 /// column major layout. All vectors must have the same vector type.
366 class MatrixTy {
367 SmallVector<Value *, 16> Vectors;
368
369 OpInfoTy OpInfo;
370
371 bool IsColumnMajor = true;
372
373 public:
374 MatrixTy() = default;
375 explicit MatrixTy(bool IsColumnMajor) : IsColumnMajor(IsColumnMajor) {}
376 MatrixTy(bool IsColumnMajor, ArrayRef<Value *> Vectors)
377 : Vectors(Vectors), IsColumnMajor(IsColumnMajor) {}
378 MatrixTy(bool IsColumnMajor, unsigned NumRows, unsigned NumColumns,
379 Type *EltTy)
380 : IsColumnMajor(IsColumnMajor) {
381
382 unsigned D = isColumnMajor() ? NumColumns : NumRows;
383 for (unsigned J = 0; J < D; ++J)
385 EltTy, isColumnMajor() ? NumRows : NumColumns)));
386 }
387
388 Value *getVector(unsigned i) const { return Vectors[i]; }
389 Value *getColumn(unsigned i) const {
390 assert(isColumnMajor() && "only supported for column-major matrixes");
391 return Vectors[i];
392 }
393 Value *getRow(unsigned i) const {
394 assert(!isColumnMajor() && "only supported for row-major matrixes");
395 return Vectors[i];
396 }
397
398 void setVector(unsigned i, Value *V) { Vectors[i] = V; }
399
400 Type *getElementType() const { return getVectorTy()->getElementType(); }
401
402 unsigned getNumVectors() const {
403 if (isColumnMajor())
404 return getNumColumns();
405 return getNumRows();
406 }
407
408 unsigned getNumColumns() const {
409 if (isColumnMajor())
410 return Vectors.size();
411 else {
412 assert(Vectors.size() > 0 && "Cannot call getNumRows without columns");
413 return getVectorTy()->getNumElements();
414 }
415 }
416 unsigned getNumRows() const {
417 if (isColumnMajor()) {
418 assert(Vectors.size() > 0 && "Cannot call getNumRows without columns");
419 return getVectorTy()->getNumElements();
420 } else
421 return Vectors.size();
422 }
423
424 void addVector(Value *V) { Vectors.push_back(V); }
425 FixedVectorType *getColumnTy() {
426 assert(isColumnMajor() && "only supported for column-major matrixes");
427 return getVectorTy();
428 }
429
430 FixedVectorType *getVectorTy() const {
431 return cast<FixedVectorType>(Vectors[0]->getType());
432 }
433
434 iterator_range<SmallVector<Value *, 8>::iterator> columns() {
435 assert(isColumnMajor() &&
436 "columns() only supported for column-major matrixes");
437 return make_range(Vectors.begin(), Vectors.end());
438 }
439
440 iterator_range<SmallVector<Value *, 8>::iterator> vectors() {
441 return make_range(Vectors.begin(), Vectors.end());
442 }
443
444 /// Embed the vectors of the matrix into a flat vector by concatenating
445 /// them.
446 Value *embedInVector(IRBuilder<> &Builder) const {
447 return Vectors.size() == 1 ? Vectors[0]
448 : concatenateVectors(Builder, Vectors);
449 }
450
451 MatrixTy &addNumLoads(unsigned N) {
452 OpInfo.NumLoads += N;
453 return *this;
454 }
455
456 void setNumLoads(unsigned N) { OpInfo.NumLoads = N; }
457
458 MatrixTy &addNumStores(unsigned N) {
459 OpInfo.NumStores += N;
460 return *this;
461 }
462
463 MatrixTy &addNumExposedTransposes(unsigned N) {
464 OpInfo.NumExposedTransposes += N;
465 return *this;
466 }
467
468 MatrixTy &addNumComputeOps(unsigned N) {
469 OpInfo.NumComputeOps += N;
470 return *this;
471 }
472
473 unsigned getNumStores() const { return OpInfo.NumStores; }
474 unsigned getNumLoads() const { return OpInfo.NumLoads; }
475 unsigned getNumComputeOps() const { return OpInfo.NumComputeOps; }
476
477 const OpInfoTy &getOpInfo() const { return OpInfo; }
478
479 bool isColumnMajor() const { return IsColumnMajor; }
480
481 unsigned getStride() const {
482 if (isColumnMajor())
483 return getNumRows();
484 return getNumColumns();
485 }
486
487 ShapeInfo shape() const { return {getNumRows(), getNumColumns()}; }
488
489 /// Extract a vector of \p NumElts starting at index (\p I, \p J). If the
490 /// matrix is column-major, the result vector is extracted from a column
491 /// vector, otherwise from a row vector.
492 Value *extractVector(unsigned I, unsigned J, unsigned NumElts,
493 IRBuilder<> &Builder) const {
494 Value *Vec = isColumnMajor() ? getColumn(J) : getRow(I);
495 assert(cast<FixedVectorType>(Vec->getType())->getNumElements() >=
496 NumElts &&
497 "Extracted vector will contain poison values");
498 return Builder.CreateShuffleVector(
499 Vec, createSequentialMask(isColumnMajor() ? I : J, NumElts, 0),
500 "block");
501 }
502 };
503
504 /// Maps instructions to their shape information. The shape information
505 /// describes the shape to be used while lowering. This matches the shape of
506 /// the result value of the instruction, with the only exceptions being store
507 /// instructions and the matrix_column_major_store intrinsics. For those, the
508 /// shape information indicates that those instructions should be lowered
509 /// using shape information as well. Note that extra care is needed when
510 /// erasing or RAUW'ing a value that is present in ShapeMap. If the
511 /// replacement is also a matrix operation, use
512 /// updateShapeAndReplaceAllUsesWith to make sure the replacement is added to
513 /// ShapeMap. We don't use ValueMap, as there are also cases where we do not
514 /// want to add shape information for a replacement instruction. When directly
515 /// erasing a value with an entry in ShapeMap, use
516 /// eraseFromParentAndRemoveFromShapeMap to make sure ShapeMap is also updated
517 /// accordingly.
518 DenseMap<Value *, ShapeInfo> ShapeMap;
519
520 /// List of instructions to remove. While lowering, we are not replacing all
521 /// users of a lowered instruction, if shape information is available and
522 /// those need to be removed after we finished lowering.
523 SmallVector<Instruction *, 16> ToRemove;
524
525 /// Map from instructions to their produced column matrix.
526 MapVector<Value *, MatrixTy> Inst2ColumnMatrix;
527
528private:
529 FastMathFlags getFastMathFlags(Instruction *Inst) const {
530 FastMathFlags FMF;
531
532 if (isa<FPMathOperator>(*Inst))
533 FMF = Inst->getFastMathFlags();
534
535 FMF.setAllowContract(Opts.matrix_allow_contract || FMF.allowContract());
536
537 return FMF;
538 }
539
540 bool isColumnMajor() const {
541 return Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor;
542 }
543
544 unsigned getStride(const ShapeInfo &SI) const {
545 return isColumnMajor() ? SI.NumRows : SI.NumColumns;
546 }
547
548 unsigned getNumVectors(const ShapeInfo &SI) const {
549 return isColumnMajor() ? SI.NumColumns : SI.NumRows;
550 }
551
552public:
553 LowerMatrixIntrinsics(const ScalarOptions &Opts, Function &F,
554 TargetTransformInfo &TTI, FunctionAnalysisManager *AM)
555 : Opts(Opts), Func(F), DL(F.getDataLayout()), TTI(TTI), AM(AM) {}
556
557 unsigned getNumOps(Type *VT) {
558 assert(isa<FixedVectorType>(VT) && "Expected vector type");
559 return getNumOps(VT->getScalarType(),
560 cast<FixedVectorType>(VT)->getNumElements());
561 }
562
563 /// Is this the minimal version executed in the backend pipelines.
564 bool isMinimal() const {
565 return !DT;
566 }
567
568 /// Return the estimated number of vector ops required for an operation on
569 /// \p VT * N.
570 unsigned getNumOps(Type *ST, unsigned N) {
571 return std::ceil((ST->getPrimitiveSizeInBits() * N).getFixedValue() /
572 double(TTI.getRegisterBitWidth(
574 .getFixedValue()));
575 }
576
577 /// Estimate the number of native vector operations for a multiply of matrices
578 /// with dimensions \p R x \p M and \p M x \p C. Native ops are computed as
579 /// ceil(ElementCount * ElementBits / RegisterBits).
580 ///
581 /// Native vector ops per operation type (VF = native vector elements):
582 /// FMAs: C * ceil(R/VF) * M (one FMA per VF output elements)
583 /// A loads: ceil(R/VF) * M (A has M columns, ceil(R/VF) native loads each)
584 /// B loads: ceil(M/VF) * C (B has C columns, ceil(M/VF) native loads each)
585 /// Stores: C * ceil(R/VF) (one store per VF output elements)
586 unsigned getNumNativeVectorOps(Type *EltType, unsigned R, unsigned M,
587 unsigned C) {
588 unsigned NumFMAs = C * getNumOps(EltType, R) * M;
589 unsigned NumALoads = getNumOps(EltType, R) * M;
590 unsigned NumBLoads = getNumOps(EltType, M) * C;
591 unsigned NumStores = getNumOps(EltType, R) * C;
592 return NumFMAs + NumALoads + NumBLoads + NumStores;
593 }
594
595 /// Return the set of vectors that a matrix value is lowered to.
596 ///
597 /// If we lowered \p MatrixVal, just return the cache result matrix. Otherwise
598 /// split the flat vector \p MatrixVal containing a matrix with shape \p SI
599 /// into vectors.
600 MatrixTy getMatrix(Value *MatrixVal, const ShapeInfo &SI,
601 IRBuilder<> &Builder) {
602 FixedVectorType *VType = cast<FixedVectorType>(MatrixVal->getType());
603 assert(VType->getNumElements() == SI.NumRows * SI.NumColumns &&
604 "The vector size must match the number of matrix elements");
605
606 // Check if we lowered MatrixVal using shape information. In that case,
607 // return the existing matrix, if it matches the requested shape
608 // information. If there is a mis-match, embed the result in a flat
609 // vector and split it later.
610 auto Found = Inst2ColumnMatrix.find(MatrixVal);
611 if (Found != Inst2ColumnMatrix.end()) {
612 MatrixTy &M = Found->second;
613 // Return the found matrix, if its shape matches the requested shape
614 // information
615 if (SI.NumRows == M.getNumRows() && SI.NumColumns == M.getNumColumns())
616 return M;
617
618 MatrixVal = M.embedInVector(Builder);
619 }
620
621 // Otherwise split MatrixVal.
622 SmallVector<Value *, 16> SplitVecs;
623 for (unsigned MaskStart = 0; MaskStart < VType->getNumElements();
624 MaskStart += getStride(SI)) {
625 Value *V = Builder.CreateShuffleVector(
626 MatrixVal, createSequentialMask(MaskStart, getStride(SI), 0),
627 "split");
628 SplitVecs.push_back(V);
629 }
630
631 if (Instruction *Inst = dyn_cast<Instruction>(MatrixVal)) {
632 if (Found != Inst2ColumnMatrix.end()) {
633 // FIXME: re: "at least": SplitVecs.size() doesn't count the shuffles
634 // that embedInVector created.
635 LLVM_DEBUG(dbgs() << "matrix reshape from " << Found->second.shape()
636 << " to " << SI << " using at least "
637 << SplitVecs.size() << " shuffles on behalf of:\n"
638 << *Inst << '\n');
639 ReshapedMatrices++;
640 } else if (!ShapeMap.contains(MatrixVal)) {
642 dbgs()
643 << "splitting a " << SI << " matrix with " << SplitVecs.size()
644 << " shuffles beacuse we do not have a shape-aware lowering for "
645 "its def:\n"
646 << *Inst << '\n');
647 (void)Inst;
648 SplitMatrices++;
649 } else {
650 // The ShapeMap has it, so it's a case where we're being lowered
651 // before the def, and we expect that InstCombine will clean things up
652 // afterward.
653 }
654 }
655
656 return {isColumnMajor(), SplitVecs};
657 }
658
659 /// If \p V already has a known shape return false. Otherwise set the shape
660 /// for instructions that support it.
661 bool setShapeInfo(Value *V, ShapeInfo Shape) {
662 assert(Shape && "Shape not set");
663 if (isa<UndefValue>(V) || !supportsShapeInfo(V))
664 return false;
665
666 auto SIter = ShapeMap.find(V);
667 if (SIter != ShapeMap.end()) {
668 if (Opts.verify_matrix_shapes &&
669 (SIter->second.NumRows != Shape.NumRows ||
670 SIter->second.NumColumns != Shape.NumColumns)) {
671 errs() << "Conflicting shapes (" << SIter->second.NumRows << "x"
672 << SIter->second.NumColumns << " vs " << Shape.NumRows << "x"
673 << Shape.NumColumns << ") for " << *V << "\n";
675 "Matrix shape verification failed, compilation aborted!");
676 }
677
678 LLVM_DEBUG(dbgs() << " not overriding existing shape: "
679 << SIter->second.NumRows << " "
680 << SIter->second.NumColumns << " for " << *V << "\n");
681 return false;
682 }
683
684 ShapeMap.insert({V, Shape});
685 LLVM_DEBUG(dbgs() << " " << Shape.NumRows << " x " << Shape.NumColumns
686 << " for " << *V << "\n");
687 return true;
688 }
689
690 /// Returns true if shape information can be used for \p V. The supported
691 /// instructions must match the instructions that can be lowered by this pass.
692 bool supportsShapeInfo(Value *V) {
694 if (!Inst)
695 return false;
696
697 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
698 if (II)
699 switch (II->getIntrinsicID()) {
700 case Intrinsic::matrix_multiply:
701 case Intrinsic::matrix_transpose:
702 case Intrinsic::matrix_column_major_load:
703 case Intrinsic::matrix_column_major_store:
704 return true;
705 default:
706 break;
707 }
708 return isShapePreserving(V) || isa<StoreInst>(V) || isa<LoadInst>(V);
709 }
710
711 /// Propagate the shape information of instructions to their users.
712 /// The work list contains instructions for which we can compute the shape,
713 /// either based on the information provided by matrix intrinsics or known
714 /// shapes of operands.
716 propagateShapeForward(SmallVectorImpl<Instruction *> &WorkList) {
718 // Pop an element for which we guaranteed to have at least one of the
719 // operand shapes. Add the shape for this and then add users to the work
720 // list.
721 LLVM_DEBUG(dbgs() << "Forward-propagate shapes:\n");
722 while (!WorkList.empty()) {
723 Instruction *Inst = WorkList.pop_back_val();
724
725 // New entry, set the value and insert operands
726 bool Propagate = false;
727 if (auto SI = computeShapeInfoForInst(Inst, ShapeMap))
728 Propagate = setShapeInfo(Inst, *SI);
729
730 if (Propagate) {
731 NewWorkList.push_back(Inst);
732 for (auto *User : Inst->users())
733 if (ShapeMap.count(User) == 0)
734 WorkList.push_back(cast<Instruction>(User));
735 }
736 }
737
738 return NewWorkList;
739 }
740
741 /// Propagate the shape to operands of instructions with shape information.
742 /// \p Worklist contains the instruction for which we already know the shape.
744 propagateShapeBackward(SmallVectorImpl<Instruction *> &WorkList) {
746
747 auto pushInstruction = [](Value *V,
748 SmallVectorImpl<Instruction *> &WorkList) {
750 if (I)
751 WorkList.push_back(I);
752 };
753 // Pop an element with known shape. Traverse the operands, if their shape
754 // derives from the result shape and is unknown, add it and add them to the
755 // worklist.
756 LLVM_DEBUG(dbgs() << "Backward-propagate shapes:\n");
757 while (!WorkList.empty()) {
758 Value *V = WorkList.pop_back_val();
759
760 size_t BeforeProcessingV = WorkList.size();
761 if (!isa<Instruction>(V))
762 continue;
763
764 Value *MatrixA;
765 Value *MatrixB;
766 Value *M;
767 Value *N;
768 Value *K;
770 m_Value(MatrixA), m_Value(MatrixB), m_Value(M),
771 m_Value(N), m_Value(K)))) {
772 if (setShapeInfo(MatrixA, {M, N}))
773 pushInstruction(MatrixA, WorkList);
774
775 if (setShapeInfo(MatrixB, {N, K}))
776 pushInstruction(MatrixB, WorkList);
777
779 m_Value(MatrixA), m_Value(M), m_Value(N)))) {
780 // Flip dimensions.
781 if (setShapeInfo(MatrixA, {M, N}))
782 pushInstruction(MatrixA, WorkList);
784 m_Value(MatrixA), m_Value(), m_Value(), m_Value(),
785 m_Value(M), m_Value(N)))) {
786 if (setShapeInfo(MatrixA, {M, N})) {
787 pushInstruction(MatrixA, WorkList);
788 }
789 } else if (isa<LoadInst>(V) ||
791 // Nothing to do, no matrix input.
792 } else if (isa<StoreInst>(V)) {
793 // Nothing to do. We forward-propagated to this so we would just
794 // backward propagate to an instruction with an already known shape.
795 } else if (isShapePreserving(V)) {
796 auto ShapedOps = getShapedOperandsForInst(cast<Instruction>(V));
797 // Propagate to all operands.
798 ShapeInfo Shape = ShapeMap[V];
799 for (Use &U : ShapedOps) {
800 if (setShapeInfo(U.get(), Shape))
801 pushInstruction(U.get(), WorkList);
802 }
803 }
804 // After we discovered new shape info for new instructions in the
805 // worklist, we use their users as seeds for the next round of forward
806 // propagation.
807 for (size_t I = BeforeProcessingV; I != WorkList.size(); I++)
808 for (User *U : WorkList[I]->users())
809 if (isa<Instruction>(U) && V != U)
810 NewWorkList.push_back(cast<Instruction>(U));
811 }
812 return NewWorkList;
813 }
814
815 /// (Op0 op Op1)^T -> Op0^T op Op1^T
816 /// Transpose \p Op0 and \p Op1 of shape \p Shape0 and \p Shape1, then use
817 /// them on both sides of \p Operation.
818 Instruction *distributeTransposes(
819 Value *Op0, ShapeInfo Shape0, Value *Op1, ShapeInfo Shape1,
820 MatrixBuilder &Builder,
821 function_ref<Instruction *(Value *, ShapeInfo, Value *, ShapeInfo)>
822 Operation) {
823 Value *T0 = Builder.CreateMatrixTranspose(
824 Op0, Shape0.NumRows, Shape0.NumColumns, Op0->getName() + "_t");
825 // We are being run after shape prop, add shape for newly created
826 // instructions so that we lower them later.
827 setShapeInfo(T0, Shape0.t());
828 Value *T1 = Builder.CreateMatrixTranspose(
829 Op1, Shape1.NumRows, Shape1.NumColumns, Op1->getName() + "_t");
830 setShapeInfo(T1, Shape1.t());
831 return Operation(T0, Shape0.t(), T1, Shape1.t());
832 }
833
834 /// Erase \p Inst from both ShapeMap (if an entry exists) and erase \p Inst
835 /// itself.
836 void eraseFromParentAndRemoveFromShapeMap(Instruction *Inst) {
837 ShapeMap.erase(Inst);
838 Inst->eraseFromParent();
839 }
840
841 /// Erase \p V from \p BB and move \II forward to avoid invalidating
842 /// iterators.
843 void eraseFromParentAndMove(Value *V, BasicBlock::reverse_iterator &II,
844 BasicBlock &BB) {
845 auto *Inst = cast<Instruction>(V);
846 // Still used, don't erase.
847 if (!Inst->use_empty())
848 return;
849 if (II != BB.rend() && Inst == &*II)
850 ++II;
851 eraseFromParentAndRemoveFromShapeMap(Inst);
852 }
853
854 /// Add a new entry to ShapeMap for \p New with \p Old's shape info, erase the
855 /// entry for \p Old and replace all uses of \p Old with \p New.
856 void updateShapeAndReplaceAllUsesWith(Instruction &Old, Value *New) {
857 // We need to remove Old from the ShapeMap otherwise RAUW will replace it
858 // with New. We should only add New it it supportsShapeInfo so we insert
859 // it conditionally instead.
860 auto S = ShapeMap.find(&Old);
861 if (S != ShapeMap.end()) {
862 ShapeInfo Shape = S->second;
863 ShapeMap.erase(S);
864 if (supportsShapeInfo(New))
865 ShapeMap.insert({New, Shape});
866 }
867 Old.replaceAllUsesWith(New);
868 }
869
870 /// Sink a top-level transpose inside matmuls and adds.
871 /// This creates and erases instructions as needed, and returns the newly
872 /// created instruction while updating the iterator to avoid invalidation. If
873 /// this returns nullptr, no new instruction was created.
874 Instruction *sinkTranspose(Instruction &I, BasicBlock::reverse_iterator &II,
875 bool &Changed) {
876 BasicBlock &BB = *I.getParent();
877 IRBuilder<> IB(&I);
878 MatrixBuilder Builder(IB);
879
880 Value *TA, *TAMA, *TAMB;
881 ConstantInt *R, *K, *C;
884 return nullptr;
885
886 // Transpose of a transpose is a nop when the shapes match.
887 Value *TATA;
889 m_Value(TATA), m_Specific(C), m_Specific(R)))) {
890 updateShapeAndReplaceAllUsesWith(I, TATA);
891 eraseFromParentAndMove(&I, II, BB);
892 eraseFromParentAndMove(TA, II, BB);
893 Changed = true;
894 return nullptr;
895 }
896
897 // k^T -> k
898 if (isSplat(TA)) {
899 updateShapeAndReplaceAllUsesWith(I, TA);
900 eraseFromParentAndMove(&I, II, BB);
901 Changed = true;
902 return nullptr;
903 }
904
905 // (A * B)^t -> B^t * A^t
906 // RxK KxC CxK KxR
908 m_Value(TAMA), m_Value(TAMB), m_ConstantInt(R),
910 auto NewInst = distributeTransposes(
911 TAMB, {K, C}, TAMA, {R, K}, Builder,
912 [&](Value *T0, ShapeInfo Shape0, Value *T1, ShapeInfo Shape1) {
913 return Builder.CreateMatrixMultiply(T0, T1, Shape0.NumRows,
914 Shape0.NumColumns,
915 Shape1.NumColumns, "mmul");
916 });
917 updateShapeAndReplaceAllUsesWith(I, NewInst);
918 eraseFromParentAndMove(&I, II, BB);
919 eraseFromParentAndMove(TA, II, BB);
920 Changed = true;
921 return NewInst;
922 }
923
924 // Same as above, but with a mul, which occurs when multiplied
925 // with a scalar.
926 // (A * k)^t -> A^t * k
927 // R x C RxC
928 if (match(TA, m_AnyMul(m_Value(TAMA), m_Value(TAMB))) &&
929 (isSplat(TAMA) || isSplat(TAMB))) {
930 IRBuilder<> LocalBuilder(&I);
931 // We know that the transposed operand is of shape RxC.
932 // An when multiplied with a scalar, the shape is preserved.
933 auto NewInst = distributeTransposes(
934 TAMA, {R, C}, TAMB, {R, C}, Builder,
935 [&](Value *T0, ShapeInfo Shape0, Value *T1, ShapeInfo Shape1) {
936 bool IsFP = I.getType()->isFPOrFPVectorTy();
937 auto *Mul = IsFP ? LocalBuilder.CreateFMul(T0, T1, "mmul")
938 : LocalBuilder.CreateMul(T0, T1, "mmul");
940 setShapeInfo(Result, Shape0);
941 return Result;
942 });
943 updateShapeAndReplaceAllUsesWith(I, NewInst);
944 eraseFromParentAndMove(&I, II, BB);
945 eraseFromParentAndMove(TA, II, BB);
946 Changed = true;
947 return NewInst;
948 }
949
950 // (A + B)^t -> A^t + B^t
951 // RxC RxC CxR CxR
952 if (match(TA, m_AnyAdd(m_Value(TAMA), m_Value(TAMB)))) {
953 IRBuilder<> LocalBuilder(&I);
954 auto NewInst = distributeTransposes(
955 TAMA, {R, C}, TAMB, {R, C}, Builder,
956 [&](Value *T0, ShapeInfo Shape0, Value *T1, ShapeInfo Shape1) {
957 bool IsFP = I.getType()->isFPOrFPVectorTy();
958 auto *Add = IsFP ? LocalBuilder.CreateFAdd(T0, T1, "madd")
959 : LocalBuilder.CreateAdd(T0, T1, "madd");
960
962 setShapeInfo(Result, Shape0);
963 return Result;
964 });
965 updateShapeAndReplaceAllUsesWith(I, NewInst);
966 eraseFromParentAndMove(&I, II, BB);
967 eraseFromParentAndMove(TA, II, BB);
968 Changed = true;
969 return NewInst;
970 }
971
972 return nullptr;
973 }
974
975 bool liftTranspose(Instruction &I) {
976 // Erase dead Instructions after lifting transposes from binops.
977 auto CleanupBinOp = [this](Instruction &T, Value *A, Value *B) {
978 if (T.use_empty())
979 eraseFromParentAndRemoveFromShapeMap(&T);
980 if (A->use_empty())
981 eraseFromParentAndRemoveFromShapeMap(cast<Instruction>(A));
982 if (A != B && B->use_empty())
983 eraseFromParentAndRemoveFromShapeMap(cast<Instruction>(B));
984 };
985
986 Value *A, *B, *AT, *BT;
987 ConstantInt *R, *K, *C;
988 // A^t * B ^t -> (B * A)^t
994 IRBuilder<> IB(&I);
995 MatrixBuilder Builder(IB);
996 Value *M = Builder.CreateMatrixMultiply(
997 BT, AT, C->getZExtValue(), K->getZExtValue(), R->getZExtValue());
998 setShapeInfo(M, {C, R});
999 Instruction *NewInst = Builder.CreateMatrixTranspose(M, C->getZExtValue(),
1000 R->getZExtValue());
1001 updateShapeAndReplaceAllUsesWith(I, NewInst);
1002 CleanupBinOp(I, A, B);
1003 return true;
1004 }
1005 // A^t + B ^t -> (A + B)^t. Pick rows and columns from first transpose. If
1006 // the shape of the second transpose is different, there's a shape conflict
1007 // which gets resolved by picking the shape of the first operand.
1008 else if (match(&I, m_FAdd(m_Value(A), m_Value(B))) &&
1010 m_Value(AT), m_ConstantInt(R), m_ConstantInt(C))) &&
1013 IRBuilder<> Builder(&I);
1014 auto *Add = Builder.CreateFAdd(AT, BT, "mfadd");
1015 MatrixBuilder MBuilder(Builder);
1016 Instruction *NewInst = MBuilder.CreateMatrixTranspose(
1017 Add, R->getZExtValue(), C->getZExtValue(), "mfadd_t");
1018 updateShapeAndReplaceAllUsesWith(I, NewInst);
1019 assert(computeShapeInfoForInst(NewInst, ShapeMap) ==
1020 computeShapeInfoForInst(&I, ShapeMap) &&
1021 "Shape of new instruction doesn't match original shape.");
1022 CleanupBinOp(I, A, B);
1023 if (auto *AddI = dyn_cast<Instruction>(Add)) {
1024 setShapeInfo(AddI, {R, C});
1025 assert(
1026 computeShapeInfoForInst(AddI, ShapeMap).value_or(ShapeMap[AddI]) ==
1027 ShapeMap[AddI] &&
1028 "Shape of updated addition doesn't match cached shape.");
1029 }
1030 return true;
1031 }
1032 return false;
1033 }
1034
1035 /// Try moving transposes in order to fold them away or into multiplies.
1036 bool optimizeTransposes() {
1037 bool Changed = false;
1038 // First sink all transposes inside matmuls and adds, hoping that we end up
1039 // with NN, NT or TN variants.
1040 for (BasicBlock &BB : reverse(Func)) {
1041 for (auto II = BB.rbegin(); II != BB.rend();) {
1042 Instruction &I = *II;
1043 // We may remove II. By default continue on the next/prev instruction.
1044 ++II;
1045 if (Instruction *NewInst = sinkTranspose(I, II, Changed))
1046 II = std::next(BasicBlock::reverse_iterator(NewInst));
1047 }
1048 }
1049
1050 // If we have a TT matmul or a TT add, lift the transpose. We may be able
1051 // to fold into consuming multiply or add.
1052 for (BasicBlock &BB : Func) {
1053 for (Instruction &I : llvm::make_early_inc_range(BB)) {
1054 Changed |= liftTranspose(I);
1055 }
1056 }
1057 return Changed;
1058 }
1059
1060 bool Visit() {
1062
1063 // Initially only the shape of matrix intrinsics is known.
1064 // Initialize the work list with ops carrying shape information.
1065 for (BasicBlock &BB : Func)
1066 for (Instruction &Inst : BB) {
1067 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Inst);
1068 if (!II)
1069 continue;
1070
1071 switch (II->getIntrinsicID()) {
1072 case Intrinsic::matrix_multiply:
1073 case Intrinsic::matrix_transpose:
1074 case Intrinsic::matrix_column_major_load:
1075 case Intrinsic::matrix_column_major_store:
1076 WorkList.push_back(&Inst);
1077 break;
1078 default:
1079 break;
1080 }
1081 }
1082
1083 // Avoid unnecessary work if there are no matrix intrinsics in the function.
1084 if (WorkList.empty())
1085 return false;
1086
1087 if (AM) {
1088 ORE = &AM->getResult<OptimizationRemarkEmitterAnalysis>(Func);
1089 AA = &AM->getResult<AAManager>(Func);
1090 DT = &AM->getResult<DominatorTreeAnalysis>(Func);
1091 LI = &AM->getResult<LoopAnalysis>(Func);
1092 }
1093
1094 // Propagate shapes until nothing changes any longer.
1095 while (!WorkList.empty()) {
1096 WorkList = propagateShapeForward(WorkList);
1097 WorkList = propagateShapeBackward(WorkList);
1098 }
1099
1100 bool Changed = false;
1101 if (!isMinimal()) {
1102 Changed |= optimizeTransposes();
1103 if (Opts.matrix_print_after_transpose_opt) {
1104 dbgs() << "Dump after matrix transpose optimization:\n";
1105 Func.print(dbgs());
1106 }
1107 }
1108
1109 SmallVector<CallInst *, 16> MaybeFusableInsts;
1110 SmallVector<Instruction *, 16> MatrixInsts;
1112
1113 // First, collect all instructions with shape information and candidates for
1114 // fusion (currently only matrix multiplies).
1115 ReversePostOrderTraversal<Function *> RPOT(&Func);
1116 for (auto *BB : RPOT)
1117 for (Instruction &I : *BB) {
1119 LifetimeEnds.push_back(cast<IntrinsicInst>(&I));
1120 if (!ShapeMap.contains(&I))
1121 continue;
1123 MaybeFusableInsts.push_back(cast<CallInst>(&I));
1124 MatrixInsts.push_back(&I);
1125 }
1126
1127 // Second, try to lower any dot products
1128 SmallPtrSet<Instruction *, 16> FusedInsts;
1129 for (CallInst *CI : MaybeFusableInsts)
1130 lowerDotProduct(CI, FusedInsts, getFastMathFlags(CI));
1131
1132 // Third, try to fuse candidates.
1133 for (CallInst *CI : MaybeFusableInsts)
1134 if (!FusedInsts.contains(CI))
1135 LowerMatrixMultiplyFused(CI, FusedInsts, LifetimeEnds);
1136
1137 Changed |= !FusedInsts.empty();
1138
1139 // Fourth, pre-process all the PHINode's. The incoming values will be
1140 // assigned later in VisitPHI.
1141 for (Instruction *Inst : MatrixInsts) {
1142 if (FusedInsts.count(Inst))
1143 continue;
1144
1145 auto *PHI = dyn_cast<PHINode>(Inst);
1146 if (!PHI)
1147 continue;
1148
1149 const ShapeInfo &SI = ShapeMap.at(Inst);
1150 auto *EltTy = cast<FixedVectorType>(PHI->getType())->getElementType();
1151 MatrixTy PhiM(isColumnMajor(), SI.NumRows, SI.NumColumns, EltTy);
1152
1153 IRBuilder<> Builder(Inst);
1154 for (unsigned VI = 0, VE = PhiM.getNumVectors(); VI != VE; ++VI)
1155 PhiM.setVector(VI, Builder.CreatePHI(PhiM.getVectorTy(),
1156 PHI->getNumIncomingValues(),
1157 PHI->getName()));
1158 assert(!Inst2ColumnMatrix.contains(PHI) && "map already contains phi?");
1159 Inst2ColumnMatrix[PHI] = PhiM;
1160 }
1161
1162 // Fifth, lower remaining instructions with shape information.
1163 for (Instruction *Inst : MatrixInsts) {
1164 if (FusedInsts.count(Inst))
1165 continue;
1166
1167 const ShapeInfo &SI = ShapeMap.at(Inst);
1168
1169 Value *Op1;
1170 Value *Op2;
1171 MatrixTy Result;
1172 IRBuilder<> Builder(Inst);
1173 if (auto *BinOp = dyn_cast<BinaryOperator>(Inst))
1174 Result = VisitBinaryOperator(BinOp, SI, Builder);
1175 else if (auto *Cast = dyn_cast<CastInst>(Inst))
1176 Result = VisitCastInstruction(Cast, SI, Builder);
1177 else if (auto *UnOp = dyn_cast<UnaryOperator>(Inst))
1178 Result = VisitUnaryOperator(UnOp, SI, Builder);
1179 else if (auto *Intr = dyn_cast<IntrinsicInst>(Inst))
1180 Result = VisitIntrinsicInst(Intr, SI, Builder);
1181 else if (auto *Select = dyn_cast<SelectInst>(Inst))
1182 Result = VisitSelectInst(Select, SI, Builder);
1183 else if (match(Inst, m_Load(m_Value(Op1))))
1184 Result = VisitLoad(cast<LoadInst>(Inst), SI, Op1, Builder);
1185 else if (match(Inst, m_Store(m_Value(Op1), m_Value(Op2))))
1186 Result = VisitStore(cast<StoreInst>(Inst), SI, Op1, Op2, Builder);
1187 else if (auto *PHI = dyn_cast<PHINode>(Inst))
1188 Result = VisitPHI(PHI, SI, Builder);
1189 else
1190 continue;
1191
1192 finalizeLowering(Inst, Result, Builder);
1193 Changed = true;
1194 }
1195
1196 if (ORE) {
1197 RemarkGenerator RemarkGen(Inst2ColumnMatrix, *ORE, Func);
1198 RemarkGen.emitRemarks();
1199 }
1200
1201 // Delete the instructions backwards, as it has a reduced likelihood of
1202 // having to update as many def-use and use-def chains.
1203 //
1204 // Because we add to ToRemove during fusion we can't guarantee that defs
1205 // are before uses. Change uses to poison temporarily as these should get
1206 // removed as well.
1207 //
1208 // For verification, we keep track of where we changed uses to poison in
1209 // PoisonedInsts and then check that we in fact remove them.
1210 SmallPtrSet<Instruction *, 16> PoisonedInsts;
1211 for (auto *Inst : reverse(ToRemove)) {
1212 for (Use &U : llvm::make_early_inc_range(Inst->uses())) {
1213 if (auto *Poisoned = dyn_cast<Instruction>(U.getUser()))
1214 PoisonedInsts.insert(Poisoned);
1215 U.set(PoisonValue::get(Inst->getType()));
1216 }
1217 Inst->eraseFromParent();
1218 PoisonedInsts.erase(Inst);
1219 }
1220 if (!PoisonedInsts.empty()) {
1221 // If we didn't remove all poisoned instructions, it's a hard error.
1222 dbgs() << "Poisoned but present instructions:\n";
1223 for (auto *I : PoisonedInsts)
1224 dbgs() << *I << "\n";
1225 llvm_unreachable("Poisoned but instruction not removed");
1226 }
1227
1228 return Changed;
1229 }
1230
1231 /// Replace intrinsic calls.
1232 MatrixTy VisitIntrinsicInst(IntrinsicInst *Inst, const ShapeInfo &SI,
1233 IRBuilder<> &Builder) {
1234 assert(Inst->getCalledFunction() &&
1235 Inst->getCalledFunction()->isIntrinsic());
1236
1237 switch (Inst->getCalledFunction()->getIntrinsicID()) {
1238 case Intrinsic::matrix_multiply:
1239 return LowerMultiply(Inst, Builder);
1240 case Intrinsic::matrix_transpose:
1241 return LowerTranspose(Inst, Builder);
1242 case Intrinsic::matrix_column_major_load:
1243 return LowerColumnMajorLoad(Inst, Builder);
1244 case Intrinsic::matrix_column_major_store:
1245 return LowerColumnMajorStore(Inst, Builder);
1246 case Intrinsic::abs:
1247 case Intrinsic::fabs: {
1248 MatrixTy Result(isColumnMajor());
1249 MatrixTy M = getMatrix(Inst->getOperand(0), SI, Builder);
1250 Builder.setFastMathFlags(getFastMathFlags(Inst));
1251
1252 for (auto *Vector : M.vectors()) {
1253 switch (Inst->getIntrinsicID()) {
1254 case Intrinsic::abs:
1255 Result.addVector(Builder.CreateBinaryIntrinsic(Intrinsic::abs, Vector,
1256 Inst->getOperand(1)));
1257 continue;
1258 case Intrinsic::fabs:
1259 Result.addVector(
1260 Builder.CreateUnaryIntrinsic(Inst->getIntrinsicID(), Vector));
1261 continue;
1262 default:
1263 llvm_unreachable("unexpected intrinsic");
1264 }
1265 }
1266
1267 return Result.addNumComputeOps(getNumOps(Result.getVectorTy()) *
1268 Result.getNumVectors());
1269 }
1270 default:
1271 break;
1272 }
1274 "only intrinsics supporting shape info should be seen here");
1275 }
1276
1277 /// Compute the alignment for a column/row \p Idx with \p Stride between them.
1278 /// The address at \p Idx == 0 has alignment \p A. If \p Stride is a
1279 /// ConstantInt, reduce the initial alignment based on the byte offset. For
1280 /// non-ConstantInt strides, return the common alignment of the initial
1281 /// alignment and the element size in bytes.
1282 Align getAlignForIndex(unsigned Idx, Value *Stride, Type *ElementTy,
1283 MaybeAlign A) const {
1284 Align InitialAlign = DL.getValueOrABITypeAlignment(A, ElementTy);
1285 if (Idx == 0)
1286 return InitialAlign;
1287
1288 TypeSize ElementSizeInBits = DL.getTypeSizeInBits(ElementTy);
1289 if (auto *ConstStride = dyn_cast<ConstantInt>(Stride)) {
1290 uint64_t StrideInBytes =
1291 ConstStride->getZExtValue() * ElementSizeInBits / 8;
1292 return commonAlignment(InitialAlign, Idx * StrideInBytes);
1293 }
1294 return commonAlignment(InitialAlign, ElementSizeInBits / 8);
1295 }
1296
1297 IntegerType *getIndexType(Value *Ptr) const {
1298 return cast<IntegerType>(DL.getIndexType(Ptr->getType()));
1299 }
1300
1301 Value *getIndex(Value *Ptr, uint64_t V) const {
1302 return ConstantInt::get(getIndexType(Ptr), V);
1303 }
1304
1305 Value *castToIndexType(Value *Ptr, Value *V, IRBuilder<> &Builder) const {
1306 assert(isa<IntegerType>(V->getType()) &&
1307 "Attempted to cast non-integral type to integer index");
1308 // In case the data layout's index type differs in width from the type of
1309 // the value we're given, truncate or zero extend to the appropriate width.
1310 // We zero extend here as indices are unsigned.
1311 return Builder.CreateZExtOrTrunc(V, getIndexType(Ptr),
1312 V->getName() + ".cast");
1313 }
1314
1315 /// Load a matrix with \p Shape starting at \p Ptr and using \p Stride between
1316 /// vectors.
1317 MatrixTy loadMatrix(Type *Ty, Value *Ptr, MaybeAlign MAlign, Value *Stride,
1318 bool IsVolatile, ShapeInfo Shape, IRBuilder<> &Builder) {
1319 auto *VType = cast<FixedVectorType>(Ty);
1320 Type *EltTy = VType->getElementType();
1321 Type *VecTy = FixedVectorType::get(EltTy, getStride(Shape));
1322 Value *EltPtr = Ptr;
1323 MatrixTy Result(isColumnMajor());
1324 Stride = castToIndexType(Ptr, Stride, Builder);
1325 for (unsigned I = 0, E = getNumVectors(Shape); I < E; ++I) {
1327 EltPtr, Builder.getIntN(Stride->getType()->getScalarSizeInBits(), I),
1328 Stride, getStride(Shape), EltTy, Builder);
1329 Value *Vector = Builder.CreateAlignedLoad(
1330 VecTy, GEP, getAlignForIndex(I, Stride, EltTy, MAlign),
1331 IsVolatile, "col.load");
1332
1333 Result.addVector(Vector);
1334 }
1335 return Result.addNumLoads(getNumOps(Result.getVectorTy()) *
1336 Result.getNumVectors());
1337 }
1338
1339 /// Loads a sub-matrix with shape \p ResultShape from a \p R x \p C matrix,
1340 /// starting at \p MatrixPtr[I][J].
1341 MatrixTy loadMatrix(Value *MatrixPtr, MaybeAlign Align, bool IsVolatile,
1342 ShapeInfo MatrixShape, Value *I, Value *J,
1343 ShapeInfo ResultShape, Type *EltTy,
1344 IRBuilder<> &Builder) {
1345 Value *Offset = Builder.CreateAdd(
1346 Builder.CreateMul(J, getIndex(MatrixPtr, getStride(MatrixShape))), I);
1347
1348 Value *TileStart = Builder.CreateInBoundsGEP(EltTy, MatrixPtr, Offset);
1349 auto *TileTy = FixedVectorType::get(EltTy, ResultShape.NumRows *
1350 ResultShape.NumColumns);
1351
1352 return loadMatrix(TileTy, TileStart, Align,
1353 getIndex(MatrixPtr, getStride(MatrixShape)), IsVolatile,
1354 ResultShape, Builder);
1355 }
1356
1357 /// Lower a load instruction with shape information.
1358 MatrixTy LowerLoad(Instruction *Inst, Value *Ptr, MaybeAlign Align,
1359 Value *Stride, bool IsVolatile, ShapeInfo Shape,
1360 IRBuilder<> &Builder) {
1361 return loadMatrix(Inst->getType(), Ptr, Align, Stride, IsVolatile, Shape,
1362 Builder);
1363 }
1364
1365 /// Lowers llvm.matrix.column.major.load.
1366 ///
1367 /// The intrinsic loads a matrix from memory using a stride between columns.
1368 MatrixTy LowerColumnMajorLoad(CallInst *Inst, IRBuilder<> &Builder) {
1369 assert(Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor &&
1370 "Intrinsic only supports column-major layout!");
1371 Value *Ptr = Inst->getArgOperand(0);
1372 Value *Stride = Inst->getArgOperand(1);
1373 return LowerLoad(Inst, Ptr, Inst->getParamAlign(0), Stride,
1374 cast<ConstantInt>(Inst->getArgOperand(2))->isOne(),
1375 {Inst->getArgOperand(3), Inst->getArgOperand(4)}, Builder);
1376 }
1377
1378 /// Stores a sub-matrix \p StoreVal into the \p R x \p C matrix starting at \p
1379 /// MatrixPtr[I][J].
1380 void storeMatrix(const MatrixTy &StoreVal, Value *MatrixPtr,
1381 MaybeAlign MAlign, bool IsVolatile, ShapeInfo MatrixShape,
1382 Value *I, Value *J, Type *EltTy, IRBuilder<> &Builder) {
1383 Value *Offset = Builder.CreateAdd(
1384 Builder.CreateMul(J, getIndex(MatrixPtr, getStride(MatrixShape))), I);
1385
1386 Value *TileStart = Builder.CreateInBoundsGEP(EltTy, MatrixPtr, Offset);
1387 auto *TileTy = FixedVectorType::get(EltTy, StoreVal.getNumRows() *
1388 StoreVal.getNumColumns());
1389
1390 storeMatrix(TileTy, StoreVal, TileStart, MAlign,
1391 getIndex(MatrixPtr, getStride(MatrixShape)), IsVolatile,
1392 Builder);
1393 }
1394
1395 /// Store matrix \p StoreVal starting at \p Ptr and using \p Stride between
1396 /// vectors.
1397 MatrixTy storeMatrix(Type *Ty, MatrixTy StoreVal, Value *Ptr,
1398 MaybeAlign MAlign, Value *Stride, bool IsVolatile,
1399 IRBuilder<> &Builder) {
1400 auto *VType = cast<FixedVectorType>(Ty);
1401 Value *EltPtr = Ptr;
1402 Stride = castToIndexType(Ptr, Stride, Builder);
1403 for (auto Vec : enumerate(StoreVal.vectors())) {
1405 EltPtr,
1406 Builder.getIntN(Stride->getType()->getScalarSizeInBits(),
1407 Vec.index()),
1408 Stride, StoreVal.getStride(), VType->getElementType(), Builder);
1409 Builder.CreateAlignedStore(Vec.value(), GEP,
1410 getAlignForIndex(Vec.index(), Stride,
1411 VType->getElementType(),
1412 MAlign),
1413 IsVolatile);
1414 }
1415 return MatrixTy(isColumnMajor())
1416 .addNumStores(getNumOps(StoreVal.getVectorTy()) *
1417 StoreVal.getNumVectors());
1418 }
1419
1420 /// Lower a store instruction with shape information.
1421 MatrixTy LowerStore(Instruction *Inst, Value *Matrix, Value *Ptr,
1422 MaybeAlign A, Value *Stride, bool IsVolatile,
1423 ShapeInfo Shape, IRBuilder<> &Builder) {
1424 auto StoreVal = getMatrix(Matrix, Shape, Builder);
1425 return storeMatrix(Matrix->getType(), StoreVal, Ptr, A, Stride, IsVolatile,
1426 Builder);
1427 }
1428
1429 /// Lowers llvm.matrix.column.major.store.
1430 ///
1431 /// The intrinsic store a matrix back memory using a stride between columns.
1432 MatrixTy LowerColumnMajorStore(CallInst *Inst, IRBuilder<> &Builder) {
1433 assert(Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor &&
1434 "Intrinsic only supports column-major layout!");
1435 Value *Matrix = Inst->getArgOperand(0);
1436 Value *Ptr = Inst->getArgOperand(1);
1437 Value *Stride = Inst->getArgOperand(2);
1438 return LowerStore(Inst, Matrix, Ptr, Inst->getParamAlign(1), Stride,
1439 cast<ConstantInt>(Inst->getArgOperand(3))->isOne(),
1440 {Inst->getArgOperand(4), Inst->getArgOperand(5)},
1441 Builder);
1442 }
1443
1444 // Set elements I..I+NumElts-1 to Block
1445 Value *insertVector(Value *Col, unsigned I, Value *Block,
1446 IRBuilder<> &Builder) {
1447
1448 // First, bring Block to the same size as Col
1449 unsigned BlockNumElts =
1450 cast<FixedVectorType>(Block->getType())->getNumElements();
1451 unsigned NumElts = cast<FixedVectorType>(Col->getType())->getNumElements();
1452 assert(NumElts >= BlockNumElts && "Too few elements for current block");
1453
1454 Block = Builder.CreateShuffleVector(
1455 Block, createSequentialMask(0, BlockNumElts, NumElts - BlockNumElts));
1456
1457 // If Col is 7 long and I is 2 and BlockNumElts is 2 the mask is: 0, 1, 7,
1458 // 8, 4, 5, 6
1459 SmallVector<int, 16> Mask;
1460 unsigned i;
1461 for (i = 0; i < I; i++)
1462 Mask.push_back(i);
1463
1464 unsigned VecNumElts =
1465 cast<FixedVectorType>(Col->getType())->getNumElements();
1466 for (; i < I + BlockNumElts; i++)
1467 Mask.push_back(i - I + VecNumElts);
1468
1469 for (; i < VecNumElts; i++)
1470 Mask.push_back(i);
1471
1472 return Builder.CreateShuffleVector(Col, Block, Mask);
1473 }
1474
1475 Value *createMulAdd(Value *Sum, Value *A, Value *B, bool UseFPOp,
1476 IRBuilder<> &Builder, bool AllowContraction,
1477 unsigned &NumComputeOps) {
1478 NumComputeOps += getNumOps(A->getType());
1479 if (!Sum)
1480 return UseFPOp ? Builder.CreateFMul(A, B) : Builder.CreateMul(A, B);
1481
1482 if (UseFPOp) {
1483 if (AllowContraction) {
1484 // Use fmuladd for floating point operations and let the backend decide
1485 // if that's profitable.
1486 return Builder.CreateIntrinsic(Intrinsic::fmuladd, A->getType(),
1487 {A, B, Sum});
1488 }
1489 NumComputeOps += getNumOps(A->getType());
1490 Value *Mul = Builder.CreateFMul(A, B);
1491 return Builder.CreateFAdd(Sum, Mul);
1492 }
1493
1494 NumComputeOps += getNumOps(A->getType());
1495 Value *Mul = Builder.CreateMul(A, B);
1496 return Builder.CreateAdd(Sum, Mul);
1497 }
1498
1499 /// Cache \p Matrix as result of \p Inst and update the uses of \p Inst. For
1500 /// users with shape information, there's nothing to do: they will use the
1501 /// cached value when they are lowered. For other users, \p Matrix is
1502 /// flattened and the uses are updated to use it. Also marks \p Inst for
1503 /// deletion.
1504 void finalizeLowering(Instruction *Inst, MatrixTy Matrix,
1505 IRBuilder<> &Builder) {
1506 auto inserted = Inst2ColumnMatrix.insert(std::make_pair(Inst, Matrix));
1507 (void)inserted;
1508 assert((inserted.second || isa<PHINode>(Inst)) &&
1509 "multiple matrix lowering mapping");
1510
1511 ToRemove.push_back(Inst);
1512 Value *Flattened = nullptr;
1513 for (Use &U : llvm::make_early_inc_range(Inst->uses())) {
1514 if (ShapeMap.contains(U.getUser()))
1515 continue;
1516
1517 if (!Flattened) {
1518 Flattened = Matrix.embedInVector(Builder);
1519 LLVM_DEBUG(
1520 if (Instruction *User = dyn_cast<Instruction>(U.getUser())) dbgs()
1521 << "flattening a " << Matrix.shape() << " matrix:\n"
1522 << *Inst
1523 << "\nbecause we do not have a shape-aware lowering for its "
1524 "user:\n"
1525 << *User << '\n';);
1526 FlattenedMatrices++;
1527 }
1528 U.set(Flattened);
1529 }
1530 }
1531
1532 /// Special case for MatMul lowering. Prevents scalar loads of row-major
1533 /// vectors Lowers to vector reduction add instead of sequential add if
1534 /// reassocation is enabled.
1535 void lowerDotProduct(CallInst *MatMul,
1536 SmallPtrSet<Instruction *, 16> &FusedInsts,
1537 FastMathFlags FMF) {
1538 if (FusedInsts.contains(MatMul) ||
1539 Opts.matrix_default_layout != MatrixLayoutTy::ColumnMajor)
1540 return;
1541 ShapeInfo LShape(MatMul->getArgOperand(2), MatMul->getArgOperand(3));
1542 ShapeInfo RShape(MatMul->getArgOperand(3), MatMul->getArgOperand(4));
1543
1544 if (LShape.NumRows != 1 || RShape.NumColumns != 1) // not a dot product
1545 return;
1546
1547 Value *LHS = MatMul->getArgOperand(0);
1548 Value *RHS = MatMul->getArgOperand(1);
1549
1550 Type *ElementType = cast<FixedVectorType>(LHS->getType())->getElementType();
1551 bool IsIntVec = ElementType->isIntegerTy();
1552
1554
1555 // Floating point reductions require reassocation.
1556 if (!IsIntVec && !FMF.allowReassoc())
1557 return;
1558
1559 auto CanBeFlattened = [](Value *Op) {
1560 if (match(Op, m_BinOp()))
1561 return true;
1562 return match(
1564 m_Load(m_Value()),
1567 m_Value(), m_One())))));
1568 };
1569 // Returns the cost benefit of using \p Op with the dot product lowering. If
1570 // the returned cost is < 0, the argument is cheaper to use in the
1571 // dot-product lowering.
1572 auto GetCostForArg = [this, &CanBeFlattened, CostKind](Value *Op,
1573 unsigned N) {
1574 if (!ShapeMap.contains(Op))
1576
1577 if (!isa<Instruction>(Op))
1578 return InstructionCost(0);
1579
1580 FixedVectorType *VecTy = cast<FixedVectorType>(Op->getType());
1581 Type *EltTy = VecTy->getElementType();
1582
1583 if (!CanBeFlattened(Op)) {
1584 InstructionCost EmbedCost(0);
1585 // Roughly estimate the cost for embedding the columns into a vector.
1586 for (unsigned I = 1; I < N; ++I)
1587 EmbedCost +=
1588 TTI.getShuffleCost(TTI::SK_Splice, FixedVectorType::get(EltTy, 1),
1589 FixedVectorType::get(EltTy, 1), CostKind);
1590 return EmbedCost;
1591 }
1592
1593 if (match(Op, m_BinOp()) && ShapeMap.contains(Op)) {
1594 InstructionCost OriginalCost =
1595 TTI.getArithmeticInstrCost(cast<Instruction>(Op)->getOpcode(),
1596 EltTy, CostKind) *
1597 N;
1598 InstructionCost NewCost = TTI.getArithmeticInstrCost(
1599 cast<Instruction>(Op)->getOpcode(), VecTy, CostKind);
1600 return NewCost - OriginalCost;
1601 }
1602
1604 // The transpose can be skipped for the dot product lowering, roughly
1605 // estimate the savings as the cost of embedding the columns in a
1606 // vector.
1607 InstructionCost EmbedCost(0);
1608 for (unsigned I = 1; I < N; ++I)
1609 EmbedCost -=
1610 TTI.getShuffleCost(TTI::SK_Splice, FixedVectorType::get(EltTy, 1),
1611 FixedVectorType::get(EltTy, 1), CostKind);
1612 return EmbedCost;
1613 }
1614
1615 // Costs for loads.
1616 if (N == 1)
1617 return InstructionCost(0);
1618
1619 return TTI.getMemoryOpCost(Instruction::Load, VecTy, Align(1), 0,
1620 CostKind) -
1621 N * TTI.getMemoryOpCost(Instruction::Load, EltTy, Align(1), 0,
1622 CostKind);
1623 };
1624
1625 // Iterate over LHS and operations feeding LHS and check if it is profitable
1626 // to flatten the visited ops. For each op, we compute the difference
1627 // between the flattened and matrix versions.
1628 SmallPtrSet<Value *, 4> Seen;
1629 SmallVector<Value *> WorkList;
1630 SmallVector<Value *> ToFlatten;
1631 WorkList.push_back(LHS);
1632 InstructionCost LHSCost(0);
1633 while (!WorkList.empty()) {
1634 Value *Op = WorkList.pop_back_val();
1635 if (!Seen.insert(Op).second)
1636 continue;
1637
1638 InstructionCost OpCost = GetCostForArg(Op, LShape.NumColumns);
1639 if (OpCost + LHSCost >= LHSCost)
1640 continue;
1641
1642 LHSCost += OpCost;
1643 ToFlatten.push_back(Op);
1644 if (auto *I = dyn_cast<Instruction>(Op))
1645 WorkList.append(I->op_begin(), I->op_end());
1646 }
1647
1648 // We compare the costs of a vector.reduce.add to sequential add.
1649 int AddOpCode = IsIntVec ? Instruction::Add : Instruction::FAdd;
1650 int MulOpCode = IsIntVec ? Instruction::Mul : Instruction::FMul;
1651 InstructionCost ReductionCost =
1652 TTI.getArithmeticReductionCost(
1653 AddOpCode, cast<FixedVectorType>(LHS->getType()),
1654 IsIntVec ? std::nullopt : std::optional(FMF), CostKind) +
1655 TTI.getArithmeticInstrCost(MulOpCode, LHS->getType(), CostKind);
1656 InstructionCost SequentialAddCost =
1657 TTI.getArithmeticInstrCost(AddOpCode, ElementType, CostKind) *
1658 (LShape.NumColumns - 1) +
1659 TTI.getArithmeticInstrCost(MulOpCode, ElementType, CostKind) *
1660 (LShape.NumColumns);
1661 if ((LHSCost + ReductionCost - SequentialAddCost) > InstructionCost(0))
1662 return;
1663
1664 FusedInsts.insert(MatMul);
1665 IRBuilder<> Builder(MatMul);
1666 auto FlattenArg = [&Builder, &FusedInsts, &CanBeFlattened,
1667 this](Value *Op) {
1668 // Matmul must be the only user of loads because we don't use LowerLoad
1669 // for row vectors (LowerLoad results in scalar loads and shufflevectors
1670 // instead of single vector load).
1671 if (!CanBeFlattened(Op))
1672 return;
1673
1674 if (match(Op, m_BinOp())) {
1675 auto It = ShapeMap.find(Op);
1676 if (It != ShapeMap.end()) {
1677 It->second = It->second.t();
1678 return;
1679 }
1680 }
1681
1682 FusedInsts.insert(cast<Instruction>(Op));
1683 // If vector uses the builtin load, lower to a LoadInst
1684 Value *Arg;
1686 m_Value(Arg)))) {
1687 auto *MatLoad = cast<IntrinsicInst>(Op);
1688 bool IsVolatile = cast<ConstantInt>(MatLoad->getArgOperand(2))->isOne();
1689 // Preserve the volatile flag and alignment of the original load.
1690 Align Alignment = getAlignForIndex(
1691 0, MatLoad->getArgOperand(1),
1692 cast<FixedVectorType>(Op->getType())->getElementType(),
1693 MatLoad->getParamAlign(0));
1694 auto *NewLoad = Builder.CreateAlignedLoad(Op->getType(), Arg, Alignment,
1695 IsVolatile);
1696 Op->replaceAllUsesWith(NewLoad);
1697 eraseFromParentAndRemoveFromShapeMap(cast<Instruction>(Op));
1698 return;
1700 m_Value(Arg)))) {
1701 ToRemove.push_back(cast<Instruction>(Op));
1702 Op->replaceAllUsesWith(Arg);
1703 return;
1704 }
1705 };
1706
1707 for (auto *V : ToFlatten)
1708 FlattenArg(V);
1709
1710 LHS = MatMul->getArgOperand(0);
1711
1712 // Insert mul/fmul and llvm.vector.reduce.fadd
1713 Value *Mul =
1714 IsIntVec ? Builder.CreateMul(LHS, RHS) : Builder.CreateFMul(LHS, RHS);
1715
1716 Value *Result;
1717 if (IsIntVec)
1718 Result = Builder.CreateAddReduce(Mul);
1719 else {
1720 Result = Builder.CreateFAddReduce(
1721 ConstantFP::getNegativeZero(ElementType), Mul);
1722 cast<Instruction>(Result)->setFastMathFlags(FMF);
1723 }
1724
1725 // pack scalar back into a matrix and then replace matmul inst
1727 Result, uint64_t(0));
1728 MatMul->replaceAllUsesWith(Result);
1729 FusedInsts.insert(MatMul);
1730 ToRemove.push_back(MatMul);
1731 }
1732
1733 /// Given \p Remainder iterations of the the matmul inner loop,
1734 /// potentially lower \p Blocksize that is used for the underlying
1735 /// vector.
1736 unsigned capBlockSize(unsigned BlockSize, unsigned Remainder, Type *EltType) {
1737 if (BlockSize <= Remainder)
1738 return BlockSize;
1739
1740 // If the remainder is also a legal type just use it.
1741 auto *VecTy = FixedVectorType::get(EltType, Remainder);
1742 if (TTI.isTypeLegal(VecTy))
1743 return Remainder;
1744
1745 // Similarly, if the vector is small enough that we don't want
1746 // to split further.
1747 if (VecTy->getPrimitiveSizeInBits() <=
1748 Opts.matrix_split_matmul_remainder_over_threshold)
1749 return Remainder;
1750
1751 // Gradually lower the vectorization factor to cover the
1752 // remainder.
1753 do {
1754 BlockSize /= 2;
1755 } while (BlockSize > Remainder);
1756 return BlockSize;
1757 }
1758
1759 /// Compute \p Result += \p A * \p B for input matrices with left-associating
1760 /// addition.
1761 ///
1762 /// We can fold a transpose into the operand that is used to extract scalars.
1763 /// This is the first operands with row-major and the second with
1764 /// column-major. If \p IsScalarMatrixTransposed we assume the appropriate
1765 /// operand is transposed.
1766 void emitMatrixMultiply(MatrixTy &Result, const MatrixTy &A,
1767 const MatrixTy &B, IRBuilder<> &Builder, bool IsTiled,
1768 bool IsScalarMatrixTransposed, FastMathFlags FMF) {
1769 const unsigned VF = std::max<unsigned>(
1770 TTI.getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
1771 .getFixedValue() /
1772 Result.getElementType()->getPrimitiveSizeInBits().getFixedValue(),
1773 1U);
1774 unsigned R = Result.getNumRows();
1775 unsigned C = Result.getNumColumns();
1776 unsigned M = A.getNumColumns();
1777
1778 bool IsFP = Result.getElementType()->isFloatingPointTy();
1779 assert(A.isColumnMajor() == B.isColumnMajor() &&
1780 Result.isColumnMajor() == A.isColumnMajor() &&
1781 "operands must agree on matrix layout");
1782 unsigned NumComputeOps = 0;
1783
1784 Builder.setFastMathFlags(FMF);
1785
1786 if (A.isColumnMajor()) {
1787 // Multiply columns from the first operand with scalars from the second
1788 // operand. Then move along the K axes and accumulate the columns. With
1789 // this the adds can be vectorized without reassociation.
1790 for (unsigned J = 0; J < C; ++J) {
1791 unsigned BlockSize = VF;
1792 // If Result is zero, we don't need to accumulate in the K==0 iteration.
1793 bool isSumZero = isa<ConstantAggregateZero>(Result.getColumn(J));
1794
1795 for (unsigned I = 0; I < R; I += BlockSize) {
1796 // Lower block size to make sure we stay within bounds.
1797 BlockSize = capBlockSize(BlockSize, R - I, Result.getElementType());
1798 Value *Sum = IsTiled ? Result.extractVector(I, J, BlockSize, Builder)
1799 : nullptr;
1800 for (unsigned K = 0; K < M; ++K) {
1801 Value *L = A.extractVector(I, K, BlockSize, Builder);
1802 Value *RH = Builder.CreateExtractElement(
1803 B.getColumn(IsScalarMatrixTransposed ? K : J),
1804 IsScalarMatrixTransposed ? J : K);
1805 Value *Splat = Builder.CreateVectorSplat(BlockSize, RH, "splat");
1806 Sum =
1807 createMulAdd(isSumZero && K == 0 ? nullptr : Sum, L, Splat,
1808 IsFP, Builder, FMF.allowContract(), NumComputeOps);
1809 }
1810 Result.setVector(J,
1811 insertVector(Result.getVector(J), I, Sum, Builder));
1812 }
1813 }
1814 } else {
1815 // Multiply rows from the second operand with scalars from the first
1816 // operand. Then move along the K axes and accumulate the rows. With this
1817 // the adds can be vectorized without reassociation.
1818 for (unsigned I = 0; I < R; ++I) {
1819 unsigned BlockSize = VF;
1820 bool isSumZero = isa<ConstantAggregateZero>(Result.getRow(I));
1821 for (unsigned J = 0; J < C; J += BlockSize) {
1822 // Lower the vectorization factor to cover the remainder.
1823 BlockSize = capBlockSize(BlockSize, C - J, Result.getElementType());
1824
1825 Value *Sum = nullptr;
1826 for (unsigned K = 0; K < M; ++K) {
1827 Value *R = B.extractVector(K, J, BlockSize, Builder);
1828 Value *LH = Builder.CreateExtractElement(
1829 A.getVector(IsScalarMatrixTransposed ? K : I),
1830 IsScalarMatrixTransposed ? I : K);
1831 Value *Splat = Builder.CreateVectorSplat(BlockSize, LH, "splat");
1832 Sum =
1833 createMulAdd(isSumZero && K == 0 ? nullptr : Sum, Splat, R,
1834 IsFP, Builder, FMF.allowContract(), NumComputeOps);
1835 }
1836 Result.setVector(I,
1837 insertVector(Result.getVector(I), J, Sum, Builder));
1838 }
1839 }
1840 }
1841 Result.addNumComputeOps(NumComputeOps);
1842 }
1843
1844 /// Ensure that the memory in \p Load does not alias \p Store by potentially
1845 /// copying it to a new location. This new or otherwise the original location
1846 /// is returned.
1847 std::pair<Value *, AllocaInst *>
1848 getNonAliasingPointer(LoadInst *Load, StoreInst *Store, CallInst *MatMul) {
1849 MemoryLocation StoreLoc = MemoryLocation::get(Store);
1850 MemoryLocation LoadLoc = MemoryLocation::get(Load);
1851
1852 // If we can statically determine noalias we're good.
1853 if (AA->isNoAlias(LoadLoc, StoreLoc))
1854 return {Load->getPointerOperand(), nullptr};
1855
1856 // Use an array type for the alloca, to avoid potentially huge alignment
1857 // requirements for large vector types.
1858 auto *VT = cast<FixedVectorType>(Load->getType());
1859 auto *ArrayTy = ArrayType::get(VT->getElementType(), VT->getNumElements());
1860 IRBuilder<> AllocaBuilder(&Func.getEntryBlock().front());
1861 AllocaInst *Alloca =
1862 AllocaBuilder.CreateAlloca(ArrayTy, Load->getPointerAddressSpace());
1863 // The fused loads use the original load's alignment.
1864 Alloca->setAlignment(std::max(Alloca->getAlign(), Load->getAlign()));
1865
1866 // If the pointers are in different address spaces, we cannot compare them
1867 // at runtime. Conservatively copy the load operand to a new buffer.
1868 if (Load->getPointerAddressSpace() != Store->getPointerAddressSpace()) {
1869 IRBuilder<> Builder(MatMul);
1870 Builder.CreateLifetimeStart(Alloca);
1871 Builder.CreateMemCpy(Alloca, Alloca->getAlign(),
1872 Load->getPointerOperand(), Load->getAlign(),
1873 LoadLoc.Size.getValue());
1874 return {Alloca, Alloca};
1875 }
1876
1877 // Create code to check if the memory locations of the Load and Store
1878 // overlap and if they do, copy Load's operand to a new buffer.
1879
1880 // First, create new blocks for 2n part of the check and the copy.
1881 BasicBlock *Check0 = MatMul->getParent();
1882 // FIXME: Use lazy DTU and update SplitBlock to accept a DTU instead of a
1883 // DT. Manually collect dominator tree updates, to avoid unnecessary work,
1884 // as we adjust Check0 and Check1's branches.
1886 for (BasicBlock *Succ : successors(Check0))
1887 DTUpdates.push_back({DT->Delete, Check0, Succ});
1888
1889 BasicBlock *Check1 =
1890 SplitBlock(MatMul->getParent(), MatMul, (DomTreeUpdater *)nullptr, LI,
1891 nullptr, "alias_cont");
1892 BasicBlock *Copy =
1893 SplitBlock(MatMul->getParent(), MatMul, (DomTreeUpdater *)nullptr, LI,
1894 nullptr, "copy");
1895 BasicBlock *Fusion =
1896 SplitBlock(MatMul->getParent(), MatMul, (DomTreeUpdater *)nullptr, LI,
1897 nullptr, "no_alias");
1898
1899 // Check if the loaded memory location begins before the end of the store
1900 // location. If the condition holds, they might overlap, otherwise they are
1901 // guaranteed to not overlap.
1902 IRBuilder<> Builder(MatMul);
1903 Check0->getTerminator()->eraseFromParent();
1904 Builder.SetInsertPoint(Check0);
1905 Type *AddrTy = DL.getAddressType(Store->getPointerOperand()->getType());
1906 Value *StoreBegin = Store->getPointerOperand();
1907 Value *StoreEnd = Builder.CreatePtrAdd(
1908 StoreBegin, ConstantInt::get(AddrTy, StoreLoc.Size.getValue()),
1909 "store.end",
1911 Value *LoadBegin = Load->getPointerOperand();
1912 CondBrInst *BR1 = Builder.CreateCondBr(
1913 Builder.CreateICmpULT(LoadBegin, StoreEnd), Check1, Fusion);
1915
1916 // Check if the store begins before the end of the load location. If the
1917 // condition holds, they alias, otherwise they are guaranteed to not
1918 // overlap.
1919 Check1->getTerminator()->eraseFromParent();
1920 Builder.SetInsertPoint(Check1->begin());
1921 Builder.CreateLifetimeStart(Alloca);
1922
1923 Value *LoadEnd = Builder.CreatePtrAdd(
1924 LoadBegin, ConstantInt::get(AddrTy, LoadLoc.Size.getValue()),
1925 "load.end",
1927 CondBrInst *BR2 = Builder.CreateCondBr(
1928 Builder.CreateICmpULT(StoreBegin, LoadEnd), Copy, Fusion);
1930
1931 // Copy load operand to new alloca.
1932 Builder.SetInsertPoint(Copy->begin());
1933 Builder.CreateMemCpy(Alloca, Alloca->getAlign(), Load->getPointerOperand(),
1934 Load->getAlign(), LoadLoc.Size.getValue());
1935 Builder.SetInsertPoint(Fusion->begin());
1936 PHINode *PHI = Builder.CreatePHI(Load->getPointerOperandType(), 3);
1937 PHI->addIncoming(Load->getPointerOperand(), Check0);
1938 PHI->addIncoming(Load->getPointerOperand(), Check1);
1939 PHI->addIncoming(Alloca, Copy);
1940
1941 // Adjust DT.
1942 DTUpdates.push_back({DT->Insert, Check0, Check1});
1943 DTUpdates.push_back({DT->Insert, Check0, Fusion});
1944 DTUpdates.push_back({DT->Insert, Check1, Copy});
1945 DTUpdates.push_back({DT->Insert, Check1, Fusion});
1946 DT->applyUpdates(DTUpdates);
1947 return {PHI, Alloca};
1948 }
1949
1950 bool isFusionProfitable(CallInst *MatMul) {
1951 if (Opts.force_fuse_matrix)
1952 return true;
1953
1954 ShapeInfo LShape(MatMul->getArgOperand(2), MatMul->getArgOperand(3));
1955 ShapeInfo RShape(MatMul->getArgOperand(3), MatMul->getArgOperand(4));
1956
1957 const unsigned R = LShape.NumRows;
1958 const unsigned C = RShape.NumColumns;
1959 const unsigned M = LShape.NumColumns;
1960 auto *EltType = cast<FixedVectorType>(MatMul->getType())->getElementType();
1961
1962 const unsigned VF = std::max<unsigned>(
1963 TTI.getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
1964 .getFixedValue() /
1966 1U);
1967
1968 // Cost model for tiling
1969 //
1970 // For tiling to be beneficial, we need reuse either along the R or
1971 // the C axis. We vectorize along the R axis so that means at least
1972 // 3 elements.
1973 // TODO: Also consider cost of copying if operands alias.
1974 if (R <= VF && C == 1)
1975 return false;
1976 // Then we need enough elements to exceed the number of vector
1977 // registers we have. Note that this is an oversimplification since
1978 // fusing also takes some extra loads which may exceed the number of
1979 // reloads necessary.
1980 unsigned Op0Regs = (R + VF - 1) / VF * M;
1981 unsigned Op1Regs = (M + VF - 1) / VF * C;
1982 return Op0Regs + Op1Regs >
1983 TTI.getNumberOfRegisters(TTI.getRegisterClassForType(true));
1984 }
1985
1986 MatrixTy getZeroMatrix(Type *EltType, unsigned R, unsigned C) {
1987 MatrixTy Res(isColumnMajor());
1988 auto *ColumType = FixedVectorType::get(EltType, R);
1989 for (unsigned I = 0; I < C; ++I)
1990 Res.addVector(ConstantAggregateZero::get(ColumType));
1991 return Res;
1992 }
1993
1994 void createTiledLoops(CallInst *MatMul, Value *LPtr, ShapeInfo LShape,
1995 Value *RPtr, ShapeInfo RShape, StoreInst *Store) {
1996 auto *EltType = cast<FixedVectorType>(MatMul->getType())->getElementType();
1997
1998 // Create the main tiling loop nest.
1999 TileInfo TI(LShape.NumRows, RShape.NumColumns, LShape.NumColumns,
2000 Opts.fuse_matrix_tile_size);
2001 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
2002 Instruction *InsertI = cast<Instruction>(MatMul);
2003 BasicBlock *Start = InsertI->getParent();
2004 BasicBlock *End =
2005 SplitBlock(InsertI->getParent(), InsertI, DT, LI, nullptr, "continue");
2006 IRBuilder<> Builder(MatMul);
2007 BasicBlock *InnerBody = TI.CreateTiledLoops(Start, End, Builder, DTU, *LI);
2008
2009 Type *TileVecTy = FixedVectorType::get(MatMul->getType()->getScalarType(),
2010 Opts.fuse_matrix_tile_size);
2011 MatrixTy TileResult(isColumnMajor());
2012 // Insert in the inner loop header.
2013 Builder.SetInsertPoint(TI.KLoop.Header->getTerminator());
2014 Constant *Init = EltType->isFloatingPointTy()
2015 ? ConstantFP::getNegativeZero(TileVecTy)
2016 : Constant::getNullValue(TileVecTy);
2017 // Create PHI nodes for the result columns to accumulate across iterations.
2018 SmallVector<PHINode *, 4> ColumnPhis;
2019 for (unsigned I = 0; I < Opts.fuse_matrix_tile_size; I++) {
2020 auto *Phi = Builder.CreatePHI(TileVecTy, 2, "result.vec." + Twine(I));
2021 Phi->addIncoming(Init, TI.RowLoop.Header->getSingleSuccessor());
2022 TileResult.addVector(Phi);
2023 ColumnPhis.push_back(Phi);
2024 }
2025
2026 // Insert in the inner loop body, which computes
2027 // Res += Load(CurrentRow, K) * Load(K, CurrentColumn)
2028 Builder.SetInsertPoint(InnerBody->getTerminator());
2029 // Load tiles of the operands.
2030 MatrixTy A =
2031 loadMatrix(LPtr, {}, false, LShape, TI.RowLoop.Index, TI.KLoop.Index,
2032 {Opts.fuse_matrix_tile_size, Opts.fuse_matrix_tile_size},
2033 EltType, Builder);
2034 MatrixTy B =
2035 loadMatrix(RPtr, {}, false, RShape, TI.KLoop.Index, TI.ColumnLoop.Index,
2036 {Opts.fuse_matrix_tile_size, Opts.fuse_matrix_tile_size},
2037 EltType, Builder);
2038 emitMatrixMultiply(TileResult, A, B, Builder, true, false,
2039 getFastMathFlags(MatMul));
2040 // Store result after the inner loop is done.
2041 Builder.SetInsertPoint(TI.RowLoop.Latch->getTerminator());
2042 storeMatrix(TileResult, Store->getPointerOperand(), Store->getAlign(),
2043 Store->isVolatile(), {LShape.NumRows, RShape.NumColumns},
2044 TI.RowLoop.Index, TI.ColumnLoop.Index, EltType, Builder);
2045
2046 for (unsigned I = 0; I < TileResult.getNumVectors(); I++)
2047 ColumnPhis[I]->addIncoming(TileResult.getVector(I), TI.KLoop.Latch);
2048
2049 // Force unrolling of a few iterations of the inner loop, to make sure there
2050 // is enough work per iteration.
2051 // FIXME: The unroller should make this decision directly instead, but
2052 // currently the cost-model is not up to the task.
2053 unsigned InnerLoopUnrollCount =
2054 std::min(10u, LShape.NumColumns / Opts.fuse_matrix_tile_size);
2055 addStringMetadataToLoop(LI->getLoopFor(TI.KLoop.Header),
2056 "llvm.loop.unroll.count", InnerLoopUnrollCount);
2057 }
2058
2059 void emitSIMDTiling(CallInst *MatMul, LoadInst *LoadOp0, LoadInst *LoadOp1,
2060 StoreInst *Store,
2061 SmallPtrSetImpl<Instruction *> &FusedInsts) {
2062 assert(Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor &&
2063 "Tiling only supported for column-major matrixes at the moment!");
2064 if (!isFusionProfitable(MatMul))
2065 return;
2066
2067 ShapeInfo LShape(MatMul->getArgOperand(2), MatMul->getArgOperand(3));
2068 ShapeInfo RShape(MatMul->getArgOperand(3), MatMul->getArgOperand(4));
2069
2070 const unsigned R = LShape.NumRows;
2071 const unsigned C = RShape.NumColumns;
2072 const unsigned M = LShape.NumColumns;
2073 auto *EltType = cast<FixedVectorType>(MatMul->getType())->getElementType();
2074
2075 auto [APtr, AAlloca] = getNonAliasingPointer(LoadOp0, Store, MatMul);
2076 auto [BPtr, BAlloca] = getNonAliasingPointer(LoadOp1, Store, MatMul);
2077 Value *CPtr = Store->getPointerOperand();
2078
2079 // Use loop-based tiling when the number of expected operations exceeds
2080 // threshold.
2081 unsigned NumOps = getNumNativeVectorOps(EltType, R, M, C);
2082 bool UseLoops = (NumOps > Opts.fuse_matrix_loops_threshold) &&
2083 R % Opts.fuse_matrix_tile_size == 0 &&
2084 C % Opts.fuse_matrix_tile_size == 0;
2085 if (UseLoops)
2086 createTiledLoops(MatMul, APtr, LShape, BPtr, RShape, Store);
2087 else {
2088 IRBuilder<> Builder(Store);
2089 for (unsigned J = 0; J < C; J += Opts.fuse_matrix_tile_size)
2090 for (unsigned I = 0; I < R; I += Opts.fuse_matrix_tile_size) {
2091 const unsigned TileR = std::min(R - I, Opts.fuse_matrix_tile_size);
2092 const unsigned TileC = std::min(C - J, Opts.fuse_matrix_tile_size);
2093 MatrixTy Res = getZeroMatrix(EltType, TileR, TileC);
2094
2095 for (unsigned K = 0; K < M; K += Opts.fuse_matrix_tile_size) {
2096 const unsigned TileM = std::min(M - K, Opts.fuse_matrix_tile_size);
2097 MatrixTy A =
2098 loadMatrix(APtr, LoadOp0->getAlign(), LoadOp0->isVolatile(),
2099 LShape, getIndex(APtr, I), getIndex(APtr, K),
2100 {TileR, TileM}, EltType, Builder);
2101 MatrixTy B =
2102 loadMatrix(BPtr, LoadOp1->getAlign(), LoadOp1->isVolatile(),
2103 RShape, getIndex(BPtr, K), getIndex(BPtr, J),
2104 {TileM, TileC}, EltType, Builder);
2105 emitMatrixMultiply(Res, A, B, Builder, true, false,
2106 getFastMathFlags(MatMul));
2107 }
2108 storeMatrix(Res, CPtr, Store->getAlign(), Store->isVolatile(), {R, M},
2109 getIndex(CPtr, I), getIndex(CPtr, J), EltType, Builder);
2110 }
2111 }
2112
2113 // End the lifetime of the allocas used for alias-safe copies.
2114 {
2115 IRBuilder<> Builder(Store);
2116 if (AAlloca)
2117 Builder.CreateLifetimeEnd(AAlloca);
2118 if (BAlloca)
2119 Builder.CreateLifetimeEnd(BAlloca);
2120 }
2121
2122 // Mark eliminated instructions as fused and remove them.
2123 FusedInsts.insert(Store);
2124 FusedInsts.insert(MatMul);
2125 eraseFromParentAndRemoveFromShapeMap(Store);
2126 eraseFromParentAndRemoveFromShapeMap(MatMul);
2127 if (LoadOp0->use_empty()) {
2128 FusedInsts.insert(LoadOp0);
2129 eraseFromParentAndRemoveFromShapeMap(LoadOp0);
2130 }
2131 if (LoadOp1 != LoadOp0 && LoadOp1->use_empty()) {
2132 FusedInsts.insert(LoadOp1);
2133 eraseFromParentAndRemoveFromShapeMap(LoadOp1);
2134 }
2135 }
2136
2137 /// Try to lower matrix multiply chains by fusing operations.
2138 ///
2139 /// Call finalizeLowering on lowered instructions. Instructions that are
2140 /// completely eliminated by fusion are added to \p FusedInsts.
2141 void
2142 LowerMatrixMultiplyFused(CallInst *MatMul,
2143 SmallPtrSetImpl<Instruction *> &FusedInsts,
2144 SmallVector<IntrinsicInst *, 16> &LifetimeEnds) {
2145 if (!Opts.fuse_matrix || !DT || Opts.fuse_matrix_tile_size == 0)
2146 return;
2147
2148 assert(AA && LI && "Analyses should be available");
2149
2150 Value *A = MatMul->getArgOperand(0);
2151 Value *B = MatMul->getArgOperand(1);
2152
2153 // We can fold the transpose into the operand that is used to fetch scalars.
2154 Value *T;
2155 if (Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor
2158 IRBuilder<> Builder(MatMul);
2159 auto *EltType =
2160 cast<FixedVectorType>(MatMul->getType())->getElementType();
2161 ShapeInfo LShape(MatMul->getArgOperand(2), MatMul->getArgOperand(3));
2162 ShapeInfo RShape(MatMul->getArgOperand(3), MatMul->getArgOperand(4));
2163 const unsigned R = LShape.NumRows;
2164 const unsigned M = LShape.NumColumns;
2165 const unsigned C = RShape.NumColumns;
2166
2167 MatrixTy MA;
2168 MatrixTy MB;
2169
2170 Value *Transpose;
2171 if (Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor) {
2172 MA = getMatrix(A, ShapeInfo(R, M), Builder);
2173 MB = getMatrix(T, ShapeInfo(C, M), Builder);
2174 Transpose = B;
2175 } else {
2176 MA = getMatrix(T, ShapeInfo(R, M), Builder);
2177 MB = getMatrix(B, ShapeInfo(C, M), Builder);
2178 Transpose = A;
2179 }
2180
2181 // Initialize the output
2182 MatrixTy Result(isColumnMajor(), R, C, EltType);
2183
2184 emitMatrixMultiply(Result, MA, MB, Builder, false, true,
2185 getFastMathFlags(MatMul));
2186
2187 FusedInsts.insert(MatMul);
2188 if (Transpose->hasOneUse()) {
2189 FusedInsts.insert(cast<Instruction>(Transpose));
2190 ToRemove.push_back(cast<Instruction>(Transpose));
2191 // TODO: add a fake entry for the folded instruction so that this is
2192 // included in the expression in the remark.
2193 Inst2ColumnMatrix[Transpose] = MatrixTy(isColumnMajor(), M, C, EltType);
2194 }
2195 finalizeLowering(MatMul, Result, Builder);
2196 return;
2197 }
2198
2199 if (!MatMul->hasOneUse() ||
2200 Opts.matrix_default_layout != MatrixLayoutTy::ColumnMajor)
2201 return;
2202
2203 // Lower {ld, ld} -> matmul -> st chains. No need to call finalizeLowering
2204 // since the single store user will be lowered as part of this.
2205 auto *LoadOp0 = dyn_cast<LoadInst>(A);
2206 auto *LoadOp1 = dyn_cast<LoadInst>(B);
2207 auto *Store = dyn_cast<StoreInst>(*MatMul->user_begin());
2208 if (LoadOp0 && LoadOp1 && Store) {
2209 // The store address must dominate the MatMul instruction, otherwise
2210 // we create invalid IR.
2211 SetVector<Value *> WorkList;
2212 WorkList.insert(Store->getOperand(1));
2213 SmallVector<Instruction *> ToHoist;
2214 for (unsigned I = 0; I != WorkList.size(); ++I) {
2215 Value *Current = WorkList[I];
2216 auto *CurrI = dyn_cast<Instruction>(Current);
2217 if (!CurrI)
2218 continue;
2219 if (isa<PHINode>(CurrI))
2220 return;
2221 if (DT->dominates(CurrI, MatMul))
2222 continue;
2223 if (CurrI->mayHaveSideEffects() || CurrI->mayReadFromMemory())
2224 return;
2225 ToHoist.push_back(CurrI);
2226 WorkList.insert_range(CurrI->operands());
2227 }
2228
2229 sort(ToHoist, [this](Instruction *A, Instruction *B) {
2230 return DT->dominates(A, B);
2231 });
2232 for (Instruction *I : ToHoist)
2233 I->moveBefore(MatMul->getIterator());
2234
2235 // Deal with lifetime.end calls that might be between Load0/Load1 and the
2236 // store. To avoid introducing loads to dead objects (i.e. after the
2237 // lifetime has been termined by @llvm.lifetime.end), either sink them
2238 // after the store if in the same block, or remove the lifetime.end marker
2239 // otherwise. This might pessimize further optimizations, by extending the
2240 // lifetime of the object until the function returns, but should be
2241 // conservatively correct.
2242 MemoryLocation Load0Loc = MemoryLocation::get(LoadOp0);
2243 MemoryLocation Load1Loc = MemoryLocation::get(LoadOp1);
2244 BasicBlock *StoreParent = Store->getParent();
2245 bool FusableOpsInSameBlock = LoadOp0->getParent() == StoreParent &&
2246 LoadOp1->getParent() == StoreParent;
2247 for (unsigned Idx = 0; Idx != LifetimeEnds.size();) {
2248 IntrinsicInst *End = LifetimeEnds[Idx];
2249 llvm::scope_exit Inc([&Idx]() { Idx++; });
2250 // If the lifetime.end is guaranteed to be before the loads or after the
2251 // store, it won't interfere with fusion.
2252 if (DT->dominates(End, LoadOp0) && DT->dominates(End, LoadOp1))
2253 continue;
2254 if (DT->dominates(Store, End))
2255 continue;
2256 // If all fusable ops are in the same block and the lifetime.end is in a
2257 // different block, it won't interfere with fusion.
2258 if (FusableOpsInSameBlock && End->getParent() != StoreParent)
2259 continue;
2260
2261 // If the loads don't alias the lifetime.end, it won't interfere with
2262 // fusion.
2263 MemoryLocation EndLoc = MemoryLocation::getForArgument(End, 0, nullptr);
2264 if (!EndLoc.Ptr)
2265 continue;
2266 if (AA->isNoAlias(Load0Loc, EndLoc) && AA->isNoAlias(Load1Loc, EndLoc))
2267 continue;
2268
2269 // If both lifetime.end and the store are in the same block, extend the
2270 // lifetime until after the store, so the new lifetime covers the loads
2271 // we introduce later.
2272 if (End->getParent() == StoreParent) {
2273 End->moveAfter(Store);
2274 continue;
2275 }
2276
2277 // Otherwise remove the conflicting lifetime.end marker.
2278 ToRemove.push_back(End);
2279 std::swap(LifetimeEnds[Idx], LifetimeEnds.back());
2280 LifetimeEnds.pop_back();
2281 Inc.release();
2282 }
2283
2284 emitSIMDTiling(MatMul, LoadOp0, LoadOp1, Store, FusedInsts);
2285 return;
2286 }
2287 }
2288
2289 /// Lowers llvm.matrix.multiply.
2290 MatrixTy LowerMultiply(CallInst *MatMul, IRBuilder<> &Builder) {
2291 auto *EltType = cast<FixedVectorType>(MatMul->getType())->getElementType();
2292 ShapeInfo LShape(MatMul->getArgOperand(2), MatMul->getArgOperand(3));
2293 ShapeInfo RShape(MatMul->getArgOperand(3), MatMul->getArgOperand(4));
2294
2295 const MatrixTy &Lhs = getMatrix(MatMul->getArgOperand(0), LShape, Builder);
2296 const MatrixTy &Rhs = getMatrix(MatMul->getArgOperand(1), RShape, Builder);
2297 assert(Lhs.getElementType() == Rhs.getElementType() &&
2298 "Matrix multiply argument element types do not match.");
2299
2300 const unsigned R = LShape.NumRows;
2301 const unsigned C = RShape.NumColumns;
2302 assert(LShape.NumColumns == RShape.NumRows);
2303
2304 // Initialize the output
2305 MatrixTy Result(isColumnMajor(), R, C, EltType);
2306 assert(Lhs.getElementType() == Result.getElementType() &&
2307 "Matrix multiply result element type does not match arguments.");
2308
2309 emitMatrixMultiply(Result, Lhs, Rhs, Builder, false, false,
2310 getFastMathFlags(MatMul));
2311 return Result;
2312 }
2313
2314 /// Lowers llvm.matrix.transpose.
2315 MatrixTy LowerTranspose(CallInst *Inst, IRBuilder<> &Builder) {
2316 MatrixTy Result(isColumnMajor());
2317 Value *InputVal = Inst->getArgOperand(0);
2318 FixedVectorType *VectorTy = cast<FixedVectorType>(InputVal->getType());
2319 ShapeInfo ArgShape(Inst->getArgOperand(1), Inst->getArgOperand(2));
2320 MatrixTy InputMatrix = getMatrix(InputVal, ArgShape, Builder);
2321
2322 const unsigned NewNumVecs =
2323 InputMatrix.isColumnMajor() ? ArgShape.NumRows : ArgShape.NumColumns;
2324 const unsigned NewNumElts =
2325 InputMatrix.isColumnMajor() ? ArgShape.NumColumns : ArgShape.NumRows;
2326
2327 for (unsigned I = 0; I < NewNumVecs; ++I) {
2328 // Build a single result vector. First initialize it.
2329 Value *ResultVector = PoisonValue::get(
2330 FixedVectorType::get(VectorTy->getElementType(), NewNumElts));
2331 // Go through the old elements and insert it into the resulting vector.
2332 for (auto J : enumerate(InputMatrix.vectors())) {
2333 Value *Elt = Builder.CreateExtractElement(J.value(), I);
2334 // Row and column indices are transposed.
2335 ResultVector =
2336 Builder.CreateInsertElement(ResultVector, Elt, J.index());
2337 }
2338 Result.addVector(ResultVector);
2339 }
2340
2341 // TODO: Improve estimate of operations needed for transposes. Currently we
2342 // just count the insertelement/extractelement instructions, but do not
2343 // account for later simplifications/combines.
2344 return Result.addNumComputeOps(2 * ArgShape.NumRows * ArgShape.NumColumns)
2345 .addNumExposedTransposes(1);
2346 }
2347
2348 /// Lower load instructions.
2349 MatrixTy VisitLoad(LoadInst *Inst, const ShapeInfo &SI, Value *Ptr,
2350 IRBuilder<> &Builder) {
2351 return LowerLoad(Inst, Ptr, Inst->getAlign(), getIndex(Ptr, getStride(SI)),
2352 Inst->isVolatile(), SI, Builder);
2353 }
2354
2355 MatrixTy VisitStore(StoreInst *Inst, const ShapeInfo &SI, Value *StoredVal,
2356 Value *Ptr, IRBuilder<> &Builder) {
2357 return LowerStore(Inst, StoredVal, Ptr, Inst->getAlign(),
2358 getIndex(Ptr, getStride(SI)), Inst->isVolatile(), SI,
2359 Builder);
2360 }
2361
2362 MatrixTy VisitPHI(PHINode *Inst, const ShapeInfo &SI, IRBuilder<> &Builder) {
2363 auto BlockIP = Inst->getParent()->getFirstInsertionPt();
2364 Builder.SetInsertPoint(BlockIP);
2365 MatrixTy PhiM = getMatrix(Inst, SI, Builder);
2366
2367 // Cache the reshaped columns per incoming block, so that a block listed
2368 // more than once contributes identical incoming values to the new PHIs.
2369 SmallDenseMap<BasicBlock *, MatrixTy> ReshapedIncoming;
2370 for (auto [IncomingV, IncomingB] :
2371 llvm::zip_equal(Inst->incoming_values(), Inst->blocks())) {
2372 // getMatrix() may insert some instructions to help with reshaping. The
2373 // safest place for those is just before the terminator of the incoming
2374 // block. If there's a valid insert point before the def, even better.
2375 Builder.SetInsertPoint(IncomingB->getTerminator());
2376 if (auto *IncomingInst = dyn_cast<Instruction>(IncomingV))
2377 if (auto MaybeIP = IncomingInst->getInsertionPointAfterDef())
2378 Builder.SetInsertPoint(*MaybeIP);
2379
2380 auto [It, Inserted] = ReshapedIncoming.try_emplace(IncomingB);
2381 if (Inserted)
2382 It->second = getMatrix(IncomingV, SI, Builder);
2383 const MatrixTy &OpM = It->second;
2384
2385 for (unsigned VI = 0, VE = PhiM.getNumVectors(); VI != VE; ++VI) {
2386 PHINode *NewPHI = cast<PHINode>(PhiM.getVector(VI));
2387 NewPHI->addIncoming(OpM.getVector(VI), IncomingB);
2388 }
2389 }
2390
2391 // finalizeLowering() may also insert instructions in some cases. The safe
2392 // place for those is at the end of the initial block of PHIs.
2393 Builder.SetInsertPoint(BlockIP);
2394 return PhiM;
2395 }
2396
2397 /// Lower binary operators.
2398 MatrixTy VisitBinaryOperator(BinaryOperator *Inst, const ShapeInfo &SI,
2399 IRBuilder<> &Builder) {
2400 Value *Lhs = Inst->getOperand(0);
2401 Value *Rhs = Inst->getOperand(1);
2402
2403 MatrixTy Result(isColumnMajor());
2404 MatrixTy A = getMatrix(Lhs, SI, Builder);
2405 MatrixTy B = getMatrix(Rhs, SI, Builder);
2406 assert(A.isColumnMajor() == B.isColumnMajor() &&
2407 Result.isColumnMajor() == A.isColumnMajor() &&
2408 "operands must agree on matrix layout");
2409
2410 Builder.setFastMathFlags(getFastMathFlags(Inst));
2411
2412 for (auto [AV, BV] : llvm::zip_equal(A.vectors(), B.vectors()))
2413 Result.addVector(Builder.CreateBinOp(Inst->getOpcode(), AV, BV));
2414
2415 return Result.addNumComputeOps(getNumOps(Result.getVectorTy()) *
2416 Result.getNumVectors());
2417 }
2418
2419 /// Lower unary operators.
2420 MatrixTy VisitUnaryOperator(UnaryOperator *Inst, const ShapeInfo &SI,
2421 IRBuilder<> &Builder) {
2422 Value *Op = Inst->getOperand(0);
2423
2424 MatrixTy Result(isColumnMajor());
2425 MatrixTy M = getMatrix(Op, SI, Builder);
2426
2427 Builder.setFastMathFlags(getFastMathFlags(Inst));
2428
2429 // Helper to perform unary op on vectors.
2430 auto BuildVectorOp = [&Builder, Inst](Value *Op) {
2431 switch (Inst->getOpcode()) {
2432 case Instruction::FNeg:
2433 return Builder.CreateFNeg(Op);
2434 default:
2435 llvm_unreachable("Unsupported unary operator for matrix");
2436 }
2437 };
2438
2439 for (auto *Vector : M.vectors())
2440 Result.addVector(BuildVectorOp(Vector));
2441
2442 return Result.addNumComputeOps(getNumOps(Result.getVectorTy()) *
2443 Result.getNumVectors());
2444 }
2445
2446 /// Lower cast instructions.
2447 MatrixTy VisitCastInstruction(CastInst *Inst, const ShapeInfo &Shape,
2448 IRBuilder<> &Builder) {
2449 Value *Op = Inst->getOperand(0);
2450
2451 MatrixTy Result(isColumnMajor());
2452 MatrixTy M = getMatrix(Op, Shape, Builder);
2453
2454 Builder.setFastMathFlags(getFastMathFlags(Inst));
2455
2456 auto *OrigVTy = cast<VectorType>(Inst->getType());
2457 auto *NewVTy = VectorType::get(OrigVTy->getElementType(),
2458 ElementCount::getFixed(M.getStride()));
2459
2460 for (auto *Vector : M.vectors())
2461 Result.addVector(Builder.CreateCast(Inst->getOpcode(), Vector, NewVTy));
2462
2463 return Result.addNumComputeOps(getNumOps(Result.getVectorTy()) *
2464 Result.getNumVectors());
2465 }
2466
2467 /// Lower selects.
2468 MatrixTy VisitSelectInst(SelectInst *Inst, const ShapeInfo &Shape,
2469 IRBuilder<> &Builder) {
2470 Value *Cond = Inst->getOperand(0);
2471 Value *OpA = Inst->getOperand(1);
2472 Value *OpB = Inst->getOperand(2);
2473
2474 MatrixTy Result(isColumnMajor());
2475 MatrixTy A = getMatrix(OpA, Shape, Builder);
2476 MatrixTy B = getMatrix(OpB, Shape, Builder);
2477
2478 SmallVector<Value*> CondV;
2479 Instruction *MDFrom = nullptr;
2480 if (isa<FixedVectorType>(Cond->getType())) {
2481 MatrixTy C = getMatrix(Cond, Shape, Builder);
2482 llvm::copy(C.vectors(), std::back_inserter(CondV));
2483 } else {
2484 CondV.resize(A.getNumVectors());
2485 llvm::fill(CondV, Cond);
2487 MDFrom = Inst;
2488 }
2489
2490 for (auto [CV, AV, BV] : llvm::zip_equal(CondV, A.vectors(), B.vectors())) {
2491 assert(!(isa<VectorType>(CV->getType()) && static_cast<bool>(MDFrom)) &&
2492 "If we have a vector conditional, we should be propagating "
2493 "profile information.");
2494 Result.addVector(Builder.CreateSelect(CV, AV, BV, "", MDFrom));
2495 }
2496
2497 return Result.addNumComputeOps(getNumOps(Result.getVectorTy()) *
2498 Result.getNumVectors());
2499 }
2500
2501 /// Helper to linearize a matrix expression tree into a string. Currently
2502 /// matrix expressions are linarized by starting at an expression leaf and
2503 /// linearizing bottom up.
2504 struct ExprLinearizer {
2505 unsigned LengthToBreak = 100;
2506 std::string Str;
2507 raw_string_ostream Stream;
2508 unsigned LineLength = 0;
2509 const DataLayout &DL;
2510
2511 /// Mapping from instructions to matrixes. It is used to identify
2512 /// matrix instructions.
2513 const MapVector<Value *, MatrixTy> &Inst2Matrix;
2514
2515 /// Mapping from values to the leaves of all expressions that the value is
2516 /// part of.
2517 const DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared;
2518
2519 /// Set of matrix expressions in the scope of a given DISubprogram.
2520 const SmallSetVector<Value *, 32> &ExprsInSubprogram;
2521
2522 /// Leaf node of the expression to linearize.
2523 Value *Leaf;
2524
2525 /// Used to keep track of sub-expressions that get reused while linearizing
2526 /// the expression. Re-used sub-expressions are marked as (reused).
2527 SmallPtrSet<Value *, 8> ReusedExprs;
2528
2529 ExprLinearizer(const DataLayout &DL,
2530 const MapVector<Value *, MatrixTy> &Inst2Matrix,
2531 const DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared,
2532 const SmallSetVector<Value *, 32> &ExprsInSubprogram,
2533 Value *Leaf)
2534 : Stream(Str), DL(DL), Inst2Matrix(Inst2Matrix), Shared(Shared),
2535 ExprsInSubprogram(ExprsInSubprogram), Leaf(Leaf) {}
2536
2537 void indent(unsigned N) {
2538 LineLength += N;
2539 for (unsigned i = 0; i < N; i++)
2540 Stream << " ";
2541 }
2542
2543 void lineBreak() {
2544 Stream << "\n";
2545 LineLength = 0;
2546 }
2547
2548 void maybeIndent(unsigned Indent) {
2549 if (LineLength >= LengthToBreak)
2550 lineBreak();
2551
2552 if (LineLength == 0)
2553 indent(Indent);
2554 }
2555
2556 void write(StringRef S) {
2557 LineLength += S.size();
2558 Stream << S;
2559 }
2560
2561 Value *getUnderlyingObjectThroughLoads(Value *V) {
2562 if (Value *Ptr = getPointerOperand(V))
2563 return getUnderlyingObjectThroughLoads(Ptr);
2564 else if (V->getType()->isPointerTy())
2565 return getUnderlyingObject(V);
2566 return V;
2567 }
2568
2569 /// Returns true if \p V is a matrix value in the given subprogram.
2570 bool isMatrix(Value *V) const { return ExprsInSubprogram.count(V); }
2571
2572 /// If \p V is a matrix value, print its shape as NumRows x NumColumns to
2573 /// \p SS.
2574 void prettyPrintMatrixType(Value *V, raw_string_ostream &SS) {
2575 auto M = Inst2Matrix.find(V);
2576 if (M == Inst2Matrix.end())
2577 SS << "unknown";
2578 else {
2579 SS << M->second.getNumRows();
2580 SS << "x";
2581 SS << M->second.getNumColumns();
2582 }
2583 }
2584
2585 /// Write the called function name. Handles calls to llvm.matrix.*
2586 /// specially: we write the name, followed by the dimensions of the input
2587 /// matrixes, followed by the scalar type name.
2588 void writeFnName(CallInst *CI) {
2589 if (!CI->getCalledFunction())
2590 write("<no called fn>");
2591 else {
2592 StringRef Name = CI->getCalledFunction()->getName();
2593 if (!Name.starts_with("llvm.matrix")) {
2594 write(Name);
2595 return;
2596 }
2597 auto *II = cast<IntrinsicInst>(CI);
2598 write(Intrinsic::getBaseName(II->getIntrinsicID())
2599 .drop_front(StringRef("llvm.matrix.").size()));
2600 write(".");
2601 std::string Tmp;
2602 raw_string_ostream SS(Tmp);
2603
2604 switch (II->getIntrinsicID()) {
2605 case Intrinsic::matrix_multiply:
2606 prettyPrintMatrixType(II->getOperand(0), SS);
2607 SS << ".";
2608 prettyPrintMatrixType(II->getOperand(1), SS);
2609 SS << "." << *II->getType()->getScalarType();
2610 break;
2611 case Intrinsic::matrix_transpose:
2612 prettyPrintMatrixType(II->getOperand(0), SS);
2613 SS << "." << *II->getType()->getScalarType();
2614 break;
2615 case Intrinsic::matrix_column_major_load:
2616 prettyPrintMatrixType(II, SS);
2617 SS << "." << *II->getType()->getScalarType();
2618 break;
2619 case Intrinsic::matrix_column_major_store:
2620 prettyPrintMatrixType(II->getOperand(0), SS);
2621 SS << "." << *II->getOperand(0)->getType()->getScalarType();
2622 break;
2623 default:
2624 llvm_unreachable("Unhandled case");
2625 }
2626 write(Tmp);
2627 }
2628 }
2629
2630 unsigned getNumShapeArgs(CallInst *CI) const {
2631 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2632 switch (II->getIntrinsicID()) {
2633 case Intrinsic::matrix_multiply:
2634 return 3;
2635 case Intrinsic::matrix_transpose:
2636 return 2;
2637 case Intrinsic::matrix_column_major_load:
2638 case Intrinsic::matrix_column_major_store:
2639 return 3;
2640 default:
2641 return 0;
2642 }
2643 }
2644 return 0;
2645 }
2646
2647 /// Special printing for values: for pointers, we print if they refer to an
2648 /// (function) external address or a stack address, for other values we
2649 /// either print the constant or "scalar"/"matrix" for other values.
2650 void write(Value *V) {
2651 V = getUnderlyingObjectThroughLoads(V);
2652 if (V->getType()->isPointerTy()) {
2653 if (isa<AllocaInst>(V)) {
2654 Stream << "stack addr";
2655 LineLength += StringRef("stack addr").size();
2656 } else {
2657 Stream << "addr";
2658 LineLength += StringRef("addr").size();
2659 }
2660 if (!V->getName().empty()) {
2661 Stream << " %" << V->getName() << "";
2662 LineLength += V->getName().size() + 2;
2663 }
2664 return;
2665 }
2666
2667 std::string Tmp;
2668 raw_string_ostream TmpStream(Tmp);
2669
2670 if (auto *CI = dyn_cast<ConstantInt>(V))
2671 TmpStream << CI->getValue();
2672 else if (isa<Constant>(V))
2673 TmpStream << "constant";
2674 else {
2675 if (isMatrix(V))
2676 TmpStream << "matrix";
2677 else
2678 TmpStream << "scalar";
2679 }
2680 Tmp = std::string(StringRef(Tmp).trim());
2681 LineLength += Tmp.size();
2682 Stream << Tmp;
2683 }
2684
2685 /// Linearize expression \p Expr starting at an indentation of \p Indent.
2686 /// Expressions that are re-used multiple times are prefixed with (reused)
2687 /// at the re-used root instruction.
2688 void linearizeExpr(Value *Expr, unsigned Indent, bool ParentReused,
2689 bool ParentShared) {
2690 auto *I = cast<Instruction>(Expr);
2691 maybeIndent(Indent);
2692 SmallVector<Value *, 8> Ops;
2693
2694 // Is Expr shared with other expression leaves?
2695 bool ExprShared = false;
2696
2697 // Deal with shared subtrees. Mark them as shared, if required.
2698 if (!ParentShared) {
2699 auto SI = Shared.find(Expr);
2700 assert(SI != Shared.end() && SI->second.count(Leaf));
2701
2702 for (Value *S : SI->second) {
2703 if (S == Leaf)
2704 continue;
2705 DebugLoc DL = cast<Instruction>(S)->getDebugLoc();
2706 write("shared with remark at line " + std::to_string(DL.getLine()) +
2707 " column " + std::to_string(DL.getCol()) + " (");
2708 }
2709 ExprShared = SI->second.size() > 1;
2710 }
2711
2712 bool Reused = !ReusedExprs.insert(Expr).second;
2713 if (Reused && !ParentReused)
2714 write("(reused) ");
2715
2716 if (auto *CI = dyn_cast<CallInst>(I)) {
2717 writeFnName(CI);
2718
2719 Ops.append(CI->arg_begin(), CI->arg_end() - getNumShapeArgs(CI));
2720 } else if (isa<BitCastInst>(Expr)) {
2721 // Special case bitcasts, which are used to materialize matrixes from
2722 // non-matrix ops.
2723 write("matrix");
2724 return;
2725 } else {
2726 Ops.append(I->value_op_begin(), I->value_op_end());
2727 write(I->getOpcodeName());
2728 }
2729
2730 write("(");
2731
2732 unsigned NumOpsToBreak = 1;
2734 NumOpsToBreak = 2;
2735
2736 for (Value *Op : Ops) {
2737 if (Ops.size() > NumOpsToBreak)
2738 lineBreak();
2739
2740 maybeIndent(Indent + 1);
2741 if (isMatrix(Op))
2742 linearizeExpr(Op, Indent + 1, Reused, ExprShared);
2743 else
2744 write(Op);
2745 if (Op != Ops.back())
2746 write(", ");
2747 }
2748
2749 write(")");
2750 }
2751
2752 const std::string &getResult() {
2753 return Str;
2754 }
2755 };
2756
2757 /// Generate remarks for matrix operations in a function. To generate remarks
2758 /// for matrix expressions, the following approach is used:
2759 /// 1. Use the inlined-at debug information to group matrix operations to the
2760 /// DISubprograms they are contained in.
2761 /// 2. Collect leaves of matrix expressions (done in
2762 /// RemarkGenerator::getExpressionLeaves) for each subprogram - expression
2763 // mapping. Leaves are lowered matrix instructions without other matrix
2764 // users (like stores) in the current subprogram.
2765 /// 3. For each leaf, create a remark containing a linearizied version of the
2766 /// matrix expression. The expression is linearized by a recursive
2767 /// bottom-up traversal of the matrix operands, starting at a leaf. Note
2768 /// that multiple leaves can share sub-expressions. Shared subexpressions
2769 /// are explicitly marked as shared().
2770 struct RemarkGenerator {
2771 const MapVector<Value *, MatrixTy> &Inst2Matrix;
2772 OptimizationRemarkEmitter &ORE;
2773 Function &Func;
2774 const DataLayout &DL;
2775
2776 RemarkGenerator(const MapVector<Value *, MatrixTy> &Inst2Matrix,
2777 OptimizationRemarkEmitter &ORE, Function &Func)
2778 : Inst2Matrix(Inst2Matrix), ORE(ORE), Func(Func),
2779 DL(Func.getDataLayout()) {}
2780
2781 /// Return all leaves of the expressions in \p ExprsInSubprogram. Those are
2782 /// instructions in Inst2Matrix returning void or without any users in
2783 /// \p ExprsInSubprogram. Currently that should only include stores.
2784 SmallVector<Value *, 4>
2785 getExpressionLeaves(const SmallSetVector<Value *, 32> &ExprsInSubprogram) {
2786 SmallVector<Value *, 4> Leaves;
2787 for (auto *Expr : ExprsInSubprogram)
2788 if (Expr->getType()->isVoidTy() ||
2789 !any_of(Expr->users(), [&ExprsInSubprogram](User *U) {
2790 return ExprsInSubprogram.count(U);
2791 }))
2792 Leaves.push_back(Expr);
2793 return Leaves;
2794 }
2795
2796 /// Recursively traverse expression \p V starting at \p Leaf and add \p Leaf
2797 /// to all visited expressions in \p Shared. Limit the matrix operations to
2798 /// the ones in \p ExprsInSubprogram.
2799 void collectSharedInfo(Value *Leaf, Value *V,
2800 const SmallSetVector<Value *, 32> &ExprsInSubprogram,
2801 DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared) {
2802
2803 if (!ExprsInSubprogram.count(V))
2804 return;
2805
2806 Shared[V].insert(Leaf);
2807
2808 for (Value *Op : cast<Instruction>(V)->operand_values())
2809 collectSharedInfo(Leaf, Op, ExprsInSubprogram, Shared);
2810 }
2811
2812 /// Calculate the number of exclusive and shared op counts for expression
2813 /// starting at \p V. Expressions used multiple times are counted once.
2814 /// Limit the matrix operations to the ones in \p ExprsInSubprogram.
2815 std::pair<OpInfoTy, OpInfoTy>
2816 sumOpInfos(Value *Root, SmallPtrSetImpl<Value *> &ReusedExprs,
2817 const SmallSetVector<Value *, 32> &ExprsInSubprogram,
2818 DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared) const {
2819 if (!ExprsInSubprogram.count(Root))
2820 return {};
2821
2822 // Already counted this expression. Stop.
2823 if (!ReusedExprs.insert(Root).second)
2824 return {};
2825
2826 OpInfoTy SharedCount;
2827 OpInfoTy Count;
2828
2829 auto I = Shared.find(Root);
2830 auto CM = Inst2Matrix.find(Root);
2831 if (I->second.size() == 1)
2832 Count = CM->second.getOpInfo();
2833 else
2834 SharedCount = CM->second.getOpInfo();
2835
2836 for (Value *Op : cast<Instruction>(Root)->operand_values()) {
2837 auto C = sumOpInfos(Op, ReusedExprs, ExprsInSubprogram, Shared);
2838 Count += C.first;
2839 SharedCount += C.second;
2840 }
2841 return {Count, SharedCount};
2842 }
2843
2844 void emitRemarks() {
2845 if (!ORE.allowExtraAnalysis(DEBUG_TYPE))
2846 return;
2847
2848 // Map matrix operations to their containting subprograms, by traversing
2849 // the inlinedAt chain. If the function does not have a DISubprogram, we
2850 // only map them to the containing function.
2851 MapVector<DISubprogram *, SmallVector<Value *, 8>> Subprog2Exprs;
2852 for (const auto &KV : Inst2Matrix) {
2853 if (Func.getSubprogram()) {
2854 auto *I = cast<Instruction>(KV.first);
2855 DILocation *Context = I->getDebugLoc();
2856 while (Context) {
2857 Subprog2Exprs[getSubprogram(Context->getScope())].push_back(
2858 KV.first);
2859 Context = DebugLoc(Context).getInlinedAt();
2860 }
2861 } else {
2862 Subprog2Exprs[nullptr].push_back(KV.first);
2863 }
2864 }
2865 for (auto &KV : Subprog2Exprs) {
2866 SmallSetVector<Value *, 32> ExprsInSubprogram(KV.second.begin(),
2867 KV.second.end());
2868 auto Leaves = getExpressionLeaves(ExprsInSubprogram);
2869
2870 DenseMap<Value *, SmallPtrSet<Value *, 2>> Shared;
2871 for (Value *Leaf : Leaves)
2872 collectSharedInfo(Leaf, Leaf, ExprsInSubprogram, Shared);
2873
2874 // Generate remarks for each leaf.
2875 for (auto *L : Leaves) {
2876
2877 DebugLoc Loc = cast<Instruction>(L)->getDebugLoc();
2878 DILocation *Context = cast<Instruction>(L)->getDebugLoc();
2879 while (Context) {
2880 if (getSubprogram(Context->getScope()) == KV.first) {
2881 Loc = Context;
2882 break;
2883 }
2884 Context = DebugLoc(Context).getInlinedAt();
2885 }
2886
2887 SmallPtrSet<Value *, 8> ReusedExprs;
2888 OpInfoTy Counts, SharedCounts;
2889 std::tie(Counts, SharedCounts) =
2890 sumOpInfos(L, ReusedExprs, ExprsInSubprogram, Shared);
2891
2892 OptimizationRemark Rem(DEBUG_TYPE, "matrix-lowered", Loc,
2894
2895 Rem << "Lowered with ";
2896 Rem << ore::NV("NumStores", Counts.NumStores) << " stores, "
2897 << ore::NV("NumLoads", Counts.NumLoads) << " loads, "
2898 << ore::NV("NumComputeOps", Counts.NumComputeOps)
2899 << " compute ops, "
2900 << ore::NV("NumExposedTransposes", Counts.NumExposedTransposes)
2901 << " exposed transposes";
2902
2903 if (SharedCounts.NumStores > 0 || SharedCounts.NumLoads > 0 ||
2904 SharedCounts.NumComputeOps > 0) {
2905 Rem << ",\nadditionally "
2906 << ore::NV("NumStores", SharedCounts.NumStores) << " stores, "
2907 << ore::NV("NumLoads", SharedCounts.NumLoads) << " loads, "
2908 << ore::NV("NumFPOps", SharedCounts.NumComputeOps)
2909 << " compute ops"
2910 << " are shared with other expressions";
2911 }
2912
2913 Rem << ("\n" + linearize(L, Shared, ExprsInSubprogram, DL));
2914 ORE.emit(Rem);
2915 }
2916 }
2917 }
2918
2919 std::string
2920 linearize(Value *L,
2921 const DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared,
2922 const SmallSetVector<Value *, 32> &ExprsInSubprogram,
2923 const DataLayout &DL) {
2924 ExprLinearizer Lin(DL, Inst2Matrix, Shared, ExprsInSubprogram, L);
2925 Lin.linearizeExpr(L, 0, false, false);
2926 return Lin.getResult();
2927 }
2928 };
2929};
2930} // namespace
2931
2934 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
2935
2936 const ScalarOptions &Opts = getScalarOptions(F);
2937 LowerMatrixIntrinsics LMT(Opts, F, TTI, Minimal ? nullptr : &AM);
2938 if (LMT.Visit()) {
2940 if (!Minimal) {
2941 PA.preserve<LoopAnalysis>();
2943 }
2944 return PA;
2945 }
2946 return PreservedAnalyses::all();
2947}
2948
2950 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
2951 static_cast<PassInfoMixin<LowerMatrixIntrinsicsPass> *>(this)->printPipeline(
2952 OS, MapClassName2PassName);
2953 OS << '<';
2954 if (Minimal)
2955 OS << "minimal";
2956 OS << '>';
2957}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
static const Function * getParent(const Value *V)
BitTracker BT
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.
Definition Compiler.h:690
Hexagon Common GEP
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...
iv users
Definition IVUsers.cpp:48
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)
Definition Lint.cpp:540
Live Register Matrix
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.
#define DEBUG_TYPE
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)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define T1
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.
SmallVector< MachineOperand, 4 > Cond
static unsigned getFastMathFlags(const MachineInstr &I, const SPIRVSubtarget &ST)
static Value * extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex, unsigned EndIndex, const Twine &Name)
Definition SROA.cpp:2695
static Value * insertVector(IRBuilderTy &IRB, Value *Old, Value *V, unsigned BeginIndex, const Twine &Name)
Definition SROA.cpp:2716
This file contains some templates that are useful if you are working with the STL at all.
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)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static const int BlockSize
Definition TarWriter.cpp:33
This pass exposes codegen information to IR-level passes.
static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget, SelectionDAG &DAG)
static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget, SelectionDAG &DAG)
Value * RHS
Value * LHS
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
void setAlignment(Align Align)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
reverse_iterator rbegin()
Definition BasicBlock.h:456
InstListType::reverse_iterator reverse_iterator
Definition BasicBlock.h:172
reverse_iterator rend()
Definition BasicBlock.h:458
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
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.
Definition InstrTypes.h:674
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
static ConstantFP * getNegativeZero(Type *Ty)
Definition Constants.h:458
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)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
void setAllowContract(bool B=true)
Definition FMF.h:90
bool allowReassoc() const
Flag queries.
Definition FMF.h:64
bool allowContract() const
Definition FMF.h:69
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:247
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:252
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2398
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2669
LLVM_ABI CallInst * CreateLifetimeStart(Value *Ptr)
Create a lifetime.start intrinsic.
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2657
LLVM_ABI CallInst * CreateLifetimeEnd(Value *Ptr)
Create a lifetime.end intrinsic.
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition IRBuilder.h:1934
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2139
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.
Definition IRBuilder.h:651
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1212
Value * CreateFAdd(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Definition IRBuilder.h:1632
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())
Definition IRBuilder.h:2092
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2284
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:288
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition IRBuilder.h:2019
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="")
Definition IRBuilder.h:2547
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.
Definition IRBuilder.h:475
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition IRBuilder.h:2691
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)
Definition IRBuilder.h:1418
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1727
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:196
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition IRBuilder.h:1953
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)
Definition IRBuilder.h:1670
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1835
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1452
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...
Definition IRBuilder.h:2909
static InstructionCost getInvalid(CostType Val=0)
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.
Definition LoopInfo.h:594
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.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:182
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
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 resize(size_type N)
void push_back(const T &Elt)
Align getAlign() const
bool isVolatile() const
Return true if this is a store to a volatile memory location.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:635
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
Analysis pass providing the TargetTransformInfo.
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
UnaryOps getOpcode() const
Definition InstrTypes.h:163
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
iterator_range< user_iterator > users()
Definition Value.h:428
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#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.
Definition ISDOpcodes.h:83
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.
Definition DXILABI.h:68
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
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.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:61
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.
Definition STLExtras.h:1685
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.
Definition STLExtras.h:856
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
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.
Definition Casting.h:643
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)
Definition APInt.h:2139
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...
Definition STLExtras.h:649
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
const ScalarOptions & getScalarOptions(const LLVMContext &C)
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
Definition InstrProf.h:143
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.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
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...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
TargetTransformInfo TTI
@ Mul
Product of integers.
@ Add
Sum 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
Definition InstrProf.h:145
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
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)
Definition DWP.cpp:746
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.
Definition BitVector.h:880
#define N