MLIR  21.0.0git
ComplexToLibm.cpp
Go to the documentation of this file.
1 //===-- ComplexToLibm.cpp - conversion from Complex to libm calls ---------===//
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 
13 #include "mlir/IR/PatternMatch.h"
14 #include <optional>
15 
16 namespace mlir {
17 #define GEN_PASS_DEF_CONVERTCOMPLEXTOLIBM
18 #include "mlir/Conversion/Passes.h.inc"
19 } // namespace mlir
20 
21 using namespace mlir;
22 
23 namespace {
24 // Functor to resolve the function name corresponding to the given complex
25 // result type.
26 struct ComplexTypeResolver {
27  std::optional<bool> operator()(Type type) const {
28  auto complexType = cast<ComplexType>(type);
29  auto elementType = complexType.getElementType();
30  if (!isa<Float32Type, Float64Type>(elementType))
31  return {};
32 
33  return elementType.getIntOrFloatBitWidth() == 64;
34  }
35 };
36 
37 // Functor to resolve the function name corresponding to the given float result
38 // type.
39 struct FloatTypeResolver {
40  std::optional<bool> operator()(Type type) const {
41  auto elementType = cast<FloatType>(type);
42  if (!isa<Float32Type, Float64Type>(elementType))
43  return {};
44 
45  return elementType.getIntOrFloatBitWidth() == 64;
46  }
47 };
48 
49 // Pattern to convert scalar complex operations to calls to libm functions.
50 // Additionally the libm function signatures are declared.
51 // TypeResolver is a functor returning the libm function name according to the
52 // expected type double or float.
53 template <typename Op, typename TypeResolver = ComplexTypeResolver>
54 struct ScalarOpToLibmCall : public OpRewritePattern<Op> {
55 public:
57  ScalarOpToLibmCall(MLIRContext *context, StringRef floatFunc,
58  StringRef doubleFunc, PatternBenefit benefit)
59  : OpRewritePattern<Op>(context, benefit), floatFunc(floatFunc),
60  doubleFunc(doubleFunc){};
61 
62  LogicalResult matchAndRewrite(Op op, PatternRewriter &rewriter) const final;
63 
64 private:
65  std::string floatFunc, doubleFunc;
66 };
67 } // namespace
68 
69 template <typename Op, typename TypeResolver>
70 LogicalResult ScalarOpToLibmCall<Op, TypeResolver>::matchAndRewrite(
71  Op op, PatternRewriter &rewriter) const {
72  auto module = SymbolTable::getNearestSymbolTable(op);
73  auto isDouble = TypeResolver()(op.getType());
74  if (!isDouble.has_value())
75  return failure();
76 
77  auto name = *isDouble ? doubleFunc : floatFunc;
78 
79  auto opFunc = dyn_cast_or_null<SymbolOpInterface>(
80  SymbolTable::lookupSymbolIn(module, name));
81  // Forward declare function if it hasn't already been
82  if (!opFunc) {
83  OpBuilder::InsertionGuard guard(rewriter);
84  rewriter.setInsertionPointToStart(&module->getRegion(0).front());
85  auto opFunctionTy = FunctionType::get(
86  rewriter.getContext(), op->getOperandTypes(), op->getResultTypes());
87  opFunc = rewriter.create<func::FuncOp>(rewriter.getUnknownLoc(), name,
88  opFunctionTy);
89  opFunc.setPrivate();
90  }
91  assert(isa<FunctionOpInterface>(SymbolTable::lookupSymbolIn(module, name)));
92 
93  rewriter.replaceOpWithNewOp<func::CallOp>(op, name, op.getType(),
94  op->getOperands());
95 
96  return success();
97 }
98 
100  PatternBenefit benefit) {
101  patterns.add<ScalarOpToLibmCall<complex::PowOp>>(patterns.getContext(),
102  "cpowf", "cpow", benefit);
103  patterns.add<ScalarOpToLibmCall<complex::SqrtOp>>(patterns.getContext(),
104  "csqrtf", "csqrt", benefit);
105  patterns.add<ScalarOpToLibmCall<complex::TanhOp>>(patterns.getContext(),
106  "ctanhf", "ctanh", benefit);
107  patterns.add<ScalarOpToLibmCall<complex::CosOp>>(patterns.getContext(),
108  "ccosf", "ccos", benefit);
109  patterns.add<ScalarOpToLibmCall<complex::SinOp>>(patterns.getContext(),
110  "csinf", "csin", benefit);
111  patterns.add<ScalarOpToLibmCall<complex::ConjOp>>(patterns.getContext(),
112  "conjf", "conj", benefit);
113  patterns.add<ScalarOpToLibmCall<complex::LogOp>>(patterns.getContext(),
114  "clogf", "clog", benefit);
115  patterns.add<ScalarOpToLibmCall<complex::AbsOp, FloatTypeResolver>>(
116  patterns.getContext(), "cabsf", "cabs", benefit);
117  patterns.add<ScalarOpToLibmCall<complex::AngleOp, FloatTypeResolver>>(
118  patterns.getContext(), "cargf", "carg", benefit);
119  patterns.add<ScalarOpToLibmCall<complex::TanOp>>(patterns.getContext(),
120  "ctanf", "ctan", benefit);
121 }
122 
123 namespace {
124 struct ConvertComplexToLibmPass
125  : public impl::ConvertComplexToLibmBase<ConvertComplexToLibmPass> {
126  void runOnOperation() override;
127 };
128 } // namespace
129 
130 void ConvertComplexToLibmPass::runOnOperation() {
131  auto module = getOperation();
132 
135 
136  ConversionTarget target(getContext());
137  target.addLegalDialect<func::FuncDialect>();
138  target.addIllegalOp<complex::PowOp, complex::SqrtOp, complex::TanhOp,
139  complex::CosOp, complex::SinOp, complex::ConjOp,
140  complex::LogOp, complex::AbsOp, complex::AngleOp,
141  complex::TanOp>();
142  if (failed(applyPartialConversion(module, target, std::move(patterns))))
143  signalPassFailure();
144 }
static MLIRContext * getContext(OpFoldResult val)
MLIRContext * getContext() const
Definition: Builders.h:55
Location getUnknownLoc()
Definition: Builders.cpp:24
This class describes a specific conversion target.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:346
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition: Builders.h:429
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:452
This provides public APIs that all operations should have.
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
Definition: PatternMatch.h:34
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Definition: PatternMatch.h:748
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Definition: PatternMatch.h:500
static Operation * lookupSymbolIn(Operation *op, StringAttr symbol)
Returns the operation registered with the given symbol name with the regions of 'symbolTableOp'.
static Operation * getNearestSymbolTable(Operation *from)
Returns the nearest symbol table from a given operation from.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
Include the generated interface declarations.
const FrozenRewritePatternSet & patterns
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
LogicalResult applyPartialConversion(ArrayRef< Operation * > ops, const ConversionTarget &target, const FrozenRewritePatternSet &patterns, ConversionConfig config=ConversionConfig())
Below we define several entry points for operation conversion.
void populateComplexToLibmConversionPatterns(RewritePatternSet &patterns, PatternBenefit benefit)
Populate the given list with patterns that convert from Complex to Libm calls.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
Definition: PatternMatch.h:314