MLIR 24.0.0git
LLVMArithOps.cpp
Go to the documentation of this file.
1//===- LLVMArithOps.cpp - LLVM dialect arithmetic ops ---------------------===//
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// This file defines the ops of op partition `Arith` of the LLVM dialect.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "IR/LLVMOps.h"
18#include "mlir/IR/Builders.h"
20#include "mlir/IR/Matchers.h"
21#include "llvm/ADT/STLExtras.h"
22
23#include <optional>
24
25using namespace mlir;
26using namespace mlir::LLVM;
27
28/// Returns a boolean type that has the same shape as `type`. It supports both
29/// fixed size vectors as well as scalable vectors.
31 Type i1Type = IntegerType::get(type.getContext(), 1);
34 return i1Type;
35}
36
37//===----------------------------------------------------------------------===//
38// Printing, parsing, folding and builder for LLVM::CmpOp.
39//===----------------------------------------------------------------------===//
40
41template <typename PredicateAttr, typename Predicate>
42static ParseResult parseCmpPredicateImpl(
43 OpAsmParser &parser, PredicateAttr &predicate,
44 function_ref<std::optional<Predicate>(StringRef)> symbolize) {
45 std::string spelling;
46 SMLoc loc = parser.getCurrentLocation();
47 if (parser.parseString(&spelling))
48 return failure();
49 std::optional<Predicate> value = symbolize(spelling);
50 if (!value)
51 return parser.emitError(loc)
52 << "'" << spelling
53 << "' is an incorrect value of the 'predicate' attribute";
54 predicate = PredicateAttr::get(parser.getContext(), *value);
55 return success();
56}
57
59 ICmpPredicateAttr &predicate) {
61 parser, predicate,
62 [](StringRef spelling) { return symbolizeICmpPredicate(spelling); });
63}
64
66 FCmpPredicateAttr &predicate) {
68 parser, predicate,
69 [](StringRef spelling) { return symbolizeFCmpPredicate(spelling); });
70}
71
73 ICmpPredicateAttr predicate) {
74 printer << '"' << stringifyICmpPredicate(predicate.getValue()) << '"';
75}
76
78 FCmpPredicateAttr predicate) {
79 printer << '"' << stringifyFCmpPredicate(predicate.getValue()) << '"';
80}
81
82/// Returns a scalar or vector boolean attribute of the given type.
83static Attribute getBoolAttribute(Type type, MLIRContext *ctx, bool value) {
84 auto boolAttr = BoolAttr::get(ctx, value);
85 ShapedType shapedType = dyn_cast<ShapedType>(type);
86 if (!shapedType)
87 return boolAttr;
88 return DenseElementsAttr::get(shapedType, boolAttr);
89}
90
91OpFoldResult ICmpOp::fold(FoldAdaptor adaptor) {
92 if (getPredicate() != ICmpPredicate::eq &&
93 getPredicate() != ICmpPredicate::ne)
94 return {};
95
96 // cmpi(eq/ne, x, x) -> true/false
97 if (getLhs() == getRhs())
99 getPredicate() == ICmpPredicate::eq);
100
101 // cmpi(eq/ne, alloca, null) -> false/true
102 if (getLhs().getDefiningOp<AllocaOp>() && getRhs().getDefiningOp<ZeroOp>())
104 getPredicate() == ICmpPredicate::ne);
105
106 // cmpi(eq/ne, null, alloca) -> cmpi(eq/ne, alloca, null)
107 if (getLhs().getDefiningOp<ZeroOp>() && getRhs().getDefiningOp<AllocaOp>()) {
108 Value lhs = getLhs();
109 Value rhs = getRhs();
110 getLhsMutable().assign(rhs);
111 getRhsMutable().assign(lhs);
112 return getResult();
113 }
114
115 return {};
116}
117
118//===----------------------------------------------------------------------===//
119// ShlOp
120//===----------------------------------------------------------------------===//
121
122OpFoldResult LLVM::ShlOp::fold(FoldAdaptor adaptor) {
123 auto rhs = dyn_cast_or_null<IntegerAttr>(adaptor.getRhs());
124 if (!rhs)
125 return {};
126
127 if (rhs.getValue().uge(getLhs().getType().getIntOrFloatBitWidth()))
128 return {}; // TODO: Fold into poison.
129
130 auto lhs = dyn_cast_or_null<IntegerAttr>(adaptor.getLhs());
131 if (!lhs)
132 return {};
133
134 return IntegerAttr::get(getType(), lhs.getValue().shl(rhs.getValue()));
135}
136
137//===----------------------------------------------------------------------===//
138// OrOp
139//===----------------------------------------------------------------------===//
140
141OpFoldResult LLVM::OrOp::fold(FoldAdaptor adaptor) {
142 auto lhs = dyn_cast_or_null<IntegerAttr>(adaptor.getLhs());
143 if (!lhs)
144 return {};
145
146 auto rhs = dyn_cast_or_null<IntegerAttr>(adaptor.getRhs());
147 if (!rhs)
148 return {};
149
150 return IntegerAttr::get(getType(), lhs.getValue() | rhs.getValue());
151}
152
153//===----------------------------------------------------------------------===//
154// UDivOp
155//===----------------------------------------------------------------------===//
156Speculation::Speculatability UDivOp::getSpeculatability() {
157 // X / 0 => UB
158 Value divisor = getRhs();
159 if (matchPattern(divisor, m_IntRangeWithoutZeroU()))
161
163}
164
165//===----------------------------------------------------------------------===//
166// SDivOp
167//===----------------------------------------------------------------------===//
168Speculation::Speculatability SDivOp::getSpeculatability() {
169 // This function conservatively assumes that all signed division by -1 are
170 // not speculatable.
171 // X / 0 => UB
172 // INT_MIN / -1 => UB
173 Value divisor = getRhs();
174 if (matchPattern(divisor, m_IntRangeWithoutZeroS()) &&
177
179}
180
181//===----------------------------------------------------------------------===//
182// URemOp
183//===----------------------------------------------------------------------===//
184
185Speculation::Speculatability URemOp::getSpeculatability() {
186 // urem(x, 0) => UB
187 Value divisor = getRhs();
188 if (matchPattern(divisor, m_IntRangeWithoutZeroU()))
190
192}
193
194//===----------------------------------------------------------------------===//
195// SRemOp
196//===----------------------------------------------------------------------===//
197
198Speculation::Speculatability SRemOp::getSpeculatability() {
199 // srem(x, 0) => UB
200 // srem(INT_MIN, -1) => UB
201 Value divisor = getRhs();
202 if (matchPattern(divisor, m_IntRangeWithoutZeroS()) &&
205
207}
208
209#define GET_OP_CLASSES
210#include "mlir/Dialect/LLVMIR/LLVMArithOps.cpp.inc"
return success()
static ParseResult parseCmpPredicateImpl(OpAsmParser &parser, PredicateAttr &predicate, function_ref< std::optional< Predicate >(StringRef)> symbolize)
static Attribute getBoolAttribute(Type type, MLIRContext *ctx, bool value)
Returns a scalar or vector boolean attribute of the given type.
b getContext())
MLIRContext * getContext() const
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
ParseResult parseString(std::string *string)
Parse a quoted string token.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
Attributes are known-constant values of operations.
Definition Attributes.h:25
static BoolAttr get(MLIRContext *context, bool value)
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
This class represents a single result from folding an operation.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getVectorType(Type elementType, unsigned numElements, bool isScalable=false)
Creates an LLVM dialect-compatible vector type with the given element type and length.
mlir::ParseResult parseCmpPredicate(mlir::OpAsmParser &parser, mlir::LLVM::ICmpPredicateAttr &predicate)
void printCmpPredicate(mlir::OpAsmPrinter &printer, mlir::Operation *, mlir::LLVM::ICmpPredicateAttr predicate)
bool isCompatibleVectorType(Type type)
Returns true if the given type is a vector type compatible with the LLVM dialect.
mlir::Type getI1SameShape(mlir::Type type)
Returns a boolean type that has the same shape as type.
llvm::ElementCount getVectorNumElements(Type type)
Returns the element count of any LLVM-compatible vector type.
Speculatability
This enum is returned from the getSpeculatability method in the ConditionallySpeculatable op interfac...
constexpr auto Speculatable
constexpr auto NotSpeculatable
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
detail::constant_int_range_predicate_matcher m_IntRangeWithoutNegOneS()
Matches a constant scalar / vector splat / tensor splat integer or a signed integer range that does n...
Definition Matchers.h:471
detail::constant_int_range_predicate_matcher m_IntRangeWithoutZeroS()
Matches a constant scalar / vector splat / tensor splat integer or a signed integer range that does n...
Definition Matchers.h:462
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
detail::constant_int_range_predicate_matcher m_IntRangeWithoutZeroU()
Matches a constant scalar / vector splat / tensor splat integer or a unsigned integer range that does...
Definition Matchers.h:455