MLIR 24.0.0git
AffineStructures.h
Go to the documentation of this file.
1//===- AffineStructures.h - MLIR Affine Structures Class --------*- 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//
9// Structures for affine/polyhedral analysis of ML functions.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_DIALECT_AFFINE_ANALYSIS_AFFINESTRUCTURES_H
14#define MLIR_DIALECT_AFFINE_ANALYSIS_AFFINESTRUCTURES_H
15
19#include "mlir/IR/AffineExpr.h"
21#include <optional>
22
23namespace mlir {
24class AffineMap;
25class IntegerSet;
26class MemRefType;
27class MLIRContext;
28struct MutableAffineMap;
29class Value;
30
31namespace presburger {
33} // namespace presburger
34
35namespace affine {
36class AffineForOp;
37class AffineIfOp;
38class AffineParallelOp;
39class AffineValueMap;
40
41/// FlatAffineValueConstraints is an extension of FlatLinearValueConstraints
42/// with helper functions for Affine dialect ops.
44public:
46
47 /// Creates an affine constraint system from an IntegerSet. Returns failure
48 /// if `set` is semi-affine, as flattening is not implemented for those.
49 static FailureOr<FlatAffineValueConstraints>
50 create(IntegerSet set, ValueRange operands = {});
51
52 /// Return the kind of this object.
53 Kind getKind() const override { return Kind::FlatAffineValueConstraints; }
54
55 static bool classof(const IntegerRelation *cst) {
56 return cst->getKind() >= Kind::FlatAffineValueConstraints &&
57 cst->getKind() <= Kind::FlatAffineRelation;
58 }
59
60 /// Adds constraints (lower and upper bounds) for the specified 'affine.for'
61 /// operation's Value using IR information stored in its bound maps. The
62 /// right variable is first looked up using `forOp`'s Value. Asserts if the
63 /// Value corresponding to the 'affine.for' operation isn't found in the
64 /// constraint system. Returns failure for the yet unimplemented/unsupported
65 /// cases. Any new variables that are found in the bound operands of the
66 /// 'affine.for' operation are added as trailing variables (either
67 /// dimensional or symbolic depending on whether the operand is a valid
68 /// symbol).
69 LogicalResult addAffineForOpDomain(AffineForOp forOp);
70
71 /// Add constraints (lower and upper bounds) for the specified
72 /// 'affine.parallel' operation's Value using IR information stored in its
73 /// bound maps. Returns failure for the yet unimplemented/unsupported cases.
74 /// Asserts if the Value corresponding to the 'affine.parallel' operation
75 /// isn't found in the constraint system.
76 LogicalResult addAffineParallelOpDomain(AffineParallelOp parallelOp);
77
78 /// Adds constraints (lower and upper bounds) for each loop in the loop nest
79 /// described by the bound maps `lbMaps` and `ubMaps` of a computation slice.
80 /// Every pair (`lbMaps[i]`, `ubMaps[i]`) describes the bounds of a loop in
81 /// the nest, sorted outer-to-inner. `operands` contains the bound operands
82 /// for a single bound map. All the bound maps will use the same bound
83 /// operands. Note that some loops described by a computation slice might not
84 /// exist yet in the IR so the Value attached to those dimension variables
85 /// might be empty. For that reason, this method doesn't perform Value
86 /// look-ups to retrieve the dimension variable positions. Instead, it
87 /// assumes the position of the dim variables in the constraint system is
88 /// the same as the position of the loop in the loop nest.
91 ArrayRef<Value> operands);
92
93 /// Adds constraints imposed by the `affine.if` operation. These constraints
94 /// are collected from the IntegerSet attached to the given `affine.if`
95 /// instance argument (`ifOp`). It is asserted that:
96 /// 1) The IntegerSet of the given `affine.if` instance should not contain
97 /// semi-affine expressions,
98 /// 2) The columns of the constraint system created from `ifOp` should match
99 /// the columns in the current one regarding numbers and values.
100 void addAffineIfOpDomain(AffineIfOp ifOp);
101
102 /// Adds a bound for the variable at the specified position with constraints
103 /// being drawn from the specified bound map and operands. In case of an
104 /// EQ bound, the bound map is expected to have exactly one result. In case
105 /// of a LB/UB, the bound map may have more than one result, for each of which
106 /// an inequality is added.
107 LogicalResult addBound(presburger::BoundType type, unsigned pos,
108 AffineMap boundMap, ValueRange operands);
110
111 /// Add the specified values as a dim or symbol var depending on its nature,
112 /// if it already doesn't exist in the system. `val` has to be either a
113 /// terminal symbol or a loop IV, i.e., it cannot be the result of an
114 /// affine.apply of any symbols or loop IVs. Return failure if the addition
115 /// wasn't possible due to the above conditions not being met. This method can
116 /// also fail if the addition of the domain of an affine IV fails. The
117 /// variable is added to the end of the existing dims or symbols. Additional
118 /// information on the variable is extracted from the IR and added to the
119 /// constraint system.
120 LogicalResult addInductionVarOrTerminalSymbol(Value val);
121
122 /// Adds slice lower bounds represented by lower bounds in `lbMaps` and upper
123 /// bounds in `ubMaps` to each variable in the constraint system which has
124 /// a value in `values`. Note that both lower/upper bounds share the same
125 /// operand list `operands`.
126 /// This function assumes `values.size` == `lbMaps.size` == `ubMaps.size`.
127 /// Note that both lower/upper bounds use operands from `operands`.
128 LogicalResult addSliceBounds(ArrayRef<Value> values,
129 ArrayRef<AffineMap> lbMaps,
130 ArrayRef<AffineMap> ubMaps,
131 ArrayRef<Value> operands);
132
133 /// Changes all symbol variables which are loop IVs to dim variables.
135
136 /// Returns the bound for the variable at `pos` from the inequality at
137 /// `ineqPos` as a 1-d affine value map (affine map + operands). The returned
138 /// affine value map can either be a lower bound or an upper bound depending
139 /// on the sign of atIneq(ineqPos, pos). Asserts if the row at `ineqPos` does
140 /// not involve the `pos`th variable.
141 void getIneqAsAffineValueMap(unsigned pos, unsigned ineqPos,
142 AffineValueMap &vmap,
143 MLIRContext *context) const;
144
145 /// Composes the affine value map with this FlatAffineValueConstrains, adding
146 /// the results of the map as dimensions at the front
147 /// [0, vMap->getNumResults()) and with the dimensions set to the equalities
148 /// specified by the value map.
149 ///
150 /// Returns failure if the composition fails (when vMap is a semi-affine map).
151 /// The vMap's operand Value's are used to look up the right positions in
152 /// the FlatAffineValueConstraints with which to associate. Every operand of
153 /// vMap should have a matching dim/symbol column in this constraint system
154 /// (with the same associated Value).
155 LogicalResult composeMap(const AffineValueMap *vMap);
156};
157
158/// A FlatAffineRelation represents a set of ordered pairs (domain -> range)
159/// where "domain" and "range" are tuples of variables. The relation is
160/// represented as a FlatAffineValueConstraints with separation of dimension
161/// variables into domain and range. The variables are stored as:
162/// [domainVars, rangeVars, symbolVars, localVars, constant].
163///
164/// Deprecated: use IntegerRelation and store SSA Values in the PresburgerSpace
165/// of the relation using PresburgerSpace::identifiers. Note that
166/// FlatAffineRelation::numDomainDims and FlatAffineRelation::numRangeDims are
167/// independent of numDomain and numRange of the relation's space. In
168/// particular, operations such as FlatAffineRelation::compose do not ensure
169/// consistency between numDomainDims/numRangeDims and numDomain/numRange which
170/// may lead to unexpected behaviour.
172public:
173 FlatAffineRelation(unsigned numReservedInequalities,
174 unsigned numReservedEqualities, unsigned numReservedCols,
175 unsigned numDomainDims, unsigned numRangeDims,
176 unsigned numSymbols, unsigned numLocals,
177 ArrayRef<std::optional<Value>> valArgs = {})
179 numReservedInequalities, numReservedEqualities, numReservedCols,
180 numDomainDims + numRangeDims, numSymbols, numLocals, valArgs),
182
184 unsigned numSymbols = 0, unsigned numLocals = 0)
186 numLocals),
188
193
198
199 /// Return the kind of this object.
200 Kind getKind() const override { return Kind::FlatAffineRelation; }
201
202 static bool classof(const IntegerRelation *cst) {
203 return cst->getKind() == Kind::FlatAffineRelation;
204 }
205
206 /// Returns a set corresponding to the domain/range of the affine relation.
209
210 /// Returns the number of variables corresponding to domain/range of
211 /// relation.
212 inline unsigned getNumDomainDims() const { return numDomainDims; }
213 inline unsigned getNumRangeDims() const { return numRangeDims; }
214
215 /// Given affine relation `other: (domainOther -> rangeOther)`, this operation
216 /// takes the composition of `other` on `this: (domainThis -> rangeThis)`.
217 /// The resulting relation represents tuples of the form: `domainOther ->
218 /// rangeThis`.
219 void compose(const FlatAffineRelation &other);
220
221 /// Swap domain and range of the relation.
222 /// `(domain -> range)` is converted to `(range -> domain)`.
223 void inverse();
224
225 /// Insert `num` variables of the specified kind after the `pos` variable
226 /// of that kind. The coefficient columns corresponding to the added
227 /// variables are initialized to zero.
228 void insertDomainVar(unsigned pos, unsigned num = 1);
229 void insertRangeVar(unsigned pos, unsigned num = 1);
230
231 /// Append `num` variables of the specified kind after the last variable
232 /// of that kind. The coefficient columns corresponding to the added
233 /// variables are initialized to zero.
234 void appendDomainVar(unsigned num = 1);
235 void appendRangeVar(unsigned num = 1);
236
237 /// Removes variables in the column range [varStart, varLimit), and copies any
238 /// remaining valid data into place, updates member variables, and resizes
239 /// arrays as needed.
240 void removeVarRange(VarKind kind, unsigned varStart,
241 unsigned varLimit) override;
242 using IntegerRelation::removeVarRange;
243
244protected:
245 // Number of dimension variables corresponding to domain variables.
247
248 // Number of dimension variables corresponding to range variables.
249 unsigned numRangeDims;
250};
251
252/// Builds a relation from the given AffineMap/AffineValueMap `map`, containing
253/// all pairs of the form `operands -> result` that satisfy `map`. `rel` is set
254/// to the relation built. For example, give the AffineMap:
255///
256/// (d0, d1)[s0] -> (d0 + s0, d0 - s0)
257///
258/// the resulting relation formed is:
259///
260/// (d0, d1) -> (r1, r2)
261/// [d0 d1 r1 r2 s0 const]
262/// 1 0 -1 0 1 0 = 0
263/// 0 1 0 -1 -1 0 = 0
264///
265/// For AffineValueMap, the domain and symbols have Value set corresponding to
266/// the Value in `map`. Returns failure if the AffineMap could not be flattened
267/// (i.e., semi-affine is not yet handled).
268LogicalResult getRelationFromMap(AffineMap &map,
270LogicalResult getRelationFromMap(const AffineValueMap &map,
272
273} // namespace affine
274} // namespace mlir
275
276#endif // MLIR_DIALECT_AFFINE_ANALYSIS_AFFINESTRUCTURES_H
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
void addBound(presburger::BoundType type, Value val, int64_t value)
Adds a constant bound for the variable associated with the given Value.
FlatLinearValueConstraints(unsigned numReservedInequalities, unsigned numReservedEqualities, unsigned numReservedCols, unsigned numDims, unsigned numSymbols, unsigned numLocals, ArrayRef< std::optional< Value > > valArgs)
Constructs a constraint system reserving memory for the specified number of constraints and variables...
An integer set representing a conjunction of one or more affine equalities and inequalities.
Definition IntegerSet.h:44
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:63
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:389
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
An AffineValueMap is an affine map plus its ML value operands and results for analysis purposes.
A FlatAffineRelation represents a set of ordered pairs (domain -> range) where "domain" and "range" a...
FlatAffineRelation(unsigned numReservedInequalities, unsigned numReservedEqualities, unsigned numReservedCols, unsigned numDomainDims, unsigned numRangeDims, unsigned numSymbols, unsigned numLocals, ArrayRef< std::optional< Value > > valArgs={})
static bool classof(const IntegerRelation *cst)
void appendDomainVar(unsigned num=1)
Append num variables of the specified kind after the last variable of that kind.
void compose(const FlatAffineRelation &other)
Given affine relation other: (domainOther -> rangeOther), this operation takes the composition of oth...
unsigned getNumDomainDims() const
Returns the number of variables corresponding to domain/range of relation.
void inverse()
Swap domain and range of the relation.
FlatAffineValueConstraints getDomainSet() const
Returns a set corresponding to the domain/range of the affine relation.
FlatAffineRelation(unsigned numDomainDims=0, unsigned numRangeDims=0, unsigned numSymbols=0, unsigned numLocals=0)
Kind getKind() const override
Return the kind of this object.
void removeVarRange(VarKind kind, unsigned varStart, unsigned varLimit) override
Removes variables in the column range [varStart, varLimit), and copies any remaining valid data into ...
FlatAffineValueConstraints getRangeSet() const
void insertRangeVar(unsigned pos, unsigned num=1)
FlatAffineRelation(unsigned numDomainDims, unsigned numRangeDims, FlatAffineValueConstraints &fac)
FlatAffineRelation(unsigned numDomainDims, unsigned numRangeDims, IntegerPolyhedron &fac)
void insertDomainVar(unsigned pos, unsigned num=1)
Insert num variables of the specified kind after the pos variable of that kind.
FlatAffineValueConstraints is an extension of FlatLinearValueConstraints with helper functions for Af...
LogicalResult addBound(presburger::BoundType type, unsigned pos, AffineMap boundMap, ValueRange operands)
Adds a bound for the variable at the specified position with constraints being drawn from the specifi...
void addAffineIfOpDomain(AffineIfOp ifOp)
Adds constraints imposed by the affine.if operation.
void convertLoopIVSymbolsToDims()
Changes all symbol variables which are loop IVs to dim variables.
LogicalResult addDomainFromSliceMaps(ArrayRef< AffineMap > lbMaps, ArrayRef< AffineMap > ubMaps, ArrayRef< Value > operands)
Adds constraints (lower and upper bounds) for each loop in the loop nest described by the bound maps ...
LogicalResult addAffineParallelOpDomain(AffineParallelOp parallelOp)
Add constraints (lower and upper bounds) for the specified 'affine.parallel' operation's Value using ...
Kind getKind() const override
Return the kind of this object.
LogicalResult addAffineForOpDomain(AffineForOp forOp)
Adds constraints (lower and upper bounds) for the specified 'affine.for' operation's Value using IR i...
static FailureOr< FlatAffineValueConstraints > create(IntegerSet set, ValueRange operands={})
Creates an affine constraint system from an IntegerSet.
FlatLinearValueConstraints(unsigned numReservedInequalities, unsigned numReservedEqualities, unsigned numReservedCols, unsigned numDims, unsigned numSymbols, unsigned numLocals, ArrayRef< std::optional< Value > > valArgs)
Constructs a constraint system reserving memory for the specified number of constraints and variables...
void getIneqAsAffineValueMap(unsigned pos, unsigned ineqPos, AffineValueMap &vmap, MLIRContext *context) const
Returns the bound for the variable at pos from the inequality at ineqPos as a 1-d affine value map (a...
LogicalResult addSliceBounds(ArrayRef< Value > values, ArrayRef< AffineMap > lbMaps, ArrayRef< AffineMap > ubMaps, ArrayRef< Value > operands)
Adds slice lower bounds represented by lower bounds in lbMaps and upper bounds in ubMaps to each vari...
LogicalResult composeMap(const AffineValueMap *vMap)
Composes the affine value map with this FlatAffineValueConstrains, adding the results of the map as d...
LogicalResult addInductionVarOrTerminalSymbol(Value val)
Add the specified values as a dim or symbol var depending on its nature, if it already doesn't exist ...
static bool classof(const IntegerRelation *cst)
IntegerPolyhedron(unsigned numReservedInequalities, unsigned numReservedEqualities, unsigned numReservedCols, const PresburgerSpace &space)
Constructs a set reserving memory for the specified number of constraints and variables.
An IntegerRelation represents the set of points from a PresburgerSpace that satisfy a list of affine ...
Kind
All derived classes of IntegerRelation.
IntegerRelation(unsigned numReservedInequalities, unsigned numReservedEqualities, unsigned numReservedCols, const PresburgerSpace &space)
Constructs a relation reserving memory for the specified number of constraints and variables.
This class represents a multi-affine function with the domain as Z^d, where d is the number of domain...
LogicalResult getRelationFromMap(AffineMap &map, presburger::IntegerRelation &rel)
Builds a relation from the given AffineMap/AffineValueMap map, containing all pairs of the form opera...
BoundType
The type of bound: equal, lower bound or upper bound.
Include the generated interface declarations.
A mutable affine map. Its affine expressions are however unique.
Definition AffineMap.h:430