|
| 1 | +//===- EmulateUnsupportedFloats.cpp - Promote small floats --*- 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 | +// This pass promotes small floats (of some unsupported types T) to a supported |
| 9 | +// type U by wrapping all float operations on Ts with expansion to and |
| 10 | +// truncation from U, then operating on U. |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +#include "mlir/Dialect/Arith/Transforms/Passes.h" |
| 14 | + |
| 15 | +#include "mlir/Dialect/Arith/IR/Arith.h" |
| 16 | +#include "mlir/Dialect/Vector/IR/VectorOps.h" |
| 17 | +#include "mlir/IR/BuiltinTypes.h" |
| 18 | +#include "mlir/IR/Location.h" |
| 19 | +#include "mlir/IR/PatternMatch.h" |
| 20 | +#include "mlir/Transforms/DialectConversion.h" |
| 21 | +#include "llvm/ADT/STLExtras.h" |
| 22 | +#include <optional> |
| 23 | + |
| 24 | +namespace mlir::arith { |
| 25 | +#define GEN_PASS_DEF_ARITHEMULATEUNSUPPORTEDFLOATS |
| 26 | +#include "mlir/Dialect/Arith/Transforms/Passes.h.inc" |
| 27 | +} // namespace mlir::arith |
| 28 | + |
| 29 | +using namespace mlir; |
| 30 | + |
| 31 | +namespace { |
| 32 | +struct EmulateUnsupportedFloatsPass |
| 33 | + : arith::impl::ArithEmulateUnsupportedFloatsBase< |
| 34 | + EmulateUnsupportedFloatsPass> { |
| 35 | + using arith::impl::ArithEmulateUnsupportedFloatsBase< |
| 36 | + EmulateUnsupportedFloatsPass>::ArithEmulateUnsupportedFloatsBase; |
| 37 | + |
| 38 | + void runOnOperation() override; |
| 39 | +}; |
| 40 | + |
| 41 | +struct EmulateFloatPattern final : ConversionPattern { |
| 42 | + EmulateFloatPattern(TypeConverter &converter, MLIRContext *ctx) |
| 43 | + : ConversionPattern(converter, Pattern::MatchAnyOpTypeTag(), 1, ctx) {} |
| 44 | + |
| 45 | + LogicalResult match(Operation *op) const override; |
| 46 | + void rewrite(Operation *op, ArrayRef<Value> operands, |
| 47 | + ConversionPatternRewriter &rewriter) const override; |
| 48 | +}; |
| 49 | +} // end namespace |
| 50 | + |
| 51 | +/// Map strings to float types. This function is here because no one else needs |
| 52 | +/// it yet, feel free to abstract it out. |
| 53 | +static std::optional<FloatType> parseFloatType(MLIRContext *ctx, |
| 54 | + StringRef name) { |
| 55 | + Builder b(ctx); |
| 56 | + return llvm::StringSwitch<std::optional<FloatType>>(name) |
| 57 | + .Case("f8E5M2", b.getFloat8E5M2Type()) |
| 58 | + .Case("f8E4M3FN", b.getFloat8E4M3FNType()) |
| 59 | + .Case("f8E5M2FNUZ", b.getFloat8E5M2FNUZType()) |
| 60 | + .Case("f8E4M3FNUZ", b.getFloat8E4M3FNUZType()) |
| 61 | + .Case("bf16", b.getBF16Type()) |
| 62 | + .Case("f16", b.getF16Type()) |
| 63 | + .Case("f32", b.getF32Type()) |
| 64 | + .Case("f64", b.getF64Type()) |
| 65 | + .Case("f80", b.getF80Type()) |
| 66 | + .Case("f128", b.getF128Type()) |
| 67 | + .Default(std::nullopt); |
| 68 | +} |
| 69 | + |
| 70 | +LogicalResult EmulateFloatPattern::match(Operation *op) const { |
| 71 | + if (getTypeConverter()->isLegal(op)) |
| 72 | + return failure(); |
| 73 | + // The rewrite doesn't handle cloning regions. |
| 74 | + if (op->getNumRegions() != 0) |
| 75 | + return failure(); |
| 76 | + return success(); |
| 77 | +} |
| 78 | + |
| 79 | +void EmulateFloatPattern::rewrite(Operation *op, ArrayRef<Value> operands, |
| 80 | + ConversionPatternRewriter &rewriter) const { |
| 81 | + Location loc = op->getLoc(); |
| 82 | + TypeConverter *converter = getTypeConverter(); |
| 83 | + SmallVector<Type> resultTypes; |
| 84 | + assert( |
| 85 | + succeeded(converter->convertTypes(op->getResultTypes(), resultTypes)) && |
| 86 | + "type conversions shouldn't fail in this pass"); |
| 87 | + Operation *expandedOp = |
| 88 | + rewriter.create(loc, op->getName().getIdentifier(), operands, resultTypes, |
| 89 | + op->getAttrs(), op->getSuccessors(), /*regions=*/{}); |
| 90 | + SmallVector<Value> newResults(expandedOp->getResults()); |
| 91 | + for (auto [res, oldType, newType] : llvm::zip_equal( |
| 92 | + MutableArrayRef{newResults}, op->getResultTypes(), resultTypes)) { |
| 93 | + if (oldType != newType) |
| 94 | + res = rewriter.create<arith::TruncFOp>(loc, oldType, res); |
| 95 | + } |
| 96 | + rewriter.replaceOp(op, newResults); |
| 97 | +} |
| 98 | + |
| 99 | +void mlir::arith::populateEmulateUnsupportedFloatsConversions( |
| 100 | + TypeConverter &converter, ArrayRef<Type> sourceTypes, Type targetType) { |
| 101 | + converter.addConversion([sourceTypes = SmallVector<Type>(sourceTypes), |
| 102 | + targetType](Type type) -> std::optional<Type> { |
| 103 | + if (llvm::is_contained(sourceTypes, type)) |
| 104 | + return targetType; |
| 105 | + if (auto shaped = type.dyn_cast<ShapedType>()) |
| 106 | + if (llvm::is_contained(sourceTypes, shaped.getElementType())) |
| 107 | + return shaped.clone(targetType); |
| 108 | + // All other types legal |
| 109 | + return type; |
| 110 | + }); |
| 111 | + converter.addTargetMaterialization( |
| 112 | + [](OpBuilder &b, Type target, ValueRange input, Location loc) { |
| 113 | + return b.create<arith::ExtFOp>(loc, target, input); |
| 114 | + }); |
| 115 | +} |
| 116 | + |
| 117 | +void mlir::arith::populateEmulateUnsupportedFloatsPatterns( |
| 118 | + RewritePatternSet &patterns, TypeConverter &converter) { |
| 119 | + patterns.add<EmulateFloatPattern>(converter, patterns.getContext()); |
| 120 | +} |
| 121 | + |
| 122 | +void mlir::arith::populateEmulateUnsupportedFloatsLegality( |
| 123 | + ConversionTarget &target, TypeConverter &converter) { |
| 124 | + // Don't try to legalize functions and other ops that don't need expansion. |
| 125 | + target.markUnknownOpDynamicallyLegal([](Operation *op) { return true; }); |
| 126 | + target.addDynamicallyLegalDialect<arith::ArithDialect>( |
| 127 | + [&](Operation *op) -> std::optional<bool> { |
| 128 | + return converter.isLegal(op); |
| 129 | + }); |
| 130 | + // Manually mark arithmetic-performing vector instructions. |
| 131 | + target.addDynamicallyLegalOp< |
| 132 | + vector::ContractionOp, vector::ReductionOp, vector::MultiDimReductionOp, |
| 133 | + vector::FMAOp, vector::OuterProductOp, vector::MatmulOp, vector::ScanOp>( |
| 134 | + [&](Operation *op) { return converter.isLegal(op); }); |
| 135 | + target.addLegalOp<arith::ExtFOp, arith::TruncFOp, arith::ConstantOp, |
| 136 | + vector::SplatOp>(); |
| 137 | +} |
| 138 | + |
| 139 | +void EmulateUnsupportedFloatsPass::runOnOperation() { |
| 140 | + MLIRContext *ctx = &getContext(); |
| 141 | + Operation *op = getOperation(); |
| 142 | + SmallVector<Type> sourceTypes; |
| 143 | + Type targetType; |
| 144 | + |
| 145 | + std::optional<FloatType> maybeTargetType = parseFloatType(ctx, targetTypeStr); |
| 146 | + if (!maybeTargetType) { |
| 147 | + emitError(UnknownLoc::get(ctx), "could not map target type '" + |
| 148 | + targetTypeStr + |
| 149 | + "' to a known floating-point type"); |
| 150 | + return signalPassFailure(); |
| 151 | + } |
| 152 | + targetType = *maybeTargetType; |
| 153 | + for (StringRef sourceTypeStr : sourceTypeStrs) { |
| 154 | + std::optional<FloatType> maybeSourceType = |
| 155 | + parseFloatType(ctx, sourceTypeStr); |
| 156 | + if (!maybeSourceType) { |
| 157 | + emitError(UnknownLoc::get(ctx), "could not map source type '" + |
| 158 | + sourceTypeStr + |
| 159 | + "' to a known floating-point type"); |
| 160 | + return signalPassFailure(); |
| 161 | + } |
| 162 | + sourceTypes.push_back(*maybeSourceType); |
| 163 | + } |
| 164 | + if (sourceTypes.empty()) |
| 165 | + (void)emitOptionalWarning( |
| 166 | + std::nullopt, |
| 167 | + "no source types specified, float emulation will do nothing"); |
| 168 | + |
| 169 | + if (llvm::is_contained(sourceTypes, targetType)) { |
| 170 | + emitError(UnknownLoc::get(ctx), |
| 171 | + "target type cannot be an unsupported source type"); |
| 172 | + return signalPassFailure(); |
| 173 | + } |
| 174 | + TypeConverter converter; |
| 175 | + arith::populateEmulateUnsupportedFloatsConversions(converter, sourceTypes, |
| 176 | + targetType); |
| 177 | + RewritePatternSet patterns(ctx); |
| 178 | + arith::populateEmulateUnsupportedFloatsPatterns(patterns, converter); |
| 179 | + ConversionTarget target(getContext()); |
| 180 | + arith::populateEmulateUnsupportedFloatsLegality(target, converter); |
| 181 | + |
| 182 | + if (failed(applyPartialConversion(op, target, std::move(patterns)))) |
| 183 | + signalPassFailure(); |
| 184 | +} |
0 commit comments