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 20 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h" 21 #include "llvm/ADT/GraphTraits.h" 22 #include "llvm/ADT/PostOrderIterator.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/Analysis/DomTreeUpdater.h" 26 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 27 #include "llvm/Analysis/TargetTransformInfo.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/Analysis/VectorUtils.h" 30 #include "llvm/IR/CFG.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/DebugInfoMetadata.h" 33 #include "llvm/IR/Function.h" 34 #include "llvm/IR/IRBuilder.h" 35 #include "llvm/IR/Instructions.h" 36 #include "llvm/IR/IntrinsicInst.h" 37 #include "llvm/IR/PatternMatch.h" 38 #include "llvm/InitializePasses.h" 39 #include "llvm/Pass.h" 40 #include "llvm/Support/Alignment.h" 41 #include "llvm/Support/CommandLine.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Transforms/Scalar.h" 44 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 45 #include "llvm/Transforms/Utils/LoopUtils.h" 46 #include "llvm/Transforms/Utils/MatrixUtils.h" 47 48 using namespace llvm; 49 using namespace PatternMatch; 50 51 #define DEBUG_TYPE "lower-matrix-intrinsics" 52 53 static cl::opt<bool> EnableShapePropagation( 54 "matrix-propagate-shape", cl::init(true), cl::Hidden, 55 cl::desc("Enable/disable shape propagation from matrix intrinsics to other " 56 "instructions.")); 57 58 static cl::opt<bool> 59 FuseMatrix("fuse-matrix", cl::init(true), cl::Hidden, 60 cl::desc("Enable/disable fusing matrix instructions.")); 61 // TODO: Allow and use non-square tiles. 62 static cl::opt<unsigned> TileSize( 63 "fuse-matrix-tile-size", cl::init(4), cl::Hidden, 64 cl::desc( 65 "Tile size for matrix instruction fusion using square-shaped tiles.")); 66 static cl::opt<bool> TileUseLoops("fuse-matrix-use-loops", cl::init(false), 67 cl::Hidden, 68 cl::desc("Generate loop nest for tiling.")); 69 static cl::opt<bool> ForceFusion( 70 "force-fuse-matrix", cl::init(false), cl::Hidden, 71 cl::desc("Force matrix instruction fusion even if not profitable.")); 72 static cl::opt<bool> AllowContractEnabled( 73 "matrix-allow-contract", cl::init(false), cl::Hidden, 74 cl::desc("Allow the use of FMAs if available and profitable. This may " 75 "result in different results, due to less rounding error.")); 76 77 enum class MatrixLayoutTy { ColumnMajor, RowMajor }; 78 79 static cl::opt<MatrixLayoutTy> MatrixLayout( 80 "matrix-default-layout", cl::init(MatrixLayoutTy::ColumnMajor), 81 cl::desc("Sets the default matrix layout"), 82 cl::values(clEnumValN(MatrixLayoutTy::ColumnMajor, "column-major", 83 "Use column-major layout"), 84 clEnumValN(MatrixLayoutTy::RowMajor, "row-major", 85 "Use row-major layout"))); 86 87 /// Helper function to either return Scope, if it is a subprogram or the 88 /// attached subprogram for a local scope. 89 static DISubprogram *getSubprogram(DIScope *Scope) { 90 if (auto *Subprogram = dyn_cast<DISubprogram>(Scope)) 91 return Subprogram; 92 return cast<DILocalScope>(Scope)->getSubprogram(); 93 } 94 95 namespace { 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 // 137 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 unsigned AS = cast<PointerType>(BasePtr->getType())->getAddressSpace(); 145 146 // Compute the start of the vector with index VecIdx as VecIdx * Stride. 147 Value *VecStart = Builder.CreateMul(VecIdx, Stride, "vec.start"); 148 149 // Get pointer to the start of the selected vector. Skip GEP creation, 150 // if we select vector 0. 151 if (isa<ConstantInt>(VecStart) && cast<ConstantInt>(VecStart)->isZero()) 152 VecStart = BasePtr; 153 else 154 VecStart = Builder.CreateGEP(EltType, BasePtr, VecStart, "vec.gep"); 155 156 // Cast elementwise vector start pointer to a pointer to a vector 157 // (EltType x NumElements)*. 158 auto *VecType = FixedVectorType::get(EltType, NumElements); 159 Type *VecPtrType = PointerType::get(VecType, AS); 160 return Builder.CreatePointerCast(VecStart, VecPtrType, "vec.cast"); 161 } 162 163 /// LowerMatrixIntrinsics contains the methods used to lower matrix intrinsics. 164 /// 165 /// Currently, the lowering for each matrix intrinsic is done as follows: 166 /// 1. Propagate the shape information from intrinsics to connected 167 /// instructions. 168 /// 2. Lower instructions with shape information (assuming column-major layout). 169 /// The lowering works similarly using row-major layout. 170 /// 2.1. Get column vectors for each argument. If we already lowered the 171 /// definition of an argument, use the produced column vectors directly. 172 /// If not, split the operand vector containing an embedded matrix into 173 /// a set of column vectors, 174 /// 2.2. Lower the instruction in terms of column major operations, which 175 /// yields a set of column vectors containing result matrix. Note that we 176 /// lower all instructions that have shape information. Besides the 177 /// intrinsics, this includes stores for example. 178 /// 2.3. Update uses of the lowered instruction. If we have shape information 179 /// for a user, there is nothing to do, as we will look up the result 180 /// column matrix when lowering the user. For other uses, we embed the 181 /// result matrix in a flat vector and update the use. 182 /// 2.4. Cache the result column matrix for the instruction we lowered 183 /// 3. After we lowered all instructions in a function, remove the now 184 /// obsolete instructions. 185 /// 186 class LowerMatrixIntrinsics { 187 Function &Func; 188 const DataLayout &DL; 189 const TargetTransformInfo &TTI; 190 AliasAnalysis *AA; 191 DominatorTree *DT; 192 LoopInfo *LI; 193 OptimizationRemarkEmitter *ORE; 194 195 /// Contains estimates of the number of operations (loads, stores, compute) required to lower a matrix operation. 196 struct OpInfoTy { 197 /// Number of stores emitted to generate this matrix. 198 unsigned NumStores = 0; 199 /// Number of loads emitted to generate this matrix. 200 unsigned NumLoads = 0; 201 /// Number of compute operations emitted to generate this matrix. 202 unsigned NumComputeOps = 0; 203 204 OpInfoTy &operator+=(const OpInfoTy &RHS) { 205 NumStores += RHS.NumStores; 206 NumLoads += RHS.NumLoads; 207 NumComputeOps += RHS.NumComputeOps; 208 return *this; 209 } 210 }; 211 212 /// Wrapper class representing a matrix as a set of vectors, either in row or 213 /// column major layout. All vectors must have the same vector type. 214 class MatrixTy { 215 SmallVector<Value *, 16> Vectors; 216 217 OpInfoTy OpInfo; 218 219 bool IsColumnMajor = true; 220 221 public: 222 MatrixTy() 223 : Vectors(), 224 IsColumnMajor(MatrixLayout == MatrixLayoutTy::ColumnMajor) {} 225 MatrixTy(ArrayRef<Value *> Vectors) 226 : Vectors(Vectors.begin(), Vectors.end()), 227 IsColumnMajor(MatrixLayout == MatrixLayoutTy::ColumnMajor) {} 228 MatrixTy(unsigned NumRows, unsigned NumColumns, Type *EltTy) 229 : IsColumnMajor(MatrixLayout == MatrixLayoutTy::ColumnMajor) { 230 231 unsigned D = isColumnMajor() ? NumColumns : NumRows; 232 for (unsigned J = 0; J < D; ++J) 233 addVector(UndefValue::get(FixedVectorType::get( 234 EltTy, isColumnMajor() ? NumRows : NumColumns))); 235 } 236 237 Value *getVector(unsigned i) const { return Vectors[i]; } 238 Value *getColumn(unsigned i) const { 239 assert(isColumnMajor() && "only supported for column-major matrixes"); 240 return Vectors[i]; 241 } 242 Value *getRow(unsigned i) const { 243 assert(!isColumnMajor() && "only supported for row-major matrixes"); 244 return Vectors[i]; 245 } 246 247 void setVector(unsigned i, Value *V) { Vectors[i] = V; } 248 249 Type *getElementType() const { return getVectorTy()->getElementType(); } 250 251 unsigned getNumVectors() const { 252 if (isColumnMajor()) 253 return getNumColumns(); 254 return getNumRows(); 255 } 256 257 unsigned getNumColumns() const { 258 if (isColumnMajor()) 259 return Vectors.size(); 260 else { 261 assert(Vectors.size() > 0 && "Cannot call getNumRows without columns"); 262 return cast<FixedVectorType>(Vectors[0]->getType())->getNumElements(); 263 } 264 } 265 unsigned getNumRows() const { 266 if (isColumnMajor()) { 267 assert(Vectors.size() > 0 && "Cannot call getNumRows without columns"); 268 return cast<FixedVectorType>(Vectors[0]->getType())->getNumElements(); 269 } else 270 return Vectors.size(); 271 } 272 273 void addVector(Value *V) { Vectors.push_back(V); } 274 VectorType *getColumnTy() { 275 assert(isColumnMajor() && "only supported for column-major matrixes"); 276 return getVectorTy(); 277 } 278 279 VectorType *getVectorTy() const { 280 return cast<VectorType>(Vectors[0]->getType()); 281 } 282 283 iterator_range<SmallVector<Value *, 8>::iterator> columns() { 284 assert(isColumnMajor() && 285 "columns() only supported for column-major matrixes"); 286 return make_range(Vectors.begin(), Vectors.end()); 287 } 288 289 iterator_range<SmallVector<Value *, 8>::iterator> vectors() { 290 return make_range(Vectors.begin(), Vectors.end()); 291 } 292 293 /// Embed the vectors of the matrix into a flat vector by concatenating 294 /// them. 295 Value *embedInVector(IRBuilder<> &Builder) const { 296 return Vectors.size() == 1 ? Vectors[0] 297 : concatenateVectors(Builder, Vectors); 298 } 299 300 MatrixTy &addNumLoads(unsigned N) { 301 OpInfo.NumLoads += N; 302 return *this; 303 } 304 305 void setNumLoads(unsigned N) { OpInfo.NumLoads = N; } 306 307 MatrixTy &addNumStores(unsigned N) { 308 OpInfo.NumStores += N; 309 return *this; 310 } 311 312 MatrixTy &addNumComputeOps(unsigned N) { 313 OpInfo.NumComputeOps += N; 314 return *this; 315 } 316 317 unsigned getNumStores() const { return OpInfo.NumStores; } 318 unsigned getNumLoads() const { return OpInfo.NumLoads; } 319 unsigned getNumComputeOps() const { return OpInfo.NumComputeOps; } 320 321 const OpInfoTy &getOpInfo() const { return OpInfo; } 322 323 bool isColumnMajor() const { return IsColumnMajor; } 324 325 unsigned getStride() const { 326 if (isColumnMajor()) 327 return getNumRows(); 328 return getNumColumns(); 329 } 330 331 /// Extract a vector of \p NumElts starting at index (\p I, \p J). If the 332 /// matrix is column-major, the result vector is extracted from a column 333 /// vector, otherwise from a row vector. 334 Value *extractVector(unsigned I, unsigned J, unsigned NumElts, 335 IRBuilder<> &Builder) const { 336 Value *Vec = isColumnMajor() ? getColumn(J) : getRow(I); 337 return Builder.CreateShuffleVector( 338 Vec, createSequentialMask(isColumnMajor() ? I : J, NumElts, 0), 339 "block"); 340 } 341 }; 342 343 struct ShapeInfo { 344 unsigned NumRows; 345 unsigned NumColumns; 346 347 bool IsColumnMajor; 348 349 ShapeInfo(unsigned NumRows = 0, unsigned NumColumns = 0) 350 : NumRows(NumRows), NumColumns(NumColumns), 351 IsColumnMajor(MatrixLayout == MatrixLayoutTy::ColumnMajor) {} 352 353 ShapeInfo(Value *NumRows, Value *NumColumns) 354 : ShapeInfo(cast<ConstantInt>(NumRows)->getZExtValue(), 355 cast<ConstantInt>(NumColumns)->getZExtValue()) {} 356 357 bool operator==(const ShapeInfo &other) { 358 return NumRows == other.NumRows && NumColumns == other.NumColumns; 359 } 360 bool operator!=(const ShapeInfo &other) { return !(*this == other); } 361 362 /// Returns true if shape-information is defined, meaning both dimensions 363 /// are != 0. 364 operator bool() const { 365 assert(NumRows == 0 || NumColumns != 0); 366 return NumRows != 0; 367 } 368 369 unsigned getStride() const { 370 if (IsColumnMajor) 371 return NumRows; 372 return NumColumns; 373 } 374 375 unsigned getNumVectors() const { 376 if (IsColumnMajor) 377 return NumColumns; 378 return NumRows; 379 } 380 }; 381 382 /// Maps instructions to their shape information. The shape information 383 /// describes the shape to be used while lowering. This matches the shape of 384 /// the result value of the instruction, with the only exceptions being store 385 /// instructions and the matrix_column_major_store intrinsics. For those, the 386 /// shape information indicates that those instructions should be lowered 387 /// using shape information as well. 388 DenseMap<Value *, ShapeInfo> ShapeMap; 389 390 /// List of instructions to remove. While lowering, we are not replacing all 391 /// users of a lowered instruction, if shape information is available and 392 /// those need to be removed after we finished lowering. 393 SmallVector<Instruction *, 16> ToRemove; 394 395 /// Map from instructions to their produced column matrix. 396 MapVector<Value *, MatrixTy> Inst2ColumnMatrix; 397 398 public: 399 LowerMatrixIntrinsics(Function &F, TargetTransformInfo &TTI, 400 AliasAnalysis *AA, DominatorTree *DT, LoopInfo *LI, 401 OptimizationRemarkEmitter *ORE) 402 : Func(F), DL(F.getParent()->getDataLayout()), TTI(TTI), AA(AA), DT(DT), 403 LI(LI), ORE(ORE) {} 404 405 unsigned getNumOps(Type *VT) { 406 assert(isa<VectorType>(VT) && "Expected vector type"); 407 return getNumOps(VT->getScalarType(), 408 cast<FixedVectorType>(VT)->getNumElements()); 409 } 410 411 // 412 /// Return the estimated number of vector ops required for an operation on 413 /// \p VT * N. 414 unsigned getNumOps(Type *ST, unsigned N) { 415 return std::ceil((ST->getPrimitiveSizeInBits() * N).getFixedSize() / 416 double(TTI.getRegisterBitWidth(true))); 417 } 418 419 /// Return the set of vectors that a matrix value is lowered to. 420 /// 421 /// If we lowered \p MatrixVal, just return the cache result matrix. Otherwise 422 /// split the flat vector \p MatrixVal containing a matrix with shape \p SI 423 /// into vectors. 424 MatrixTy getMatrix(Value *MatrixVal, const ShapeInfo &SI, 425 IRBuilder<> &Builder) { 426 VectorType *VType = dyn_cast<VectorType>(MatrixVal->getType()); 427 assert(VType && "MatrixVal must be a vector type"); 428 assert(cast<FixedVectorType>(VType)->getNumElements() == 429 SI.NumRows * SI.NumColumns && 430 "The vector size must match the number of matrix elements"); 431 432 // Check if we lowered MatrixVal using shape information. In that case, 433 // return the existing matrix, if it matches the requested shape 434 // information. If there is a mis-match, embed the result in a flat 435 // vector and split it later. 436 auto Found = Inst2ColumnMatrix.find(MatrixVal); 437 if (Found != Inst2ColumnMatrix.end()) { 438 MatrixTy &M = Found->second; 439 // Return the found matrix, if its shape matches the requested shape 440 // information 441 if (SI.NumRows == M.getNumRows() && SI.NumColumns == M.getNumColumns()) 442 return M; 443 444 MatrixVal = M.embedInVector(Builder); 445 } 446 447 // Otherwise split MatrixVal. 448 SmallVector<Value *, 16> SplitVecs; 449 for (unsigned MaskStart = 0; 450 MaskStart < cast<FixedVectorType>(VType)->getNumElements(); 451 MaskStart += SI.getStride()) { 452 Value *V = Builder.CreateShuffleVector( 453 MatrixVal, createSequentialMask(MaskStart, SI.getStride(), 0), 454 "split"); 455 SplitVecs.push_back(V); 456 } 457 458 return {SplitVecs}; 459 } 460 461 /// If \p V already has a known shape return false. Otherwise set the shape 462 /// for instructions that support it. 463 bool setShapeInfo(Value *V, ShapeInfo Shape) { 464 assert(Shape && "Shape not set"); 465 if (isa<UndefValue>(V) || !supportsShapeInfo(V)) 466 return false; 467 468 auto SIter = ShapeMap.find(V); 469 if (SIter != ShapeMap.end()) { 470 LLVM_DEBUG(dbgs() << " not overriding existing shape: " 471 << SIter->second.NumRows << " " 472 << SIter->second.NumColumns << " for " << *V << "\n"); 473 return false; 474 } 475 476 ShapeMap.insert({V, Shape}); 477 LLVM_DEBUG(dbgs() << " " << Shape.NumRows << " x " << Shape.NumColumns 478 << " for " << *V << "\n"); 479 return true; 480 } 481 482 bool isUniformShape(Value *V) { 483 Instruction *I = dyn_cast<Instruction>(V); 484 if (!I) 485 return true; 486 487 switch (I->getOpcode()) { 488 case Instruction::FAdd: 489 case Instruction::FSub: 490 case Instruction::FMul: // Scalar multiply. 491 case Instruction::FNeg: 492 case Instruction::Add: 493 case Instruction::Mul: 494 case Instruction::Sub: 495 return true; 496 default: 497 return false; 498 } 499 } 500 501 /// Returns true if shape information can be used for \p V. The supported 502 /// instructions must match the instructions that can be lowered by this pass. 503 bool supportsShapeInfo(Value *V) { 504 Instruction *Inst = dyn_cast<Instruction>(V); 505 if (!Inst) 506 return false; 507 508 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst); 509 if (II) 510 switch (II->getIntrinsicID()) { 511 case Intrinsic::matrix_multiply: 512 case Intrinsic::matrix_transpose: 513 case Intrinsic::matrix_column_major_load: 514 case Intrinsic::matrix_column_major_store: 515 return true; 516 default: 517 return false; 518 } 519 return isUniformShape(V) || isa<StoreInst>(V) || isa<LoadInst>(V); 520 } 521 522 /// Propagate the shape information of instructions to their users. 523 /// The work list contains instructions for which we can compute the shape, 524 /// either based on the information provided by matrix intrinsics or known 525 /// shapes of operands. 526 SmallVector<Instruction *, 32> 527 propagateShapeForward(SmallVectorImpl<Instruction *> &WorkList) { 528 SmallVector<Instruction *, 32> NewWorkList; 529 // Pop an element for which we guaranteed to have at least one of the 530 // operand shapes. Add the shape for this and then add users to the work 531 // list. 532 LLVM_DEBUG(dbgs() << "Forward-propagate shapes:\n"); 533 while (!WorkList.empty()) { 534 Instruction *Inst = WorkList.pop_back_val(); 535 536 // New entry, set the value and insert operands 537 bool Propagate = false; 538 539 Value *MatrixA; 540 Value *MatrixB; 541 Value *M; 542 Value *N; 543 Value *K; 544 if (match(Inst, m_Intrinsic<Intrinsic::matrix_multiply>( 545 m_Value(MatrixA), m_Value(MatrixB), m_Value(M), 546 m_Value(N), m_Value(K)))) { 547 Propagate = setShapeInfo(Inst, {M, K}); 548 } else if (match(Inst, m_Intrinsic<Intrinsic::matrix_transpose>( 549 m_Value(MatrixA), m_Value(M), m_Value(N)))) { 550 // Flip dimensions. 551 Propagate = setShapeInfo(Inst, {N, M}); 552 } else if (match(Inst, m_Intrinsic<Intrinsic::matrix_column_major_store>( 553 m_Value(MatrixA), m_Value(), m_Value(), 554 m_Value(), m_Value(M), m_Value(N)))) { 555 Propagate = setShapeInfo(Inst, {N, M}); 556 } else if (match(Inst, m_Intrinsic<Intrinsic::matrix_column_major_load>( 557 m_Value(), m_Value(), m_Value(), m_Value(M), 558 m_Value(N)))) { 559 Propagate = setShapeInfo(Inst, {M, N}); 560 } else if (match(Inst, m_Store(m_Value(MatrixA), m_Value()))) { 561 auto OpShape = ShapeMap.find(MatrixA); 562 if (OpShape != ShapeMap.end()) 563 setShapeInfo(Inst, OpShape->second); 564 continue; 565 } else if (isUniformShape(Inst)) { 566 // Find the first operand that has a known shape and use that. 567 for (auto &Op : Inst->operands()) { 568 auto OpShape = ShapeMap.find(Op.get()); 569 if (OpShape != ShapeMap.end()) { 570 Propagate |= setShapeInfo(Inst, OpShape->second); 571 break; 572 } 573 } 574 } 575 576 if (Propagate) { 577 NewWorkList.push_back(Inst); 578 for (auto *User : Inst->users()) 579 if (ShapeMap.count(User) == 0) 580 WorkList.push_back(cast<Instruction>(User)); 581 } 582 } 583 584 return NewWorkList; 585 } 586 587 /// Propagate the shape to operands of instructions with shape information. 588 /// \p Worklist contains the instruction for which we already know the shape. 589 SmallVector<Instruction *, 32> 590 propagateShapeBackward(SmallVectorImpl<Instruction *> &WorkList) { 591 SmallVector<Instruction *, 32> NewWorkList; 592 593 auto pushInstruction = [](Value *V, 594 SmallVectorImpl<Instruction *> &WorkList) { 595 Instruction *I = dyn_cast<Instruction>(V); 596 if (I) 597 WorkList.push_back(I); 598 }; 599 // Pop an element with known shape. Traverse the operands, if their shape 600 // derives from the result shape and is unknown, add it and add them to the 601 // worklist. 602 LLVM_DEBUG(dbgs() << "Backward-propagate shapes:\n"); 603 while (!WorkList.empty()) { 604 Value *V = WorkList.pop_back_val(); 605 606 size_t BeforeProcessingV = WorkList.size(); 607 if (!isa<Instruction>(V)) 608 continue; 609 610 Value *MatrixA; 611 Value *MatrixB; 612 Value *M; 613 Value *N; 614 Value *K; 615 if (match(V, m_Intrinsic<Intrinsic::matrix_multiply>( 616 m_Value(MatrixA), m_Value(MatrixB), m_Value(M), 617 m_Value(N), m_Value(K)))) { 618 if (setShapeInfo(MatrixA, {M, N})) 619 pushInstruction(MatrixA, WorkList); 620 621 if (setShapeInfo(MatrixB, {N, K})) 622 pushInstruction(MatrixB, WorkList); 623 624 } else if (match(V, m_Intrinsic<Intrinsic::matrix_transpose>( 625 m_Value(MatrixA), m_Value(M), m_Value(N)))) { 626 // Flip dimensions. 627 if (setShapeInfo(MatrixA, {M, N})) 628 pushInstruction(MatrixA, WorkList); 629 } else if (match(V, m_Intrinsic<Intrinsic::matrix_column_major_store>( 630 m_Value(MatrixA), m_Value(), m_Value(), m_Value(), 631 m_Value(M), m_Value(N)))) { 632 if (setShapeInfo(MatrixA, {M, N})) { 633 pushInstruction(MatrixA, WorkList); 634 } 635 } else if (isa<LoadInst>(V) || 636 match(V, m_Intrinsic<Intrinsic::matrix_column_major_load>())) { 637 // Nothing to do, no matrix input. 638 } else if (isa<StoreInst>(V)) { 639 // Nothing to do. We forward-propagated to this so we would just 640 // backward propagate to an instruction with an already known shape. 641 } else if (isUniformShape(V)) { 642 // Propagate to all operands. 643 ShapeInfo Shape = ShapeMap[V]; 644 for (Use &U : cast<Instruction>(V)->operands()) { 645 if (setShapeInfo(U.get(), Shape)) 646 pushInstruction(U.get(), WorkList); 647 } 648 } 649 // After we discovered new shape info for new instructions in the 650 // worklist, we use their users as seeds for the next round of forward 651 // propagation. 652 for (size_t I = BeforeProcessingV; I != WorkList.size(); I++) 653 for (User *U : WorkList[I]->users()) 654 if (isa<Instruction>(U) && V != U) 655 NewWorkList.push_back(cast<Instruction>(U)); 656 } 657 return NewWorkList; 658 } 659 660 bool Visit() { 661 if (EnableShapePropagation) { 662 SmallVector<Instruction *, 32> WorkList; 663 664 // Initially only the shape of matrix intrinsics is known. 665 // Initialize the work list with ops carrying shape information. 666 for (BasicBlock &BB : Func) 667 for (Instruction &Inst : BB) { 668 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Inst); 669 if (!II) 670 continue; 671 672 switch (II->getIntrinsicID()) { 673 case Intrinsic::matrix_multiply: 674 case Intrinsic::matrix_transpose: 675 case Intrinsic::matrix_column_major_load: 676 case Intrinsic::matrix_column_major_store: 677 WorkList.push_back(&Inst); 678 break; 679 default: 680 break; 681 } 682 } 683 // Propagate shapes until nothing changes any longer. 684 while (!WorkList.empty()) { 685 WorkList = propagateShapeForward(WorkList); 686 WorkList = propagateShapeBackward(WorkList); 687 } 688 } 689 690 bool Changed = false; 691 SmallVector<CallInst *, 16> MaybeFusableInsts; 692 SmallVector<Instruction *, 16> MatrixInsts; 693 694 // First, collect all instructions with shape information and candidates for 695 // fusion (currently only matrix multiplies). 696 ReversePostOrderTraversal<Function *> RPOT(&Func); 697 for (auto *BB : RPOT) 698 for (Instruction &I : *BB) { 699 if (ShapeMap.find(&I) == ShapeMap.end()) 700 continue; 701 if (match(&I, m_Intrinsic<Intrinsic::matrix_multiply>())) 702 MaybeFusableInsts.push_back(cast<CallInst>(&I)); 703 MatrixInsts.push_back(&I); 704 } 705 706 // Second, try to fuse candidates. 707 SmallPtrSet<Instruction *, 16> FusedInsts; 708 for (CallInst *CI : MaybeFusableInsts) 709 LowerMatrixMultiplyFused(CI, FusedInsts); 710 Changed = !FusedInsts.empty(); 711 712 // Third, lower remaining instructions with shape information. 713 for (Instruction *Inst : MatrixInsts) { 714 if (FusedInsts.count(Inst)) 715 continue; 716 717 IRBuilder<> Builder(Inst); 718 719 if (CallInst *CInst = dyn_cast<CallInst>(Inst)) 720 Changed |= VisitCallInst(CInst); 721 722 Value *Op1; 723 Value *Op2; 724 if (auto *BinOp = dyn_cast<BinaryOperator>(Inst)) 725 Changed |= VisitBinaryOperator(BinOp); 726 if (auto *UnOp = dyn_cast<UnaryOperator>(Inst)) 727 Changed |= VisitUnaryOperator(UnOp); 728 if (match(Inst, m_Load(m_Value(Op1)))) 729 Changed |= VisitLoad(cast<LoadInst>(Inst), Op1, Builder); 730 else if (match(Inst, m_Store(m_Value(Op1), m_Value(Op2)))) 731 Changed |= VisitStore(cast<StoreInst>(Inst), Op1, Op2, Builder); 732 } 733 734 if (ORE) { 735 RemarkGenerator RemarkGen(Inst2ColumnMatrix, *ORE, Func); 736 RemarkGen.emitRemarks(); 737 } 738 739 for (Instruction *Inst : reverse(ToRemove)) 740 Inst->eraseFromParent(); 741 742 return Changed; 743 } 744 745 /// Turns \p BasePtr into an elementwise pointer to \p EltType. 746 Value *createElementPtr(Value *BasePtr, Type *EltType, IRBuilder<> &Builder) { 747 unsigned AS = cast<PointerType>(BasePtr->getType())->getAddressSpace(); 748 Type *EltPtrType = PointerType::get(EltType, AS); 749 return Builder.CreatePointerCast(BasePtr, EltPtrType); 750 } 751 752 /// Replace intrinsic calls 753 bool VisitCallInst(CallInst *Inst) { 754 if (!Inst->getCalledFunction() || !Inst->getCalledFunction()->isIntrinsic()) 755 return false; 756 757 switch (Inst->getCalledFunction()->getIntrinsicID()) { 758 case Intrinsic::matrix_multiply: 759 LowerMultiply(Inst); 760 break; 761 case Intrinsic::matrix_transpose: 762 LowerTranspose(Inst); 763 break; 764 case Intrinsic::matrix_column_major_load: 765 LowerColumnMajorLoad(Inst); 766 break; 767 case Intrinsic::matrix_column_major_store: 768 LowerColumnMajorStore(Inst); 769 break; 770 default: 771 return false; 772 } 773 return true; 774 } 775 776 /// Compute the alignment for a column/row \p Idx with \p Stride between them. 777 /// The address at \p Idx == 0 has alignment \p A. If \p Stride is a 778 /// ConstantInt, reduce the initial alignment based on the byte offset. For 779 /// non-ConstantInt strides, return the common alignment of the initial 780 /// alignment and the element size in bytes. 781 Align getAlignForIndex(unsigned Idx, Value *Stride, Type *ElementTy, 782 MaybeAlign A) const { 783 Align InitialAlign = DL.getValueOrABITypeAlignment(A, ElementTy); 784 if (Idx == 0) 785 return InitialAlign; 786 787 TypeSize ElementSizeInBits = DL.getTypeSizeInBits(ElementTy); 788 if (auto *ConstStride = dyn_cast<ConstantInt>(Stride)) { 789 uint64_t StrideInBytes = 790 ConstStride->getZExtValue() * ElementSizeInBits / 8; 791 return commonAlignment(InitialAlign, Idx * StrideInBytes); 792 } 793 return commonAlignment(InitialAlign, ElementSizeInBits / 8); 794 } 795 796 /// Load a matrix with \p Shape starting at \p Ptr and using \p Stride between 797 /// vectors. 798 MatrixTy loadMatrix(Type *Ty, Value *Ptr, MaybeAlign MAlign, Value *Stride, 799 bool IsVolatile, ShapeInfo Shape, IRBuilder<> &Builder) { 800 auto VType = cast<VectorType>(Ty); 801 Value *EltPtr = createElementPtr(Ptr, VType->getElementType(), Builder); 802 MatrixTy Result; 803 for (unsigned I = 0, E = Shape.getNumVectors(); I < E; ++I) { 804 Value *GEP = computeVectorAddr(EltPtr, Builder.getInt64(I), Stride, 805 Shape.getStride(), VType->getElementType(), 806 Builder); 807 Value *Vector = Builder.CreateAlignedLoad( 808 GEP, getAlignForIndex(I, Stride, VType->getElementType(), MAlign), 809 IsVolatile, "col.load"); 810 811 Result.addVector(Vector); 812 } 813 return Result.addNumLoads(getNumOps(Result.getVectorTy()) * 814 Result.getNumVectors()); 815 } 816 817 /// Loads a sub-matrix with shape \p ResultShape from a \p R x \p C matrix, 818 /// starting at \p MatrixPtr[I][J]. 819 MatrixTy loadMatrix(Value *MatrixPtr, MaybeAlign Align, bool IsVolatile, 820 ShapeInfo MatrixShape, Value *I, Value *J, 821 ShapeInfo ResultShape, Type *EltTy, 822 IRBuilder<> &Builder) { 823 824 Value *Offset = Builder.CreateAdd( 825 Builder.CreateMul(J, Builder.getInt64(MatrixShape.getStride())), I); 826 827 unsigned AS = cast<PointerType>(MatrixPtr->getType())->getAddressSpace(); 828 Value *EltPtr = 829 Builder.CreatePointerCast(MatrixPtr, PointerType::get(EltTy, AS)); 830 Value *TileStart = Builder.CreateGEP(EltTy, EltPtr, Offset); 831 auto *TileTy = FixedVectorType::get(EltTy, ResultShape.NumRows * 832 ResultShape.NumColumns); 833 Type *TilePtrTy = PointerType::get(TileTy, AS); 834 Value *TilePtr = 835 Builder.CreatePointerCast(TileStart, TilePtrTy, "col.cast"); 836 837 return loadMatrix(TileTy, TilePtr, Align, 838 Builder.getInt64(MatrixShape.getStride()), IsVolatile, 839 ResultShape, Builder); 840 } 841 842 /// Lower a load instruction with shape information. 843 void LowerLoad(Instruction *Inst, Value *Ptr, MaybeAlign Align, Value *Stride, 844 bool IsVolatile, ShapeInfo Shape) { 845 IRBuilder<> Builder(Inst); 846 finalizeLowering(Inst, 847 loadMatrix(Inst->getType(), Ptr, Align, Stride, IsVolatile, 848 Shape, Builder), 849 Builder); 850 } 851 852 /// Lowers llvm.matrix.column.major.load. 853 /// 854 /// The intrinsic loads a matrix from memory using a stride between columns. 855 void LowerColumnMajorLoad(CallInst *Inst) { 856 assert(MatrixLayout == MatrixLayoutTy::ColumnMajor && 857 "Intrinsic only supports column-major layout!"); 858 Value *Ptr = Inst->getArgOperand(0); 859 Value *Stride = Inst->getArgOperand(1); 860 LowerLoad(Inst, Ptr, Inst->getParamAlign(0), Stride, 861 cast<ConstantInt>(Inst->getArgOperand(2))->isOne(), 862 {Inst->getArgOperand(3), Inst->getArgOperand(4)}); 863 } 864 865 /// Stores a sub-matrix \p StoreVal into the \p R x \p C matrix starting at \p 866 /// MatrixPtr[I][J]. 867 void storeMatrix(const MatrixTy &StoreVal, Value *MatrixPtr, 868 MaybeAlign MAlign, bool IsVolatile, ShapeInfo MatrixShape, 869 Value *I, Value *J, Type *EltTy, IRBuilder<> &Builder) { 870 Value *Offset = Builder.CreateAdd( 871 Builder.CreateMul(J, Builder.getInt64(MatrixShape.getStride())), I); 872 873 unsigned AS = cast<PointerType>(MatrixPtr->getType())->getAddressSpace(); 874 Value *EltPtr = 875 Builder.CreatePointerCast(MatrixPtr, PointerType::get(EltTy, AS)); 876 Value *TileStart = Builder.CreateGEP(EltTy, EltPtr, Offset); 877 auto *TileTy = FixedVectorType::get(EltTy, StoreVal.getNumRows() * 878 StoreVal.getNumColumns()); 879 Type *TilePtrTy = PointerType::get(TileTy, AS); 880 Value *TilePtr = 881 Builder.CreatePointerCast(TileStart, TilePtrTy, "col.cast"); 882 883 storeMatrix(TileTy, StoreVal, TilePtr, MAlign, 884 Builder.getInt64(MatrixShape.getStride()), IsVolatile, Builder); 885 } 886 887 /// Store matrix \p StoreVal starting at \p Ptr and using \p Stride between 888 /// vectors. 889 MatrixTy storeMatrix(Type *Ty, MatrixTy StoreVal, Value *Ptr, 890 MaybeAlign MAlign, Value *Stride, bool IsVolatile, 891 IRBuilder<> &Builder) { 892 auto VType = cast<VectorType>(Ty); 893 Value *EltPtr = createElementPtr(Ptr, VType->getElementType(), Builder); 894 for (auto Vec : enumerate(StoreVal.vectors())) { 895 Value *GEP = computeVectorAddr(EltPtr, Builder.getInt64(Vec.index()), 896 Stride, StoreVal.getStride(), 897 VType->getElementType(), Builder); 898 Builder.CreateAlignedStore(Vec.value(), GEP, 899 getAlignForIndex(Vec.index(), Stride, 900 VType->getElementType(), 901 MAlign), 902 IsVolatile); 903 } 904 return MatrixTy().addNumStores(getNumOps(StoreVal.getVectorTy()) * 905 StoreVal.getNumVectors()); 906 } 907 908 /// Lower a store instruction with shape information. 909 void LowerStore(Instruction *Inst, Value *Matrix, Value *Ptr, MaybeAlign A, 910 Value *Stride, bool IsVolatile, ShapeInfo Shape) { 911 IRBuilder<> Builder(Inst); 912 auto StoreVal = getMatrix(Matrix, Shape, Builder); 913 finalizeLowering(Inst, 914 storeMatrix(Matrix->getType(), StoreVal, Ptr, A, Stride, 915 IsVolatile, Builder), 916 Builder); 917 } 918 919 /// Lowers llvm.matrix.column.major.store. 920 /// 921 /// The intrinsic store a matrix back memory using a stride between columns. 922 void LowerColumnMajorStore(CallInst *Inst) { 923 assert(MatrixLayout == MatrixLayoutTy::ColumnMajor && 924 "Intrinsic only supports column-major layout!"); 925 Value *Matrix = Inst->getArgOperand(0); 926 Value *Ptr = Inst->getArgOperand(1); 927 Value *Stride = Inst->getArgOperand(2); 928 LowerStore(Inst, Matrix, Ptr, Inst->getParamAlign(1), Stride, 929 cast<ConstantInt>(Inst->getArgOperand(3))->isOne(), 930 {Inst->getArgOperand(4), Inst->getArgOperand(5)}); 931 } 932 933 // Set elements I..I+NumElts-1 to Block 934 Value *insertVector(Value *Col, unsigned I, Value *Block, 935 IRBuilder<> &Builder) { 936 937 // First, bring Block to the same size as Col 938 unsigned BlockNumElts = 939 cast<FixedVectorType>(Block->getType())->getNumElements(); 940 unsigned NumElts = cast<FixedVectorType>(Col->getType())->getNumElements(); 941 assert(NumElts >= BlockNumElts && "Too few elements for current block"); 942 943 Block = Builder.CreateShuffleVector( 944 Block, createSequentialMask(0, BlockNumElts, NumElts - BlockNumElts)); 945 946 // If Col is 7 long and I is 2 and BlockNumElts is 2 the mask is: 0, 1, 7, 947 // 8, 4, 5, 6 948 SmallVector<int, 16> Mask; 949 unsigned i; 950 for (i = 0; i < I; i++) 951 Mask.push_back(i); 952 953 unsigned VecNumElts = 954 cast<FixedVectorType>(Col->getType())->getNumElements(); 955 for (; i < I + BlockNumElts; i++) 956 Mask.push_back(i - I + VecNumElts); 957 958 for (; i < VecNumElts; i++) 959 Mask.push_back(i); 960 961 return Builder.CreateShuffleVector(Col, Block, Mask); 962 } 963 964 Value *createMulAdd(Value *Sum, Value *A, Value *B, bool UseFPOp, 965 IRBuilder<> &Builder, bool AllowContraction, 966 unsigned &NumComputeOps) { 967 NumComputeOps += getNumOps(A->getType()); 968 if (!Sum) 969 return UseFPOp ? Builder.CreateFMul(A, B) : Builder.CreateMul(A, B); 970 971 if (UseFPOp) { 972 if (AllowContraction) { 973 // Use fmuladd for floating point operations and let the backend decide 974 // if that's profitable. 975 Function *FMulAdd = Intrinsic::getDeclaration( 976 Func.getParent(), Intrinsic::fmuladd, A->getType()); 977 return Builder.CreateCall(FMulAdd, {A, B, Sum}); 978 } 979 NumComputeOps += getNumOps(A->getType()); 980 Value *Mul = Builder.CreateFMul(A, B); 981 return Builder.CreateFAdd(Sum, Mul); 982 } 983 984 NumComputeOps += getNumOps(A->getType()); 985 Value *Mul = Builder.CreateMul(A, B); 986 return Builder.CreateAdd(Sum, Mul); 987 } 988 989 /// Cache \p Matrix as result of \p Inst and update the uses of \p Inst. For 990 /// users with shape information, there's nothing to do: the will use the 991 /// cached value when they are lowered. For other users, \p Matrix is 992 /// flattened and the uses are updated to use it. Also marks \p Inst for 993 /// deletion. 994 void finalizeLowering(Instruction *Inst, MatrixTy Matrix, 995 IRBuilder<> &Builder) { 996 Inst2ColumnMatrix.insert(std::make_pair(Inst, Matrix)); 997 998 ToRemove.push_back(Inst); 999 Value *Flattened = nullptr; 1000 for (Use &U : llvm::make_early_inc_range(Inst->uses())) { 1001 if (ShapeMap.find(U.getUser()) == ShapeMap.end()) { 1002 if (!Flattened) 1003 Flattened = Matrix.embedInVector(Builder); 1004 U.set(Flattened); 1005 } 1006 } 1007 } 1008 1009 /// Compute \p Result += \p A * \p B for input matrices with left-associating 1010 /// addition. 1011 void emitMatrixMultiply(MatrixTy &Result, const MatrixTy &A, 1012 const MatrixTy &B, bool AllowContraction, 1013 IRBuilder<> &Builder, bool isTiled) { 1014 const unsigned VF = std::max<unsigned>( 1015 TTI.getRegisterBitWidth(true) / 1016 Result.getElementType()->getPrimitiveSizeInBits().getFixedSize(), 1017 1U); 1018 unsigned R = Result.getNumRows(); 1019 unsigned C = Result.getNumColumns(); 1020 unsigned M = A.getNumColumns(); 1021 1022 bool IsFP = Result.getElementType()->isFloatingPointTy(); 1023 assert(A.isColumnMajor() == B.isColumnMajor() && 1024 Result.isColumnMajor() == A.isColumnMajor() && 1025 "operands must agree on matrix layout"); 1026 unsigned NumComputeOps = 0; 1027 if (A.isColumnMajor()) { 1028 // Multiply columns from the first operand with scalars from the second 1029 // operand. Then move along the K axes and accumulate the columns. With 1030 // this the adds can be vectorized without reassociation. 1031 for (unsigned J = 0; J < C; ++J) { 1032 unsigned BlockSize = VF; 1033 // If Result is zero, we don't need to accumulate in the K==0 iteration. 1034 bool isSumZero = isa<ConstantAggregateZero>(Result.getColumn(J)); 1035 1036 for (unsigned I = 0; I < R; I += BlockSize) { 1037 // Gradually lower the vectorization factor to cover the remainder. 1038 while (I + BlockSize > R) 1039 BlockSize /= 2; 1040 1041 Value *Sum = isTiled ? Result.extractVector(I, J, BlockSize, Builder) 1042 : nullptr; 1043 for (unsigned K = 0; K < M; ++K) { 1044 Value *L = A.extractVector(I, K, BlockSize, Builder); 1045 Value *RH = Builder.CreateExtractElement(B.getColumn(J), K); 1046 Value *Splat = Builder.CreateVectorSplat(BlockSize, RH, "splat"); 1047 Sum = createMulAdd(isSumZero && K == 0 ? nullptr : Sum, L, Splat, 1048 Result.getElementType()->isFloatingPointTy(), 1049 Builder, AllowContraction, NumComputeOps); 1050 } 1051 Result.setVector(J, 1052 insertVector(Result.getVector(J), I, Sum, Builder)); 1053 } 1054 } 1055 } else { 1056 // Multiply rows from the second operand with scalars from the first 1057 // operand. Then move along the K axes and accumulate the rows. With this 1058 // the adds can be vectorized without reassociation. 1059 for (unsigned I = 0; I < R; ++I) { 1060 unsigned BlockSize = VF; 1061 bool isSumZero = isa<ConstantAggregateZero>(Result.getRow(I)); 1062 for (unsigned J = 0; J < C; J += BlockSize) { 1063 // Gradually lower the vectorization factor to cover the remainder. 1064 while (J + BlockSize > C) 1065 BlockSize /= 2; 1066 1067 Value *Sum = nullptr; 1068 for (unsigned K = 0; K < M; ++K) { 1069 Value *R = B.extractVector(K, J, BlockSize, Builder); 1070 Value *LH = Builder.CreateExtractElement(A.getVector(I), K); 1071 Value *Splat = Builder.CreateVectorSplat(BlockSize, LH, "splat"); 1072 Sum = createMulAdd(isSumZero && K == 0 ? nullptr : Sum, Splat, R, 1073 IsFP, Builder, AllowContraction, NumComputeOps); 1074 } 1075 Result.setVector(I, 1076 insertVector(Result.getVector(I), J, Sum, Builder)); 1077 } 1078 } 1079 } 1080 Result.addNumComputeOps(NumComputeOps); 1081 } 1082 1083 /// Ensure that the memory in \p Load does not alias \p Store by potentially 1084 /// copying it to a new location. This new or otherwise the original location 1085 /// is returned. 1086 Value *getNonAliasingPointer(LoadInst *Load, StoreInst *Store, 1087 CallInst *MatMul) { 1088 MemoryLocation StoreLoc = MemoryLocation::get(Store); 1089 MemoryLocation LoadLoc = MemoryLocation::get(Load); 1090 1091 AliasResult LdAliased = AA->alias(LoadLoc, StoreLoc); 1092 1093 // If we can statically determine noalias we're good. 1094 if (!LdAliased) 1095 return Load->getPointerOperand(); 1096 1097 // Create code to check if the memory locations of the Load and Store 1098 // overlap and if they do, copy Load's operand to a new buffer. 1099 1100 // First, create new blocks for 2n part of the check and the copy. 1101 BasicBlock *Check0 = MatMul->getParent(); 1102 // FIXME: Use lazy DTU and update SplitBlock to accept a DTU instead of a 1103 // DT. Manually collect dominator tree updates, to avoid unnecessary work, 1104 // as we adjust Check0 and Check1's branches. 1105 SmallVector<DominatorTree::UpdateType, 4> DTUpdates; 1106 for (BasicBlock *Succ : successors(Check0)) 1107 DTUpdates.push_back({DT->Delete, Check0, Succ}); 1108 1109 BasicBlock *Check1 = 1110 SplitBlock(MatMul->getParent(), MatMul, (DomTreeUpdater *)nullptr, LI, 1111 nullptr, "alias_cont"); 1112 BasicBlock *Copy = 1113 SplitBlock(MatMul->getParent(), MatMul, (DomTreeUpdater *)nullptr, LI, 1114 nullptr, "copy"); 1115 BasicBlock *Fusion = 1116 SplitBlock(MatMul->getParent(), MatMul, (DomTreeUpdater *)nullptr, LI, 1117 nullptr, "no_alias"); 1118 1119 // Check if the loaded memory location begins before the end of the store 1120 // location. If the condition holds, they might overlap, otherwise they are 1121 // guaranteed to not overlap. 1122 IRBuilder<> Builder(MatMul); 1123 Check0->getTerminator()->eraseFromParent(); 1124 Builder.SetInsertPoint(Check0); 1125 Type *IntPtrTy = Builder.getIntPtrTy(Load->getModule()->getDataLayout()); 1126 Value *StoreBegin = Builder.CreatePtrToInt( 1127 const_cast<Value *>(StoreLoc.Ptr), IntPtrTy, "store.begin"); 1128 Value *StoreEnd = Builder.CreateAdd( 1129 StoreBegin, ConstantInt::get(IntPtrTy, StoreLoc.Size.getValue()), 1130 "store.end", true, true); 1131 Value *LoadBegin = Builder.CreatePtrToInt(const_cast<Value *>(LoadLoc.Ptr), 1132 IntPtrTy, "load.begin"); 1133 Builder.CreateCondBr(Builder.CreateICmpULT(LoadBegin, StoreEnd), Check1, 1134 Fusion); 1135 1136 // Check if the store begins before the end of the load location. If the 1137 // condition holds, they alias, otherwise they are guaranteed to not 1138 // overlap. 1139 Check1->getTerminator()->eraseFromParent(); 1140 Builder.SetInsertPoint(Check1, Check1->begin()); 1141 Value *LoadEnd = Builder.CreateAdd( 1142 LoadBegin, ConstantInt::get(IntPtrTy, LoadLoc.Size.getValue()), 1143 "load.end", true, true); 1144 Builder.CreateCondBr(Builder.CreateICmpULT(StoreBegin, LoadEnd), Copy, 1145 Fusion); 1146 1147 // Copy load operand to new alloca. 1148 Builder.SetInsertPoint(Copy, Copy->begin()); 1149 AllocaInst *NewLd = 1150 Builder.CreateAlloca(Load->getType(), Load->getPointerAddressSpace()); 1151 Builder.CreateMemCpy(NewLd, NewLd->getAlign(), 1152 Load->getPointerOperand(), Load->getAlign(), 1153 LoadLoc.Size.getValue()); 1154 Builder.SetInsertPoint(Fusion, Fusion->begin()); 1155 PHINode *PHI = Builder.CreatePHI(Load->getPointerOperandType(), 3); 1156 PHI->addIncoming(Load->getPointerOperand(), Check0); 1157 PHI->addIncoming(Load->getPointerOperand(), Check1); 1158 PHI->addIncoming(NewLd, Copy); 1159 1160 // Adjust DT. 1161 DTUpdates.push_back({DT->Insert, Check0, Check1}); 1162 DTUpdates.push_back({DT->Insert, Check0, Fusion}); 1163 DTUpdates.push_back({DT->Insert, Check1, Copy}); 1164 DTUpdates.push_back({DT->Insert, Check1, Fusion}); 1165 DT->applyUpdates(DTUpdates); 1166 return PHI; 1167 } 1168 1169 bool isFusionProfitable(CallInst *MatMul) { 1170 if (ForceFusion) 1171 return true; 1172 1173 ShapeInfo LShape(MatMul->getArgOperand(2), MatMul->getArgOperand(3)); 1174 ShapeInfo RShape(MatMul->getArgOperand(3), MatMul->getArgOperand(4)); 1175 1176 const unsigned R = LShape.NumRows; 1177 const unsigned C = RShape.NumColumns; 1178 const unsigned M = LShape.NumColumns; 1179 auto *EltType = cast<VectorType>(MatMul->getType())->getElementType(); 1180 1181 const unsigned VF = 1182 std::max<unsigned>(TTI.getRegisterBitWidth(true) / 1183 EltType->getPrimitiveSizeInBits().getFixedSize(), 1184 1U); 1185 1186 // Cost model for tiling 1187 // 1188 // For tiling to be beneficial, we need reuse either along the R or 1189 // the C axis. We vectorize along the R axis so that means at least 1190 // 3 elements. 1191 // TODO: Also consider cost of copying if operands alias. 1192 if (R <= VF && C == 1) 1193 return false; 1194 // Then we need enough elements to exceed the number of vector 1195 // registers we have. Note that this is an oversimplification since 1196 // fusing also takes some extra loads which may exceed the number of 1197 // reloads necessary. 1198 unsigned Op0Regs = (R + VF - 1) / VF * M; 1199 unsigned Op1Regs = (M + VF - 1) / VF * C; 1200 return Op0Regs + Op1Regs > TTI.getNumberOfRegisters(true); 1201 } 1202 1203 MatrixTy getZeroMatrix(Type *EltType, unsigned R, unsigned C) { 1204 MatrixTy Res; 1205 auto *ColumType = FixedVectorType::get(EltType, R); 1206 for (unsigned I = 0; I < C; ++I) 1207 Res.addVector(ConstantAggregateZero::get(ColumType)); 1208 return Res; 1209 } 1210 1211 void createTiledLoops(CallInst *MatMul, Value *LPtr, ShapeInfo LShape, 1212 Value *RPtr, ShapeInfo RShape, StoreInst *Store, 1213 bool AllowContract) { 1214 auto *EltType = cast<VectorType>(MatMul->getType())->getElementType(); 1215 1216 // Create the main tiling loop nest. 1217 TileInfo TI(LShape.NumRows, RShape.NumColumns, LShape.NumColumns, TileSize); 1218 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); 1219 Instruction *InsertI = cast<Instruction>(MatMul); 1220 BasicBlock *Start = InsertI->getParent(); 1221 BasicBlock *End = 1222 SplitBlock(InsertI->getParent(), InsertI, DT, LI, nullptr, "continue"); 1223 IRBuilder<> Builder(MatMul); 1224 BasicBlock *InnerBody = TI.CreateTiledLoops(Start, End, Builder, DTU, *LI); 1225 1226 Type *TileVecTy = 1227 FixedVectorType::get(MatMul->getType()->getScalarType(), TileSize); 1228 MatrixTy TileResult; 1229 // Insert in the inner loop header. 1230 Builder.SetInsertPoint(TI.InnerLoopHeader->getTerminator()); 1231 // Create PHI nodes for the result columns to accumulate across iterations. 1232 SmallVector<PHINode *, 4> ColumnPhis; 1233 for (unsigned I = 0; I < TileSize; I++) { 1234 auto *Phi = Builder.CreatePHI(TileVecTy, 2, "result.vec." + Twine(I)); 1235 Phi->addIncoming(ConstantAggregateZero::get(TileVecTy), 1236 TI.RowLoopHeader->getSingleSuccessor()); 1237 TileResult.addVector(Phi); 1238 ColumnPhis.push_back(Phi); 1239 } 1240 1241 // Insert in the inner loop body, which computes 1242 // Res += Load(CurrentRow, K) * Load(K, CurrentColumn) 1243 Builder.SetInsertPoint(InnerBody->getTerminator()); 1244 // Load tiles of the operands. 1245 MatrixTy A = loadMatrix(LPtr, {}, false, LShape, TI.CurrentRow, TI.CurrentK, 1246 {TileSize, TileSize}, EltType, Builder); 1247 MatrixTy B = loadMatrix(RPtr, {}, false, RShape, TI.CurrentK, TI.CurrentCol, 1248 {TileSize, TileSize}, EltType, Builder); 1249 emitMatrixMultiply(TileResult, A, B, AllowContract, Builder, true); 1250 // Store result after the inner loop is done. 1251 Builder.SetInsertPoint(TI.RowLoopLatch->getTerminator()); 1252 storeMatrix(TileResult, Store->getPointerOperand(), Store->getAlign(), 1253 Store->isVolatile(), {LShape.NumRows, RShape.NumColumns}, 1254 TI.CurrentRow, TI.CurrentCol, EltType, Builder); 1255 1256 for (unsigned I = 0; I < TileResult.getNumVectors(); I++) 1257 ColumnPhis[I]->addIncoming(TileResult.getVector(I), TI.InnerLoopLatch); 1258 1259 // Force unrolling of a few iterations of the inner loop, to make sure there 1260 // is enough work per iteration. 1261 // FIXME: The unroller should make this decision directly instead, but 1262 // currently the cost-model is not up to the task. 1263 unsigned InnerLoopUnrollCount = std::min(10u, LShape.NumColumns / TileSize); 1264 addStringMetadataToLoop(LI->getLoopFor(TI.InnerLoopHeader), 1265 "llvm.loop.unroll.count", InnerLoopUnrollCount); 1266 } 1267 1268 void emitSIMDTiling(CallInst *MatMul, LoadInst *LoadOp0, LoadInst *LoadOp1, 1269 StoreInst *Store, 1270 SmallPtrSetImpl<Instruction *> &FusedInsts) { 1271 assert(MatrixLayout == MatrixLayoutTy::ColumnMajor && 1272 "Tiling only supported for column-major matrixes at the moment!"); 1273 if (!isFusionProfitable(MatMul)) 1274 return; 1275 1276 ShapeInfo LShape(MatMul->getArgOperand(2), MatMul->getArgOperand(3)); 1277 ShapeInfo RShape(MatMul->getArgOperand(3), MatMul->getArgOperand(4)); 1278 1279 const unsigned R = LShape.NumRows; 1280 const unsigned C = RShape.NumColumns; 1281 const unsigned M = LShape.NumColumns; 1282 auto *EltType = cast<VectorType>(MatMul->getType())->getElementType(); 1283 1284 Value *APtr = getNonAliasingPointer(LoadOp0, Store, MatMul); 1285 Value *BPtr = getNonAliasingPointer(LoadOp1, Store, MatMul); 1286 Value *CPtr = Store->getPointerOperand(); 1287 1288 bool AllowContract = AllowContractEnabled || (isa<FPMathOperator>(MatMul) && 1289 MatMul->hasAllowContract()); 1290 if (TileUseLoops && (R % TileSize == 0 && C % TileSize == 0)) 1291 createTiledLoops(MatMul, APtr, LShape, BPtr, RShape, Store, 1292 AllowContract); 1293 else { 1294 IRBuilder<> Builder(Store); 1295 for (unsigned J = 0; J < C; J += TileSize) 1296 for (unsigned I = 0; I < R; I += TileSize) { 1297 const unsigned TileR = std::min(R - I, unsigned(TileSize)); 1298 const unsigned TileC = std::min(C - J, unsigned(TileSize)); 1299 MatrixTy Res = getZeroMatrix(EltType, TileR, TileC); 1300 1301 for (unsigned K = 0; K < M; K += TileSize) { 1302 const unsigned TileM = std::min(M - K, unsigned(TileSize)); 1303 MatrixTy A = 1304 loadMatrix(APtr, LoadOp0->getAlign(), LoadOp0->isVolatile(), 1305 LShape, Builder.getInt64(I), Builder.getInt64(K), 1306 {TileR, TileM}, EltType, Builder); 1307 MatrixTy B = 1308 loadMatrix(BPtr, LoadOp1->getAlign(), LoadOp1->isVolatile(), 1309 RShape, Builder.getInt64(K), Builder.getInt64(J), 1310 {TileM, TileC}, EltType, Builder); 1311 emitMatrixMultiply(Res, A, B, AllowContract, Builder, true); 1312 } 1313 storeMatrix(Res, CPtr, Store->getAlign(), Store->isVolatile(), {R, M}, 1314 Builder.getInt64(I), Builder.getInt64(J), EltType, 1315 Builder); 1316 } 1317 } 1318 1319 // Mark eliminated instructions as fused and remove them. 1320 FusedInsts.insert(Store); 1321 FusedInsts.insert(MatMul); 1322 Store->eraseFromParent(); 1323 MatMul->eraseFromParent(); 1324 if (LoadOp0->hasNUses(0)) { 1325 FusedInsts.insert(LoadOp0); 1326 LoadOp0->eraseFromParent(); 1327 } 1328 if (LoadOp1->hasNUses(0)) { 1329 FusedInsts.insert(LoadOp1); 1330 LoadOp1->eraseFromParent(); 1331 } 1332 } 1333 1334 /// Try to lower matrix multiply chains by fusing operations. 1335 /// 1336 /// Currently we only lower {ld, ld} -> matmul -> st chains. 1337 // 1338 /// No need to return a MatrixTy object for the result of the operation, since 1339 /// the single store user will be lowered as part of this. Instructions that 1340 /// are completely eliminated by fusion are added to \p FusedInsts. 1341 void LowerMatrixMultiplyFused(CallInst *MatMul, 1342 SmallPtrSetImpl<Instruction *> &FusedInsts) { 1343 if (!FuseMatrix || !MatMul->hasOneUse() || 1344 MatrixLayout != MatrixLayoutTy::ColumnMajor || !DT) 1345 return; 1346 1347 assert(AA && LI && "Analyses should be available"); 1348 1349 auto *LoadOp0 = dyn_cast<LoadInst>(MatMul->getOperand(0)); 1350 auto *LoadOp1 = dyn_cast<LoadInst>(MatMul->getOperand(1)); 1351 auto *Store = dyn_cast<StoreInst>(*MatMul->user_begin()); 1352 if (LoadOp0 && LoadOp1 && Store) { 1353 // The store address must dominate the MatMul instruction, otherwise 1354 // we create invalid IR. 1355 // FIXME: See if we can hoist the store address computation. 1356 auto *AddrI = dyn_cast<Instruction>(Store->getOperand(1)); 1357 if (AddrI && (!DT->dominates(AddrI, MatMul))) 1358 return; 1359 1360 emitSIMDTiling(MatMul, LoadOp0, LoadOp1, Store, FusedInsts); 1361 return; 1362 } 1363 } 1364 1365 /// Lowers llvm.matrix.multiply. 1366 void LowerMultiply(CallInst *MatMul) { 1367 IRBuilder<> Builder(MatMul); 1368 auto *EltType = cast<VectorType>(MatMul->getType())->getElementType(); 1369 ShapeInfo LShape(MatMul->getArgOperand(2), MatMul->getArgOperand(3)); 1370 ShapeInfo RShape(MatMul->getArgOperand(3), MatMul->getArgOperand(4)); 1371 1372 const MatrixTy &Lhs = getMatrix(MatMul->getArgOperand(0), LShape, Builder); 1373 const MatrixTy &Rhs = getMatrix(MatMul->getArgOperand(1), RShape, Builder); 1374 assert(Lhs.getElementType() == Rhs.getElementType() && 1375 "Matrix multiply argument element types do not match."); 1376 1377 const unsigned R = LShape.NumRows; 1378 const unsigned C = RShape.NumColumns; 1379 assert(LShape.NumColumns == RShape.NumRows); 1380 1381 // Initialize the output 1382 MatrixTy Result(R, C, EltType); 1383 assert(Lhs.getElementType() == Result.getElementType() && 1384 "Matrix multiply result element type does not match arguments."); 1385 1386 bool AllowContract = AllowContractEnabled || (isa<FPMathOperator>(MatMul) && 1387 MatMul->hasAllowContract()); 1388 emitMatrixMultiply(Result, Lhs, Rhs, AllowContract, Builder, false); 1389 finalizeLowering(MatMul, Result, Builder); 1390 } 1391 1392 /// Lowers llvm.matrix.transpose. 1393 void LowerTranspose(CallInst *Inst) { 1394 MatrixTy Result; 1395 IRBuilder<> Builder(Inst); 1396 Value *InputVal = Inst->getArgOperand(0); 1397 VectorType *VectorTy = cast<VectorType>(InputVal->getType()); 1398 ShapeInfo ArgShape(Inst->getArgOperand(1), Inst->getArgOperand(2)); 1399 MatrixTy InputMatrix = getMatrix(InputVal, ArgShape, Builder); 1400 1401 const unsigned NewNumVecs = 1402 InputMatrix.isColumnMajor() ? ArgShape.NumRows : ArgShape.NumColumns; 1403 const unsigned NewNumElts = 1404 InputMatrix.isColumnMajor() ? ArgShape.NumColumns : ArgShape.NumRows; 1405 1406 for (unsigned I = 0; I < NewNumVecs; ++I) { 1407 // Build a single result vector. First initialize it. 1408 Value *ResultVector = UndefValue::get( 1409 FixedVectorType::get(VectorTy->getElementType(), NewNumElts)); 1410 // Go through the old elements and insert it into the resulting vector. 1411 for (auto J : enumerate(InputMatrix.vectors())) { 1412 Value *Elt = Builder.CreateExtractElement(J.value(), I); 1413 // Row and column indices are transposed. 1414 ResultVector = 1415 Builder.CreateInsertElement(ResultVector, Elt, J.index()); 1416 } 1417 Result.addVector(ResultVector); 1418 } 1419 1420 // TODO: Improve estimate of operations needed for transposes. Currently we 1421 // just count the insertelement/extractelement instructions, but do not 1422 // account for later simplifications/combines. 1423 finalizeLowering( 1424 Inst, 1425 Result.addNumComputeOps(2 * ArgShape.NumRows * ArgShape.NumColumns), 1426 Builder); 1427 } 1428 1429 /// Lower load instructions, if shape information is available. 1430 bool VisitLoad(LoadInst *Inst, Value *Ptr, IRBuilder<> &Builder) { 1431 auto I = ShapeMap.find(Inst); 1432 if (I == ShapeMap.end()) 1433 return false; 1434 1435 LowerLoad(Inst, Ptr, Inst->getAlign(), 1436 Builder.getInt64(I->second.getStride()), Inst->isVolatile(), 1437 I->second); 1438 return true; 1439 } 1440 1441 bool VisitStore(StoreInst *Inst, Value *StoredVal, Value *Ptr, 1442 IRBuilder<> &Builder) { 1443 auto I = ShapeMap.find(StoredVal); 1444 if (I == ShapeMap.end()) 1445 return false; 1446 1447 LowerStore(Inst, StoredVal, Ptr, Inst->getAlign(), 1448 Builder.getInt64(I->second.getStride()), Inst->isVolatile(), 1449 I->second); 1450 return true; 1451 } 1452 1453 /// Lower binary operators, if shape information is available. 1454 bool VisitBinaryOperator(BinaryOperator *Inst) { 1455 auto I = ShapeMap.find(Inst); 1456 if (I == ShapeMap.end()) 1457 return false; 1458 1459 Value *Lhs = Inst->getOperand(0); 1460 Value *Rhs = Inst->getOperand(1); 1461 1462 IRBuilder<> Builder(Inst); 1463 ShapeInfo &Shape = I->second; 1464 1465 MatrixTy Result; 1466 MatrixTy A = getMatrix(Lhs, Shape, Builder); 1467 MatrixTy B = getMatrix(Rhs, Shape, Builder); 1468 assert(A.isColumnMajor() == B.isColumnMajor() && 1469 Result.isColumnMajor() == A.isColumnMajor() && 1470 "operands must agree on matrix layout"); 1471 1472 // Helper to perform binary op on vectors. 1473 auto BuildVectorOp = [&Builder, Inst](Value *LHS, Value *RHS) { 1474 switch (Inst->getOpcode()) { 1475 case Instruction::Add: 1476 return Builder.CreateAdd(LHS, RHS); 1477 case Instruction::Mul: 1478 return Builder.CreateMul(LHS, RHS); 1479 case Instruction::Sub: 1480 return Builder.CreateSub(LHS, RHS); 1481 case Instruction::FAdd: 1482 return Builder.CreateFAdd(LHS, RHS); 1483 case Instruction::FMul: 1484 return Builder.CreateFMul(LHS, RHS); 1485 case Instruction::FSub: 1486 return Builder.CreateFSub(LHS, RHS); 1487 default: 1488 llvm_unreachable("Unsupported binary operator for matrix"); 1489 } 1490 }; 1491 1492 for (unsigned I = 0; I < Shape.getNumVectors(); ++I) 1493 Result.addVector(BuildVectorOp(A.getVector(I), B.getVector(I))); 1494 1495 finalizeLowering(Inst, 1496 Result.addNumComputeOps(getNumOps(Result.getVectorTy()) * 1497 Result.getNumVectors()), 1498 Builder); 1499 return true; 1500 } 1501 1502 /// Lower unary operators, if shape information is available. 1503 bool VisitUnaryOperator(UnaryOperator *Inst) { 1504 auto I = ShapeMap.find(Inst); 1505 if (I == ShapeMap.end()) 1506 return false; 1507 1508 Value *Op = Inst->getOperand(0); 1509 1510 IRBuilder<> Builder(Inst); 1511 ShapeInfo &Shape = I->second; 1512 1513 MatrixTy Result; 1514 MatrixTy M = getMatrix(Op, Shape, Builder); 1515 1516 // Helper to perform unary op on vectors. 1517 auto BuildVectorOp = [&Builder, Inst](Value *Op) { 1518 switch (Inst->getOpcode()) { 1519 case Instruction::FNeg: 1520 return Builder.CreateFNeg(Op); 1521 default: 1522 llvm_unreachable("Unsupported unary operator for matrix"); 1523 } 1524 }; 1525 1526 for (unsigned I = 0; I < Shape.getNumVectors(); ++I) 1527 Result.addVector(BuildVectorOp(M.getVector(I))); 1528 1529 finalizeLowering(Inst, 1530 Result.addNumComputeOps(getNumOps(Result.getVectorTy()) * 1531 Result.getNumVectors()), 1532 Builder); 1533 return true; 1534 } 1535 1536 /// Helper to linearize a matrix expression tree into a string. Currently 1537 /// matrix expressions are linarized by starting at an expression leaf and 1538 /// linearizing bottom up. 1539 struct ExprLinearizer { 1540 unsigned LengthToBreak = 100; 1541 std::string Str; 1542 raw_string_ostream Stream; 1543 unsigned LineLength = 0; 1544 const DataLayout &DL; 1545 1546 /// Mapping from instructions to matrixes. It is used to identify 1547 /// matrix instructions. 1548 const MapVector<Value *, MatrixTy> &Inst2Matrix; 1549 1550 /// Mapping from values to the leaves of all expressions that the value is 1551 /// part of. 1552 const DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared; 1553 1554 /// Set of matrix expressions in the scope of a given DISubprogram. 1555 const SmallSetVector<Value *, 32> &ExprsInSubprogram; 1556 1557 /// Leaf node of the expression to linearize. 1558 Value *Leaf; 1559 1560 /// Used to keep track of sub-expressions that get reused while linearizing 1561 /// the expression. Re-used sub-expressions are marked as (reused). 1562 SmallPtrSet<Value *, 8> ReusedExprs; 1563 1564 ExprLinearizer(const DataLayout &DL, 1565 const MapVector<Value *, MatrixTy> &Inst2Matrix, 1566 const DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared, 1567 const SmallSetVector<Value *, 32> &ExprsInSubprogram, 1568 Value *Leaf) 1569 : Str(), Stream(Str), DL(DL), Inst2Matrix(Inst2Matrix), Shared(Shared), 1570 ExprsInSubprogram(ExprsInSubprogram), Leaf(Leaf) {} 1571 1572 void indent(unsigned N) { 1573 LineLength += N; 1574 for (unsigned i = 0; i < N; i++) 1575 Stream << " "; 1576 } 1577 1578 void lineBreak() { 1579 Stream << "\n"; 1580 LineLength = 0; 1581 } 1582 1583 void maybeIndent(unsigned Indent) { 1584 if (LineLength >= LengthToBreak) 1585 lineBreak(); 1586 1587 if (LineLength == 0) 1588 indent(Indent); 1589 } 1590 1591 void write(StringRef S) { 1592 LineLength += S.size(); 1593 Stream << S; 1594 } 1595 1596 Value *getUnderlyingObjectThroughLoads(Value *V) { 1597 if (Value *Ptr = getPointerOperand(V)) 1598 return getUnderlyingObjectThroughLoads(Ptr); 1599 else if (V->getType()->isPointerTy()) 1600 return getUnderlyingObject(V); 1601 return V; 1602 } 1603 1604 /// Returns true if \p V is a matrix value in the given subprogram. 1605 bool isMatrix(Value *V) const { return ExprsInSubprogram.count(V); } 1606 1607 /// If \p V is a matrix value, print its shape as as NumRows x NumColumns to 1608 /// \p SS. 1609 void prettyPrintMatrixType(Value *V, raw_string_ostream &SS) { 1610 auto M = Inst2Matrix.find(V); 1611 if (M == Inst2Matrix.end()) 1612 SS << "unknown"; 1613 else { 1614 SS << M->second.getNumRows(); 1615 SS << "x"; 1616 SS << M->second.getNumColumns(); 1617 } 1618 } 1619 1620 /// Write the called function name. Handles calls to llvm.matrix.* 1621 /// specially: we write the name, followed by the dimensions of the input 1622 /// matrixes, followed by the scalar type name. 1623 void writeFnName(CallInst *CI) { 1624 if (!CI->getCalledFunction()) 1625 write("<no called fn>"); 1626 else { 1627 StringRef Name = CI->getCalledFunction()->getName(); 1628 if (!Name.startswith("llvm.matrix")) { 1629 write(Name); 1630 return; 1631 } 1632 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); 1633 write(StringRef(Intrinsic::getName(II->getIntrinsicID(), {})) 1634 .drop_front(StringRef("llvm.matrix.").size())); 1635 write("."); 1636 std::string Tmp; 1637 raw_string_ostream SS(Tmp); 1638 1639 switch (II->getIntrinsicID()) { 1640 case Intrinsic::matrix_multiply: 1641 prettyPrintMatrixType(II->getOperand(0), SS); 1642 SS << "."; 1643 prettyPrintMatrixType(II->getOperand(1), SS); 1644 SS << "." << *II->getType()->getScalarType(); 1645 break; 1646 case Intrinsic::matrix_transpose: 1647 prettyPrintMatrixType(II->getOperand(0), SS); 1648 SS << "." << *II->getType()->getScalarType(); 1649 break; 1650 case Intrinsic::matrix_column_major_load: 1651 prettyPrintMatrixType(II, SS); 1652 SS << "." << *II->getType()->getScalarType(); 1653 break; 1654 case Intrinsic::matrix_column_major_store: 1655 prettyPrintMatrixType(II->getOperand(0), SS); 1656 SS << "." << *II->getOperand(0)->getType()->getScalarType(); 1657 break; 1658 default: 1659 llvm_unreachable("Unhandled case"); 1660 } 1661 SS.flush(); 1662 write(Tmp); 1663 } 1664 } 1665 1666 unsigned getNumShapeArgs(CallInst *CI) const { 1667 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 1668 switch (II->getIntrinsicID()) { 1669 case Intrinsic::matrix_multiply: 1670 return 3; 1671 case Intrinsic::matrix_transpose: 1672 return 2; 1673 case Intrinsic::matrix_column_major_load: 1674 case Intrinsic::matrix_column_major_store: 1675 return 3; 1676 default: 1677 return 0; 1678 } 1679 } 1680 return 0; 1681 } 1682 1683 /// Special printing for values: for pointers, we print if they refer to an 1684 /// (function) external address or a stack address, for other values we 1685 /// either print the constant or "scalar"/"matrix" for other values. 1686 void write(Value *V) { 1687 V = getUnderlyingObjectThroughLoads(V); 1688 if (V->getType()->isPointerTy()) { 1689 if (isa<AllocaInst>(V)) { 1690 Stream << "stack addr"; 1691 LineLength += StringRef("stack addr").size(); 1692 } else { 1693 Stream << "addr"; 1694 LineLength += StringRef("addr").size(); 1695 } 1696 if (!V->getName().empty()) { 1697 Stream << " %" << V->getName() << ""; 1698 LineLength += V->getName().size() + 2; 1699 } 1700 return; 1701 } 1702 1703 std::string Tmp; 1704 raw_string_ostream TmpStream(Tmp); 1705 1706 if (auto *CI = dyn_cast<ConstantInt>(V)) 1707 TmpStream << CI->getValue(); 1708 else if (isa<Constant>(V)) 1709 TmpStream << "constant"; 1710 else { 1711 if (isMatrix(V)) 1712 TmpStream << "matrix"; 1713 else 1714 TmpStream << "scalar"; 1715 } 1716 TmpStream.flush(); 1717 Tmp = std::string(StringRef(Tmp).trim()); 1718 LineLength += Tmp.size(); 1719 Stream << Tmp; 1720 } 1721 1722 /// Linearize expression \p Expr starting at an indentation of \p Indent. 1723 /// Expressions that are re-used multiple times are prefixed with (reused) 1724 /// at the re-used root instruction. 1725 void linearizeExpr(Value *Expr, unsigned Indent, bool ParentReused, 1726 bool ParentShared) { 1727 auto *I = cast<Instruction>(Expr); 1728 maybeIndent(Indent); 1729 SmallVector<Value *, 8> Ops; 1730 1731 // Is Expr shared with other expression leaves? 1732 bool ExprShared = false; 1733 1734 // Deal with shared subtrees. Mark them as shared, if required. 1735 if (!ParentShared) { 1736 auto SI = Shared.find(Expr); 1737 assert(SI != Shared.end() && SI->second.count(Leaf)); 1738 1739 for (Value *S : SI->second) { 1740 if (S == Leaf) 1741 continue; 1742 DebugLoc DL = cast<Instruction>(S)->getDebugLoc(); 1743 write("shared with remark at line " + std::to_string(DL.getLine()) + 1744 " column " + std::to_string(DL.getCol()) + " ("); 1745 } 1746 ExprShared = SI->second.size() > 1; 1747 } 1748 1749 bool Reused = !ReusedExprs.insert(Expr).second; 1750 if (Reused && !ParentReused) 1751 write("(reused) "); 1752 1753 if (auto *CI = dyn_cast<CallInst>(I)) { 1754 writeFnName(CI); 1755 1756 Ops.append(CI->arg_begin(), CI->arg_end() - getNumShapeArgs(CI)); 1757 } else if (isa<BitCastInst>(Expr)) { 1758 // Special case bitcasts, which are used to materialize matrixes from 1759 // non-matrix ops. 1760 write("matrix"); 1761 return; 1762 } else { 1763 Ops.append(I->value_op_begin(), I->value_op_end()); 1764 write(std::string(I->getOpcodeName())); 1765 } 1766 1767 write(std::string("(")); 1768 1769 unsigned NumOpsToBreak = 1; 1770 if (match(Expr, m_Intrinsic<Intrinsic::matrix_column_major_load>())) 1771 NumOpsToBreak = 2; 1772 1773 for (Value *Op : Ops) { 1774 if (Ops.size() > NumOpsToBreak) 1775 lineBreak(); 1776 1777 maybeIndent(Indent + 1); 1778 if (isMatrix(Op)) 1779 linearizeExpr(Op, Indent + 1, Reused, ExprShared); 1780 else 1781 write(Op); 1782 if (Op != Ops.back()) 1783 write(", "); 1784 } 1785 1786 write(")"); 1787 } 1788 1789 const std::string &getResult() { 1790 Stream.flush(); 1791 return Str; 1792 } 1793 }; 1794 1795 /// Generate remarks for matrix operations in a function. To generate remarks 1796 /// for matrix expressions, the following approach is used: 1797 /// 1. Use the inlined-at debug information to group matrix operations to the 1798 /// DISubprograms they are contained in. 1799 /// 2. Collect leaves of matrix expressions (done in 1800 /// RemarkGenerator::getExpressionLeaves) for each subprogram - expression 1801 // mapping. Leaves are lowered matrix instructions without other matrix 1802 // users (like stores) in the current subprogram. 1803 /// 3. For each leaf, create a remark containing a linearizied version of the 1804 /// matrix expression. The expression is linearized by a recursive 1805 /// bottom-up traversal of the matrix operands, starting at a leaf. Note 1806 /// that multiple leaves can share sub-expressions. Shared subexpressions 1807 /// are explicitly marked as shared(). 1808 struct RemarkGenerator { 1809 const MapVector<Value *, MatrixTy> &Inst2Matrix; 1810 OptimizationRemarkEmitter &ORE; 1811 Function &Func; 1812 const DataLayout &DL; 1813 1814 RemarkGenerator(const MapVector<Value *, MatrixTy> &Inst2Matrix, 1815 OptimizationRemarkEmitter &ORE, Function &Func) 1816 : Inst2Matrix(Inst2Matrix), ORE(ORE), Func(Func), 1817 DL(Func.getParent()->getDataLayout()) {} 1818 1819 /// Return all leaves of the expressions in \p ExprsInSubprogram. Those are 1820 /// instructions in Inst2Matrix returning void or without any users in 1821 /// \p ExprsInSubprogram. Currently that should only include stores. 1822 SmallVector<Value *, 4> 1823 getExpressionLeaves(const SmallSetVector<Value *, 32> &ExprsInSubprogram) { 1824 SmallVector<Value *, 4> Leaves; 1825 for (auto *Expr : ExprsInSubprogram) 1826 if (Expr->getType()->isVoidTy() || 1827 !any_of(Expr->users(), [&ExprsInSubprogram](User *U) { 1828 return ExprsInSubprogram.count(U); 1829 })) 1830 Leaves.push_back(Expr); 1831 return Leaves; 1832 } 1833 1834 /// Recursively traverse expression \p V starting at \p Leaf and add \p Leaf 1835 /// to all visited expressions in \p Shared. Limit the matrix operations to 1836 /// the ones in \p ExprsInSubprogram. 1837 void collectSharedInfo(Value *Leaf, Value *V, 1838 const SmallSetVector<Value *, 32> &ExprsInSubprogram, 1839 DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared) { 1840 1841 if (!ExprsInSubprogram.count(V)) 1842 return; 1843 1844 auto I = Shared.insert({V, {}}); 1845 I.first->second.insert(Leaf); 1846 1847 for (Value *Op : cast<Instruction>(V)->operand_values()) 1848 collectSharedInfo(Leaf, Op, ExprsInSubprogram, Shared); 1849 } 1850 1851 /// Calculate the number of exclusive and shared op counts for expression 1852 /// starting at \p V. Expressions used multiple times are counted once. 1853 /// Limit the matrix operations to the ones in \p ExprsInSubprogram. 1854 std::pair<OpInfoTy, OpInfoTy> 1855 sumOpInfos(Value *Root, SmallPtrSetImpl<Value *> &ReusedExprs, 1856 const SmallSetVector<Value *, 32> &ExprsInSubprogram, 1857 DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared) const { 1858 if (!ExprsInSubprogram.count(Root)) 1859 return {}; 1860 1861 // Already counted this expression. Stop. 1862 if (!ReusedExprs.insert(Root).second) 1863 return {}; 1864 1865 OpInfoTy SharedCount; 1866 OpInfoTy Count; 1867 1868 auto I = Shared.find(Root); 1869 auto CM = Inst2Matrix.find(Root); 1870 if (I->second.size() == 1) 1871 Count = CM->second.getOpInfo(); 1872 else 1873 SharedCount = CM->second.getOpInfo(); 1874 1875 for (Value *Op : cast<Instruction>(Root)->operand_values()) { 1876 auto C = sumOpInfos(Op, ReusedExprs, ExprsInSubprogram, Shared); 1877 Count += C.first; 1878 SharedCount += C.second; 1879 } 1880 return {Count, SharedCount}; 1881 } 1882 1883 void emitRemarks() { 1884 if (!ORE.allowExtraAnalysis(DEBUG_TYPE)) 1885 return; 1886 1887 // Map matrix operations to their containting subprograms, by traversing 1888 // the inlinedAt chain. If the function does not have a DISubprogram, we 1889 // only map them to the containing function. 1890 MapVector<DISubprogram *, SmallVector<Value *, 8>> Subprog2Exprs; 1891 for (auto &KV : Inst2Matrix) { 1892 if (Func.getSubprogram()) { 1893 auto *I = cast<Instruction>(KV.first); 1894 DILocation *Context = I->getDebugLoc(); 1895 while (Context) { 1896 auto I = 1897 Subprog2Exprs.insert({getSubprogram(Context->getScope()), {}}); 1898 I.first->second.push_back(KV.first); 1899 Context = DebugLoc(Context).getInlinedAt(); 1900 } 1901 } else { 1902 auto I = Subprog2Exprs.insert({nullptr, {}}); 1903 I.first->second.push_back(KV.first); 1904 } 1905 } 1906 for (auto &KV : Subprog2Exprs) { 1907 SmallSetVector<Value *, 32> ExprsInSubprogram(KV.second.begin(), 1908 KV.second.end()); 1909 auto Leaves = getExpressionLeaves(ExprsInSubprogram); 1910 1911 DenseMap<Value *, SmallPtrSet<Value *, 2>> Shared; 1912 for (Value *Leaf : Leaves) 1913 collectSharedInfo(Leaf, Leaf, ExprsInSubprogram, Shared); 1914 1915 // Generate remarks for each leaf. 1916 for (auto *L : Leaves) { 1917 1918 DebugLoc Loc = cast<Instruction>(L)->getDebugLoc(); 1919 DILocation *Context = cast<Instruction>(L)->getDebugLoc(); 1920 while (Context) { 1921 if (getSubprogram(Context->getScope()) == KV.first) { 1922 Loc = Context; 1923 break; 1924 } 1925 Context = DebugLoc(Context).getInlinedAt(); 1926 } 1927 1928 SmallPtrSet<Value *, 8> ReusedExprs; 1929 OpInfoTy Counts, SharedCounts; 1930 std::tie(Counts, SharedCounts) = 1931 sumOpInfos(L, ReusedExprs, ExprsInSubprogram, Shared); 1932 1933 OptimizationRemark Rem(DEBUG_TYPE, "matrix-lowered", Loc, 1934 cast<Instruction>(L)->getParent()); 1935 1936 Rem << "Lowered with "; 1937 Rem << ore::NV("NumStores", Counts.NumStores) << " stores, " 1938 << ore::NV("NumLoads", Counts.NumLoads) << " loads, " 1939 << ore::NV("NumComputeOps", Counts.NumComputeOps) 1940 << " compute ops"; 1941 1942 if (SharedCounts.NumStores > 0 || SharedCounts.NumLoads > 0 || 1943 SharedCounts.NumComputeOps > 0) { 1944 Rem << ",\nadditionally " 1945 << ore::NV("NumStores", SharedCounts.NumStores) << " stores, " 1946 << ore::NV("NumLoads", SharedCounts.NumLoads) << " loads, " 1947 << ore::NV("NumFPOps", SharedCounts.NumComputeOps) 1948 << " compute ops" 1949 << " are shared with other expressions"; 1950 } 1951 1952 Rem << ("\n" + linearize(L, Shared, ExprsInSubprogram, DL)); 1953 ORE.emit(Rem); 1954 } 1955 } 1956 } 1957 1958 std::string 1959 linearize(Value *L, 1960 const DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared, 1961 const SmallSetVector<Value *, 32> &ExprsInSubprogram, 1962 const DataLayout &DL) { 1963 ExprLinearizer Lin(DL, Inst2Matrix, Shared, ExprsInSubprogram, L); 1964 Lin.linearizeExpr(L, 0, false, false); 1965 return Lin.getResult(); 1966 } 1967 }; 1968 }; 1969 } // namespace 1970 1971 PreservedAnalyses LowerMatrixIntrinsicsPass::run(Function &F, 1972 FunctionAnalysisManager &AM) { 1973 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 1974 OptimizationRemarkEmitter *ORE = nullptr; 1975 AAResults *AA = nullptr; 1976 DominatorTree *DT = nullptr; 1977 LoopInfo *LI = nullptr; 1978 1979 if (!Minimal) { 1980 ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 1981 AA = &AM.getResult<AAManager>(F); 1982 DT = &AM.getResult<DominatorTreeAnalysis>(F); 1983 LI = &AM.getResult<LoopAnalysis>(F); 1984 } 1985 1986 LowerMatrixIntrinsics LMT(F, TTI, AA, DT, LI, ORE); 1987 if (LMT.Visit()) { 1988 PreservedAnalyses PA; 1989 if (!Minimal) { 1990 PA.preserve<LoopAnalysis>(); 1991 PA.preserve<DominatorTreeAnalysis>(); 1992 } 1993 return PA; 1994 } 1995 return PreservedAnalyses::all(); 1996 } 1997 1998 namespace { 1999 2000 class LowerMatrixIntrinsicsLegacyPass : public FunctionPass { 2001 public: 2002 static char ID; 2003 2004 LowerMatrixIntrinsicsLegacyPass() : FunctionPass(ID) { 2005 initializeLowerMatrixIntrinsicsLegacyPassPass( 2006 *PassRegistry::getPassRegistry()); 2007 } 2008 2009 bool runOnFunction(Function &F) override { 2010 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 2011 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 2012 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 2013 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2014 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 2015 LowerMatrixIntrinsics LMT(F, TTI, &AA, &DT, &LI, &ORE); 2016 bool C = LMT.Visit(); 2017 return C; 2018 } 2019 2020 void getAnalysisUsage(AnalysisUsage &AU) const override { 2021 AU.addRequired<TargetTransformInfoWrapperPass>(); 2022 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 2023 AU.addRequired<AAResultsWrapperPass>(); 2024 AU.addRequired<DominatorTreeWrapperPass>(); 2025 AU.addPreserved<DominatorTreeWrapperPass>(); 2026 AU.addRequired<LoopInfoWrapperPass>(); 2027 AU.addPreserved<LoopInfoWrapperPass>(); 2028 } 2029 }; 2030 } // namespace 2031 2032 static const char pass_name[] = "Lower the matrix intrinsics"; 2033 char LowerMatrixIntrinsicsLegacyPass::ID = 0; 2034 INITIALIZE_PASS_BEGIN(LowerMatrixIntrinsicsLegacyPass, DEBUG_TYPE, pass_name, 2035 false, false) 2036 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 2037 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 2038 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2039 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 2040 INITIALIZE_PASS_END(LowerMatrixIntrinsicsLegacyPass, DEBUG_TYPE, pass_name, 2041 false, false) 2042 2043 Pass *llvm::createLowerMatrixIntrinsicsPass() { 2044 return new LowerMatrixIntrinsicsLegacyPass(); 2045 } 2046 2047 namespace { 2048 2049 /// A lightweight version of the matrix lowering pass that only requires TTI. 2050 /// Advanced features that require DT, AA or ORE like tiling are disabled. This 2051 /// is used to lower matrix intrinsics if the main lowering pass is not run, for 2052 /// example with -O0. 2053 class LowerMatrixIntrinsicsMinimalLegacyPass : public FunctionPass { 2054 public: 2055 static char ID; 2056 2057 LowerMatrixIntrinsicsMinimalLegacyPass() : FunctionPass(ID) { 2058 initializeLowerMatrixIntrinsicsMinimalLegacyPassPass( 2059 *PassRegistry::getPassRegistry()); 2060 } 2061 2062 bool runOnFunction(Function &F) override { 2063 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 2064 LowerMatrixIntrinsics LMT(F, TTI, nullptr, nullptr, nullptr, nullptr); 2065 bool C = LMT.Visit(); 2066 return C; 2067 } 2068 2069 void getAnalysisUsage(AnalysisUsage &AU) const override { 2070 AU.addRequired<TargetTransformInfoWrapperPass>(); 2071 AU.setPreservesCFG(); 2072 } 2073 }; 2074 } // namespace 2075 2076 static const char pass_name_minimal[] = "Lower the matrix intrinsics (minimal)"; 2077 char LowerMatrixIntrinsicsMinimalLegacyPass::ID = 0; 2078 INITIALIZE_PASS_BEGIN(LowerMatrixIntrinsicsMinimalLegacyPass, 2079 "lower-matrix-intrinsics-minimal", pass_name_minimal, 2080 false, false) 2081 INITIALIZE_PASS_END(LowerMatrixIntrinsicsMinimalLegacyPass, 2082 "lower-matrix-intrinsics-minimal", pass_name_minimal, false, 2083 false) 2084 2085 Pass *llvm::createLowerMatrixIntrinsicsMinimalPass() { 2086 return new LowerMatrixIntrinsicsMinimalLegacyPass(); 2087 } 2088