1 //===- Builders.cpp - Helpers for constructing MLIR Classes ---------------===// 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 #include "mlir/IR/Builders.h" 10 #include "mlir/IR/AffineExpr.h" 11 #include "mlir/IR/AffineMap.h" 12 #include "mlir/IR/BlockAndValueMapping.h" 13 #include "mlir/IR/BuiltinTypes.h" 14 #include "mlir/IR/Dialect.h" 15 #include "mlir/IR/IntegerSet.h" 16 #include "mlir/IR/Matchers.h" 17 #include "mlir/IR/SymbolTable.h" 18 #include "llvm/Support/raw_ostream.h" 19 20 using namespace mlir; 21 22 Identifier Builder::getIdentifier(const Twine &str) { 23 return Identifier::get(str, context); 24 } 25 26 //===----------------------------------------------------------------------===// 27 // Locations. 28 //===----------------------------------------------------------------------===// 29 30 Location Builder::getUnknownLoc() { return UnknownLoc::get(context); } 31 32 Location Builder::getFusedLoc(ArrayRef<Location> locs, Attribute metadata) { 33 return FusedLoc::get(locs, metadata, context); 34 } 35 36 //===----------------------------------------------------------------------===// 37 // Types. 38 //===----------------------------------------------------------------------===// 39 40 FloatType Builder::getBF16Type() { return FloatType::getBF16(context); } 41 42 FloatType Builder::getF16Type() { return FloatType::getF16(context); } 43 44 FloatType Builder::getF32Type() { return FloatType::getF32(context); } 45 46 FloatType Builder::getF64Type() { return FloatType::getF64(context); } 47 48 FloatType Builder::getF80Type() { return FloatType::getF80(context); } 49 50 FloatType Builder::getF128Type() { return FloatType::getF128(context); } 51 52 IndexType Builder::getIndexType() { return IndexType::get(context); } 53 54 IntegerType Builder::getI1Type() { return IntegerType::get(context, 1); } 55 56 IntegerType Builder::getI8Type() { return IntegerType::get(context, 8); } 57 58 IntegerType Builder::getI32Type() { return IntegerType::get(context, 32); } 59 60 IntegerType Builder::getI64Type() { return IntegerType::get(context, 64); } 61 62 IntegerType Builder::getIntegerType(unsigned width) { 63 return IntegerType::get(context, width); 64 } 65 66 IntegerType Builder::getIntegerType(unsigned width, bool isSigned) { 67 return IntegerType::get( 68 context, width, isSigned ? IntegerType::Signed : IntegerType::Unsigned); 69 } 70 71 FunctionType Builder::getFunctionType(TypeRange inputs, TypeRange results) { 72 return FunctionType::get(context, inputs, results); 73 } 74 75 TupleType Builder::getTupleType(TypeRange elementTypes) { 76 return TupleType::get(context, elementTypes); 77 } 78 79 NoneType Builder::getNoneType() { return NoneType::get(context); } 80 81 //===----------------------------------------------------------------------===// 82 // Attributes. 83 //===----------------------------------------------------------------------===// 84 85 NamedAttribute Builder::getNamedAttr(StringRef name, Attribute val) { 86 return NamedAttribute(getIdentifier(name), val); 87 } 88 89 UnitAttr Builder::getUnitAttr() { return UnitAttr::get(context); } 90 91 BoolAttr Builder::getBoolAttr(bool value) { 92 return BoolAttr::get(context, value); 93 } 94 95 DictionaryAttr Builder::getDictionaryAttr(ArrayRef<NamedAttribute> value) { 96 return DictionaryAttr::get(context, value); 97 } 98 99 IntegerAttr Builder::getIndexAttr(int64_t value) { 100 return IntegerAttr::get(getIndexType(), APInt(64, value)); 101 } 102 103 IntegerAttr Builder::getI64IntegerAttr(int64_t value) { 104 return IntegerAttr::get(getIntegerType(64), APInt(64, value)); 105 } 106 107 DenseIntElementsAttr Builder::getBoolVectorAttr(ArrayRef<bool> values) { 108 return DenseIntElementsAttr::get( 109 VectorType::get(static_cast<int64_t>(values.size()), getI1Type()), 110 values); 111 } 112 113 DenseIntElementsAttr Builder::getI32VectorAttr(ArrayRef<int32_t> values) { 114 return DenseIntElementsAttr::get( 115 VectorType::get(static_cast<int64_t>(values.size()), getIntegerType(32)), 116 values); 117 } 118 119 DenseIntElementsAttr Builder::getI64VectorAttr(ArrayRef<int64_t> values) { 120 return DenseIntElementsAttr::get( 121 VectorType::get(static_cast<int64_t>(values.size()), getIntegerType(64)), 122 values); 123 } 124 125 DenseIntElementsAttr Builder::getIndexVectorAttr(ArrayRef<int64_t> values) { 126 return DenseIntElementsAttr::get( 127 VectorType::get(static_cast<int64_t>(values.size()), getIndexType()), 128 values); 129 } 130 131 DenseIntElementsAttr Builder::getI32TensorAttr(ArrayRef<int32_t> values) { 132 return DenseIntElementsAttr::get( 133 RankedTensorType::get(static_cast<int64_t>(values.size()), 134 getIntegerType(32)), 135 values); 136 } 137 138 DenseIntElementsAttr Builder::getI64TensorAttr(ArrayRef<int64_t> values) { 139 return DenseIntElementsAttr::get( 140 RankedTensorType::get(static_cast<int64_t>(values.size()), 141 getIntegerType(64)), 142 values); 143 } 144 145 DenseIntElementsAttr Builder::getIndexTensorAttr(ArrayRef<int64_t> values) { 146 return DenseIntElementsAttr::get( 147 RankedTensorType::get(static_cast<int64_t>(values.size()), 148 getIndexType()), 149 values); 150 } 151 152 IntegerAttr Builder::getI32IntegerAttr(int32_t value) { 153 return IntegerAttr::get(getIntegerType(32), APInt(32, value)); 154 } 155 156 IntegerAttr Builder::getSI32IntegerAttr(int32_t value) { 157 return IntegerAttr::get(getIntegerType(32, /*isSigned=*/true), 158 APInt(32, value, /*isSigned=*/true)); 159 } 160 161 IntegerAttr Builder::getUI32IntegerAttr(uint32_t value) { 162 return IntegerAttr::get(getIntegerType(32, /*isSigned=*/false), 163 APInt(32, (uint64_t)value, /*isSigned=*/false)); 164 } 165 166 IntegerAttr Builder::getI16IntegerAttr(int16_t value) { 167 return IntegerAttr::get(getIntegerType(16), APInt(16, value)); 168 } 169 170 IntegerAttr Builder::getI8IntegerAttr(int8_t value) { 171 return IntegerAttr::get(getIntegerType(8), APInt(8, value)); 172 } 173 174 IntegerAttr Builder::getIntegerAttr(Type type, int64_t value) { 175 if (type.isIndex()) 176 return IntegerAttr::get(type, APInt(64, value)); 177 return IntegerAttr::get( 178 type, APInt(type.getIntOrFloatBitWidth(), value, type.isSignedInteger())); 179 } 180 181 IntegerAttr Builder::getIntegerAttr(Type type, const APInt &value) { 182 return IntegerAttr::get(type, value); 183 } 184 185 FloatAttr Builder::getF64FloatAttr(double value) { 186 return FloatAttr::get(getF64Type(), APFloat(value)); 187 } 188 189 FloatAttr Builder::getF32FloatAttr(float value) { 190 return FloatAttr::get(getF32Type(), APFloat(value)); 191 } 192 193 FloatAttr Builder::getF16FloatAttr(float value) { 194 return FloatAttr::get(getF16Type(), value); 195 } 196 197 FloatAttr Builder::getFloatAttr(Type type, double value) { 198 return FloatAttr::get(type, value); 199 } 200 201 FloatAttr Builder::getFloatAttr(Type type, const APFloat &value) { 202 return FloatAttr::get(type, value); 203 } 204 205 StringAttr Builder::getStringAttr(const Twine &bytes) { 206 return StringAttr::get(context, bytes); 207 } 208 209 ArrayAttr Builder::getArrayAttr(ArrayRef<Attribute> value) { 210 return ArrayAttr::get(context, value); 211 } 212 213 FlatSymbolRefAttr Builder::getSymbolRefAttr(Operation *value) { 214 auto symName = 215 value->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName()); 216 assert(symName && "value does not have a valid symbol name"); 217 return getSymbolRefAttr(symName.getValue()); 218 } 219 220 FlatSymbolRefAttr Builder::getSymbolRefAttr(StringAttr value) { 221 return SymbolRefAttr::get(value); 222 } 223 224 SymbolRefAttr 225 Builder::getSymbolRefAttr(StringAttr value, 226 ArrayRef<FlatSymbolRefAttr> nestedReferences) { 227 return SymbolRefAttr::get(value, nestedReferences); 228 } 229 230 ArrayAttr Builder::getBoolArrayAttr(ArrayRef<bool> values) { 231 auto attrs = llvm::to_vector<8>(llvm::map_range( 232 values, [this](bool v) -> Attribute { return getBoolAttr(v); })); 233 return getArrayAttr(attrs); 234 } 235 236 ArrayAttr Builder::getI32ArrayAttr(ArrayRef<int32_t> values) { 237 auto attrs = llvm::to_vector<8>(llvm::map_range( 238 values, [this](int32_t v) -> Attribute { return getI32IntegerAttr(v); })); 239 return getArrayAttr(attrs); 240 } 241 ArrayAttr Builder::getI64ArrayAttr(ArrayRef<int64_t> values) { 242 auto attrs = llvm::to_vector<8>(llvm::map_range( 243 values, [this](int64_t v) -> Attribute { return getI64IntegerAttr(v); })); 244 return getArrayAttr(attrs); 245 } 246 247 ArrayAttr Builder::getIndexArrayAttr(ArrayRef<int64_t> values) { 248 auto attrs = llvm::to_vector<8>( 249 llvm::map_range(values, [this](int64_t v) -> Attribute { 250 return getIntegerAttr(IndexType::get(getContext()), v); 251 })); 252 return getArrayAttr(attrs); 253 } 254 255 ArrayAttr Builder::getF32ArrayAttr(ArrayRef<float> values) { 256 auto attrs = llvm::to_vector<8>(llvm::map_range( 257 values, [this](float v) -> Attribute { return getF32FloatAttr(v); })); 258 return getArrayAttr(attrs); 259 } 260 261 ArrayAttr Builder::getF64ArrayAttr(ArrayRef<double> values) { 262 auto attrs = llvm::to_vector<8>(llvm::map_range( 263 values, [this](double v) -> Attribute { return getF64FloatAttr(v); })); 264 return getArrayAttr(attrs); 265 } 266 267 ArrayAttr Builder::getStrArrayAttr(ArrayRef<StringRef> values) { 268 auto attrs = llvm::to_vector<8>(llvm::map_range( 269 values, [this](StringRef v) -> Attribute { return getStringAttr(v); })); 270 return getArrayAttr(attrs); 271 } 272 273 ArrayAttr Builder::getTypeArrayAttr(TypeRange values) { 274 auto attrs = llvm::to_vector<8>(llvm::map_range( 275 values, [](Type v) -> Attribute { return TypeAttr::get(v); })); 276 return getArrayAttr(attrs); 277 } 278 279 ArrayAttr Builder::getAffineMapArrayAttr(ArrayRef<AffineMap> values) { 280 auto attrs = llvm::to_vector<8>(llvm::map_range( 281 values, [](AffineMap v) -> Attribute { return AffineMapAttr::get(v); })); 282 return getArrayAttr(attrs); 283 } 284 285 Attribute Builder::getZeroAttr(Type type) { 286 if (type.isa<FloatType>()) 287 return getFloatAttr(type, 0.0); 288 if (type.isa<IndexType>()) 289 return getIndexAttr(0); 290 if (auto integerType = type.dyn_cast<IntegerType>()) 291 return getIntegerAttr(type, APInt(type.cast<IntegerType>().getWidth(), 0)); 292 if (type.isa<RankedTensorType, VectorType>()) { 293 auto vtType = type.cast<ShapedType>(); 294 auto element = getZeroAttr(vtType.getElementType()); 295 if (!element) 296 return {}; 297 return DenseElementsAttr::get(vtType, element); 298 } 299 return {}; 300 } 301 302 //===----------------------------------------------------------------------===// 303 // Affine Expressions, Affine Maps, and Integer Sets. 304 //===----------------------------------------------------------------------===// 305 306 AffineExpr Builder::getAffineDimExpr(unsigned position) { 307 return mlir::getAffineDimExpr(position, context); 308 } 309 310 AffineExpr Builder::getAffineSymbolExpr(unsigned position) { 311 return mlir::getAffineSymbolExpr(position, context); 312 } 313 314 AffineExpr Builder::getAffineConstantExpr(int64_t constant) { 315 return mlir::getAffineConstantExpr(constant, context); 316 } 317 318 AffineMap Builder::getEmptyAffineMap() { return AffineMap::get(context); } 319 320 AffineMap Builder::getConstantAffineMap(int64_t val) { 321 return AffineMap::get(/*dimCount=*/0, /*symbolCount=*/0, 322 getAffineConstantExpr(val)); 323 } 324 325 AffineMap Builder::getDimIdentityMap() { 326 return AffineMap::get(/*dimCount=*/1, /*symbolCount=*/0, getAffineDimExpr(0)); 327 } 328 329 AffineMap Builder::getMultiDimIdentityMap(unsigned rank) { 330 SmallVector<AffineExpr, 4> dimExprs; 331 dimExprs.reserve(rank); 332 for (unsigned i = 0; i < rank; ++i) 333 dimExprs.push_back(getAffineDimExpr(i)); 334 return AffineMap::get(/*dimCount=*/rank, /*symbolCount=*/0, dimExprs, 335 context); 336 } 337 338 AffineMap Builder::getSymbolIdentityMap() { 339 return AffineMap::get(/*dimCount=*/0, /*symbolCount=*/1, 340 getAffineSymbolExpr(0)); 341 } 342 343 AffineMap Builder::getSingleDimShiftAffineMap(int64_t shift) { 344 // expr = d0 + shift. 345 auto expr = getAffineDimExpr(0) + shift; 346 return AffineMap::get(/*dimCount=*/1, /*symbolCount=*/0, expr); 347 } 348 349 AffineMap Builder::getShiftedAffineMap(AffineMap map, int64_t shift) { 350 SmallVector<AffineExpr, 4> shiftedResults; 351 shiftedResults.reserve(map.getNumResults()); 352 for (auto resultExpr : map.getResults()) 353 shiftedResults.push_back(resultExpr + shift); 354 return AffineMap::get(map.getNumDims(), map.getNumSymbols(), shiftedResults, 355 context); 356 } 357 358 //===----------------------------------------------------------------------===// 359 // OpBuilder 360 //===----------------------------------------------------------------------===// 361 362 OpBuilder::Listener::~Listener() {} 363 364 /// Insert the given operation at the current insertion point and return it. 365 Operation *OpBuilder::insert(Operation *op) { 366 if (block) 367 block->getOperations().insert(insertPoint, op); 368 369 if (listener) 370 listener->notifyOperationInserted(op); 371 return op; 372 } 373 374 /// Add new block with 'argTypes' arguments and set the insertion point to the 375 /// end of it. The block is inserted at the provided insertion point of 376 /// 'parent'. 377 Block *OpBuilder::createBlock(Region *parent, Region::iterator insertPt, 378 TypeRange argTypes, ArrayRef<Location> locs) { 379 assert(parent && "expected valid parent region"); 380 if (insertPt == Region::iterator()) 381 insertPt = parent->end(); 382 383 Block *b = new Block(); 384 b->addArguments(argTypes, locs); 385 parent->getBlocks().insert(insertPt, b); 386 setInsertionPointToEnd(b); 387 388 if (listener) 389 listener->notifyBlockCreated(b); 390 return b; 391 } 392 393 /// Add new block with 'argTypes' arguments and set the insertion point to the 394 /// end of it. The block is placed before 'insertBefore'. 395 Block *OpBuilder::createBlock(Block *insertBefore, TypeRange argTypes, 396 ArrayRef<Location> locs) { 397 assert(insertBefore && "expected valid insertion block"); 398 return createBlock(insertBefore->getParent(), Region::iterator(insertBefore), 399 argTypes, locs); 400 } 401 402 /// Create an operation given the fields represented as an OperationState. 403 Operation *OpBuilder::createOperation(const OperationState &state) { 404 return insert(Operation::create(state)); 405 } 406 407 /// Attempts to fold the given operation and places new results within 408 /// 'results'. Returns success if the operation was folded, failure otherwise. 409 /// Note: This function does not erase the operation on a successful fold. 410 LogicalResult OpBuilder::tryFold(Operation *op, 411 SmallVectorImpl<Value> &results) { 412 results.reserve(op->getNumResults()); 413 auto cleanupFailure = [&] { 414 results.assign(op->result_begin(), op->result_end()); 415 return failure(); 416 }; 417 418 // If this operation is already a constant, there is nothing to do. 419 if (matchPattern(op, m_Constant())) 420 return cleanupFailure(); 421 422 // Check to see if any operands to the operation is constant and whether 423 // the operation knows how to constant fold itself. 424 SmallVector<Attribute, 4> constOperands(op->getNumOperands()); 425 for (unsigned i = 0, e = op->getNumOperands(); i != e; ++i) 426 matchPattern(op->getOperand(i), m_Constant(&constOperands[i])); 427 428 // Try to fold the operation. 429 SmallVector<OpFoldResult, 4> foldResults; 430 if (failed(op->fold(constOperands, foldResults)) || foldResults.empty()) 431 return cleanupFailure(); 432 433 // A temporary builder used for creating constants during folding. 434 OpBuilder cstBuilder(context); 435 SmallVector<Operation *, 1> generatedConstants; 436 437 // Populate the results with the folded results. 438 Dialect *dialect = op->getDialect(); 439 for (auto &it : llvm::enumerate(foldResults)) { 440 // Normal values get pushed back directly. 441 if (auto value = it.value().dyn_cast<Value>()) { 442 results.push_back(value); 443 continue; 444 } 445 446 // Otherwise, try to materialize a constant operation. 447 if (!dialect) 448 return cleanupFailure(); 449 450 // Ask the dialect to materialize a constant operation for this value. 451 Attribute attr = it.value().get<Attribute>(); 452 auto *constOp = dialect->materializeConstant( 453 cstBuilder, attr, op->getResult(it.index()).getType(), op->getLoc()); 454 if (!constOp) { 455 // Erase any generated constants. 456 for (Operation *cst : generatedConstants) 457 cst->erase(); 458 return cleanupFailure(); 459 } 460 assert(matchPattern(constOp, m_Constant())); 461 462 generatedConstants.push_back(constOp); 463 results.push_back(constOp->getResult(0)); 464 } 465 466 // If we were successful, insert any generated constants. 467 for (Operation *cst : generatedConstants) 468 insert(cst); 469 470 return success(); 471 } 472 473 Operation *OpBuilder::clone(Operation &op, BlockAndValueMapping &mapper) { 474 Operation *newOp = op.clone(mapper); 475 // The `insert` call below handles the notification for inserting `newOp` 476 // itself. But if `newOp` has any regions, we need to notify the listener 477 // about any ops that got inserted inside those regions as part of cloning. 478 if (listener) { 479 auto walkFn = [&](Operation *walkedOp) { 480 listener->notifyOperationInserted(walkedOp); 481 }; 482 for (Region ®ion : newOp->getRegions()) 483 region.walk(walkFn); 484 } 485 return insert(newOp); 486 } 487 488 Operation *OpBuilder::clone(Operation &op) { 489 BlockAndValueMapping mapper; 490 return clone(op, mapper); 491 } 492