blob: f6cd24512da8b7d883d3a373eee001134e2f32d4 [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
21#include "mlir/IR/CFGFunction.h"
Tatiana Shpeisman565b9642018-07-16 11:47:09 -070022#include "mlir/IR/MLFunction.h"
23#include "mlir/IR/Statements.h"
Chris Lattner158e0a3e2018-07-08 20:51:38 -070024
25namespace mlir {
26class MLIRContext;
27class Module;
Chris Lattnerfc647d52018-08-27 21:05:16 -070028class UnknownLoc;
29class UniquedFilename;
30class FileLineColLoc;
Chris Lattner158e0a3e2018-07-08 20:51:38 -070031class Type;
32class PrimitiveType;
33class IntegerType;
34class FunctionType;
35class VectorType;
36class RankedTensorType;
37class UnrankedTensorType;
Chris Lattner1ac20cb2018-07-10 10:59:53 -070038class BoolAttr;
39class IntegerAttr;
40class FloatAttr;
41class StringAttr;
James Molloyf0d2f442018-08-03 01:54:46 -070042class TypeAttr;
Chris Lattner1ac20cb2018-07-10 10:59:53 -070043class ArrayAttr;
Chris Lattner4613d9e2018-08-19 21:17:22 -070044class FunctionAttr;
MLIR Teamb61885d2018-07-18 16:29:21 -070045class AffineMapAttr;
Chris Lattner1ac20cb2018-07-10 10:59:53 -070046class AffineMap;
47class AffineExpr;
48class AffineConstantExpr;
49class AffineDimExpr;
50class AffineSymbolExpr;
Chris Lattner158e0a3e2018-07-08 20:51:38 -070051
52/// This class is a general helper class for creating context-global objects
53/// like types, attributes, and affine expressions.
54class Builder {
55public:
56 explicit Builder(MLIRContext *context) : context(context) {}
57 explicit Builder(Module *module);
58
59 MLIRContext *getContext() const { return context; }
60
Chris Lattner1ac20cb2018-07-10 10:59:53 -070061 Identifier getIdentifier(StringRef str);
62 Module *createModule();
63
Chris Lattnerfc647d52018-08-27 21:05:16 -070064 // Locations.
65 UnknownLoc *getUnknownLoc();
66 UniquedFilename getUniquedFilename(StringRef filename);
67 FileLineColLoc *getFileLineColLoc(UniquedFilename filename, unsigned line,
68 unsigned column);
69
Chris Lattner158e0a3e2018-07-08 20:51:38 -070070 // Types.
Chris Lattnerc3251192018-07-27 13:09:58 -070071 FloatType *getBF16Type();
72 FloatType *getF16Type();
73 FloatType *getF32Type();
74 FloatType *getF64Type();
75
76 OtherType *getAffineIntType();
77 OtherType *getTFControlType();
James Molloy72b0cbe2018-08-01 12:55:27 -070078 OtherType *getTFStringType();
Chris Lattner158e0a3e2018-07-08 20:51:38 -070079 IntegerType *getIntegerType(unsigned width);
80 FunctionType *getFunctionType(ArrayRef<Type *> inputs,
81 ArrayRef<Type *> results);
Jacques Pienaarc03c6952018-08-10 11:56:47 -070082 MemRefType *getMemRefType(ArrayRef<int> shape, Type *elementType,
83 ArrayRef<AffineMap *> affineMapComposition = {},
84 unsigned memorySpace = 0);
Chris Lattner158e0a3e2018-07-08 20:51:38 -070085 VectorType *getVectorType(ArrayRef<unsigned> shape, Type *elementType);
86 RankedTensorType *getTensorType(ArrayRef<int> shape, Type *elementType);
87 UnrankedTensorType *getTensorType(Type *elementType);
88
Chris Lattner1ac20cb2018-07-10 10:59:53 -070089 // Attributes.
90 BoolAttr *getBoolAttr(bool value);
91 IntegerAttr *getIntegerAttr(int64_t value);
92 FloatAttr *getFloatAttr(double value);
93 StringAttr *getStringAttr(StringRef bytes);
94 ArrayAttr *getArrayAttr(ArrayRef<Attribute *> value);
MLIR Teamb61885d2018-07-18 16:29:21 -070095 AffineMapAttr *getAffineMapAttr(AffineMap *value);
James Molloyf0d2f442018-08-03 01:54:46 -070096 TypeAttr *getTypeAttr(Type *type);
Chris Lattner1aa46322018-08-21 17:55:22 -070097 FunctionAttr *getFunctionAttr(const Function *value);
Chris Lattner1ac20cb2018-07-10 10:59:53 -070098
99 // Affine Expressions and Affine Map.
100 AffineMap *getAffineMap(unsigned dimCount, unsigned symbolCount,
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700101 ArrayRef<AffineExpr *> results,
102 ArrayRef<AffineExpr *> rangeSizes);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700103 AffineDimExpr *getDimExpr(unsigned position);
104 AffineSymbolExpr *getSymbolExpr(unsigned position);
105 AffineConstantExpr *getConstantExpr(int64_t constant);
106 AffineExpr *getAddExpr(AffineExpr *lhs, AffineExpr *rhs);
107 AffineExpr *getSubExpr(AffineExpr *lhs, AffineExpr *rhs);
108 AffineExpr *getMulExpr(AffineExpr *lhs, AffineExpr *rhs);
109 AffineExpr *getModExpr(AffineExpr *lhs, AffineExpr *rhs);
110 AffineExpr *getFloorDivExpr(AffineExpr *lhs, AffineExpr *rhs);
111 AffineExpr *getCeilDivExpr(AffineExpr *lhs, AffineExpr *rhs);
112
Uday Bondhugulabc535622018-08-07 14:24:38 -0700113 // Integer set.
114 IntegerSet *getIntegerSet(unsigned dimCount, unsigned symbolCount,
115 ArrayRef<AffineExpr *> constraints,
116 ArrayRef<bool> isEq);
117
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700118 // Special cases of affine maps and integer sets
119 // One constant result: () -> (val).
120 AffineMap *getConstantMap(int64_t val);
121 // One dimension id identity map: (i) -> (i).
122 AffineMap *getDimIdentityMap();
123 // One symbol identity map: ()[s] -> (s).
124 AffineMap *getSymbolIdentityMap();
125
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700126 // TODO: Helpers for affine map/exprs, etc.
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700127protected:
128 MLIRContext *context;
129};
130
131/// This class helps build a CFGFunction. Instructions that are created are
132/// automatically inserted at an insertion point or added to the current basic
133/// block.
134class CFGFuncBuilder : public Builder {
135public:
Chris Lattner8174f3a2018-07-29 16:45:23 -0700136 CFGFuncBuilder(BasicBlock *block, BasicBlock::iterator insertPoint)
137 : Builder(block->getFunction()->getContext()),
138 function(block->getFunction()) {
139 setInsertionPoint(block, insertPoint);
140 }
141
142 CFGFuncBuilder(OperationInst *insertBefore)
143 : CFGFuncBuilder(insertBefore->getBlock(),
144 BasicBlock::iterator(insertBefore)) {}
145
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700146 CFGFuncBuilder(BasicBlock *block)
147 : Builder(block->getFunction()->getContext()),
148 function(block->getFunction()) {
149 setInsertionPoint(block);
150 }
Chris Lattner8174f3a2018-07-29 16:45:23 -0700151
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700152 CFGFuncBuilder(CFGFunction *function)
153 : Builder(function->getContext()), function(function) {}
154
155 /// Reset the insertion point to no location. Creating an operation without a
156 /// set insertion point is an error, but this can still be useful when the
157 /// current insertion point a builder refers to is being removed.
158 void clearInsertionPoint() {
159 this->block = nullptr;
160 insertPoint = BasicBlock::iterator();
161 }
162
Chris Lattner8174f3a2018-07-29 16:45:23 -0700163 /// Set the insertion point to the specified location.
164 void setInsertionPoint(BasicBlock *block, BasicBlock::iterator insertPoint) {
165 assert(block->getFunction() == function &&
166 "can't move to a different function");
167 this->block = block;
168 this->insertPoint = insertPoint;
169 }
170
171 /// Set the insertion point to the specified operation.
172 void setInsertionPoint(OperationInst *inst) {
173 setInsertionPoint(inst->getBlock(), BasicBlock::iterator(inst));
174 }
175
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700176 /// Set the insertion point to the end of the specified block.
177 void setInsertionPoint(BasicBlock *block) {
Chris Lattner8174f3a2018-07-29 16:45:23 -0700178 setInsertionPoint(block, block->end());
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700179 }
180
Chris Lattner992a1272018-08-07 12:02:37 -0700181 void insert(OperationInst *opInst) {
182 block->getOperations().insert(insertPoint, opInst);
183 }
184
Chris Lattner8a9310a2018-08-24 21:13:19 -0700185 /// Add new basic block and set the insertion point to the end of it. If an
186 /// 'insertBefore' basic block is passed, the block will be placed before the
187 /// specified block. If not, the block will be appended to the end of the
188 /// current function.
189 BasicBlock *createBlock(BasicBlock *insertBefore = nullptr);
Tatiana Shpeisman6708b452018-07-24 10:15:13 -0700190
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700191 /// Create an operation given the fields represented as an OperationState.
192 OperationInst *createOperation(const OperationState &state);
193
Chris Lattner7879f842018-09-02 22:01:45 -0700194 /// Create operation of specific op type at the current insertion point
195 /// without verifying to see if it is valid.
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700196 template <typename OpTy, typename... Args>
Chris Lattnerfc647d52018-08-27 21:05:16 -0700197 OpPointer<OpTy> create(Location *location, Args... args) {
Chris Lattner1628fa02018-08-23 14:32:25 -0700198 OperationState state(getContext(), location, OpTy::getOperationName());
Chris Lattner1eb77482018-08-22 19:25:49 -0700199 OpTy::build(this, &state, args...);
200 auto *inst = createOperation(state);
Chris Lattner992a1272018-08-07 12:02:37 -0700201 auto result = inst->template getAs<OpTy>();
202 assert(result && "Builder didn't return the right type");
203 return result;
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700204 }
205
Chris Lattner7879f842018-09-02 22:01:45 -0700206 /// Create operation of specific op type at the current insertion point. If
207 /// the result is an invalid op (the verifier hook fails), emit a the
208 /// specified error message and return null.
209 template <typename OpTy, typename... Args>
Chris Lattner015100b2018-09-09 20:40:23 -0700210 OpPointer<OpTy> createChecked(Location *location, Args... args) {
Chris Lattner7879f842018-09-02 22:01:45 -0700211 OperationState state(getContext(), location, OpTy::getOperationName());
212 OpTy::build(this, &state, args...);
213 auto *inst = createOperation(state);
Chris Lattner7879f842018-09-02 22:01:45 -0700214
Chris Lattner015100b2018-09-09 20:40:23 -0700215 // If the OperationInst we produce is valid, return it.
216 if (!OpTy::verifyInvariants(inst)) {
217 auto result = inst->template getAs<OpTy>();
218 assert(result && "Builder didn't return the right type");
Chris Lattner7879f842018-09-02 22:01:45 -0700219 return result;
Chris Lattner015100b2018-09-09 20:40:23 -0700220 }
221
222 // Otherwise, the error message got emitted. Just remove the instruction
223 // we made.
Chris Lattner7879f842018-09-02 22:01:45 -0700224 inst->eraseFromBlock();
225 return OpPointer<OpTy>();
226 }
227
Uday Bondhugula15984952018-08-01 22:36:12 -0700228 OperationInst *cloneOperation(const OperationInst &srcOpInst) {
229 auto *op = srcOpInst.clone();
Chris Lattner992a1272018-08-07 12:02:37 -0700230 insert(op);
Uday Bondhugula15984952018-08-01 22:36:12 -0700231 return op;
232 }
233
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700234 // Terminators.
235
Chris Lattnerfc647d52018-08-27 21:05:16 -0700236 ReturnInst *createReturn(Location *location, ArrayRef<CFGValue *> operands) {
Chris Lattner1628fa02018-08-23 14:32:25 -0700237 return insertTerminator(ReturnInst::create(location, operands));
Chris Lattner40746442018-07-21 14:32:09 -0700238 }
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700239
Chris Lattnerfc647d52018-08-27 21:05:16 -0700240 BranchInst *createBranch(Location *location, BasicBlock *dest,
Chris Lattner8a9310a2018-08-24 21:13:19 -0700241 ArrayRef<CFGValue *> operands = {}) {
242 return insertTerminator(BranchInst::create(location, dest, operands));
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700243 }
244
Chris Lattnerfc647d52018-08-27 21:05:16 -0700245 CondBranchInst *createCondBranch(Location *location, CFGValue *condition,
Chris Lattner091a6b52018-08-23 14:58:27 -0700246 BasicBlock *trueDest,
247 BasicBlock *falseDest) {
James Molloy4f788372018-07-24 15:01:27 -0700248 return insertTerminator(
Chris Lattner1628fa02018-08-23 14:32:25 -0700249 CondBranchInst::create(location, condition, trueDest, falseDest));
James Molloy4f788372018-07-24 15:01:27 -0700250 }
251
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700252private:
253 template <typename T>
254 T *insertTerminator(T *term) {
255 block->setTerminator(term);
256 return term;
257 }
258
259 CFGFunction *function;
260 BasicBlock *block = nullptr;
261 BasicBlock::iterator insertPoint;
262};
263
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700264/// This class helps build an MLFunction. Statements that are created are
265/// automatically inserted at an insertion point or added to the current
266/// statement block.
267class MLFuncBuilder : public Builder {
268public:
Chris Lattnere787b322018-08-08 11:14:57 -0700269 /// Create ML function builder and set insertion point to the given statement,
270 /// which will cause subsequent insertions to go right before it.
271 MLFuncBuilder(Statement *stmt)
272 // TODO: Eliminate findFunction from this.
273 : Builder(stmt->findFunction()->getContext()) {
274 setInsertionPoint(stmt);
275 }
276
277 MLFuncBuilder(StmtBlock *block, StmtBlock::iterator insertPoint)
278 // TODO: Eliminate findFunction from this.
Tatiana Shpeismand880b352018-07-31 23:14:16 -0700279 : Builder(block->findFunction()->getContext()) {
Chris Lattnere787b322018-08-08 11:14:57 -0700280 setInsertionPoint(block, insertPoint);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700281 }
282
283 /// Reset the insertion point to no location. Creating an operation without a
284 /// set insertion point is an error, but this can still be useful when the
285 /// current insertion point a builder refers to is being removed.
286 void clearInsertionPoint() {
287 this->block = nullptr;
288 insertPoint = StmtBlock::iterator();
289 }
290
Tatiana Shpeismand880b352018-07-31 23:14:16 -0700291 /// Set the insertion point to the specified location.
292 /// Unlike CFGFuncBuilder, MLFuncBuilder allows to set insertion
293 /// point to a different function.
294 void setInsertionPoint(StmtBlock *block, StmtBlock::iterator insertPoint) {
295 // TODO: check that insertPoint is in this rather than some other block.
296 this->block = block;
297 this->insertPoint = insertPoint;
298 }
299
Uday Bondhugula67701712018-08-21 16:01:23 -0700300 /// Set the insertion point to the specified operation, which will cause
301 /// subsequent insertions to go right before it.
Chris Lattnere787b322018-08-08 11:14:57 -0700302 void setInsertionPoint(Statement *stmt) {
Tatiana Shpeismand880b352018-07-31 23:14:16 -0700303 setInsertionPoint(stmt->getBlock(), StmtBlock::iterator(stmt));
304 }
305
Chris Lattnere787b322018-08-08 11:14:57 -0700306 /// Set the insertion point to the start of the specified block.
307 void setInsertionPointToStart(StmtBlock *block) {
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700308 setInsertionPoint(block, block->begin());
Uday Bondhugula15984952018-08-01 22:36:12 -0700309 }
310
Chris Lattnere787b322018-08-08 11:14:57 -0700311 /// Set the insertion point to the end of the specified block.
312 void setInsertionPointToEnd(StmtBlock *block) {
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700313 setInsertionPoint(block, block->end());
Chris Lattnere787b322018-08-08 11:14:57 -0700314 }
315
Uday Bondhugula84b80952018-08-03 13:22:26 -0700316 /// Get the current insertion point of the builder.
317 StmtBlock::iterator getInsertionPoint() const { return insertPoint; }
318
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700319 /// Create an operation given the fields represented as an OperationState.
320 OperationStmt *createOperation(const OperationState &state);
321
Chris Lattner992a1272018-08-07 12:02:37 -0700322 /// Create operation of specific op type at the current insertion point.
Jacques Pienaarac86d102018-08-03 08:16:37 -0700323 template <typename OpTy, typename... Args>
Chris Lattnerfc647d52018-08-27 21:05:16 -0700324 OpPointer<OpTy> create(Location *location, Args... args) {
Chris Lattner1628fa02018-08-23 14:32:25 -0700325 OperationState state(getContext(), location, OpTy::getOperationName());
Chris Lattner1eb77482018-08-22 19:25:49 -0700326 OpTy::build(this, &state, args...);
327 auto *stmt = createOperation(state);
Chris Lattner992a1272018-08-07 12:02:37 -0700328 auto result = stmt->template getAs<OpTy>();
329 assert(result && "Builder didn't return the right type");
330 return result;
Jacques Pienaarac86d102018-08-03 08:16:37 -0700331 }
332
Chris Lattner7879f842018-09-02 22:01:45 -0700333 /// Create operation of specific op type at the current insertion point. If
334 /// the result is an invalid op (the verifier hook fails), emit an error and
335 /// return null.
336 template <typename OpTy, typename... Args>
Chris Lattner015100b2018-09-09 20:40:23 -0700337 OpPointer<OpTy> createChecked(Location *location, Args... args) {
Chris Lattner7879f842018-09-02 22:01:45 -0700338 OperationState state(getContext(), location, OpTy::getOperationName());
339 OpTy::build(this, &state, args...);
340 auto *stmt = createOperation(state);
Chris Lattner7879f842018-09-02 22:01:45 -0700341
Chris Lattner015100b2018-09-09 20:40:23 -0700342 // If the OperationStmt we produce is valid, return it.
343 if (!OpTy::verifyInvariants(stmt)) {
344 auto result = stmt->template getAs<OpTy>();
345 assert(result && "Builder didn't return the right type");
Chris Lattner7879f842018-09-02 22:01:45 -0700346 return result;
Chris Lattner015100b2018-09-09 20:40:23 -0700347 }
348
349 // Otherwise, the error message got emitted. Just remove the statement
350 // we made.
Chris Lattner7879f842018-09-02 22:01:45 -0700351 stmt->eraseFromBlock();
352 return OpPointer<OpTy>();
353 }
354
Chris Lattnere787b322018-08-08 11:14:57 -0700355 /// Create a deep copy of the specified statement, remapping any operands that
356 /// use values outside of the statement using the map that is provided (
357 /// leaving them alone if no entry is present). Replaces references to cloned
358 /// sub-statements to the corresponding statement that is copied, and adds
359 /// those mappings to the map.
360 Statement *clone(const Statement &stmt,
361 OperationStmt::OperandMapTy &operandMapping) {
362 Statement *cloneStmt = stmt.clone(operandMapping, getContext());
Uday Bondhugula134154e2018-08-06 18:40:34 -0700363 block->getStatements().insert(insertPoint, cloneStmt);
364 return cloneStmt;
Uday Bondhugula84b80952018-08-03 13:22:26 -0700365 }
366
Tatiana Shpeismanc6aa35b2018-08-28 15:26:20 -0700367 // Create for statement. When step is not specified, it is set to 1.
Chris Lattnerfc647d52018-08-27 21:05:16 -0700368 ForStmt *createFor(Location *location, ArrayRef<MLValue *> lbOperands,
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700369 AffineMap *lbMap, ArrayRef<MLValue *> ubOperands,
370 AffineMap *ubMap, int64_t step = 1);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700371
Tatiana Shpeismanc6aa35b2018-08-28 15:26:20 -0700372 /// Create if statement.
373 IfStmt *createIf(Location *location, ArrayRef<MLValue *> operands,
374 IntegerSet *set);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700375
376private:
377 StmtBlock *block = nullptr;
378 StmtBlock::iterator insertPoint;
379};
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700380
381} // namespace mlir
382
383#endif