1 //===- VectorToLLVM.cpp - Conversion from Vector to the LLVM dialect ------===// 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 #include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h" 10 #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h" 11 #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h" 12 #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 13 #include "mlir/Dialect/StandardOps/Ops.h" 14 #include "mlir/Dialect/VectorOps/VectorOps.h" 15 #include "mlir/IR/Attributes.h" 16 #include "mlir/IR/Builders.h" 17 #include "mlir/IR/MLIRContext.h" 18 #include "mlir/IR/Module.h" 19 #include "mlir/IR/Operation.h" 20 #include "mlir/IR/PatternMatch.h" 21 #include "mlir/IR/StandardTypes.h" 22 #include "mlir/IR/Types.h" 23 #include "mlir/Pass/Pass.h" 24 #include "mlir/Pass/PassManager.h" 25 #include "mlir/Transforms/DialectConversion.h" 26 #include "mlir/Transforms/Passes.h" 27 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Module.h" 30 #include "llvm/IR/Type.h" 31 #include "llvm/Support/Allocator.h" 32 #include "llvm/Support/ErrorHandling.h" 33 34 using namespace mlir; 35 using namespace mlir::vector; 36 37 template <typename T> 38 static LLVM::LLVMType getPtrToElementType(T containerType, 39 LLVMTypeConverter &lowering) { 40 return lowering.convertType(containerType.getElementType()) 41 .template cast<LLVM::LLVMType>() 42 .getPointerTo(); 43 } 44 45 // Helper to reduce vector type by one rank at front. 46 static VectorType reducedVectorTypeFront(VectorType tp) { 47 assert((tp.getRank() > 1) && "unlowerable vector type"); 48 return VectorType::get(tp.getShape().drop_front(), tp.getElementType()); 49 } 50 51 // Helper to reduce vector type by *all* but one rank at back. 52 static VectorType reducedVectorTypeBack(VectorType tp) { 53 assert((tp.getRank() > 1) && "unlowerable vector type"); 54 return VectorType::get(tp.getShape().take_back(), tp.getElementType()); 55 } 56 57 // Helper that picks the proper sequence for inserting. 58 static Value insertOne(ConversionPatternRewriter &rewriter, 59 LLVMTypeConverter &lowering, Location loc, Value val1, 60 Value val2, Type llvmType, int64_t rank, int64_t pos) { 61 if (rank == 1) { 62 auto idxType = rewriter.getIndexType(); 63 auto constant = rewriter.create<LLVM::ConstantOp>( 64 loc, lowering.convertType(idxType), 65 rewriter.getIntegerAttr(idxType, pos)); 66 return rewriter.create<LLVM::InsertElementOp>(loc, llvmType, val1, val2, 67 constant); 68 } 69 return rewriter.create<LLVM::InsertValueOp>(loc, llvmType, val1, val2, 70 rewriter.getI64ArrayAttr(pos)); 71 } 72 73 // Helper that picks the proper sequence for inserting. 74 static Value insertOne(PatternRewriter &rewriter, Location loc, Value from, 75 Value into, int64_t offset) { 76 auto vectorType = into.getType().cast<VectorType>(); 77 if (vectorType.getRank() > 1) 78 return rewriter.create<InsertOp>(loc, from, into, offset); 79 return rewriter.create<vector::InsertElementOp>( 80 loc, vectorType, from, into, 81 rewriter.create<ConstantIndexOp>(loc, offset)); 82 } 83 84 // Helper that picks the proper sequence for extracting. 85 static Value extractOne(ConversionPatternRewriter &rewriter, 86 LLVMTypeConverter &lowering, Location loc, Value val, 87 Type llvmType, int64_t rank, int64_t pos) { 88 if (rank == 1) { 89 auto idxType = rewriter.getIndexType(); 90 auto constant = rewriter.create<LLVM::ConstantOp>( 91 loc, lowering.convertType(idxType), 92 rewriter.getIntegerAttr(idxType, pos)); 93 return rewriter.create<LLVM::ExtractElementOp>(loc, llvmType, val, 94 constant); 95 } 96 return rewriter.create<LLVM::ExtractValueOp>(loc, llvmType, val, 97 rewriter.getI64ArrayAttr(pos)); 98 } 99 100 // Helper that picks the proper sequence for extracting. 101 static Value extractOne(PatternRewriter &rewriter, Location loc, Value vector, 102 int64_t offset) { 103 auto vectorType = vector.getType().cast<VectorType>(); 104 if (vectorType.getRank() > 1) 105 return rewriter.create<ExtractOp>(loc, vector, offset); 106 return rewriter.create<vector::ExtractElementOp>( 107 loc, vectorType.getElementType(), vector, 108 rewriter.create<ConstantIndexOp>(loc, offset)); 109 } 110 111 // Helper that returns a subset of `arrayAttr` as a vector of int64_t. 112 // TODO(rriddle): Better support for attribute subtype forwarding + slicing. 113 static SmallVector<int64_t, 4> getI64SubArray(ArrayAttr arrayAttr, 114 unsigned dropFront = 0, 115 unsigned dropBack = 0) { 116 assert(arrayAttr.size() > dropFront + dropBack && "Out of bounds"); 117 auto range = arrayAttr.getAsRange<IntegerAttr>(); 118 SmallVector<int64_t, 4> res; 119 res.reserve(arrayAttr.size() - dropFront - dropBack); 120 for (auto it = range.begin() + dropFront, eit = range.end() - dropBack; 121 it != eit; ++it) 122 res.push_back((*it).getValue().getSExtValue()); 123 return res; 124 } 125 126 namespace { 127 class VectorBroadcastOpConversion : public LLVMOpLowering { 128 public: 129 explicit VectorBroadcastOpConversion(MLIRContext *context, 130 LLVMTypeConverter &typeConverter) 131 : LLVMOpLowering(vector::BroadcastOp::getOperationName(), context, 132 typeConverter) {} 133 134 PatternMatchResult 135 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 136 ConversionPatternRewriter &rewriter) const override { 137 auto broadcastOp = cast<vector::BroadcastOp>(op); 138 VectorType dstVectorType = broadcastOp.getVectorType(); 139 if (lowering.convertType(dstVectorType) == nullptr) 140 return matchFailure(); 141 // Rewrite when the full vector type can be lowered (which 142 // implies all 'reduced' types can be lowered too). 143 auto adaptor = vector::BroadcastOpOperandAdaptor(operands); 144 VectorType srcVectorType = 145 broadcastOp.getSourceType().dyn_cast<VectorType>(); 146 rewriter.replaceOp( 147 op, expandRanks(adaptor.source(), // source value to be expanded 148 op->getLoc(), // location of original broadcast 149 srcVectorType, dstVectorType, rewriter)); 150 return matchSuccess(); 151 } 152 153 private: 154 // Expands the given source value over all the ranks, as defined 155 // by the source and destination type (a null source type denotes 156 // expansion from a scalar value into a vector). 157 // 158 // TODO(ajcbik): consider replacing this one-pattern lowering 159 // with a two-pattern lowering using other vector 160 // ops once all insert/extract/shuffle operations 161 // are available with lowering implementation. 162 // 163 Value expandRanks(Value value, Location loc, VectorType srcVectorType, 164 VectorType dstVectorType, 165 ConversionPatternRewriter &rewriter) const { 166 assert((dstVectorType != nullptr) && "invalid result type in broadcast"); 167 // Determine rank of source and destination. 168 int64_t srcRank = srcVectorType ? srcVectorType.getRank() : 0; 169 int64_t dstRank = dstVectorType.getRank(); 170 int64_t curDim = dstVectorType.getDimSize(0); 171 if (srcRank < dstRank) 172 // Duplicate this rank. 173 return duplicateOneRank(value, loc, srcVectorType, dstVectorType, dstRank, 174 curDim, rewriter); 175 // If all trailing dimensions are the same, the broadcast consists of 176 // simply passing through the source value and we are done. Otherwise, 177 // any non-matching dimension forces a stretch along this rank. 178 assert((srcVectorType != nullptr) && (srcRank > 0) && 179 (srcRank == dstRank) && "invalid rank in broadcast"); 180 for (int64_t r = 0; r < dstRank; r++) { 181 if (srcVectorType.getDimSize(r) != dstVectorType.getDimSize(r)) { 182 return stretchOneRank(value, loc, srcVectorType, dstVectorType, dstRank, 183 curDim, rewriter); 184 } 185 } 186 return value; 187 } 188 189 // Picks the best way to duplicate a single rank. For the 1-D case, a 190 // single insert-elt/shuffle is the most efficient expansion. For higher 191 // dimensions, however, we need dim x insert-values on a new broadcast 192 // with one less leading dimension, which will be lowered "recursively" 193 // to matching LLVM IR. 194 // For example: 195 // v = broadcast s : f32 to vector<4x2xf32> 196 // becomes: 197 // x = broadcast s : f32 to vector<2xf32> 198 // v = [x,x,x,x] 199 // becomes: 200 // x = [s,s] 201 // v = [x,x,x,x] 202 Value duplicateOneRank(Value value, Location loc, VectorType srcVectorType, 203 VectorType dstVectorType, int64_t rank, int64_t dim, 204 ConversionPatternRewriter &rewriter) const { 205 Type llvmType = lowering.convertType(dstVectorType); 206 assert((llvmType != nullptr) && "unlowerable vector type"); 207 if (rank == 1) { 208 Value undef = rewriter.create<LLVM::UndefOp>(loc, llvmType); 209 Value expand = 210 insertOne(rewriter, lowering, loc, undef, value, llvmType, rank, 0); 211 SmallVector<int32_t, 4> zeroValues(dim, 0); 212 return rewriter.create<LLVM::ShuffleVectorOp>( 213 loc, expand, undef, rewriter.getI32ArrayAttr(zeroValues)); 214 } 215 Value expand = expandRanks(value, loc, srcVectorType, 216 reducedVectorTypeFront(dstVectorType), rewriter); 217 Value result = rewriter.create<LLVM::UndefOp>(loc, llvmType); 218 for (int64_t d = 0; d < dim; ++d) { 219 result = 220 insertOne(rewriter, lowering, loc, result, expand, llvmType, rank, d); 221 } 222 return result; 223 } 224 225 // Picks the best way to stretch a single rank. For the 1-D case, a 226 // single insert-elt/shuffle is the most efficient expansion when at 227 // a stretch. Otherwise, every dimension needs to be expanded 228 // individually and individually inserted in the resulting vector. 229 // For example: 230 // v = broadcast w : vector<4x1x2xf32> to vector<4x2x2xf32> 231 // becomes: 232 // a = broadcast w[0] : vector<1x2xf32> to vector<2x2xf32> 233 // b = broadcast w[1] : vector<1x2xf32> to vector<2x2xf32> 234 // c = broadcast w[2] : vector<1x2xf32> to vector<2x2xf32> 235 // d = broadcast w[3] : vector<1x2xf32> to vector<2x2xf32> 236 // v = [a,b,c,d] 237 // becomes: 238 // x = broadcast w[0][0] : vector<2xf32> to vector <2x2xf32> 239 // y = broadcast w[1][0] : vector<2xf32> to vector <2x2xf32> 240 // a = [x, y] 241 // etc. 242 Value stretchOneRank(Value value, Location loc, VectorType srcVectorType, 243 VectorType dstVectorType, int64_t rank, int64_t dim, 244 ConversionPatternRewriter &rewriter) const { 245 Type llvmType = lowering.convertType(dstVectorType); 246 assert((llvmType != nullptr) && "unlowerable vector type"); 247 Value result = rewriter.create<LLVM::UndefOp>(loc, llvmType); 248 bool atStretch = dim != srcVectorType.getDimSize(0); 249 if (rank == 1) { 250 assert(atStretch); 251 Type redLlvmType = lowering.convertType(dstVectorType.getElementType()); 252 Value one = 253 extractOne(rewriter, lowering, loc, value, redLlvmType, rank, 0); 254 Value expand = 255 insertOne(rewriter, lowering, loc, result, one, llvmType, rank, 0); 256 SmallVector<int32_t, 4> zeroValues(dim, 0); 257 return rewriter.create<LLVM::ShuffleVectorOp>( 258 loc, expand, result, rewriter.getI32ArrayAttr(zeroValues)); 259 } 260 VectorType redSrcType = reducedVectorTypeFront(srcVectorType); 261 VectorType redDstType = reducedVectorTypeFront(dstVectorType); 262 Type redLlvmType = lowering.convertType(redSrcType); 263 for (int64_t d = 0; d < dim; ++d) { 264 int64_t pos = atStretch ? 0 : d; 265 Value one = 266 extractOne(rewriter, lowering, loc, value, redLlvmType, rank, pos); 267 Value expand = expandRanks(one, loc, redSrcType, redDstType, rewriter); 268 result = 269 insertOne(rewriter, lowering, loc, result, expand, llvmType, rank, d); 270 } 271 return result; 272 } 273 }; 274 275 class VectorShuffleOpConversion : public LLVMOpLowering { 276 public: 277 explicit VectorShuffleOpConversion(MLIRContext *context, 278 LLVMTypeConverter &typeConverter) 279 : LLVMOpLowering(vector::ShuffleOp::getOperationName(), context, 280 typeConverter) {} 281 282 PatternMatchResult 283 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 284 ConversionPatternRewriter &rewriter) const override { 285 auto loc = op->getLoc(); 286 auto adaptor = vector::ShuffleOpOperandAdaptor(operands); 287 auto shuffleOp = cast<vector::ShuffleOp>(op); 288 auto v1Type = shuffleOp.getV1VectorType(); 289 auto v2Type = shuffleOp.getV2VectorType(); 290 auto vectorType = shuffleOp.getVectorType(); 291 Type llvmType = lowering.convertType(vectorType); 292 auto maskArrayAttr = shuffleOp.mask(); 293 294 // Bail if result type cannot be lowered. 295 if (!llvmType) 296 return matchFailure(); 297 298 // Get rank and dimension sizes. 299 int64_t rank = vectorType.getRank(); 300 assert(v1Type.getRank() == rank); 301 assert(v2Type.getRank() == rank); 302 int64_t v1Dim = v1Type.getDimSize(0); 303 304 // For rank 1, where both operands have *exactly* the same vector type, 305 // there is direct shuffle support in LLVM. Use it! 306 if (rank == 1 && v1Type == v2Type) { 307 Value shuffle = rewriter.create<LLVM::ShuffleVectorOp>( 308 loc, adaptor.v1(), adaptor.v2(), maskArrayAttr); 309 rewriter.replaceOp(op, shuffle); 310 return matchSuccess(); 311 } 312 313 // For all other cases, insert the individual values individually. 314 Value insert = rewriter.create<LLVM::UndefOp>(loc, llvmType); 315 int64_t insPos = 0; 316 for (auto en : llvm::enumerate(maskArrayAttr)) { 317 int64_t extPos = en.value().cast<IntegerAttr>().getInt(); 318 Value value = adaptor.v1(); 319 if (extPos >= v1Dim) { 320 extPos -= v1Dim; 321 value = adaptor.v2(); 322 } 323 Value extract = 324 extractOne(rewriter, lowering, loc, value, llvmType, rank, extPos); 325 insert = insertOne(rewriter, lowering, loc, insert, extract, llvmType, 326 rank, insPos++); 327 } 328 rewriter.replaceOp(op, insert); 329 return matchSuccess(); 330 } 331 }; 332 333 class VectorExtractElementOpConversion : public LLVMOpLowering { 334 public: 335 explicit VectorExtractElementOpConversion(MLIRContext *context, 336 LLVMTypeConverter &typeConverter) 337 : LLVMOpLowering(vector::ExtractElementOp::getOperationName(), context, 338 typeConverter) {} 339 340 PatternMatchResult 341 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 342 ConversionPatternRewriter &rewriter) const override { 343 auto adaptor = vector::ExtractElementOpOperandAdaptor(operands); 344 auto extractEltOp = cast<vector::ExtractElementOp>(op); 345 auto vectorType = extractEltOp.getVectorType(); 346 auto llvmType = lowering.convertType(vectorType.getElementType()); 347 348 // Bail if result type cannot be lowered. 349 if (!llvmType) 350 return matchFailure(); 351 352 rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>( 353 op, llvmType, adaptor.vector(), adaptor.position()); 354 return matchSuccess(); 355 } 356 }; 357 358 class VectorExtractOpConversion : public LLVMOpLowering { 359 public: 360 explicit VectorExtractOpConversion(MLIRContext *context, 361 LLVMTypeConverter &typeConverter) 362 : LLVMOpLowering(vector::ExtractOp::getOperationName(), context, 363 typeConverter) {} 364 365 PatternMatchResult 366 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 367 ConversionPatternRewriter &rewriter) const override { 368 auto loc = op->getLoc(); 369 auto adaptor = vector::ExtractOpOperandAdaptor(operands); 370 auto extractOp = cast<vector::ExtractOp>(op); 371 auto vectorType = extractOp.getVectorType(); 372 auto resultType = extractOp.getResult().getType(); 373 auto llvmResultType = lowering.convertType(resultType); 374 auto positionArrayAttr = extractOp.position(); 375 376 // Bail if result type cannot be lowered. 377 if (!llvmResultType) 378 return matchFailure(); 379 380 // One-shot extraction of vector from array (only requires extractvalue). 381 if (resultType.isa<VectorType>()) { 382 Value extracted = rewriter.create<LLVM::ExtractValueOp>( 383 loc, llvmResultType, adaptor.vector(), positionArrayAttr); 384 rewriter.replaceOp(op, extracted); 385 return matchSuccess(); 386 } 387 388 // Potential extraction of 1-D vector from array. 389 auto *context = op->getContext(); 390 Value extracted = adaptor.vector(); 391 auto positionAttrs = positionArrayAttr.getValue(); 392 if (positionAttrs.size() > 1) { 393 auto oneDVectorType = reducedVectorTypeBack(vectorType); 394 auto nMinusOnePositionAttrs = 395 ArrayAttr::get(positionAttrs.drop_back(), context); 396 extracted = rewriter.create<LLVM::ExtractValueOp>( 397 loc, lowering.convertType(oneDVectorType), extracted, 398 nMinusOnePositionAttrs); 399 } 400 401 // Remaining extraction of element from 1-D LLVM vector 402 auto position = positionAttrs.back().cast<IntegerAttr>(); 403 auto i64Type = LLVM::LLVMType::getInt64Ty(lowering.getDialect()); 404 auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position); 405 extracted = 406 rewriter.create<LLVM::ExtractElementOp>(loc, extracted, constant); 407 rewriter.replaceOp(op, extracted); 408 409 return matchSuccess(); 410 } 411 }; 412 413 /// Conversion pattern that turns a vector.fma on a 1-D vector 414 /// into an llvm.intr.fmuladd. This is a trivial 1-1 conversion. 415 /// This does not match vectors of n >= 2 rank. 416 /// 417 /// Example: 418 /// ``` 419 /// vector.fma %a, %a, %a : vector<8xf32> 420 /// ``` 421 /// is converted to: 422 /// ``` 423 /// llvm.intr.fma %va, %va, %va: 424 /// (!llvm<"<8 x float>">, !llvm<"<8 x float>">, !llvm<"<8 x float>">) 425 /// -> !llvm<"<8 x float>"> 426 /// ``` 427 class VectorFMAOp1DConversion : public LLVMOpLowering { 428 public: 429 explicit VectorFMAOp1DConversion(MLIRContext *context, 430 LLVMTypeConverter &typeConverter) 431 : LLVMOpLowering(vector::FMAOp::getOperationName(), context, 432 typeConverter) {} 433 434 PatternMatchResult 435 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 436 ConversionPatternRewriter &rewriter) const override { 437 auto adaptor = vector::FMAOpOperandAdaptor(operands); 438 vector::FMAOp fmaOp = cast<vector::FMAOp>(op); 439 VectorType vType = fmaOp.getVectorType(); 440 if (vType.getRank() != 1) 441 return matchFailure(); 442 rewriter.replaceOpWithNewOp<LLVM::FMAOp>(op, adaptor.lhs(), adaptor.rhs(), 443 adaptor.acc()); 444 return matchSuccess(); 445 } 446 }; 447 448 class VectorInsertElementOpConversion : public LLVMOpLowering { 449 public: 450 explicit VectorInsertElementOpConversion(MLIRContext *context, 451 LLVMTypeConverter &typeConverter) 452 : LLVMOpLowering(vector::InsertElementOp::getOperationName(), context, 453 typeConverter) {} 454 455 PatternMatchResult 456 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 457 ConversionPatternRewriter &rewriter) const override { 458 auto adaptor = vector::InsertElementOpOperandAdaptor(operands); 459 auto insertEltOp = cast<vector::InsertElementOp>(op); 460 auto vectorType = insertEltOp.getDestVectorType(); 461 auto llvmType = lowering.convertType(vectorType); 462 463 // Bail if result type cannot be lowered. 464 if (!llvmType) 465 return matchFailure(); 466 467 rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>( 468 op, llvmType, adaptor.dest(), adaptor.source(), adaptor.position()); 469 return matchSuccess(); 470 } 471 }; 472 473 class VectorInsertOpConversion : public LLVMOpLowering { 474 public: 475 explicit VectorInsertOpConversion(MLIRContext *context, 476 LLVMTypeConverter &typeConverter) 477 : LLVMOpLowering(vector::InsertOp::getOperationName(), context, 478 typeConverter) {} 479 480 PatternMatchResult 481 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 482 ConversionPatternRewriter &rewriter) const override { 483 auto loc = op->getLoc(); 484 auto adaptor = vector::InsertOpOperandAdaptor(operands); 485 auto insertOp = cast<vector::InsertOp>(op); 486 auto sourceType = insertOp.getSourceType(); 487 auto destVectorType = insertOp.getDestVectorType(); 488 auto llvmResultType = lowering.convertType(destVectorType); 489 auto positionArrayAttr = insertOp.position(); 490 491 // Bail if result type cannot be lowered. 492 if (!llvmResultType) 493 return matchFailure(); 494 495 // One-shot insertion of a vector into an array (only requires insertvalue). 496 if (sourceType.isa<VectorType>()) { 497 Value inserted = rewriter.create<LLVM::InsertValueOp>( 498 loc, llvmResultType, adaptor.dest(), adaptor.source(), 499 positionArrayAttr); 500 rewriter.replaceOp(op, inserted); 501 return matchSuccess(); 502 } 503 504 // Potential extraction of 1-D vector from array. 505 auto *context = op->getContext(); 506 Value extracted = adaptor.dest(); 507 auto positionAttrs = positionArrayAttr.getValue(); 508 auto position = positionAttrs.back().cast<IntegerAttr>(); 509 auto oneDVectorType = destVectorType; 510 if (positionAttrs.size() > 1) { 511 oneDVectorType = reducedVectorTypeBack(destVectorType); 512 auto nMinusOnePositionAttrs = 513 ArrayAttr::get(positionAttrs.drop_back(), context); 514 extracted = rewriter.create<LLVM::ExtractValueOp>( 515 loc, lowering.convertType(oneDVectorType), extracted, 516 nMinusOnePositionAttrs); 517 } 518 519 // Insertion of an element into a 1-D LLVM vector. 520 auto i64Type = LLVM::LLVMType::getInt64Ty(lowering.getDialect()); 521 auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position); 522 Value inserted = rewriter.create<LLVM::InsertElementOp>( 523 loc, lowering.convertType(oneDVectorType), extracted, adaptor.source(), 524 constant); 525 526 // Potential insertion of resulting 1-D vector into array. 527 if (positionAttrs.size() > 1) { 528 auto nMinusOnePositionAttrs = 529 ArrayAttr::get(positionAttrs.drop_back(), context); 530 inserted = rewriter.create<LLVM::InsertValueOp>(loc, llvmResultType, 531 adaptor.dest(), inserted, 532 nMinusOnePositionAttrs); 533 } 534 535 rewriter.replaceOp(op, inserted); 536 return matchSuccess(); 537 } 538 }; 539 540 /// Rank reducing rewrite for n-D FMA into (n-1)-D FMA where n > 1. 541 /// 542 /// Example: 543 /// ``` 544 /// %d = vector.fma %a, %b, %c : vector<2x4xf32> 545 /// ``` 546 /// is rewritten into: 547 /// ``` 548 /// %r = splat %f0: vector<2x4xf32> 549 /// %va = vector.extractvalue %a[0] : vector<2x4xf32> 550 /// %vb = vector.extractvalue %b[0] : vector<2x4xf32> 551 /// %vc = vector.extractvalue %c[0] : vector<2x4xf32> 552 /// %vd = vector.fma %va, %vb, %vc : vector<4xf32> 553 /// %r2 = vector.insertvalue %vd, %r[0] : vector<4xf32> into vector<2x4xf32> 554 /// %va2 = vector.extractvalue %a2[1] : vector<2x4xf32> 555 /// %vb2 = vector.extractvalue %b2[1] : vector<2x4xf32> 556 /// %vc2 = vector.extractvalue %c2[1] : vector<2x4xf32> 557 /// %vd2 = vector.fma %va2, %vb2, %vc2 : vector<4xf32> 558 /// %r3 = vector.insertvalue %vd2, %r2[1] : vector<4xf32> into vector<2x4xf32> 559 /// // %r3 holds the final value. 560 /// ``` 561 class VectorFMAOpNDRewritePattern : public OpRewritePattern<FMAOp> { 562 public: 563 using OpRewritePattern<FMAOp>::OpRewritePattern; 564 565 PatternMatchResult matchAndRewrite(FMAOp op, 566 PatternRewriter &rewriter) const override { 567 auto vType = op.getVectorType(); 568 if (vType.getRank() < 2) 569 return matchFailure(); 570 571 auto loc = op.getLoc(); 572 auto elemType = vType.getElementType(); 573 Value zero = rewriter.create<ConstantOp>(loc, elemType, 574 rewriter.getZeroAttr(elemType)); 575 Value desc = rewriter.create<SplatOp>(loc, vType, zero); 576 for (int64_t i = 0, e = vType.getShape().front(); i != e; ++i) { 577 Value extrLHS = rewriter.create<ExtractOp>(loc, op.lhs(), i); 578 Value extrRHS = rewriter.create<ExtractOp>(loc, op.rhs(), i); 579 Value extrACC = rewriter.create<ExtractOp>(loc, op.acc(), i); 580 Value fma = rewriter.create<FMAOp>(loc, extrLHS, extrRHS, extrACC); 581 desc = rewriter.create<InsertOp>(loc, fma, desc, i); 582 } 583 rewriter.replaceOp(op, desc); 584 return matchSuccess(); 585 } 586 }; 587 588 // When ranks are different, InsertStridedSlice needs to extract a properly 589 // ranked vector from the destination vector into which to insert. This pattern 590 // only takes care of this part and forwards the rest of the conversion to 591 // another pattern that converts InsertStridedSlice for operands of the same 592 // rank. 593 // 594 // RewritePattern for InsertStridedSliceOp where source and destination vectors 595 // have different ranks. In this case: 596 // 1. the proper subvector is extracted from the destination vector 597 // 2. a new InsertStridedSlice op is created to insert the source in the 598 // destination subvector 599 // 3. the destination subvector is inserted back in the proper place 600 // 4. the op is replaced by the result of step 3. 601 // The new InsertStridedSlice from step 2. will be picked up by a 602 // `VectorInsertStridedSliceOpSameRankRewritePattern`. 603 class VectorInsertStridedSliceOpDifferentRankRewritePattern 604 : public OpRewritePattern<InsertStridedSliceOp> { 605 public: 606 using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern; 607 608 PatternMatchResult matchAndRewrite(InsertStridedSliceOp op, 609 PatternRewriter &rewriter) const override { 610 auto srcType = op.getSourceVectorType(); 611 auto dstType = op.getDestVectorType(); 612 613 if (op.offsets().getValue().empty()) 614 return matchFailure(); 615 616 auto loc = op.getLoc(); 617 int64_t rankDiff = dstType.getRank() - srcType.getRank(); 618 assert(rankDiff >= 0); 619 if (rankDiff == 0) 620 return matchFailure(); 621 622 int64_t rankRest = dstType.getRank() - rankDiff; 623 // Extract / insert the subvector of matching rank and InsertStridedSlice 624 // on it. 625 Value extracted = 626 rewriter.create<ExtractOp>(loc, op.dest(), 627 getI64SubArray(op.offsets(), /*dropFront=*/0, 628 /*dropFront=*/rankRest)); 629 // A different pattern will kick in for InsertStridedSlice with matching 630 // ranks. 631 auto stridedSliceInnerOp = rewriter.create<InsertStridedSliceOp>( 632 loc, op.source(), extracted, 633 getI64SubArray(op.offsets(), /*dropFront=*/rankDiff), 634 getI64SubArray(op.strides(), /*dropFront=*/0)); 635 rewriter.replaceOpWithNewOp<InsertOp>( 636 op, stridedSliceInnerOp.getResult(), op.dest(), 637 getI64SubArray(op.offsets(), /*dropFront=*/0, 638 /*dropFront=*/rankRest)); 639 return matchSuccess(); 640 } 641 }; 642 643 // RewritePattern for InsertStridedSliceOp where source and destination vectors 644 // have the same rank. In this case, we reduce 645 // 1. the proper subvector is extracted from the destination vector 646 // 2. a new InsertStridedSlice op is created to insert the source in the 647 // destination subvector 648 // 3. the destination subvector is inserted back in the proper place 649 // 4. the op is replaced by the result of step 3. 650 // The new InsertStridedSlice from step 2. will be picked up by a 651 // `VectorInsertStridedSliceOpSameRankRewritePattern`. 652 class VectorInsertStridedSliceOpSameRankRewritePattern 653 : public OpRewritePattern<InsertStridedSliceOp> { 654 public: 655 using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern; 656 657 PatternMatchResult matchAndRewrite(InsertStridedSliceOp op, 658 PatternRewriter &rewriter) const override { 659 auto srcType = op.getSourceVectorType(); 660 auto dstType = op.getDestVectorType(); 661 662 if (op.offsets().getValue().empty()) 663 return matchFailure(); 664 665 int64_t rankDiff = dstType.getRank() - srcType.getRank(); 666 assert(rankDiff >= 0); 667 if (rankDiff != 0) 668 return matchFailure(); 669 670 if (srcType == dstType) { 671 rewriter.replaceOp(op, op.source()); 672 return matchSuccess(); 673 } 674 675 int64_t offset = 676 op.offsets().getValue().front().cast<IntegerAttr>().getInt(); 677 int64_t size = srcType.getShape().front(); 678 int64_t stride = 679 op.strides().getValue().front().cast<IntegerAttr>().getInt(); 680 681 auto loc = op.getLoc(); 682 Value res = op.dest(); 683 // For each slice of the source vector along the most major dimension. 684 for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e; 685 off += stride, ++idx) { 686 // 1. extract the proper subvector (or element) from source 687 Value extractedSource = extractOne(rewriter, loc, op.source(), idx); 688 if (extractedSource.getType().isa<VectorType>()) { 689 // 2. If we have a vector, extract the proper subvector from destination 690 // Otherwise we are at the element level and no need to recurse. 691 Value extractedDest = extractOne(rewriter, loc, op.dest(), off); 692 // 3. Reduce the problem to lowering a new InsertStridedSlice op with 693 // smaller rank. 694 InsertStridedSliceOp insertStridedSliceOp = 695 rewriter.create<InsertStridedSliceOp>( 696 loc, extractedSource, extractedDest, 697 getI64SubArray(op.offsets(), /* dropFront=*/1), 698 getI64SubArray(op.strides(), /* dropFront=*/1)); 699 // Call matchAndRewrite recursively from within the pattern. This 700 // circumvents the current limitation that a given pattern cannot 701 // be called multiple times by the PatternRewrite infrastructure (to 702 // avoid infinite recursion, but in this case, infinite recursion 703 // cannot happen because the rank is strictly decreasing). 704 // TODO(rriddle, nicolasvasilache) Implement something like a hook for 705 // a potential function that must decrease and allow the same pattern 706 // multiple times. 707 auto success = matchAndRewrite(insertStridedSliceOp, rewriter); 708 (void)success; 709 assert(success && "Unexpected failure"); 710 extractedSource = insertStridedSliceOp; 711 } 712 // 4. Insert the extractedSource into the res vector. 713 res = insertOne(rewriter, loc, extractedSource, res, off); 714 } 715 716 rewriter.replaceOp(op, res); 717 return matchSuccess(); 718 } 719 }; 720 721 class VectorOuterProductOpConversion : public LLVMOpLowering { 722 public: 723 explicit VectorOuterProductOpConversion(MLIRContext *context, 724 LLVMTypeConverter &typeConverter) 725 : LLVMOpLowering(vector::OuterProductOp::getOperationName(), context, 726 typeConverter) {} 727 728 PatternMatchResult 729 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 730 ConversionPatternRewriter &rewriter) const override { 731 auto loc = op->getLoc(); 732 auto adaptor = vector::OuterProductOpOperandAdaptor(operands); 733 auto *ctx = op->getContext(); 734 auto vLHS = adaptor.lhs().getType().cast<LLVM::LLVMType>(); 735 auto vRHS = adaptor.rhs().getType().cast<LLVM::LLVMType>(); 736 auto rankLHS = vLHS.getUnderlyingType()->getVectorNumElements(); 737 auto rankRHS = vRHS.getUnderlyingType()->getVectorNumElements(); 738 auto llvmArrayOfVectType = lowering.convertType( 739 cast<vector::OuterProductOp>(op).getResult().getType()); 740 Value desc = rewriter.create<LLVM::UndefOp>(loc, llvmArrayOfVectType); 741 Value a = adaptor.lhs(), b = adaptor.rhs(); 742 Value acc = adaptor.acc().empty() ? nullptr : adaptor.acc().front(); 743 SmallVector<Value, 8> lhs, accs; 744 lhs.reserve(rankLHS); 745 accs.reserve(rankLHS); 746 for (unsigned d = 0, e = rankLHS; d < e; ++d) { 747 // shufflevector explicitly requires i32. 748 auto attr = rewriter.getI32IntegerAttr(d); 749 SmallVector<Attribute, 4> bcastAttr(rankRHS, attr); 750 auto bcastArrayAttr = ArrayAttr::get(bcastAttr, ctx); 751 Value aD = nullptr, accD = nullptr; 752 // 1. Broadcast the element a[d] into vector aD. 753 aD = rewriter.create<LLVM::ShuffleVectorOp>(loc, a, a, bcastArrayAttr); 754 // 2. If acc is present, extract 1-d vector acc[d] into accD. 755 if (acc) 756 accD = rewriter.create<LLVM::ExtractValueOp>( 757 loc, vRHS, acc, rewriter.getI64ArrayAttr(d)); 758 // 3. Compute aD outer b (plus accD, if relevant). 759 Value aOuterbD = 760 accD 761 ? rewriter.create<LLVM::FMAOp>(loc, vRHS, aD, b, accD).getResult() 762 : rewriter.create<LLVM::FMulOp>(loc, aD, b).getResult(); 763 // 4. Insert as value `d` in the descriptor. 764 desc = rewriter.create<LLVM::InsertValueOp>(loc, llvmArrayOfVectType, 765 desc, aOuterbD, 766 rewriter.getI64ArrayAttr(d)); 767 } 768 rewriter.replaceOp(op, desc); 769 return matchSuccess(); 770 } 771 }; 772 773 class VectorTypeCastOpConversion : public LLVMOpLowering { 774 public: 775 explicit VectorTypeCastOpConversion(MLIRContext *context, 776 LLVMTypeConverter &typeConverter) 777 : LLVMOpLowering(vector::TypeCastOp::getOperationName(), context, 778 typeConverter) {} 779 780 PatternMatchResult 781 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 782 ConversionPatternRewriter &rewriter) const override { 783 auto loc = op->getLoc(); 784 vector::TypeCastOp castOp = cast<vector::TypeCastOp>(op); 785 MemRefType sourceMemRefType = 786 castOp.getOperand().getType().cast<MemRefType>(); 787 MemRefType targetMemRefType = 788 castOp.getResult().getType().cast<MemRefType>(); 789 790 // Only static shape casts supported atm. 791 if (!sourceMemRefType.hasStaticShape() || 792 !targetMemRefType.hasStaticShape()) 793 return matchFailure(); 794 795 auto llvmSourceDescriptorTy = 796 operands[0].getType().dyn_cast<LLVM::LLVMType>(); 797 if (!llvmSourceDescriptorTy || !llvmSourceDescriptorTy.isStructTy()) 798 return matchFailure(); 799 MemRefDescriptor sourceMemRef(operands[0]); 800 801 auto llvmTargetDescriptorTy = lowering.convertType(targetMemRefType) 802 .dyn_cast_or_null<LLVM::LLVMType>(); 803 if (!llvmTargetDescriptorTy || !llvmTargetDescriptorTy.isStructTy()) 804 return matchFailure(); 805 806 int64_t offset; 807 SmallVector<int64_t, 4> strides; 808 auto successStrides = 809 getStridesAndOffset(sourceMemRefType, strides, offset); 810 bool isContiguous = (strides.back() == 1); 811 if (isContiguous) { 812 auto sizes = sourceMemRefType.getShape(); 813 for (int index = 0, e = strides.size() - 2; index < e; ++index) { 814 if (strides[index] != strides[index + 1] * sizes[index + 1]) { 815 isContiguous = false; 816 break; 817 } 818 } 819 } 820 // Only contiguous source tensors supported atm. 821 if (failed(successStrides) || !isContiguous) 822 return matchFailure(); 823 824 auto int64Ty = LLVM::LLVMType::getInt64Ty(lowering.getDialect()); 825 826 // Create descriptor. 827 auto desc = MemRefDescriptor::undef(rewriter, loc, llvmTargetDescriptorTy); 828 Type llvmTargetElementTy = desc.getElementType(); 829 // Set allocated ptr. 830 Value allocated = sourceMemRef.allocatedPtr(rewriter, loc); 831 allocated = 832 rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, allocated); 833 desc.setAllocatedPtr(rewriter, loc, allocated); 834 // Set aligned ptr. 835 Value ptr = sourceMemRef.alignedPtr(rewriter, loc); 836 ptr = rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, ptr); 837 desc.setAlignedPtr(rewriter, loc, ptr); 838 // Fill offset 0. 839 auto attr = rewriter.getIntegerAttr(rewriter.getIndexType(), 0); 840 auto zero = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, attr); 841 desc.setOffset(rewriter, loc, zero); 842 843 // Fill size and stride descriptors in memref. 844 for (auto indexedSize : llvm::enumerate(targetMemRefType.getShape())) { 845 int64_t index = indexedSize.index(); 846 auto sizeAttr = 847 rewriter.getIntegerAttr(rewriter.getIndexType(), indexedSize.value()); 848 auto size = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, sizeAttr); 849 desc.setSize(rewriter, loc, index, size); 850 auto strideAttr = 851 rewriter.getIntegerAttr(rewriter.getIndexType(), strides[index]); 852 auto stride = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, strideAttr); 853 desc.setStride(rewriter, loc, index, stride); 854 } 855 856 rewriter.replaceOp(op, {desc}); 857 return matchSuccess(); 858 } 859 }; 860 861 class VectorPrintOpConversion : public LLVMOpLowering { 862 public: 863 explicit VectorPrintOpConversion(MLIRContext *context, 864 LLVMTypeConverter &typeConverter) 865 : LLVMOpLowering(vector::PrintOp::getOperationName(), context, 866 typeConverter) {} 867 868 // Proof-of-concept lowering implementation that relies on a small 869 // runtime support library, which only needs to provide a few 870 // printing methods (single value for all data types, opening/closing 871 // bracket, comma, newline). The lowering fully unrolls a vector 872 // in terms of these elementary printing operations. The advantage 873 // of this approach is that the library can remain unaware of all 874 // low-level implementation details of vectors while still supporting 875 // output of any shaped and dimensioned vector. Due to full unrolling, 876 // this approach is less suited for very large vectors though. 877 // 878 // TODO(ajcbik): rely solely on libc in future? something else? 879 // 880 PatternMatchResult 881 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 882 ConversionPatternRewriter &rewriter) const override { 883 auto printOp = cast<vector::PrintOp>(op); 884 auto adaptor = vector::PrintOpOperandAdaptor(operands); 885 Type printType = printOp.getPrintType(); 886 887 if (lowering.convertType(printType) == nullptr) 888 return matchFailure(); 889 890 // Make sure element type has runtime support (currently just Float/Double). 891 VectorType vectorType = printType.dyn_cast<VectorType>(); 892 Type eltType = vectorType ? vectorType.getElementType() : printType; 893 int64_t rank = vectorType ? vectorType.getRank() : 0; 894 Operation *printer; 895 if (eltType.isInteger(32)) 896 printer = getPrintI32(op); 897 else if (eltType.isInteger(64)) 898 printer = getPrintI64(op); 899 else if (eltType.isF32()) 900 printer = getPrintFloat(op); 901 else if (eltType.isF64()) 902 printer = getPrintDouble(op); 903 else 904 return matchFailure(); 905 906 // Unroll vector into elementary print calls. 907 emitRanks(rewriter, op, adaptor.source(), vectorType, printer, rank); 908 emitCall(rewriter, op->getLoc(), getPrintNewline(op)); 909 rewriter.eraseOp(op); 910 return matchSuccess(); 911 } 912 913 private: 914 void emitRanks(ConversionPatternRewriter &rewriter, Operation *op, 915 Value value, VectorType vectorType, Operation *printer, 916 int64_t rank) const { 917 Location loc = op->getLoc(); 918 if (rank == 0) { 919 emitCall(rewriter, loc, printer, value); 920 return; 921 } 922 923 emitCall(rewriter, loc, getPrintOpen(op)); 924 Operation *printComma = getPrintComma(op); 925 int64_t dim = vectorType.getDimSize(0); 926 for (int64_t d = 0; d < dim; ++d) { 927 auto reducedType = 928 rank > 1 ? reducedVectorTypeFront(vectorType) : nullptr; 929 auto llvmType = lowering.convertType( 930 rank > 1 ? reducedType : vectorType.getElementType()); 931 Value nestedVal = 932 extractOne(rewriter, lowering, loc, value, llvmType, rank, d); 933 emitRanks(rewriter, op, nestedVal, reducedType, printer, rank - 1); 934 if (d != dim - 1) 935 emitCall(rewriter, loc, printComma); 936 } 937 emitCall(rewriter, loc, getPrintClose(op)); 938 } 939 940 // Helper to emit a call. 941 static void emitCall(ConversionPatternRewriter &rewriter, Location loc, 942 Operation *ref, ValueRange params = ValueRange()) { 943 rewriter.create<LLVM::CallOp>(loc, ArrayRef<Type>{}, 944 rewriter.getSymbolRefAttr(ref), params); 945 } 946 947 // Helper for printer method declaration (first hit) and lookup. 948 static Operation *getPrint(Operation *op, LLVM::LLVMDialect *dialect, 949 StringRef name, ArrayRef<LLVM::LLVMType> params) { 950 auto module = op->getParentOfType<ModuleOp>(); 951 auto func = module.lookupSymbol<LLVM::LLVMFuncOp>(name); 952 if (func) 953 return func; 954 OpBuilder moduleBuilder(module.getBodyRegion()); 955 return moduleBuilder.create<LLVM::LLVMFuncOp>( 956 op->getLoc(), name, 957 LLVM::LLVMType::getFunctionTy(LLVM::LLVMType::getVoidTy(dialect), 958 params, /*isVarArg=*/false)); 959 } 960 961 // Helpers for method names. 962 Operation *getPrintI32(Operation *op) const { 963 LLVM::LLVMDialect *dialect = lowering.getDialect(); 964 return getPrint(op, dialect, "print_i32", 965 LLVM::LLVMType::getInt32Ty(dialect)); 966 } 967 Operation *getPrintI64(Operation *op) const { 968 LLVM::LLVMDialect *dialect = lowering.getDialect(); 969 return getPrint(op, dialect, "print_i64", 970 LLVM::LLVMType::getInt64Ty(dialect)); 971 } 972 Operation *getPrintFloat(Operation *op) const { 973 LLVM::LLVMDialect *dialect = lowering.getDialect(); 974 return getPrint(op, dialect, "print_f32", 975 LLVM::LLVMType::getFloatTy(dialect)); 976 } 977 Operation *getPrintDouble(Operation *op) const { 978 LLVM::LLVMDialect *dialect = lowering.getDialect(); 979 return getPrint(op, dialect, "print_f64", 980 LLVM::LLVMType::getDoubleTy(dialect)); 981 } 982 Operation *getPrintOpen(Operation *op) const { 983 return getPrint(op, lowering.getDialect(), "print_open", {}); 984 } 985 Operation *getPrintClose(Operation *op) const { 986 return getPrint(op, lowering.getDialect(), "print_close", {}); 987 } 988 Operation *getPrintComma(Operation *op) const { 989 return getPrint(op, lowering.getDialect(), "print_comma", {}); 990 } 991 Operation *getPrintNewline(Operation *op) const { 992 return getPrint(op, lowering.getDialect(), "print_newline", {}); 993 } 994 }; 995 996 /// Progressive lowering of StridedSliceOp to either: 997 /// 1. extractelement + insertelement for the 1-D case 998 /// 2. extract + optional strided_slice + insert for the n-D case. 999 class VectorStridedSliceOpConversion : public OpRewritePattern<StridedSliceOp> { 1000 public: 1001 using OpRewritePattern<StridedSliceOp>::OpRewritePattern; 1002 1003 PatternMatchResult matchAndRewrite(StridedSliceOp op, 1004 PatternRewriter &rewriter) const override { 1005 auto dstType = op.getResult().getType().cast<VectorType>(); 1006 1007 assert(!op.offsets().getValue().empty() && "Unexpected empty offsets"); 1008 1009 int64_t offset = 1010 op.offsets().getValue().front().cast<IntegerAttr>().getInt(); 1011 int64_t size = op.sizes().getValue().front().cast<IntegerAttr>().getInt(); 1012 int64_t stride = 1013 op.strides().getValue().front().cast<IntegerAttr>().getInt(); 1014 1015 auto loc = op.getLoc(); 1016 auto elemType = dstType.getElementType(); 1017 assert(elemType.isIntOrIndexOrFloat()); 1018 Value zero = rewriter.create<ConstantOp>(loc, elemType, 1019 rewriter.getZeroAttr(elemType)); 1020 Value res = rewriter.create<SplatOp>(loc, dstType, zero); 1021 for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e; 1022 off += stride, ++idx) { 1023 Value extracted = extractOne(rewriter, loc, op.vector(), off); 1024 if (op.offsets().getValue().size() > 1) { 1025 StridedSliceOp stridedSliceOp = rewriter.create<StridedSliceOp>( 1026 loc, extracted, getI64SubArray(op.offsets(), /* dropFront=*/1), 1027 getI64SubArray(op.sizes(), /* dropFront=*/1), 1028 getI64SubArray(op.strides(), /* dropFront=*/1)); 1029 // Call matchAndRewrite recursively from within the pattern. This 1030 // circumvents the current limitation that a given pattern cannot 1031 // be called multiple times by the PatternRewrite infrastructure (to 1032 // avoid infinite recursion, but in this case, infinite recursion 1033 // cannot happen because the rank is strictly decreasing). 1034 // TODO(rriddle, nicolasvasilache) Implement something like a hook for 1035 // a potential function that must decrease and allow the same pattern 1036 // multiple times. 1037 auto success = matchAndRewrite(stridedSliceOp, rewriter); 1038 (void)success; 1039 assert(success && "Unexpected failure"); 1040 extracted = stridedSliceOp; 1041 } 1042 res = insertOne(rewriter, loc, extracted, res, idx); 1043 } 1044 rewriter.replaceOp(op, {res}); 1045 return matchSuccess(); 1046 } 1047 }; 1048 1049 } // namespace 1050 1051 /// Populate the given list with patterns that convert from Vector to LLVM. 1052 void mlir::populateVectorToLLVMConversionPatterns( 1053 LLVMTypeConverter &converter, OwningRewritePatternList &patterns) { 1054 MLIRContext *ctx = converter.getDialect()->getContext(); 1055 patterns.insert<VectorFMAOpNDRewritePattern, 1056 VectorInsertStridedSliceOpDifferentRankRewritePattern, 1057 VectorInsertStridedSliceOpSameRankRewritePattern, 1058 VectorStridedSliceOpConversion>(ctx); 1059 patterns.insert<VectorBroadcastOpConversion, VectorShuffleOpConversion, 1060 VectorExtractElementOpConversion, VectorExtractOpConversion, 1061 VectorFMAOp1DConversion, VectorInsertElementOpConversion, 1062 VectorInsertOpConversion, VectorOuterProductOpConversion, 1063 VectorTypeCastOpConversion, VectorPrintOpConversion>( 1064 ctx, converter); 1065 } 1066 1067 namespace { 1068 struct LowerVectorToLLVMPass : public ModulePass<LowerVectorToLLVMPass> { 1069 void runOnModule() override; 1070 }; 1071 } // namespace 1072 1073 void LowerVectorToLLVMPass::runOnModule() { 1074 // Perform progressive lowering of operations on "slices". 1075 // Folding and DCE get rid of all non-leaking tuple ops. 1076 { 1077 OwningRewritePatternList patterns; 1078 populateVectorSlicesLoweringPatterns(patterns, &getContext()); 1079 applyPatternsGreedily(getModule(), patterns); 1080 } 1081 1082 // Convert to the LLVM IR dialect. 1083 LLVMTypeConverter converter(&getContext()); 1084 OwningRewritePatternList patterns; 1085 populateVectorToLLVMConversionPatterns(converter, patterns); 1086 populateStdToLLVMConversionPatterns(converter, patterns); 1087 1088 ConversionTarget target(getContext()); 1089 target.addLegalDialect<LLVM::LLVMDialect>(); 1090 target.addDynamicallyLegalOp<FuncOp>( 1091 [&](FuncOp op) { return converter.isSignatureLegal(op.getType()); }); 1092 if (failed( 1093 applyPartialConversion(getModule(), target, patterns, &converter))) { 1094 signalPassFailure(); 1095 } 1096 } 1097 1098 OpPassBase<ModuleOp> *mlir::createLowerVectorToLLVMPass() { 1099 return new LowerVectorToLLVMPass(); 1100 } 1101 1102 static PassRegistration<LowerVectorToLLVMPass> 1103 pass("convert-vector-to-llvm", 1104 "Lower the operations from the vector dialect into the LLVM dialect"); 1105