1 //===- LinalgToStandard.cpp - conversion from Linalg to Standard 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/LinalgToStandard/LinalgToStandard.h" 10 11 #include "../PassDetail.h" 12 #include "mlir/Dialect/Affine/IR/AffineOps.h" 13 #include "mlir/Dialect/Linalg/IR/LinalgOps.h" 14 #include "mlir/Dialect/Linalg/Transforms/Transforms.h" 15 #include "mlir/Dialect/MemRef/IR/MemRef.h" 16 #include "mlir/Dialect/SCF/SCF.h" 17 #include "mlir/Dialect/StandardOps/IR/Ops.h" 18 19 using namespace mlir; 20 using namespace mlir::linalg; 21 22 /// Helper function to extract the operand types that are passed to the 23 /// generated CallOp. MemRefTypes have their layout canonicalized since the 24 /// information is not used in signature generation. 25 /// Note that static size information is not modified. 26 static SmallVector<Type, 4> extractOperandTypes(Operation *op) { 27 SmallVector<Type, 4> result; 28 result.reserve(op->getNumOperands()); 29 if (auto indexedGenericOp = dyn_cast<IndexedGenericOp>(op)) { 30 auto *ctx = op->getContext(); 31 auto numLoops = indexedGenericOp.getNumLoops(); 32 result.reserve(op->getNumOperands() + numLoops); 33 result.assign(numLoops, IndexType::get(ctx)); 34 } 35 for (auto type : op->getOperandTypes()) { 36 // The underlying descriptor type (e.g. LLVM) does not have layout 37 // information. Canonicalizing the type at the level of std when going into 38 // a library call avoids needing to introduce DialectCastOp. 39 if (auto memrefType = type.dyn_cast<MemRefType>()) 40 result.push_back(eraseStridedLayout(memrefType)); 41 else 42 result.push_back(type); 43 } 44 return result; 45 } 46 47 // Get a SymbolRefAttr containing the library function name for the LinalgOp. 48 // If the library function does not exist, insert a declaration. 49 static FlatSymbolRefAttr getLibraryCallSymbolRef(Operation *op, 50 PatternRewriter &rewriter) { 51 auto linalgOp = cast<LinalgOp>(op); 52 auto fnName = linalgOp.getLibraryCallName(); 53 if (fnName.empty()) { 54 op->emitWarning("No library call defined for: ") << *op; 55 return {}; 56 } 57 58 // fnName is a dynamic std::string, unique it via a SymbolRefAttr. 59 FlatSymbolRefAttr fnNameAttr = rewriter.getSymbolRefAttr(fnName); 60 auto module = op->getParentOfType<ModuleOp>(); 61 if (module.lookupSymbol(fnName)) { 62 return fnNameAttr; 63 } 64 65 SmallVector<Type, 4> inputTypes(extractOperandTypes(op)); 66 assert(op->getNumResults() == 0 && 67 "Library call for linalg operation can be generated only for ops that " 68 "have void return types"); 69 auto libFnType = rewriter.getFunctionType(inputTypes, {}); 70 71 OpBuilder::InsertionGuard guard(rewriter); 72 // Insert before module terminator. 73 rewriter.setInsertionPoint(module.getBody(), 74 std::prev(module.getBody()->end())); 75 FuncOp funcOp = 76 rewriter.create<FuncOp>(op->getLoc(), fnNameAttr.getValue(), libFnType); 77 // Insert a function attribute that will trigger the emission of the 78 // corresponding `_mlir_ciface_xxx` interface so that external libraries see 79 // a normalized ABI. This interface is added during std to llvm conversion. 80 funcOp->setAttr("llvm.emit_c_interface", UnitAttr::get(op->getContext())); 81 funcOp.setPrivate(); 82 return fnNameAttr; 83 } 84 85 static SmallVector<Value, 4> 86 createTypeCanonicalizedMemRefOperands(OpBuilder &b, Location loc, 87 ValueRange operands) { 88 SmallVector<Value, 4> res; 89 res.reserve(operands.size()); 90 for (auto op : operands) { 91 auto memrefType = op.getType().dyn_cast<MemRefType>(); 92 if (!memrefType) { 93 res.push_back(op); 94 continue; 95 } 96 Value cast = 97 b.create<memref::CastOp>(loc, eraseStridedLayout(memrefType), op); 98 res.push_back(cast); 99 } 100 return res; 101 } 102 103 LogicalResult mlir::linalg::LinalgOpToLibraryCallRewrite::matchAndRewrite( 104 LinalgOp op, PatternRewriter &rewriter) const { 105 // Only LinalgOp for which there is no specialized pattern go through this. 106 if (isa<CopyOp>(op) || isa<IndexedGenericOp>(op)) 107 return failure(); 108 109 auto libraryCallName = getLibraryCallSymbolRef(op, rewriter); 110 if (!libraryCallName) 111 return failure(); 112 113 // TODO: Add support for more complex library call signatures that include 114 // indices or captured values. 115 rewriter.replaceOpWithNewOp<mlir::CallOp>( 116 op, libraryCallName.getValue(), TypeRange(), 117 createTypeCanonicalizedMemRefOperands(rewriter, op->getLoc(), 118 op->getOperands())); 119 return success(); 120 } 121 122 LogicalResult mlir::linalg::CopyOpToLibraryCallRewrite::matchAndRewrite( 123 CopyOp op, PatternRewriter &rewriter) const { 124 auto inputPerm = op.inputPermutation(); 125 if (inputPerm.hasValue() && !inputPerm->isIdentity()) 126 return failure(); 127 auto outputPerm = op.outputPermutation(); 128 if (outputPerm.hasValue() && !outputPerm->isIdentity()) 129 return failure(); 130 131 auto libraryCallName = getLibraryCallSymbolRef(op, rewriter); 132 if (!libraryCallName) 133 return failure(); 134 135 rewriter.replaceOpWithNewOp<mlir::CallOp>( 136 op, libraryCallName.getValue(), TypeRange(), 137 createTypeCanonicalizedMemRefOperands(rewriter, op.getLoc(), 138 op.getOperands())); 139 return success(); 140 } 141 142 LogicalResult mlir::linalg::CopyTransposeRewrite::matchAndRewrite( 143 CopyOp op, PatternRewriter &rewriter) const { 144 Value in = op.input(), out = op.output(); 145 146 // If either inputPerm or outputPerm are non-identities, insert transposes. 147 auto inputPerm = op.inputPermutation(); 148 if (inputPerm.hasValue() && !inputPerm->isIdentity()) 149 in = rewriter.create<memref::TransposeOp>(op.getLoc(), in, 150 AffineMapAttr::get(*inputPerm)); 151 auto outputPerm = op.outputPermutation(); 152 if (outputPerm.hasValue() && !outputPerm->isIdentity()) 153 out = rewriter.create<memref::TransposeOp>(op.getLoc(), out, 154 AffineMapAttr::get(*outputPerm)); 155 156 // If nothing was transposed, fail and let the conversion kick in. 157 if (in == op.input() && out == op.output()) 158 return failure(); 159 160 auto libraryCallName = getLibraryCallSymbolRef(op, rewriter); 161 if (!libraryCallName) 162 return failure(); 163 164 rewriter.replaceOpWithNewOp<mlir::CallOp>( 165 op, libraryCallName.getValue(), TypeRange(), 166 createTypeCanonicalizedMemRefOperands(rewriter, op.getLoc(), {in, out})); 167 return success(); 168 } 169 170 LogicalResult 171 mlir::linalg::IndexedGenericOpToLibraryCallRewrite::matchAndRewrite( 172 IndexedGenericOp op, PatternRewriter &rewriter) const { 173 auto libraryCallName = getLibraryCallSymbolRef(op, rewriter); 174 if (!libraryCallName) 175 return failure(); 176 177 // TODO: Use induction variables values instead of zeros, when 178 // IndexedGenericOp is tiled. 179 auto zero = rewriter.create<mlir::ConstantOp>( 180 op.getLoc(), rewriter.getIntegerAttr(rewriter.getIndexType(), 0)); 181 auto indexedGenericOp = cast<IndexedGenericOp>(op); 182 auto numLoops = indexedGenericOp.getNumLoops(); 183 SmallVector<Value, 4> operands; 184 operands.reserve(numLoops + op.getNumOperands()); 185 for (unsigned i = 0; i < numLoops; ++i) 186 operands.push_back(zero); 187 for (auto operand : op.getOperands()) 188 operands.push_back(operand); 189 rewriter.replaceOpWithNewOp<mlir::CallOp>( 190 op, libraryCallName.getValue(), TypeRange(), 191 createTypeCanonicalizedMemRefOperands(rewriter, op.getLoc(), operands)); 192 return success(); 193 } 194 195 /// Populate the given list with patterns that convert from Linalg to Standard. 196 void mlir::linalg::populateLinalgToStandardConversionPatterns( 197 RewritePatternSet &patterns) { 198 // TODO: ConvOp conversion needs to export a descriptor with relevant 199 // attribute values such as kernel striding and dilation. 200 // clang-format off 201 patterns.add< 202 CopyOpToLibraryCallRewrite, 203 CopyTransposeRewrite, 204 IndexedGenericOpToLibraryCallRewrite, 205 LinalgOpToLibraryCallRewrite>(patterns.getContext()); 206 // clang-format on 207 } 208 209 namespace { 210 struct ConvertLinalgToStandardPass 211 : public ConvertLinalgToStandardBase<ConvertLinalgToStandardPass> { 212 void runOnOperation() override; 213 }; 214 } // namespace 215 216 void ConvertLinalgToStandardPass::runOnOperation() { 217 auto module = getOperation(); 218 ConversionTarget target(getContext()); 219 target.addLegalDialect<AffineDialect, memref::MemRefDialect, scf::SCFDialect, 220 StandardOpsDialect>(); 221 target.addLegalOp<ModuleOp, FuncOp, ReturnOp>(); 222 target.addLegalOp<linalg::ReshapeOp, linalg::RangeOp>(); 223 RewritePatternSet patterns(&getContext()); 224 populateLinalgToStandardConversionPatterns(patterns); 225 if (failed(applyFullConversion(module, target, std::move(patterns)))) 226 signalPassFailure(); 227 } 228 229 std::unique_ptr<OperationPass<ModuleOp>> 230 mlir::createConvertLinalgToStandardPass() { 231 return std::make_unique<ConvertLinalgToStandardPass>(); 232 } 233