MLIR 24.0.0git
OptimizeForNVVM.cpp
Go to the documentation of this file.
1//===- OptimizeForNVVM.cpp - Optimize LLVM IR for NVVM --------------------===//
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
10
17#include "mlir/IR/Builders.h"
19#include "mlir/Pass/Pass.h"
21
22namespace mlir {
23namespace NVVM {
24#define GEN_PASS_DEF_NVVMOPTIMIZEFORTARGETPASS
25#include "mlir/Dialect/NVVM/Transforms/Passes.h.inc"
26} // namespace NVVM
27} // namespace mlir
28
29using namespace mlir;
31namespace {
32// Replaces fdiv on fp16 with fp32 multiplication with reciprocal plus one
33// (conditional) Newton iteration.
34//
35// This as accurate as promoting the division to fp32 in the NVPTX backend, but
36// faster because it performs less Newton iterations, avoids the slow path
37// for e.g. denormals, and allows reuse of the reciprocal for multiple divisions
38// by the same divisor.
39struct ExpandDivF16 : public OpRewritePattern<LLVM::FDivOp> {
40 using OpRewritePattern<LLVM::FDivOp>::OpRewritePattern;
41
42private:
43 LogicalResult matchAndRewrite(LLVM::FDivOp op,
44 PatternRewriter &rewriter) const override;
45};
46
47struct NVVMOptimizeForTarget
48 : public NVVM::impl::NVVMOptimizeForTargetPassBase<NVVMOptimizeForTarget> {
49 void runOnOperation() override;
51 void getDependentDialects(DialectRegistry &registry) const override {
52 registry.insert<NVVM::NVVMDialect>();
53 }
54};
55} // namespace
57LogicalResult ExpandDivF16::matchAndRewrite(LLVM::FDivOp op,
58 PatternRewriter &rewriter) const {
59 if (!op.getType().isF16())
60 return rewriter.notifyMatchFailure(op, "not f16");
61 Location loc = op.getLoc();
62
63 Type f32Type = rewriter.getF32Type();
64 Type i32Type = rewriter.getI32Type();
65
66 // Extend lhs and rhs to fp32.
67 Value lhs = LLVM::FPExtOp::create(rewriter, loc, f32Type, op.getLhs());
68 Value rhs = LLVM::FPExtOp::create(rewriter, loc, f32Type, op.getRhs());
69
70 // float rcp = rcp.approx.ftz.f32(rhs), approx = lhs * rcp.
71 Value rcp = NVVM::RcpApproxFtzF32Op::create(rewriter, loc, f32Type, rhs);
72 Value approx = LLVM::FMulOp::create(rewriter, loc, lhs, rcp);
73
74 // Refine the approximation with one Newton iteration:
75 // float refined = approx + (lhs - approx * rhs) * rcp;
76 Value err = LLVM::FMAOp::create(
77 rewriter, loc, approx, LLVM::FNegOp::create(rewriter, loc, rhs), lhs);
78 Value refined = LLVM::FMAOp::create(rewriter, loc, err, rcp, approx);
79
80 // Use refined value if approx is normal (exponent neither all 0 or all 1).
81 Value mask = LLVM::ConstantOp::create(rewriter, loc, i32Type,
82 rewriter.getI32IntegerAttr(0x7f800000));
83 Value cast = LLVM::BitcastOp::create(rewriter, loc, i32Type, approx);
84 Value exp = LLVM::AndOp::create(rewriter, loc, i32Type, cast, mask);
85 Value zero = LLVM::ConstantOp::create(rewriter, loc, i32Type,
86 rewriter.getI32IntegerAttr(0));
87 Value pred = LLVM::OrOp::create(
88 rewriter, loc,
89 LLVM::ICmpOp::create(rewriter, loc, LLVM::ICmpPredicate::eq, exp, zero),
90 LLVM::ICmpOp::create(rewriter, loc, LLVM::ICmpPredicate::eq, exp, mask));
92 LLVM::SelectOp::create(rewriter, loc, f32Type, pred, approx, refined);
93
94 // Replace with trucation back to fp16.
95 rewriter.replaceOpWithNewOp<LLVM::FPTruncOp>(op, op.getType(), result);
96
97 return success();
98}
99
100void NVVMOptimizeForTarget::runOnOperation() {
101 MLIRContext *ctx = getOperation()->getContext();
102 RewritePatternSet patterns(ctx);
103 patterns.add<ExpandDivF16>(ctx);
104 if (failed(applyPatternsGreedily(getOperation(), std::move(patterns))))
105 return signalPassFailure();
106}
return success()
IntegerAttr getI32IntegerAttr(int32_t value)
Definition Builders.cpp:208
FloatType getF32Type()
Definition Builders.cpp:51
IntegerType getI32Type()
Definition Builders.cpp:71
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
void getDependentDialects(::mlir::DialectRegistry &registry) const override
Return the dialect that must be loaded in the context before this pass.
virtual void runOnOperation()=0
The polymorphic API that runs the pass over the currently held operation.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Include the generated interface declarations.
LogicalResult applyPatternsGreedily(Region &region, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...