1 //===- VectorToSCF.cpp - Conversion from Vector to mix of SCF and Std -----===// 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 // This file implements target-dependent lowering of vector transfer operations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include <type_traits> 14 15 #include "mlir/Conversion/VectorToSCF/VectorToSCF.h" 16 #include "mlir/Dialect/Affine/EDSC/Intrinsics.h" 17 #include "mlir/Dialect/SCF/EDSC/Builders.h" 18 #include "mlir/Dialect/SCF/EDSC/Intrinsics.h" 19 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h" 20 #include "mlir/Dialect/Vector/EDSC/Intrinsics.h" 21 #include "mlir/Dialect/Vector/VectorOps.h" 22 #include "mlir/Dialect/Vector/VectorUtils.h" 23 #include "mlir/IR/AffineExpr.h" 24 #include "mlir/IR/AffineMap.h" 25 #include "mlir/IR/Attributes.h" 26 #include "mlir/IR/Builders.h" 27 #include "mlir/IR/Location.h" 28 #include "mlir/IR/Matchers.h" 29 #include "mlir/IR/OperationSupport.h" 30 #include "mlir/IR/PatternMatch.h" 31 #include "mlir/IR/Types.h" 32 33 using namespace mlir; 34 using namespace mlir::edsc; 35 using namespace mlir::edsc::intrinsics; 36 using vector::TransferReadOp; 37 using vector::TransferWriteOp; 38 39 namespace { 40 /// Helper class captures the common information needed to lower N>1-D vector 41 /// transfer operations (read and write). 42 /// On construction, this class opens an edsc::ScopedContext for simpler IR 43 /// manipulation. 44 /// In pseudo-IR, for an n-D vector_transfer_read such as: 45 /// 46 /// ``` 47 /// vector_transfer_read(%m, %offsets, identity_map, %fill) : 48 /// memref<(leading_dims) x (major_dims) x (minor_dims) x type>, 49 /// vector<(major_dims) x (minor_dims) x type> 50 /// ``` 51 /// 52 /// where rank(minor_dims) is the lower-level vector rank (e.g. 1 for LLVM or 53 /// higher). 54 /// 55 /// This is the entry point to emitting pseudo-IR resembling: 56 /// 57 /// ``` 58 /// %tmp = alloc(): memref<(major_dims) x vector<minor_dim x type>> 59 /// for (%ivs_major, {0}, {vector_shape}, {1}) { // (N-1)-D loop nest 60 /// if (any_of(%ivs_major + %offsets, <, major_dims)) { 61 /// %v = vector_transfer_read( 62 /// {%offsets_leading, %ivs_major + %offsets_major, %offsets_minor}, 63 /// %ivs_minor): 64 /// memref<(leading_dims) x (major_dims) x (minor_dims) x type>, 65 /// vector<(minor_dims) x type>; 66 /// store(%v, %tmp); 67 /// } else { 68 /// %v = splat(vector<(minor_dims) x type>, %fill) 69 /// store(%v, %tmp, %ivs_major); 70 /// } 71 /// } 72 /// %res = load(%tmp, %0): memref<(major_dims) x vector<minor_dim x type>>): 73 // vector<(major_dims) x (minor_dims) x type> 74 /// ``` 75 /// 76 template <typename ConcreteOp> 77 class NDTransferOpHelper { 78 public: 79 NDTransferOpHelper(PatternRewriter &rewriter, ConcreteOp xferOp, 80 const VectorTransferToSCFOptions &options) 81 : rewriter(rewriter), options(options), loc(xferOp.getLoc()), 82 scope(std::make_unique<ScopedContext>(rewriter, loc)), xferOp(xferOp), 83 op(xferOp.getOperation()) { 84 vectorType = xferOp.getVectorType(); 85 // TODO(ntv, ajcbik): when we go to k > 1-D vectors adapt minorRank. 86 minorRank = 1; 87 majorRank = vectorType.getRank() - minorRank; 88 leadingRank = xferOp.getMemRefType().getRank() - (majorRank + minorRank); 89 majorVectorType = 90 VectorType::get(vectorType.getShape().take_front(majorRank), 91 vectorType.getElementType()); 92 minorVectorType = 93 VectorType::get(vectorType.getShape().take_back(minorRank), 94 vectorType.getElementType()); 95 /// Memref of minor vector type is used for individual transfers. 96 memRefMinorVectorType = 97 MemRefType::get(majorVectorType.getShape(), minorVectorType, {}, 98 xferOp.getMemRefType().getMemorySpace()); 99 } 100 101 LogicalResult doReplace(); 102 103 private: 104 /// Creates the loop nest on the "major" dimensions and calls the 105 /// `loopBodyBuilder` lambda in the context of the loop nest. 106 template <typename Lambda> 107 void emitLoops(Lambda loopBodyBuilder); 108 109 /// Operate within the body of `emitLoops` to: 110 /// 1. Compute the indexings `majorIvs + majorOffsets` and save them in 111 /// `majorIvsPlusOffsets`. 112 /// 2. Return a boolean that determines whether the first `majorIvs.rank()` 113 /// dimensions `majorIvs + majorOffsets` are all within `memrefBounds`. 114 Value emitInBoundsCondition(ValueRange majorIvs, ValueRange majorOffsets, 115 MemRefBoundsCapture &memrefBounds, 116 SmallVectorImpl<Value> &majorIvsPlusOffsets); 117 118 /// Common state to lower vector transfer ops. 119 PatternRewriter &rewriter; 120 const VectorTransferToSCFOptions &options; 121 Location loc; 122 std::unique_ptr<ScopedContext> scope; 123 ConcreteOp xferOp; 124 Operation *op; 125 // A vector transfer copies data between: 126 // - memref<(leading_dims) x (major_dims) x (minor_dims) x type> 127 // - vector<(major_dims) x (minor_dims) x type> 128 unsigned minorRank; // for now always 1 129 unsigned majorRank; // vector rank - minorRank 130 unsigned leadingRank; // memref rank - vector rank 131 VectorType vectorType; // vector<(major_dims) x (minor_dims) x type> 132 VectorType majorVectorType; // vector<(major_dims) x type> 133 VectorType minorVectorType; // vector<(minor_dims) x type> 134 MemRefType memRefMinorVectorType; // memref<vector<(minor_dims) x type>> 135 }; 136 137 template <typename ConcreteOp> 138 template <typename Lambda> 139 void NDTransferOpHelper<ConcreteOp>::emitLoops(Lambda loopBodyBuilder) { 140 /// Loop nest operates on the major dimensions 141 MemRefBoundsCapture memrefBoundsCapture(xferOp.memref()); 142 143 if (options.unroll) { 144 auto shape = majorVectorType.getShape(); 145 auto strides = computeStrides(shape); 146 unsigned numUnrolledInstances = computeMaxLinearIndex(shape); 147 ValueRange indices(xferOp.indices()); 148 for (unsigned idx = 0; idx < numUnrolledInstances; ++idx) { 149 SmallVector<int64_t, 4> offsets = delinearize(strides, idx); 150 SmallVector<Value, 4> offsetValues = 151 llvm::to_vector<4>(llvm::map_range(offsets, [](int64_t off) -> Value { 152 return std_constant_index(off); 153 })); 154 loopBodyBuilder(offsetValues, indices.take_front(leadingRank), 155 indices.drop_front(leadingRank).take_front(majorRank), 156 indices.take_back(minorRank), memrefBoundsCapture); 157 } 158 } else { 159 VectorBoundsCapture vectorBoundsCapture(majorVectorType); 160 auto majorLbs = vectorBoundsCapture.getLbs(); 161 auto majorUbs = vectorBoundsCapture.getUbs(); 162 auto majorSteps = vectorBoundsCapture.getSteps(); 163 SmallVector<Value, 8> majorIvs(vectorBoundsCapture.rank()); 164 AffineLoopNestBuilder(majorIvs, majorLbs, majorUbs, majorSteps)([&] { 165 ValueRange indices(xferOp.indices()); 166 loopBodyBuilder(majorIvs, indices.take_front(leadingRank), 167 indices.drop_front(leadingRank).take_front(majorRank), 168 indices.take_back(minorRank), memrefBoundsCapture); 169 }); 170 } 171 } 172 173 template <typename ConcreteOp> 174 Value NDTransferOpHelper<ConcreteOp>::emitInBoundsCondition( 175 ValueRange majorIvs, ValueRange majorOffsets, 176 MemRefBoundsCapture &memrefBounds, 177 SmallVectorImpl<Value> &majorIvsPlusOffsets) { 178 Value inBoundsCondition; 179 majorIvsPlusOffsets.reserve(majorIvs.size()); 180 unsigned idx = 0; 181 for (auto it : llvm::zip(majorIvs, majorOffsets, memrefBounds.getUbs())) { 182 Value iv = std::get<0>(it), off = std::get<1>(it), ub = std::get<2>(it); 183 using namespace mlir::edsc::op; 184 majorIvsPlusOffsets.push_back(iv + off); 185 if (xferOp.isMaskedDim(leadingRank + idx)) { 186 Value inBounds = majorIvsPlusOffsets.back() < ub; 187 inBoundsCondition = 188 (inBoundsCondition) ? (inBoundsCondition && inBounds) : inBounds; 189 } 190 ++idx; 191 } 192 return inBoundsCondition; 193 } 194 195 template <> 196 LogicalResult NDTransferOpHelper<TransferReadOp>::doReplace() { 197 Value alloc, result; 198 if (options.unroll) 199 result = std_splat(vectorType, xferOp.padding()); 200 else 201 alloc = std_alloc(memRefMinorVectorType); 202 203 emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets, 204 ValueRange majorOffsets, ValueRange minorOffsets, 205 MemRefBoundsCapture &memrefBounds) { 206 /// Lambda to load 1-D vector in the current loop ivs + offset context. 207 auto load1DVector = [&](ValueRange majorIvsPlusOffsets) -> Value { 208 SmallVector<Value, 8> indexing; 209 indexing.reserve(leadingRank + majorRank + minorRank); 210 indexing.append(leadingOffsets.begin(), leadingOffsets.end()); 211 indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end()); 212 indexing.append(minorOffsets.begin(), minorOffsets.end()); 213 Value memref = xferOp.memref(); 214 auto map = TransferReadOp::getTransferMinorIdentityMap( 215 xferOp.getMemRefType(), minorVectorType); 216 ArrayAttr masked; 217 if (xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) { 218 OpBuilder &b = ScopedContext::getBuilderRef(); 219 masked = b.getBoolArrayAttr({true}); 220 } 221 return vector_transfer_read(minorVectorType, memref, indexing, 222 AffineMapAttr::get(map), xferOp.padding(), 223 masked); 224 }; 225 226 // 1. Compute the inBoundsCondition in the current loops ivs + offset 227 // context. 228 SmallVector<Value, 4> majorIvsPlusOffsets; 229 Value inBoundsCondition = emitInBoundsCondition( 230 majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets); 231 232 if (inBoundsCondition) { 233 // 2. If the condition is not null, we need an IfOp, which may yield 234 // if `options.unroll` is true. 235 SmallVector<Type, 1> resultType; 236 if (options.unroll) 237 resultType.push_back(vectorType); 238 239 // 3. If in-bounds, progressively lower to a 1-D transfer read, otherwise 240 // splat a 1-D vector. 241 ValueRange ifResults = conditionBuilder( 242 resultType, inBoundsCondition, 243 [&]() -> scf::ValueVector { 244 Value vector = load1DVector(majorIvsPlusOffsets); 245 // 3.a. If `options.unroll` is true, insert the 1-D vector in the 246 // aggregate. We must yield and merge with the `else` branch. 247 if (options.unroll) { 248 vector = vector_insert(vector, result, majorIvs); 249 return {vector}; 250 } 251 // 3.b. Otherwise, just go through the temporary `alloc`. 252 std_store(vector, alloc, majorIvs); 253 return {}; 254 }, 255 [&]() -> scf::ValueVector { 256 Value vector = std_splat(minorVectorType, xferOp.padding()); 257 // 3.c. If `options.unroll` is true, insert the 1-D vector in the 258 // aggregate. We must yield and merge with the `then` branch. 259 if (options.unroll) { 260 vector = vector_insert(vector, result, majorIvs); 261 return {vector}; 262 } 263 // 3.d. Otherwise, just go through the temporary `alloc`. 264 std_store(vector, alloc, majorIvs); 265 return {}; 266 }); 267 268 if (!resultType.empty()) 269 result = *ifResults.begin(); 270 } else { 271 // 4. Guaranteed in-bounds, progressively lower to a 1-D transfer read. 272 Value loaded1D = load1DVector(majorIvsPlusOffsets); 273 // 5.a. If `options.unroll` is true, insert the 1-D vector in the 274 // aggregate. 275 if (options.unroll) 276 result = vector_insert(loaded1D, result, majorIvs); 277 // 5.b. Otherwise, just go through the temporary `alloc`. 278 else 279 std_store(loaded1D, alloc, majorIvs); 280 } 281 }); 282 283 assert((!options.unroll ^ (bool)result) && 284 "Expected resulting Value iff unroll"); 285 if (!result) 286 result = std_load(vector_type_cast(MemRefType::get({}, vectorType), alloc)); 287 rewriter.replaceOp(op, result); 288 289 return success(); 290 } 291 292 template <> 293 LogicalResult NDTransferOpHelper<TransferWriteOp>::doReplace() { 294 Value alloc; 295 if (!options.unroll) { 296 alloc = std_alloc(memRefMinorVectorType); 297 std_store(xferOp.vector(), 298 vector_type_cast(MemRefType::get({}, vectorType), alloc)); 299 } 300 301 emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets, 302 ValueRange majorOffsets, ValueRange minorOffsets, 303 MemRefBoundsCapture &memrefBounds) { 304 // Lower to 1-D vector_transfer_write and let recursion handle it. 305 auto emitTransferWrite = [&](ValueRange majorIvsPlusOffsets) { 306 SmallVector<Value, 8> indexing; 307 indexing.reserve(leadingRank + majorRank + minorRank); 308 indexing.append(leadingOffsets.begin(), leadingOffsets.end()); 309 indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end()); 310 indexing.append(minorOffsets.begin(), minorOffsets.end()); 311 Value result; 312 // If `options.unroll` is true, extract the 1-D vector from the 313 // aggregate. 314 if (options.unroll) 315 result = vector_extract(xferOp.vector(), majorIvs); 316 else 317 result = std_load(alloc, majorIvs); 318 auto map = TransferWriteOp::getTransferMinorIdentityMap( 319 xferOp.getMemRefType(), minorVectorType); 320 ArrayAttr masked; 321 if (xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) { 322 OpBuilder &b = ScopedContext::getBuilderRef(); 323 masked = b.getBoolArrayAttr({true}); 324 } 325 vector_transfer_write(result, xferOp.memref(), indexing, 326 AffineMapAttr::get(map), masked); 327 }; 328 329 // 1. Compute the inBoundsCondition in the current loops ivs + offset 330 // context. 331 SmallVector<Value, 4> majorIvsPlusOffsets; 332 Value inBoundsCondition = emitInBoundsCondition( 333 majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets); 334 335 if (inBoundsCondition) { 336 // 2.a. If the condition is not null, we need an IfOp, to write 337 // conditionally. Progressively lower to a 1-D transfer write. 338 conditionBuilder(inBoundsCondition, 339 [&] { emitTransferWrite(majorIvsPlusOffsets); }); 340 } else { 341 // 2.b. Guaranteed in-bounds. Progressively lower to a 1-D transfer write. 342 emitTransferWrite(majorIvsPlusOffsets); 343 } 344 }); 345 346 rewriter.eraseOp(op); 347 348 return success(); 349 } 350 351 } // namespace 352 353 /// Analyzes the `transfer` to find an access dimension along the fastest remote 354 /// MemRef dimension. If such a dimension with coalescing properties is found, 355 /// `pivs` and `vectorBoundsCapture` are swapped so that the invocation of 356 /// LoopNestBuilder captures it in the innermost loop. 357 template <typename TransferOpTy> 358 static int computeCoalescedIndex(TransferOpTy transfer) { 359 // rank of the remote memory access, coalescing behavior occurs on the 360 // innermost memory dimension. 361 auto remoteRank = transfer.getMemRefType().getRank(); 362 // Iterate over the results expressions of the permutation map to determine 363 // the loop order for creating pointwise copies between remote and local 364 // memories. 365 int coalescedIdx = -1; 366 auto exprs = transfer.permutation_map().getResults(); 367 for (auto en : llvm::enumerate(exprs)) { 368 auto dim = en.value().template dyn_cast<AffineDimExpr>(); 369 if (!dim) { 370 continue; 371 } 372 auto memRefDim = dim.getPosition(); 373 if (memRefDim == remoteRank - 1) { 374 // memRefDim has coalescing properties, it should be swapped in the last 375 // position. 376 assert(coalescedIdx == -1 && "Unexpected > 1 coalesced indices"); 377 coalescedIdx = en.index(); 378 } 379 } 380 return coalescedIdx; 381 } 382 383 /// Emits remote memory accesses that are clipped to the boundaries of the 384 /// MemRef. 385 template <typename TransferOpTy> 386 static SmallVector<Value, 8> 387 clip(TransferOpTy transfer, MemRefBoundsCapture &bounds, ArrayRef<Value> ivs) { 388 using namespace mlir::edsc; 389 390 Value zero(std_constant_index(0)), one(std_constant_index(1)); 391 SmallVector<Value, 8> memRefAccess(transfer.indices()); 392 SmallVector<Value, 8> clippedScalarAccessExprs(memRefAccess.size()); 393 // Indices accessing to remote memory are clipped and their expressions are 394 // returned in clippedScalarAccessExprs. 395 for (unsigned memRefDim = 0; memRefDim < clippedScalarAccessExprs.size(); 396 ++memRefDim) { 397 // Linear search on a small number of entries. 398 int loopIndex = -1; 399 auto exprs = transfer.permutation_map().getResults(); 400 for (auto en : llvm::enumerate(exprs)) { 401 auto expr = en.value(); 402 auto dim = expr.template dyn_cast<AffineDimExpr>(); 403 // Sanity check. 404 assert( 405 (dim || expr.template cast<AffineConstantExpr>().getValue() == 0) && 406 "Expected dim or 0 in permutationMap"); 407 if (dim && memRefDim == dim.getPosition()) { 408 loopIndex = en.index(); 409 break; 410 } 411 } 412 413 // We cannot distinguish atm between unrolled dimensions that implement 414 // the "always full" tile abstraction and need clipping from the other 415 // ones. So we conservatively clip everything. 416 using namespace edsc::op; 417 auto N = bounds.ub(memRefDim); 418 auto i = memRefAccess[memRefDim]; 419 if (loopIndex < 0) { 420 auto N_minus_1 = N - one; 421 auto select_1 = std_select(i < N, i, N_minus_1); 422 clippedScalarAccessExprs[memRefDim] = 423 std_select(i < zero, zero, select_1); 424 } else { 425 auto ii = ivs[loopIndex]; 426 auto i_plus_ii = i + ii; 427 auto N_minus_1 = N - one; 428 auto select_1 = std_select(i_plus_ii < N, i_plus_ii, N_minus_1); 429 clippedScalarAccessExprs[memRefDim] = 430 std_select(i_plus_ii < zero, zero, select_1); 431 } 432 } 433 434 return clippedScalarAccessExprs; 435 } 436 437 namespace mlir { 438 439 template <typename TransferOpTy> 440 VectorTransferRewriter<TransferOpTy>::VectorTransferRewriter( 441 VectorTransferToSCFOptions options, MLIRContext *context) 442 : RewritePattern(TransferOpTy::getOperationName(), 1, context), 443 options(options) {} 444 445 /// Used for staging the transfer in a local buffer. 446 template <typename TransferOpTy> 447 MemRefType VectorTransferRewriter<TransferOpTy>::tmpMemRefType( 448 TransferOpTy transfer) const { 449 auto vectorType = transfer.getVectorType(); 450 return MemRefType::get(vectorType.getShape(), vectorType.getElementType(), {}, 451 0); 452 } 453 454 /// Lowers TransferReadOp into a combination of: 455 /// 1. local memory allocation; 456 /// 2. perfect loop nest over: 457 /// a. scalar load from local buffers (viewed as a scalar memref); 458 /// a. scalar store to original memref (with clipping). 459 /// 3. vector_load from local buffer (viewed as a memref<1 x vector>); 460 /// 4. local memory deallocation. 461 /// 462 /// Lowers the data transfer part of a TransferReadOp while ensuring no 463 /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by 464 /// clipping. This means that a given value in memory can be read multiple 465 /// times and concurrently. 466 /// 467 /// Important notes about clipping and "full-tiles only" abstraction: 468 /// ================================================================= 469 /// When using clipping for dealing with boundary conditions, the same edge 470 /// value will appear multiple times (a.k.a edge padding). This is fine if the 471 /// subsequent vector operations are all data-parallel but **is generally 472 /// incorrect** in the presence of reductions or extract operations. 473 /// 474 /// More generally, clipping is a scalar abstraction that is expected to work 475 /// fine as a baseline for CPUs and GPUs but not for vector_load and DMAs. 476 /// To deal with real vector_load and DMAs, a "padded allocation + view" 477 /// abstraction with the ability to read out-of-memref-bounds (but still within 478 /// the allocated region) is necessary. 479 /// 480 /// Whether using scalar loops or vector_load/DMAs to perform the transfer, 481 /// junk values will be materialized in the vectors and generally need to be 482 /// filtered out and replaced by the "neutral element". This neutral element is 483 /// op-dependent so, in the future, we expect to create a vector filter and 484 /// apply it to a splatted constant vector with the proper neutral element at 485 /// each ssa-use. This filtering is not necessary for pure data-parallel 486 /// operations. 487 /// 488 /// In the case of vector_store/DMAs, Read-Modify-Write will be required, which 489 /// also have concurrency implications. Note that by using clipped scalar stores 490 /// in the presence of data-parallel only operations, we generate code that 491 /// writes the same value multiple time on the edge locations. 492 /// 493 /// TODO(ntv): implement alternatives to clipping. 494 /// TODO(ntv): support non-data-parallel operations. 495 496 /// Performs the rewrite. 497 template <> 498 LogicalResult VectorTransferRewriter<TransferReadOp>::matchAndRewrite( 499 Operation *op, PatternRewriter &rewriter) const { 500 using namespace mlir::edsc::op; 501 502 TransferReadOp transfer = cast<TransferReadOp>(op); 503 if (AffineMap::isMinorIdentity(transfer.permutation_map())) { 504 // If > 1D, emit a bunch of loops around 1-D vector transfers. 505 if (transfer.getVectorType().getRank() > 1) 506 return NDTransferOpHelper<TransferReadOp>(rewriter, transfer, options) 507 .doReplace(); 508 // If 1-D this is now handled by the target-specific lowering. 509 if (transfer.getVectorType().getRank() == 1) 510 return failure(); 511 } 512 513 // Conservative lowering to scalar load / stores. 514 // 1. Setup all the captures. 515 ScopedContext scope(rewriter, transfer.getLoc()); 516 StdIndexedValue remote(transfer.memref()); 517 MemRefBoundsCapture memRefBoundsCapture(transfer.memref()); 518 VectorBoundsCapture vectorBoundsCapture(transfer.vector()); 519 int coalescedIdx = computeCoalescedIndex(transfer); 520 // Swap the vectorBoundsCapture which will reorder loop bounds. 521 if (coalescedIdx >= 0) 522 vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1, 523 coalescedIdx); 524 525 auto lbs = vectorBoundsCapture.getLbs(); 526 auto ubs = vectorBoundsCapture.getUbs(); 527 SmallVector<Value, 8> steps; 528 steps.reserve(vectorBoundsCapture.getSteps().size()); 529 for (auto step : vectorBoundsCapture.getSteps()) 530 steps.push_back(std_constant_index(step)); 531 532 // 2. Emit alloc-copy-load-dealloc. 533 Value tmp = std_alloc(tmpMemRefType(transfer)); 534 StdIndexedValue local(tmp); 535 Value vec = vector_type_cast(tmp); 536 loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) { 537 auto ivs = llvm::to_vector<8>(loopIvs); 538 // Swap the ivs which will reorder memory accesses. 539 if (coalescedIdx >= 0) 540 std::swap(ivs.back(), ivs[coalescedIdx]); 541 // Computes clippedScalarAccessExprs in the loop nest scope (ivs exist). 542 local(ivs) = remote(clip(transfer, memRefBoundsCapture, ivs)); 543 }); 544 Value vectorValue = std_load(vec); 545 (std_dealloc(tmp)); // vexing parse 546 547 // 3. Propagate. 548 rewriter.replaceOp(op, vectorValue); 549 return success(); 550 } 551 552 /// Lowers TransferWriteOp into a combination of: 553 /// 1. local memory allocation; 554 /// 2. vector_store to local buffer (viewed as a memref<1 x vector>); 555 /// 3. perfect loop nest over: 556 /// a. scalar load from local buffers (viewed as a scalar memref); 557 /// a. scalar store to original memref (with clipping). 558 /// 4. local memory deallocation. 559 /// 560 /// More specifically, lowers the data transfer part while ensuring no 561 /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by 562 /// clipping. This means that a given value in memory can be written to multiple 563 /// times and concurrently. 564 /// 565 /// See `Important notes about clipping and full-tiles only abstraction` in the 566 /// description of `readClipped` above. 567 /// 568 /// TODO(ntv): implement alternatives to clipping. 569 /// TODO(ntv): support non-data-parallel operations. 570 template <> 571 LogicalResult VectorTransferRewriter<TransferWriteOp>::matchAndRewrite( 572 Operation *op, PatternRewriter &rewriter) const { 573 using namespace edsc::op; 574 575 TransferWriteOp transfer = cast<TransferWriteOp>(op); 576 if (AffineMap::isMinorIdentity(transfer.permutation_map())) { 577 // If > 1D, emit a bunch of loops around 1-D vector transfers. 578 if (transfer.getVectorType().getRank() > 1) 579 return NDTransferOpHelper<TransferWriteOp>(rewriter, transfer, options) 580 .doReplace(); 581 // If 1-D this is now handled by the target-specific lowering. 582 if (transfer.getVectorType().getRank() == 1) 583 return failure(); 584 } 585 586 // 1. Setup all the captures. 587 ScopedContext scope(rewriter, transfer.getLoc()); 588 StdIndexedValue remote(transfer.memref()); 589 MemRefBoundsCapture memRefBoundsCapture(transfer.memref()); 590 Value vectorValue(transfer.vector()); 591 VectorBoundsCapture vectorBoundsCapture(transfer.vector()); 592 int coalescedIdx = computeCoalescedIndex(transfer); 593 // Swap the vectorBoundsCapture which will reorder loop bounds. 594 if (coalescedIdx >= 0) 595 vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1, 596 coalescedIdx); 597 598 auto lbs = vectorBoundsCapture.getLbs(); 599 auto ubs = vectorBoundsCapture.getUbs(); 600 SmallVector<Value, 8> steps; 601 steps.reserve(vectorBoundsCapture.getSteps().size()); 602 for (auto step : vectorBoundsCapture.getSteps()) 603 steps.push_back(std_constant_index(step)); 604 605 // 2. Emit alloc-store-copy-dealloc. 606 Value tmp = std_alloc(tmpMemRefType(transfer)); 607 StdIndexedValue local(tmp); 608 Value vec = vector_type_cast(tmp); 609 std_store(vectorValue, vec); 610 loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) { 611 auto ivs = llvm::to_vector<8>(loopIvs); 612 // Swap the ivs which will reorder memory accesses. 613 if (coalescedIdx >= 0) 614 std::swap(ivs.back(), ivs[coalescedIdx]); 615 // Computes clippedScalarAccessExprs in the loop nest scope (ivs exist). 616 remote(clip(transfer, memRefBoundsCapture, ivs)) = local(ivs); 617 }); 618 (std_dealloc(tmp)); // vexing parse... 619 620 rewriter.eraseOp(op); 621 return success(); 622 } 623 624 void populateVectorToSCFConversionPatterns( 625 OwningRewritePatternList &patterns, MLIRContext *context, 626 const VectorTransferToSCFOptions &options) { 627 patterns.insert<VectorTransferRewriter<vector::TransferReadOp>, 628 VectorTransferRewriter<vector::TransferWriteOp>>(options, 629 context); 630 } 631 632 } // namespace mlir 633 634