blob: af089e6ee9a39c89656c61e5ec016a0970e97b62 [file] [log] [blame]
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001//===- Builders.h - Helpers for constructing MLIR Classes -------*- C++ -*-===//
2//
3// Copyright 2019 The MLIR Authors.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16// =============================================================================
17
18#ifndef MLIR_IR_BUILDERS_H
19#define MLIR_IR_BUILDERS_H
20
Uday Bondhugula15984952018-08-01 22:36:12 -070021#include "mlir/IR/Attributes.h"
Chris Lattner158e0a3e2018-07-08 20:51:38 -070022#include "mlir/IR/CFGFunction.h"
Tatiana Shpeisman565b9642018-07-16 11:47:09 -070023#include "mlir/IR/MLFunction.h"
24#include "mlir/IR/Statements.h"
Chris Lattner158e0a3e2018-07-08 20:51:38 -070025
26namespace mlir {
27class MLIRContext;
28class Module;
29class Type;
30class PrimitiveType;
31class IntegerType;
32class FunctionType;
33class VectorType;
34class RankedTensorType;
35class UnrankedTensorType;
Chris Lattner1ac20cb2018-07-10 10:59:53 -070036class BoolAttr;
37class IntegerAttr;
38class FloatAttr;
39class StringAttr;
James Molloyf0d2f442018-08-03 01:54:46 -070040class TypeAttr;
Chris Lattner1ac20cb2018-07-10 10:59:53 -070041class ArrayAttr;
MLIR Teamb61885d2018-07-18 16:29:21 -070042class AffineMapAttr;
Chris Lattner1ac20cb2018-07-10 10:59:53 -070043class AffineMap;
44class AffineExpr;
45class AffineConstantExpr;
46class AffineDimExpr;
47class AffineSymbolExpr;
Chris Lattner158e0a3e2018-07-08 20:51:38 -070048
49/// This class is a general helper class for creating context-global objects
50/// like types, attributes, and affine expressions.
51class Builder {
52public:
53 explicit Builder(MLIRContext *context) : context(context) {}
54 explicit Builder(Module *module);
55
56 MLIRContext *getContext() const { return context; }
57
Chris Lattner1ac20cb2018-07-10 10:59:53 -070058 Identifier getIdentifier(StringRef str);
59 Module *createModule();
60
Chris Lattner158e0a3e2018-07-08 20:51:38 -070061 // Types.
Chris Lattnerc3251192018-07-27 13:09:58 -070062 FloatType *getBF16Type();
63 FloatType *getF16Type();
64 FloatType *getF32Type();
65 FloatType *getF64Type();
66
67 OtherType *getAffineIntType();
68 OtherType *getTFControlType();
James Molloy72b0cbe2018-08-01 12:55:27 -070069 OtherType *getTFStringType();
Chris Lattner158e0a3e2018-07-08 20:51:38 -070070 IntegerType *getIntegerType(unsigned width);
71 FunctionType *getFunctionType(ArrayRef<Type *> inputs,
72 ArrayRef<Type *> results);
73 VectorType *getVectorType(ArrayRef<unsigned> shape, Type *elementType);
74 RankedTensorType *getTensorType(ArrayRef<int> shape, Type *elementType);
75 UnrankedTensorType *getTensorType(Type *elementType);
76
Chris Lattner1ac20cb2018-07-10 10:59:53 -070077 // Attributes.
78 BoolAttr *getBoolAttr(bool value);
79 IntegerAttr *getIntegerAttr(int64_t value);
80 FloatAttr *getFloatAttr(double value);
81 StringAttr *getStringAttr(StringRef bytes);
82 ArrayAttr *getArrayAttr(ArrayRef<Attribute *> value);
MLIR Teamb61885d2018-07-18 16:29:21 -070083 AffineMapAttr *getAffineMapAttr(AffineMap *value);
James Molloyf0d2f442018-08-03 01:54:46 -070084 TypeAttr *getTypeAttr(Type *type);
Chris Lattner1ac20cb2018-07-10 10:59:53 -070085
86 // Affine Expressions and Affine Map.
87 AffineMap *getAffineMap(unsigned dimCount, unsigned symbolCount,
Uday Bondhugula0115dbb2018-07-11 21:31:07 -070088 ArrayRef<AffineExpr *> results,
89 ArrayRef<AffineExpr *> rangeSizes);
Chris Lattner1ac20cb2018-07-10 10:59:53 -070090 AffineDimExpr *getDimExpr(unsigned position);
91 AffineSymbolExpr *getSymbolExpr(unsigned position);
92 AffineConstantExpr *getConstantExpr(int64_t constant);
93 AffineExpr *getAddExpr(AffineExpr *lhs, AffineExpr *rhs);
94 AffineExpr *getSubExpr(AffineExpr *lhs, AffineExpr *rhs);
95 AffineExpr *getMulExpr(AffineExpr *lhs, AffineExpr *rhs);
96 AffineExpr *getModExpr(AffineExpr *lhs, AffineExpr *rhs);
97 AffineExpr *getFloorDivExpr(AffineExpr *lhs, AffineExpr *rhs);
98 AffineExpr *getCeilDivExpr(AffineExpr *lhs, AffineExpr *rhs);
99
Uday Bondhugulabc535622018-08-07 14:24:38 -0700100 // Integer set.
101 IntegerSet *getIntegerSet(unsigned dimCount, unsigned symbolCount,
102 ArrayRef<AffineExpr *> constraints,
103 ArrayRef<bool> isEq);
104
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700105 // TODO: Helpers for affine map/exprs, etc.
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700106protected:
107 MLIRContext *context;
108};
109
110/// This class helps build a CFGFunction. Instructions that are created are
111/// automatically inserted at an insertion point or added to the current basic
112/// block.
113class CFGFuncBuilder : public Builder {
114public:
Chris Lattner8174f3a2018-07-29 16:45:23 -0700115 CFGFuncBuilder(BasicBlock *block, BasicBlock::iterator insertPoint)
116 : Builder(block->getFunction()->getContext()),
117 function(block->getFunction()) {
118 setInsertionPoint(block, insertPoint);
119 }
120
121 CFGFuncBuilder(OperationInst *insertBefore)
122 : CFGFuncBuilder(insertBefore->getBlock(),
123 BasicBlock::iterator(insertBefore)) {}
124
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700125 CFGFuncBuilder(BasicBlock *block)
126 : Builder(block->getFunction()->getContext()),
127 function(block->getFunction()) {
128 setInsertionPoint(block);
129 }
Chris Lattner8174f3a2018-07-29 16:45:23 -0700130
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700131 CFGFuncBuilder(CFGFunction *function)
132 : Builder(function->getContext()), function(function) {}
133
134 /// Reset the insertion point to no location. Creating an operation without a
135 /// set insertion point is an error, but this can still be useful when the
136 /// current insertion point a builder refers to is being removed.
137 void clearInsertionPoint() {
138 this->block = nullptr;
139 insertPoint = BasicBlock::iterator();
140 }
141
Chris Lattner8174f3a2018-07-29 16:45:23 -0700142 /// Set the insertion point to the specified location.
143 void setInsertionPoint(BasicBlock *block, BasicBlock::iterator insertPoint) {
144 assert(block->getFunction() == function &&
145 "can't move to a different function");
146 this->block = block;
147 this->insertPoint = insertPoint;
148 }
149
150 /// Set the insertion point to the specified operation.
151 void setInsertionPoint(OperationInst *inst) {
152 setInsertionPoint(inst->getBlock(), BasicBlock::iterator(inst));
153 }
154
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700155 /// Set the insertion point to the end of the specified block.
156 void setInsertionPoint(BasicBlock *block) {
Chris Lattner8174f3a2018-07-29 16:45:23 -0700157 setInsertionPoint(block, block->end());
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700158 }
159
Chris Lattner992a1272018-08-07 12:02:37 -0700160 void insert(OperationInst *opInst) {
161 block->getOperations().insert(insertPoint, opInst);
162 }
163
Tatiana Shpeisman6708b452018-07-24 10:15:13 -0700164 // Add new basic block and set the insertion point to the end of it.
165 BasicBlock *createBlock();
166
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700167 /// Create an operation given the fields represented as an OperationState.
168 OperationInst *createOperation(const OperationState &state);
169
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700170 /// Create operation of specific op type at the current insertion point.
171 template <typename OpTy, typename... Args>
172 OpPointer<OpTy> create(Args... args) {
Chris Lattner992a1272018-08-07 12:02:37 -0700173 auto *inst = createOperation(OpTy::build(this, args...));
174 auto result = inst->template getAs<OpTy>();
175 assert(result && "Builder didn't return the right type");
176 return result;
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700177 }
178
Uday Bondhugula15984952018-08-01 22:36:12 -0700179 OperationInst *cloneOperation(const OperationInst &srcOpInst) {
180 auto *op = srcOpInst.clone();
Chris Lattner992a1272018-08-07 12:02:37 -0700181 insert(op);
Uday Bondhugula15984952018-08-01 22:36:12 -0700182 return op;
183 }
184
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700185 // Terminators.
186
Chris Lattner40746442018-07-21 14:32:09 -0700187 ReturnInst *createReturnInst(ArrayRef<CFGValue *> operands) {
188 return insertTerminator(ReturnInst::create(operands));
189 }
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700190
191 BranchInst *createBranchInst(BasicBlock *dest) {
Chris Lattner40746442018-07-21 14:32:09 -0700192 return insertTerminator(BranchInst::create(dest));
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700193 }
194
James Molloy4f788372018-07-24 15:01:27 -0700195 CondBranchInst *createCondBranchInst(CFGValue *condition,
196 BasicBlock *trueDest,
197 BasicBlock *falseDest) {
198 return insertTerminator(
199 CondBranchInst::create(condition, trueDest, falseDest));
200 }
201
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700202private:
203 template <typename T>
204 T *insertTerminator(T *term) {
205 block->setTerminator(term);
206 return term;
207 }
208
209 CFGFunction *function;
210 BasicBlock *block = nullptr;
211 BasicBlock::iterator insertPoint;
212};
213
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700214/// This class helps build an MLFunction. Statements that are created are
215/// automatically inserted at an insertion point or added to the current
216/// statement block.
217class MLFuncBuilder : public Builder {
218public:
Chris Lattnere787b322018-08-08 11:14:57 -0700219 /// Create ML function builder and set insertion point to the given statement,
220 /// which will cause subsequent insertions to go right before it.
221 MLFuncBuilder(Statement *stmt)
222 // TODO: Eliminate findFunction from this.
223 : Builder(stmt->findFunction()->getContext()) {
224 setInsertionPoint(stmt);
225 }
226
227 MLFuncBuilder(StmtBlock *block, StmtBlock::iterator insertPoint)
228 // TODO: Eliminate findFunction from this.
Tatiana Shpeismand880b352018-07-31 23:14:16 -0700229 : Builder(block->findFunction()->getContext()) {
Chris Lattnere787b322018-08-08 11:14:57 -0700230 setInsertionPoint(block, insertPoint);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700231 }
232
233 /// Reset the insertion point to no location. Creating an operation without a
234 /// set insertion point is an error, but this can still be useful when the
235 /// current insertion point a builder refers to is being removed.
236 void clearInsertionPoint() {
237 this->block = nullptr;
238 insertPoint = StmtBlock::iterator();
239 }
240
Tatiana Shpeismand880b352018-07-31 23:14:16 -0700241 /// Set the insertion point to the specified location.
242 /// Unlike CFGFuncBuilder, MLFuncBuilder allows to set insertion
243 /// point to a different function.
244 void setInsertionPoint(StmtBlock *block, StmtBlock::iterator insertPoint) {
245 // TODO: check that insertPoint is in this rather than some other block.
246 this->block = block;
247 this->insertPoint = insertPoint;
248 }
249
250 /// Set the insertion point to the specified operation.
Chris Lattnere787b322018-08-08 11:14:57 -0700251 void setInsertionPoint(Statement *stmt) {
Tatiana Shpeismand880b352018-07-31 23:14:16 -0700252 setInsertionPoint(stmt->getBlock(), StmtBlock::iterator(stmt));
253 }
254
Chris Lattnere787b322018-08-08 11:14:57 -0700255 /// Set the insertion point to the start of the specified block.
256 void setInsertionPointToStart(StmtBlock *block) {
Uday Bondhugula15984952018-08-01 22:36:12 -0700257 this->block = block;
258 insertPoint = block->begin();
259 }
260
Chris Lattnere787b322018-08-08 11:14:57 -0700261 /// Set the insertion point to the end of the specified block.
262 void setInsertionPointToEnd(StmtBlock *block) {
263 this->block = block;
264 insertPoint = block->end();
265 }
266
Uday Bondhugula84b80952018-08-03 13:22:26 -0700267 /// Get the current insertion point of the builder.
268 StmtBlock::iterator getInsertionPoint() const { return insertPoint; }
269
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700270 /// Create an operation given the fields represented as an OperationState.
271 OperationStmt *createOperation(const OperationState &state);
272
Chris Lattner992a1272018-08-07 12:02:37 -0700273 /// Create operation of specific op type at the current insertion point.
Jacques Pienaarac86d102018-08-03 08:16:37 -0700274 template <typename OpTy, typename... Args>
275 OpPointer<OpTy> create(Args... args) {
Chris Lattner992a1272018-08-07 12:02:37 -0700276 auto stmt = createOperation(OpTy::build(this, args...));
277 auto result = stmt->template getAs<OpTy>();
278 assert(result && "Builder didn't return the right type");
279 return result;
Jacques Pienaarac86d102018-08-03 08:16:37 -0700280 }
281
Chris Lattnere787b322018-08-08 11:14:57 -0700282 /// Create a deep copy of the specified statement, remapping any operands that
283 /// use values outside of the statement using the map that is provided (
284 /// leaving them alone if no entry is present). Replaces references to cloned
285 /// sub-statements to the corresponding statement that is copied, and adds
286 /// those mappings to the map.
287 Statement *clone(const Statement &stmt,
288 OperationStmt::OperandMapTy &operandMapping) {
289 Statement *cloneStmt = stmt.clone(operandMapping, getContext());
Uday Bondhugula134154e2018-08-06 18:40:34 -0700290 block->getStatements().insert(insertPoint, cloneStmt);
291 return cloneStmt;
Uday Bondhugula84b80952018-08-03 13:22:26 -0700292 }
293
Chris Lattner1604e472018-07-23 08:42:19 -0700294 // Creates for statement. When step is not specified, it is set to 1.
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -0700295 ForStmt *createFor(AffineConstantExpr *lowerBound,
296 AffineConstantExpr *upperBound,
297 AffineConstantExpr *step = nullptr);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700298
Uday Bondhugulabc535622018-08-07 14:24:38 -0700299 IfStmt *createIf(IntegerSet *condition) {
300 auto *stmt = new IfStmt(condition);
Tatiana Shpeismand880b352018-07-31 23:14:16 -0700301 block->getStatements().insert(insertPoint, stmt);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700302 return stmt;
303 }
304
305private:
306 StmtBlock *block = nullptr;
307 StmtBlock::iterator insertPoint;
308};
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700309
310} // namespace mlir
311
312#endif