1 //===- SparseBufferRewriting.cpp - Sparse buffer rewriting rules ----------===// 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 implements rewriting rules that are specific to sparse tensor 10 // primitives with memref operands. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodegenUtils.h" 15 16 #include "mlir/Dialect/Arith/IR/Arith.h" 17 #include "mlir/Dialect/Func/IR/FuncOps.h" 18 #include "mlir/Dialect/Linalg/IR/Linalg.h" 19 #include "mlir/Dialect/Math/IR/Math.h" 20 #include "mlir/Dialect/MemRef/IR/MemRef.h" 21 #include "mlir/Dialect/SCF/IR/SCF.h" 22 #include "mlir/Dialect/SparseTensor/IR/SparseTensor.h" 23 #include "mlir/Dialect/SparseTensor/Transforms/Passes.h" 24 #include "mlir/Support/LLVM.h" 25 26 using namespace mlir; 27 using namespace mlir::sparse_tensor; 28 29 //===---------------------------------------------------------------------===// 30 // Helper methods for the actual rewriting rules. 31 //===---------------------------------------------------------------------===// 32 33 static constexpr uint64_t loIdx = 0; 34 static constexpr uint64_t hiIdx = 1; 35 static constexpr uint64_t xStartIdx = 2; 36 37 static constexpr const char kPartitionFuncNamePrefix[] = "_sparse_partition_"; 38 static constexpr const char kBinarySearchFuncNamePrefix[] = 39 "_sparse_binary_search_"; 40 static constexpr const char kHybridQuickSortFuncNamePrefix[] = 41 "_sparse_hybrid_qsort_"; 42 static constexpr const char kSortStableFuncNamePrefix[] = 43 "_sparse_sort_stable_"; 44 static constexpr const char kShiftDownFuncNamePrefix[] = "_sparse_shift_down_"; 45 static constexpr const char kHeapSortFuncNamePrefix[] = "_sparse_heap_sort_"; 46 static constexpr const char kQuickSortFuncNamePrefix[] = "_sparse_qsort_"; 47 48 using FuncGeneratorType = function_ref<void( 49 OpBuilder &, ModuleOp, func::FuncOp, uint64_t, uint64_t, bool, uint32_t)>; 50 51 /// Constructs a function name with this format to facilitate quick sort: 52 /// <namePrefix><nx>_<x type>_<y0 type>..._<yn type> for sort 53 /// <namePrefix><nx>_<x type>_coo_<ny>_<y0 type>..._<yn type> for sort_coo 54 static void getMangledSortHelperFuncName(llvm::raw_svector_ostream &nameOstream, 55 StringRef namePrefix, uint64_t nx, 56 uint64_t ny, bool isCoo, 57 ValueRange operands) { 58 nameOstream << namePrefix << nx << "_" 59 << getMemRefType(operands[xStartIdx]).getElementType(); 60 61 if (isCoo) 62 nameOstream << "_coo_" << ny; 63 64 uint64_t yBufferOffset = isCoo ? 1 : nx; 65 for (Value v : operands.drop_front(xStartIdx + yBufferOffset)) 66 nameOstream << "_" << getMemRefType(v).getElementType(); 67 } 68 69 /// Looks up a function that is appropriate for the given operands being 70 /// sorted, and creates such a function if it doesn't exist yet. The 71 /// parameters `nx` and `ny` tell the number of x and y values provided 72 /// by the buffer in xStartIdx, and `isCoo` indicates whether the instruction 73 /// being processed is a sparse_tensor.sort or sparse_tensor.sort_coo. 74 // 75 // All sorting function generators take (lo, hi, xs, ys) in `operands` as 76 // parameters for the sorting functions. Other parameters, such as the recursive 77 // call depth, are appended to the end of the parameter list as 78 // "trailing parameters". 79 static FlatSymbolRefAttr 80 getMangledSortHelperFunc(OpBuilder &builder, func::FuncOp insertPoint, 81 TypeRange resultTypes, StringRef namePrefix, 82 uint64_t nx, uint64_t ny, bool isCoo, 83 ValueRange operands, FuncGeneratorType createFunc, 84 uint32_t nTrailingP = 0) { 85 SmallString<32> nameBuffer; 86 llvm::raw_svector_ostream nameOstream(nameBuffer); 87 getMangledSortHelperFuncName(nameOstream, namePrefix, nx, ny, isCoo, 88 operands.drop_back(nTrailingP)); 89 90 ModuleOp module = insertPoint->getParentOfType<ModuleOp>(); 91 MLIRContext *context = module.getContext(); 92 auto result = SymbolRefAttr::get(context, nameOstream.str()); 93 auto func = module.lookupSymbol<func::FuncOp>(result.getAttr()); 94 95 if (!func) { 96 // Create the function. 97 OpBuilder::InsertionGuard insertionGuard(builder); 98 builder.setInsertionPoint(insertPoint); 99 Location loc = insertPoint.getLoc(); 100 func = builder.create<func::FuncOp>( 101 loc, nameOstream.str(), 102 FunctionType::get(context, operands.getTypes(), resultTypes)); 103 func.setPrivate(); 104 createFunc(builder, module, func, nx, ny, isCoo, nTrailingP); 105 } 106 107 return result; 108 } 109 110 /// Creates a code block to process each pair of (xs[i], xs[j]) for sorting. 111 /// The code to process the value pairs is generated by `bodyBuilder`. 112 static void forEachIJPairInXs( 113 OpBuilder &builder, Location loc, ValueRange args, uint64_t nx, uint64_t ny, 114 bool isCoo, function_ref<void(uint64_t, Value, Value, Value)> bodyBuilder) { 115 Value iOffset, jOffset; 116 if (isCoo) { 117 Value cstep = constantIndex(builder, loc, nx + ny); 118 iOffset = builder.create<arith::MulIOp>(loc, args[0], cstep); 119 jOffset = builder.create<arith::MulIOp>(loc, args[1], cstep); 120 } 121 for (uint64_t k = 0; k < nx; k++) { 122 scf::IfOp ifOp; 123 Value i, j, buffer; 124 if (isCoo) { 125 Value ck = constantIndex(builder, loc, k); 126 i = builder.create<arith::AddIOp>(loc, ck, iOffset); 127 j = builder.create<arith::AddIOp>(loc, ck, jOffset); 128 buffer = args[xStartIdx]; 129 } else { 130 i = args[0]; 131 j = args[1]; 132 buffer = args[xStartIdx + k]; 133 } 134 bodyBuilder(k, i, j, buffer); 135 } 136 } 137 138 /// Creates a code block to process each pair of (xys[i], xys[j]) for sorting. 139 /// The code to process the value pairs is generated by `bodyBuilder`. 140 static void forEachIJPairInAllBuffers( 141 OpBuilder &builder, Location loc, ValueRange args, uint64_t nx, uint64_t ny, 142 bool isCoo, function_ref<void(uint64_t, Value, Value, Value)> bodyBuilder) { 143 144 // Create code for the first (nx + ny) buffers. When isCoo==true, these 145 // logical buffers are all from the xy buffer of the sort_coo operator. 146 forEachIJPairInXs(builder, loc, args, nx + ny, 0, isCoo, bodyBuilder); 147 148 uint64_t numHandledBuffers = isCoo ? 1 : nx + ny; 149 150 // Create code for the remaining buffers. 151 Value i = args[0]; 152 Value j = args[1]; 153 for (const auto &arg : 154 llvm::enumerate(args.drop_front(xStartIdx + numHandledBuffers))) { 155 bodyBuilder(arg.index() + nx + ny, i, j, arg.value()); 156 } 157 } 158 159 /// Creates a code block for swapping the values in index i and j for all the 160 /// buffers. 161 // 162 // The generated IR corresponds to this C like algorithm: 163 // swap(x0[i], x0[j]); 164 // swap(x1[i], x1[j]); 165 // ... 166 // swap(xn[i], xn[j]); 167 // swap(y0[i], y0[j]); 168 // ... 169 // swap(yn[i], yn[j]); 170 static void createSwap(OpBuilder &builder, Location loc, ValueRange args, 171 uint64_t nx, uint64_t ny, bool isCoo) { 172 auto swapOnePair = [&](uint64_t unused, Value i, Value j, Value buffer) { 173 Value vi = builder.create<memref::LoadOp>(loc, buffer, i); 174 Value vj = builder.create<memref::LoadOp>(loc, buffer, j); 175 builder.create<memref::StoreOp>(loc, vj, buffer, i); 176 builder.create<memref::StoreOp>(loc, vi, buffer, j); 177 }; 178 179 forEachIJPairInAllBuffers(builder, loc, args, nx, ny, isCoo, swapOnePair); 180 } 181 182 /// Creates code to compare all the (xs[i], xs[j]) pairs. The method to compare 183 /// each pair is create via `compareBuilder`. 184 static Value createInlinedCompareImplementation( 185 OpBuilder &builder, Location loc, ValueRange args, uint64_t nx, uint64_t ny, 186 bool isCoo, 187 function_ref<Value(OpBuilder &, Location, Value, Value, Value, bool, bool)> 188 compareBuilder) { 189 Value result; 190 auto bodyBuilder = [&](uint64_t k, Value i, Value j, Value buffer) { 191 bool isFirstDim = (k == 0); 192 bool isLastDim = (k == nx - 1); 193 Value val = 194 compareBuilder(builder, loc, i, j, buffer, isFirstDim, isLastDim); 195 if (isFirstDim) { 196 result = val; 197 } else if (!isLastDim) { 198 OpBuilder::InsertionGuard insertionGuard(builder); 199 auto ifOp = cast<scf::IfOp>(val.getDefiningOp()); 200 builder.setInsertionPointAfter(ifOp); 201 builder.create<scf::YieldOp>(loc, ifOp.getResult(0)); 202 } 203 }; 204 205 forEachIJPairInXs(builder, loc, args, nx, ny, isCoo, bodyBuilder); 206 207 builder.setInsertionPointAfterValue(result); 208 return result; 209 } 210 211 /// Generates code to compare whether x[i] is equal to x[j] and returns the 212 /// result of the comparison. 213 static Value createEqCompare(OpBuilder &builder, Location loc, Value i, Value j, 214 Value x, bool isFirstDim, bool isLastDim) { 215 Value vi = builder.create<memref::LoadOp>(loc, x, i); 216 Value vj = builder.create<memref::LoadOp>(loc, x, j); 217 218 Value res; 219 if (isLastDim) { 220 res = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq, vi, vj); 221 // For 1D, we create a compare without any control flow. Otherwise, we 222 // create YieldOp to return the result in the nested if-stmt. 223 if (!isFirstDim) 224 builder.create<scf::YieldOp>(loc, res); 225 } else { 226 Value ne = 227 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ne, vi, vj); 228 scf::IfOp ifOp = builder.create<scf::IfOp>(loc, builder.getIntegerType(1), 229 ne, /*else=*/true); 230 // If (x[i] != x[j]). 231 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 232 Value f = constantI1(builder, loc, false); 233 builder.create<scf::YieldOp>(loc, f); 234 235 // If (x[i] == x[j]). Set up the insertion point for the nested if-stmt that 236 // checks the remaining dimensions. 237 builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); 238 res = ifOp.getResult(0); 239 } 240 241 return res; 242 } 243 244 /// Creates code to compare whether xs[i] is equal to xs[j]. 245 // 246 // The generate IR corresponds to this C like algorithm: 247 // if (x0[i] != x0[j]) 248 // return false; 249 // else 250 // if (x1[i] != x1[j]) 251 // return false; 252 // else if (x2[2] != x2[j])) 253 // and so on ... 254 static Value createInlinedEqCompare(OpBuilder &builder, Location loc, 255 ValueRange args, uint64_t nx, uint64_t ny, 256 bool isCoo, uint32_t nTrailingP = 0) { 257 // Compare functions don't use trailing parameters. 258 (void)nTrailingP; 259 assert(nTrailingP == 0); 260 return createInlinedCompareImplementation(builder, loc, args, nx, ny, isCoo, 261 createEqCompare); 262 } 263 264 /// Generates code to compare whether x[i] is less than x[j] and returns the 265 /// result of the comparison. 266 static Value createLessThanCompare(OpBuilder &builder, Location loc, Value i, 267 Value j, Value x, bool isFirstDim, 268 bool isLastDim) { 269 Value vi = builder.create<memref::LoadOp>(loc, x, i); 270 Value vj = builder.create<memref::LoadOp>(loc, x, j); 271 272 Value res; 273 if (isLastDim) { 274 res = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, vi, vj); 275 // For 1D, we create a compare without any control flow. Otherwise, we 276 // create YieldOp to return the result in the nested if-stmt. 277 if (!isFirstDim) 278 builder.create<scf::YieldOp>(loc, res); 279 } else { 280 Value ne = 281 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ne, vi, vj); 282 scf::IfOp ifOp = builder.create<scf::IfOp>(loc, builder.getIntegerType(1), 283 ne, /*else=*/true); 284 // If (x[i] != x[j]). 285 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 286 Value lt = 287 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, vi, vj); 288 builder.create<scf::YieldOp>(loc, lt); 289 290 // If (x[i] == x[j]). Set up the insertion point for the nested if-stmt that 291 // checks the remaining dimensions. 292 builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); 293 res = ifOp.getResult(0); 294 } 295 296 return res; 297 } 298 299 /// Creates code to compare whether xs[i] is less than xs[j]. 300 // 301 // The generate IR corresponds to this C like algorithm: 302 // if (x0[i] != x0[j]) 303 // return x0[i] < x0[j]; 304 // else if (x1[j] != x1[i]) 305 // return x1[i] < x1[j]; 306 // else 307 // and so on ... 308 static Value createInlinedLessThan(OpBuilder &builder, Location loc, 309 ValueRange args, uint64_t nx, uint64_t ny, 310 bool isCoo, uint32_t nTrailingP = 0) { 311 // Compare functions don't use trailing parameters. 312 (void)nTrailingP; 313 assert(nTrailingP == 0); 314 return createInlinedCompareImplementation(builder, loc, args, nx, ny, isCoo, 315 createLessThanCompare); 316 } 317 318 /// Creates a function to use a binary search to find the insertion point for 319 /// inserting xs[hi] to the sorted values xs[lo..hi). 320 // 321 // The generate IR corresponds to this C like algorithm: 322 // p = hi 323 // while (lo < hi) 324 // mid = (lo + hi) >> 1 325 // if (xs[p] < xs[mid]) 326 // hi = mid 327 // else 328 // lo = mid - 1 329 // return lo; 330 // 331 static void createBinarySearchFunc(OpBuilder &builder, ModuleOp module, 332 func::FuncOp func, uint64_t nx, uint64_t ny, 333 bool isCoo, uint32_t nTrailingP = 0) { 334 // Binary search doesn't use trailing parameters. 335 (void)nTrailingP; 336 assert(nTrailingP == 0); 337 OpBuilder::InsertionGuard insertionGuard(builder); 338 Block *entryBlock = func.addEntryBlock(); 339 builder.setInsertionPointToStart(entryBlock); 340 341 Location loc = func.getLoc(); 342 ValueRange args = entryBlock->getArguments(); 343 Value p = args[hiIdx]; 344 SmallVector<Type, 2> types(2, p.getType()); // Only two types. 345 scf::WhileOp whileOp = builder.create<scf::WhileOp>( 346 loc, types, SmallVector<Value, 2>{args[loIdx], args[hiIdx]}); 347 348 // The before-region of the WhileOp. 349 Block *before = 350 builder.createBlock(&whileOp.getBefore(), {}, types, {loc, loc}); 351 builder.setInsertionPointToEnd(before); 352 Value cond1 = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, 353 before->getArgument(0), 354 before->getArgument(1)); 355 builder.create<scf::ConditionOp>(loc, cond1, before->getArguments()); 356 357 // The after-region of the WhileOp. 358 Block *after = 359 builder.createBlock(&whileOp.getAfter(), {}, types, {loc, loc}); 360 builder.setInsertionPointToEnd(after); 361 Value lo = after->getArgument(0); 362 Value hi = after->getArgument(1); 363 // Compute mid = (lo + hi) >> 1. 364 Value c1 = constantIndex(builder, loc, 1); 365 Value mid = builder.create<arith::ShRUIOp>( 366 loc, builder.create<arith::AddIOp>(loc, lo, hi), c1); 367 Value midp1 = builder.create<arith::AddIOp>(loc, mid, c1); 368 369 // Compare xs[p] < xs[mid]. 370 SmallVector<Value> compareOperands{p, mid}; 371 uint64_t numXBuffers = isCoo ? 1 : nx; 372 compareOperands.append(args.begin() + xStartIdx, 373 args.begin() + xStartIdx + numXBuffers); 374 Value cond2 = 375 createInlinedLessThan(builder, loc, compareOperands, nx, ny, isCoo); 376 // Update lo and hi for the WhileOp as follows: 377 // if (xs[p] < xs[mid])) 378 // hi = mid; 379 // else 380 // lo = mid + 1; 381 Value newLo = builder.create<arith::SelectOp>(loc, cond2, lo, midp1); 382 Value newHi = builder.create<arith::SelectOp>(loc, cond2, mid, hi); 383 builder.create<scf::YieldOp>(loc, ValueRange{newLo, newHi}); 384 385 builder.setInsertionPointAfter(whileOp); 386 builder.create<func::ReturnOp>(loc, whileOp.getResult(0)); 387 } 388 389 /// Creates code to advance i in a loop based on xs[p] as follows: 390 /// while (xs[i] < xs[p]) i += step (step > 0) 391 /// or 392 /// while (xs[i] > xs[p]) i += step (step < 0) 393 /// The routine returns i as well as a boolean value to indicate whether 394 /// xs[i] == xs[p]. 395 static std::pair<Value, Value> 396 createScanLoop(OpBuilder &builder, ModuleOp module, func::FuncOp func, 397 ValueRange xs, Value i, Value p, uint64_t nx, uint64_t ny, 398 bool isCoo, int step) { 399 Location loc = func.getLoc(); 400 scf::WhileOp whileOp = 401 builder.create<scf::WhileOp>(loc, TypeRange{i.getType()}, ValueRange{i}); 402 403 Block *before = 404 builder.createBlock(&whileOp.getBefore(), {}, {i.getType()}, {loc}); 405 builder.setInsertionPointToEnd(before); 406 SmallVector<Value> compareOperands; 407 if (step > 0) { 408 compareOperands.push_back(before->getArgument(0)); 409 compareOperands.push_back(p); 410 } else { 411 assert(step < 0); 412 compareOperands.push_back(p); 413 compareOperands.push_back(before->getArgument(0)); 414 } 415 compareOperands.append(xs.begin(), xs.end()); 416 Value cond = 417 createInlinedLessThan(builder, loc, compareOperands, nx, ny, isCoo); 418 builder.create<scf::ConditionOp>(loc, cond, before->getArguments()); 419 420 Block *after = 421 builder.createBlock(&whileOp.getAfter(), {}, {i.getType()}, {loc}); 422 builder.setInsertionPointToEnd(after); 423 Value cs = constantIndex(builder, loc, step); 424 i = builder.create<arith::AddIOp>(loc, after->getArgument(0), cs); 425 builder.create<scf::YieldOp>(loc, ValueRange{i}); 426 i = whileOp.getResult(0); 427 428 builder.setInsertionPointAfter(whileOp); 429 compareOperands[0] = i; 430 compareOperands[1] = p; 431 Value compareEq = 432 createInlinedEqCompare(builder, loc, compareOperands, nx, ny, isCoo); 433 434 return std::make_pair(whileOp.getResult(0), compareEq); 435 } 436 437 /// Creates and returns an IfOp to compare two elements and swap the elements 438 /// if compareFunc(data[b], data[a]) returns true. The new insertion point is 439 /// right after the swap instructions. 440 static scf::IfOp createCompareThenSwap(OpBuilder &builder, Location loc, 441 uint64_t nx, uint64_t ny, bool isCoo, 442 SmallVectorImpl<Value> &swapOperands, 443 SmallVectorImpl<Value> &compareOperands, 444 Value a, Value b) { 445 // Compare(data[b], data[a]). 446 compareOperands[0] = b; 447 compareOperands[1] = a; 448 Value cond = 449 createInlinedLessThan(builder, loc, compareOperands, nx, ny, isCoo); 450 scf::IfOp ifOp = builder.create<scf::IfOp>(loc, cond, /*else=*/false); 451 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 452 swapOperands[0] = b; 453 swapOperands[1] = a; 454 createSwap(builder, loc, swapOperands, nx, ny, isCoo); 455 return ifOp; 456 } 457 458 /// Creates code to insert the 3rd element to a list of two sorted elements. 459 static void createInsert3rd(OpBuilder &builder, Location loc, uint64_t nx, 460 uint64_t ny, bool isCoo, 461 SmallVectorImpl<Value> &swapOperands, 462 SmallVectorImpl<Value> &compareOperands, Value v0, 463 Value v1, Value v2) { 464 scf::IfOp ifOp = createCompareThenSwap(builder, loc, nx, ny, isCoo, 465 swapOperands, compareOperands, v1, v2); 466 createCompareThenSwap(builder, loc, nx, ny, isCoo, swapOperands, 467 compareOperands, v0, v1); 468 builder.setInsertionPointAfter(ifOp); 469 } 470 471 /// Creates code to sort 3 elements. 472 static void createSort3(OpBuilder &builder, Location loc, uint64_t nx, 473 uint64_t ny, bool isCoo, 474 SmallVectorImpl<Value> &swapOperands, 475 SmallVectorImpl<Value> &compareOperands, Value v0, 476 Value v1, Value v2) { 477 // Sort the first 2 elements. 478 scf::IfOp ifOp1 = createCompareThenSwap( 479 builder, loc, nx, ny, isCoo, swapOperands, compareOperands, v0, v1); 480 builder.setInsertionPointAfter(ifOp1); 481 482 // Insert the 3th element. 483 createInsert3rd(builder, loc, nx, ny, isCoo, swapOperands, compareOperands, 484 v0, v1, v2); 485 } 486 487 /// Creates code to sort 5 elements. 488 static void createSort5(OpBuilder &builder, Location loc, uint64_t nx, 489 uint64_t ny, bool isCoo, 490 SmallVectorImpl<Value> &swapOperands, 491 SmallVectorImpl<Value> &compareOperands, Value v0, 492 Value v1, Value v2, Value v3, Value v4) { 493 // Sort the first 3 elements. 494 createSort3(builder, loc, nx, ny, isCoo, swapOperands, compareOperands, v0, 495 v1, v2); 496 497 auto insert4th = [&]() { 498 scf::IfOp ifOp = createCompareThenSwap( 499 builder, loc, nx, ny, isCoo, swapOperands, compareOperands, v2, v3); 500 createInsert3rd(builder, loc, nx, ny, isCoo, swapOperands, compareOperands, 501 v0, v1, v2); 502 builder.setInsertionPointAfter(ifOp); 503 }; 504 505 // Insert the 4th element. 506 insert4th(); 507 508 // Insert the 5th element. 509 scf::IfOp ifOp = createCompareThenSwap(builder, loc, nx, ny, isCoo, 510 swapOperands, compareOperands, v3, v4); 511 insert4th(); 512 builder.setInsertionPointAfter(ifOp); 513 } 514 515 /// Creates a code block to swap the values in indices lo, mi, and hi so that 516 /// data[lo], data[mi] and data[hi] are sorted in non-decreasing values. When 517 /// the number of values in range [lo, hi) is more than a threshold, we also 518 /// include the middle of [lo, mi) and [mi, hi) and sort a total of five values. 519 static void createChoosePivot(OpBuilder &builder, ModuleOp module, 520 func::FuncOp func, uint64_t nx, uint64_t ny, 521 bool isCoo, Value lo, Value hi, Value mi, 522 ValueRange args) { 523 SmallVector<Value> compareOperands{mi, lo}; 524 uint64_t numXBuffers = isCoo ? 1 : nx; 525 compareOperands.append(args.begin() + xStartIdx, 526 args.begin() + xStartIdx + numXBuffers); 527 SmallVector<Value> swapOperands{mi, lo}; 528 swapOperands.append(args.begin() + xStartIdx, args.end()); 529 Location loc = func.getLoc(); 530 Value c1 = constantIndex(builder, loc, 1); 531 Value hiP1 = builder.create<arith::AddIOp>(loc, hi, c1); 532 Value len = builder.create<arith::SubIOp>(loc, hiP1, lo); 533 Value lenThreshold = constantIndex(builder, loc, 1000); 534 Value lenCond = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, 535 len, lenThreshold); 536 scf::IfOp lenIf = builder.create<scf::IfOp>(loc, lenCond, /*else=*/true); 537 538 // When len < 1000, choose pivot from median of 3 values. 539 builder.setInsertionPointToStart(&lenIf.getThenRegion().front()); 540 createSort3(builder, loc, nx, ny, isCoo, swapOperands, compareOperands, lo, 541 mi, hi); 542 543 // When len >= 1000, choose pivot from median of 5 values. 544 builder.setInsertionPointToStart(&lenIf.getElseRegion().front()); 545 Value miP1 = builder.create<arith::AddIOp>(loc, hi, c1); 546 Value a = builder.create<arith::AddIOp>(loc, lo, miP1); 547 // Value a is the middle between [loc, mi]. 548 a = builder.create<arith::ShRUIOp>(loc, a, c1); 549 Value b = builder.create<arith::AddIOp>(loc, mi, hiP1); 550 // Value b is the middle between [mi, hi]. 551 b = builder.create<arith::ShRUIOp>(loc, b, c1); 552 createSort5(builder, loc, nx, ny, isCoo, swapOperands, compareOperands, lo, a, 553 mi, b, hi); 554 555 builder.setInsertionPointAfter(lenIf); 556 } 557 558 /// Creates a function to perform quick sort partition on the values in the 559 /// range of index [lo, hi), assuming lo < hi. 560 // 561 // The generated IR corresponds to this C like algorithm: 562 // int partition(lo, hi, xs) { 563 // p = (lo+hi)/2 // pivot index 564 // i = lo 565 // j = hi-1 566 // while (i < j) do { 567 // while (xs[i] < xs[p]) i ++; 568 // i_eq = (xs[i] == xs[p]); 569 // while (xs[j] > xs[p]) j --; 570 // j_eq = (xs[j] == xs[p]); 571 // if (i < j) { 572 // swap(xs[i], xs[j]) 573 // if (i == p) { 574 // p = j; 575 // } else if (j == p) { 576 // p = i; 577 // } 578 // if (i_eq && j_eq) { 579 // ++i; 580 // --j; 581 // } 582 // } 583 // } 584 // return p 585 // } 586 static void createPartitionFunc(OpBuilder &builder, ModuleOp module, 587 func::FuncOp func, uint64_t nx, uint64_t ny, 588 bool isCoo, uint32_t nTrailingP = 0) { 589 // Quick sort partition doesn't use trailing parameters. 590 (void)nTrailingP; 591 assert(nTrailingP == 0); 592 OpBuilder::InsertionGuard insertionGuard(builder); 593 594 Block *entryBlock = func.addEntryBlock(); 595 builder.setInsertionPointToStart(entryBlock); 596 597 Location loc = func.getLoc(); 598 ValueRange args = entryBlock->getArguments(); 599 Value lo = args[loIdx]; 600 Value hi = args[hiIdx]; 601 Value sum = builder.create<arith::AddIOp>(loc, lo, hi); 602 Value c1 = constantIndex(builder, loc, 1); 603 Value p = builder.create<arith::ShRUIOp>(loc, sum, c1); 604 605 Value i = lo; 606 Value j = builder.create<arith::SubIOp>(loc, hi, c1); 607 createChoosePivot(builder, module, func, nx, ny, isCoo, i, j, p, args); 608 SmallVector<Value, 3> operands{i, j, p}; // Exactly three values. 609 SmallVector<Type, 3> types{i.getType(), j.getType(), p.getType()}; 610 scf::WhileOp whileOp = builder.create<scf::WhileOp>(loc, types, operands); 611 612 // The before-region of the WhileOp. 613 Block *before = 614 builder.createBlock(&whileOp.getBefore(), {}, types, {loc, loc, loc}); 615 builder.setInsertionPointToEnd(before); 616 Value cond = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, 617 before->getArgument(0), 618 before->getArgument(1)); 619 builder.create<scf::ConditionOp>(loc, cond, before->getArguments()); 620 621 // The after-region of the WhileOp. 622 Block *after = 623 builder.createBlock(&whileOp.getAfter(), {}, types, {loc, loc, loc}); 624 builder.setInsertionPointToEnd(after); 625 i = after->getArgument(0); 626 j = after->getArgument(1); 627 p = after->getArgument(2); 628 629 uint64_t numXBuffers = isCoo ? 1 : nx; 630 auto [iresult, iCompareEq] = 631 createScanLoop(builder, module, func, args.slice(xStartIdx, numXBuffers), 632 i, p, nx, ny, isCoo, 1); 633 i = iresult; 634 auto [jresult, jCompareEq] = 635 createScanLoop(builder, module, func, args.slice(xStartIdx, numXBuffers), 636 j, p, nx, ny, isCoo, -1); 637 j = jresult; 638 639 // If i < j: 640 cond = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, i, j); 641 scf::IfOp ifOp = builder.create<scf::IfOp>(loc, types, cond, /*else=*/true); 642 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 643 SmallVector<Value> swapOperands{i, j}; 644 swapOperands.append(args.begin() + xStartIdx, args.end()); 645 createSwap(builder, loc, swapOperands, nx, ny, isCoo); 646 // If the pivot is moved, update p with the new pivot. 647 Value icond = 648 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq, i, p); 649 scf::IfOp ifOpI = builder.create<scf::IfOp>(loc, TypeRange{p.getType()}, 650 icond, /*else=*/true); 651 builder.setInsertionPointToStart(&ifOpI.getThenRegion().front()); 652 builder.create<scf::YieldOp>(loc, ValueRange{j}); 653 builder.setInsertionPointToStart(&ifOpI.getElseRegion().front()); 654 Value jcond = 655 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq, j, p); 656 scf::IfOp ifOpJ = builder.create<scf::IfOp>(loc, TypeRange{p.getType()}, 657 jcond, /*else=*/true); 658 builder.setInsertionPointToStart(&ifOpJ.getThenRegion().front()); 659 builder.create<scf::YieldOp>(loc, ValueRange{i}); 660 builder.setInsertionPointToStart(&ifOpJ.getElseRegion().front()); 661 builder.create<scf::YieldOp>(loc, ValueRange{p}); 662 builder.setInsertionPointAfter(ifOpJ); 663 builder.create<scf::YieldOp>(loc, ifOpJ.getResults()); 664 builder.setInsertionPointAfter(ifOpI); 665 Value compareEqIJ = 666 builder.create<arith::AndIOp>(loc, iCompareEq, jCompareEq); 667 scf::IfOp ifOp2 = builder.create<scf::IfOp>( 668 loc, TypeRange{i.getType(), j.getType()}, compareEqIJ, /*else=*/true); 669 builder.setInsertionPointToStart(&ifOp2.getThenRegion().front()); 670 Value i2 = builder.create<arith::AddIOp>(loc, i, c1); 671 Value j2 = builder.create<arith::SubIOp>(loc, j, c1); 672 builder.create<scf::YieldOp>(loc, ValueRange{i2, j2}); 673 builder.setInsertionPointToStart(&ifOp2.getElseRegion().front()); 674 builder.create<scf::YieldOp>(loc, ValueRange{i, j}); 675 builder.setInsertionPointAfter(ifOp2); 676 builder.create<scf::YieldOp>( 677 loc, 678 ValueRange{ifOp2.getResult(0), ifOp2.getResult(1), ifOpI.getResult(0)}); 679 680 // False branch for if i < j: 681 builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); 682 builder.create<scf::YieldOp>(loc, ValueRange{i, j, p}); 683 684 // Return for the whileOp. 685 builder.setInsertionPointAfter(ifOp); 686 builder.create<scf::YieldOp>(loc, ifOp.getResults()); 687 688 // Return for the function. 689 builder.setInsertionPointAfter(whileOp); 690 builder.create<func::ReturnOp>(loc, whileOp.getResult(2)); 691 } 692 693 /// Computes (n-2)/n, assuming n has index type. 694 static Value createSubTwoDividedByTwo(OpBuilder &builder, Location loc, 695 Value n) { 696 Value i2 = constantIndex(builder, loc, 2); 697 Value res = builder.create<arith::SubIOp>(loc, n, i2); 698 Value i1 = constantIndex(builder, loc, 1); 699 return builder.create<arith::ShRUIOp>(loc, res, i1); 700 } 701 702 /// Creates a function to heapify the subtree with root `start` within the full 703 /// binary tree in the range of index [first, first + n). 704 // 705 // The generated IR corresponds to this C like algorithm: 706 // void shiftDown(first, start, n, data) { 707 // if (n >= 2) { 708 // child = start - first 709 // if ((n-2)/2 >= child) { 710 // // Left child exists. 711 // child = child * 2 + 1 // Initialize the bigger child to left child. 712 // childIndex = child + first 713 // if (child+1 < n && data[childIndex] < data[childIndex+1]) 714 // // Right child exits and is bigger. 715 // childIndex++; child++; 716 // // Shift data[start] down to where it belongs in the subtree. 717 // while (data[start] < data[childIndex) { 718 // swap(data[start], data[childIndex]) 719 // start = childIndex 720 // if ((n - 2)/2 >= child) { 721 // // Left child exists. 722 // child = 2*child + 1 723 // childIndex = child + 1 724 // if (child + 1) < n && data[childIndex] < data[childIndex+1] 725 // childIndex++; child++; 726 // } 727 // } 728 // } 729 // } 730 // } 731 // 732 static void createShiftDownFunc(OpBuilder &builder, ModuleOp module, 733 func::FuncOp func, uint64_t nx, uint64_t ny, 734 bool isCoo, uint32_t nTrailingP) { 735 // The value n is passed in as a trailing parameter. 736 assert(nTrailingP == 1); 737 OpBuilder::InsertionGuard insertionGuard(builder); 738 Block *entryBlock = func.addEntryBlock(); 739 builder.setInsertionPointToStart(entryBlock); 740 741 Location loc = func.getLoc(); 742 Value n = entryBlock->getArguments().back(); 743 ValueRange args = entryBlock->getArguments().drop_back(); 744 Value first = args[loIdx]; 745 Value start = args[hiIdx]; 746 747 // If (n >= 2). 748 Value c2 = constantIndex(builder, loc, 2); 749 Value condN = 750 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::uge, n, c2); 751 scf::IfOp ifN = builder.create<scf::IfOp>(loc, condN, /*else=*/false); 752 builder.setInsertionPointToStart(&ifN.getThenRegion().front()); 753 Value child = builder.create<arith::SubIOp>(loc, start, first); 754 755 // If ((n-2)/2 >= child). 756 Value t = createSubTwoDividedByTwo(builder, loc, n); 757 Value condNc = 758 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::uge, t, child); 759 scf::IfOp ifNc = builder.create<scf::IfOp>(loc, condNc, /*else=*/false); 760 761 builder.setInsertionPointToStart(&ifNc.getThenRegion().front()); 762 Value c1 = constantIndex(builder, loc, 1); 763 SmallVector<Value> compareOperands{start, start}; 764 uint64_t numXBuffers = isCoo ? 1 : nx; 765 compareOperands.append(args.begin() + xStartIdx, 766 args.begin() + xStartIdx + numXBuffers); 767 768 // Generate code to inspect the children of 'r' and return the larger child 769 // as follows: 770 // child = r * 2 + 1 // Left child. 771 // childIndex = child + first 772 // if (child+1 < n && data[childIndex] < data[childIndex+1]) 773 // childIndex ++; child ++ // Right child is bigger. 774 auto getLargerChild = [&](Value r) -> std::pair<Value, Value> { 775 Value lChild = builder.create<arith::ShLIOp>(loc, r, c1); 776 lChild = builder.create<arith::AddIOp>(loc, lChild, c1); 777 Value lChildIdx = builder.create<arith::AddIOp>(loc, lChild, first); 778 Value rChild = builder.create<arith::AddIOp>(loc, lChild, c1); 779 Value cond1 = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, 780 rChild, n); 781 SmallVector<Type, 2> ifTypes(2, r.getType()); 782 scf::IfOp if1 = 783 builder.create<scf::IfOp>(loc, ifTypes, cond1, /*else=*/true); 784 builder.setInsertionPointToStart(&if1.getThenRegion().front()); 785 Value rChildIdx = builder.create<arith::AddIOp>(loc, rChild, first); 786 // Compare data[left] < data[right]. 787 compareOperands[0] = lChildIdx; 788 compareOperands[1] = rChildIdx; 789 Value cond2 = 790 createInlinedLessThan(builder, loc, compareOperands, nx, ny, isCoo); 791 scf::IfOp if2 = 792 builder.create<scf::IfOp>(loc, ifTypes, cond2, /*else=*/true); 793 builder.setInsertionPointToStart(&if2.getThenRegion().front()); 794 builder.create<scf::YieldOp>(loc, ValueRange{rChild, rChildIdx}); 795 builder.setInsertionPointToStart(&if2.getElseRegion().front()); 796 builder.create<scf::YieldOp>(loc, ValueRange{lChild, lChildIdx}); 797 builder.setInsertionPointAfter(if2); 798 builder.create<scf::YieldOp>(loc, if2.getResults()); 799 builder.setInsertionPointToStart(&if1.getElseRegion().front()); 800 builder.create<scf::YieldOp>(loc, ValueRange{lChild, lChildIdx}); 801 builder.setInsertionPointAfter(if1); 802 return std::make_pair(if1.getResult(0), if1.getResult(1)); 803 }; 804 805 Value childIdx; 806 std::tie(child, childIdx) = getLargerChild(child); 807 808 // While (data[start] < data[childIndex]). 809 SmallVector<Type, 3> types(3, child.getType()); 810 scf::WhileOp whileOp = builder.create<scf::WhileOp>( 811 loc, types, SmallVector<Value, 2>{start, child, childIdx}); 812 813 // The before-region of the WhileOp. 814 SmallVector<Location, 3> locs(3, loc); 815 Block *before = builder.createBlock(&whileOp.getBefore(), {}, types, locs); 816 builder.setInsertionPointToEnd(before); 817 start = before->getArgument(0); 818 childIdx = before->getArgument(2); 819 compareOperands[0] = start; 820 compareOperands[1] = childIdx; 821 Value cond = 822 createInlinedLessThan(builder, loc, compareOperands, nx, ny, isCoo); 823 builder.create<scf::ConditionOp>(loc, cond, before->getArguments()); 824 825 // The after-region of the WhileOp. 826 Block *after = builder.createBlock(&whileOp.getAfter(), {}, types, locs); 827 start = after->getArgument(0); 828 child = after->getArgument(1); 829 childIdx = after->getArgument(2); 830 SmallVector<Value> swapOperands{start, childIdx}; 831 swapOperands.append(args.begin() + xStartIdx, args.end()); 832 createSwap(builder, loc, swapOperands, nx, ny, isCoo); 833 start = childIdx; 834 Value cond2 = 835 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::uge, t, child); 836 scf::IfOp if2 = builder.create<scf::IfOp>( 837 loc, TypeRange{child.getType(), child.getType()}, cond2, /*else=*/true); 838 builder.setInsertionPointToStart(&if2.getThenRegion().front()); 839 auto [newChild, newChildIdx] = getLargerChild(child); 840 builder.create<scf::YieldOp>(loc, ValueRange{newChild, newChildIdx}); 841 builder.setInsertionPointToStart(&if2.getElseRegion().front()); 842 builder.create<scf::YieldOp>(loc, ValueRange{child, childIdx}); 843 builder.setInsertionPointAfter(if2); 844 builder.create<scf::YieldOp>( 845 loc, ValueRange{start, if2.getResult(0), if2.getResult(1)}); 846 847 builder.setInsertionPointAfter(ifN); 848 builder.create<func::ReturnOp>(loc); 849 } 850 851 /// Creates a function to perform heap sort on the values in the range of index 852 /// [lo, hi) with the assumption hi - lo >= 2. 853 // 854 // The generate IR corresponds to this C like algorithm: 855 // void heapSort(lo, hi, data) { 856 // n = hi - lo 857 // for i = (n-2)/2 downto 0 858 // shiftDown(lo, lo+i, n) 859 // 860 // for l = n downto 2 861 // swap(lo, lo+l-1) 862 // shiftdown(lo, lo, l-1) 863 // } 864 static void createHeapSortFunc(OpBuilder &builder, ModuleOp module, 865 func::FuncOp func, uint64_t nx, uint64_t ny, 866 bool isCoo, uint32_t nTrailingP) { 867 // Heap sort function doesn't have trailing parameters. 868 (void)nTrailingP; 869 assert(nTrailingP == 0); 870 OpBuilder::InsertionGuard insertionGuard(builder); 871 Block *entryBlock = func.addEntryBlock(); 872 builder.setInsertionPointToStart(entryBlock); 873 874 Location loc = func.getLoc(); 875 ValueRange args = entryBlock->getArguments(); 876 Value lo = args[loIdx]; 877 Value hi = args[hiIdx]; 878 Value n = builder.create<arith::SubIOp>(loc, hi, lo); 879 880 // For i = (n-2)/2 downto 0. 881 Value c0 = constantIndex(builder, loc, 0); 882 Value c1 = constantIndex(builder, loc, 1); 883 Value s = createSubTwoDividedByTwo(builder, loc, n); 884 Value up = builder.create<arith::AddIOp>(loc, s, c1); 885 scf::ForOp forI = builder.create<scf::ForOp>(loc, c0, up, c1); 886 builder.setInsertionPointToStart(forI.getBody()); 887 Value i = builder.create<arith::SubIOp>(loc, s, forI.getInductionVar()); 888 Value lopi = builder.create<arith::AddIOp>(loc, lo, i); 889 SmallVector<Value> shiftDownOperands = {lo, lopi}; 890 shiftDownOperands.append(args.begin() + xStartIdx, args.end()); 891 shiftDownOperands.push_back(n); 892 FlatSymbolRefAttr shiftDownFunc = getMangledSortHelperFunc( 893 builder, func, TypeRange(), kShiftDownFuncNamePrefix, nx, ny, isCoo, 894 shiftDownOperands, createShiftDownFunc, /*nTrailingP=*/1); 895 builder.create<func::CallOp>(loc, shiftDownFunc, TypeRange(), 896 shiftDownOperands); 897 898 builder.setInsertionPointAfter(forI); 899 // For l = n downto 2. 900 up = builder.create<arith::SubIOp>(loc, n, c1); 901 scf::ForOp forL = builder.create<scf::ForOp>(loc, c0, up, c1); 902 builder.setInsertionPointToStart(forL.getBody()); 903 Value l = builder.create<arith::SubIOp>(loc, n, forL.getInductionVar()); 904 Value loplm1 = builder.create<arith::AddIOp>(loc, lo, l); 905 loplm1 = builder.create<arith::SubIOp>(loc, loplm1, c1); 906 SmallVector<Value> swapOperands{lo, loplm1}; 907 swapOperands.append(args.begin() + xStartIdx, args.end()); 908 createSwap(builder, loc, swapOperands, nx, ny, isCoo); 909 shiftDownOperands[1] = lo; 910 shiftDownOperands[shiftDownOperands.size() - 1] = 911 builder.create<arith::SubIOp>(loc, l, c1); 912 builder.create<func::CallOp>(loc, shiftDownFunc, TypeRange(), 913 shiftDownOperands); 914 915 builder.setInsertionPointAfter(forL); 916 builder.create<func::ReturnOp>(loc); 917 } 918 919 /// A helper for generating code to perform quick sort. It partitions [lo, hi), 920 /// recursively calls quick sort to process the smaller partition and returns 921 /// the bigger partition to be processed by the enclosed while-loop. 922 static std::pair<Value, Value> 923 createQuickSort(OpBuilder &builder, ModuleOp module, func::FuncOp func, 924 ValueRange args, uint64_t nx, uint64_t ny, bool isCoo, 925 uint32_t nTrailingP) { 926 MLIRContext *context = module.getContext(); 927 Location loc = func.getLoc(); 928 Value lo = args[loIdx]; 929 Value hi = args[hiIdx]; 930 FlatSymbolRefAttr partitionFunc = getMangledSortHelperFunc( 931 builder, func, {IndexType::get(context)}, kPartitionFuncNamePrefix, nx, 932 ny, isCoo, args.drop_back(nTrailingP), createPartitionFunc); 933 Value p = builder 934 .create<func::CallOp>(loc, partitionFunc, 935 TypeRange{IndexType::get(context)}, 936 args.drop_back(nTrailingP)) 937 .getResult(0); 938 Value pP1 = 939 builder.create<arith::AddIOp>(loc, p, constantIndex(builder, loc, 1)); 940 Value lenLow = builder.create<arith::SubIOp>(loc, p, lo); 941 Value lenHigh = builder.create<arith::SubIOp>(loc, hi, p); 942 Value cond = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ule, 943 lenLow, lenHigh); 944 945 SmallVector<Type, 2> types(2, lo.getType()); // Only two types. 946 scf::IfOp ifOp = builder.create<scf::IfOp>(loc, types, cond, /*else=*/true); 947 948 Value c0 = constantIndex(builder, loc, 0); 949 auto mayRecursion = [&](Value low, Value high, Value len) { 950 Value cond = 951 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ne, len, c0); 952 scf::IfOp ifOp = builder.create<scf::IfOp>(loc, cond, /*else=*/false); 953 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 954 SmallVector<Value> operands{low, high}; 955 operands.append(args.begin() + xStartIdx, args.end()); 956 builder.create<func::CallOp>(loc, func, operands); 957 builder.setInsertionPointAfter(ifOp); 958 }; 959 960 // Recursively call quickSort to process the smaller partition and return 961 // the bigger partition to be processed by the enclosed while-loop. 962 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 963 mayRecursion(lo, p, lenLow); 964 builder.create<scf::YieldOp>(loc, ValueRange{pP1, hi}); 965 966 builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); 967 mayRecursion(pP1, hi, lenHigh); 968 builder.create<scf::YieldOp>(loc, ValueRange{lo, p}); 969 970 builder.setInsertionPointAfter(ifOp); 971 return std::make_pair(ifOp.getResult(0), ifOp.getResult(1)); 972 } 973 974 /// Creates a function to perform insertion sort on the values in the range of 975 /// index [lo, hi). 976 // 977 // The generate IR corresponds to this C like algorithm: 978 // void insertionSort(lo, hi, data) { 979 // for (i = lo+1; i < hi; i++) { 980 // d = data[i]; 981 // p = binarySearch(lo, i-1, data) 982 // for (j = 0; j > i - p; j++) 983 // data[i-j] = data[i-j-1] 984 // data[p] = d 985 // } 986 // } 987 static void createSortStableFunc(OpBuilder &builder, ModuleOp module, 988 func::FuncOp func, uint64_t nx, uint64_t ny, 989 bool isCoo, uint32_t nTrailingP) { 990 // Stable sort function doesn't use trailing parameters. 991 (void)nTrailingP; 992 assert(nTrailingP == 0); 993 OpBuilder::InsertionGuard insertionGuard(builder); 994 Block *entryBlock = func.addEntryBlock(); 995 builder.setInsertionPointToStart(entryBlock); 996 997 MLIRContext *context = module.getContext(); 998 Location loc = func.getLoc(); 999 ValueRange args = entryBlock->getArguments(); 1000 Value c1 = constantIndex(builder, loc, 1); 1001 Value lo = args[loIdx]; 1002 Value hi = args[hiIdx]; 1003 Value lop1 = builder.create<arith::AddIOp>(loc, lo, c1); 1004 1005 // Start the outer for-stmt with induction variable i. 1006 scf::ForOp forOpI = builder.create<scf::ForOp>(loc, lop1, hi, c1); 1007 builder.setInsertionPointToStart(forOpI.getBody()); 1008 Value i = forOpI.getInductionVar(); 1009 1010 // Binary search to find the insertion point p. 1011 SmallVector<Value> operands{lo, i}; 1012 operands.append(args.begin() + xStartIdx, args.end()); 1013 FlatSymbolRefAttr searchFunc = getMangledSortHelperFunc( 1014 builder, func, {IndexType::get(context)}, kBinarySearchFuncNamePrefix, nx, 1015 ny, isCoo, operands, createBinarySearchFunc); 1016 Value p = builder 1017 .create<func::CallOp>(loc, searchFunc, TypeRange{c1.getType()}, 1018 operands) 1019 .getResult(0); 1020 1021 // Move the value at data[i] to a temporary location. 1022 operands[0] = operands[1] = i; 1023 SmallVector<Value> d; 1024 forEachIJPairInAllBuffers( 1025 builder, loc, operands, nx, ny, isCoo, 1026 [&](uint64_t unused, Value i, Value unused2, Value buffer) { 1027 d.push_back(builder.create<memref::LoadOp>(loc, buffer, i)); 1028 }); 1029 1030 // Start the inner for-stmt with induction variable j, for moving data[p..i) 1031 // to data[p+1..i+1). 1032 Value imp = builder.create<arith::SubIOp>(loc, i, p); 1033 Value c0 = constantIndex(builder, loc, 0); 1034 scf::ForOp forOpJ = builder.create<scf::ForOp>(loc, c0, imp, c1); 1035 builder.setInsertionPointToStart(forOpJ.getBody()); 1036 Value j = forOpJ.getInductionVar(); 1037 Value imj = builder.create<arith::SubIOp>(loc, i, j); 1038 operands[1] = imj; 1039 operands[0] = builder.create<arith::SubIOp>(loc, imj, c1); 1040 forEachIJPairInAllBuffers( 1041 builder, loc, operands, nx, ny, isCoo, 1042 [&](uint64_t unused, Value imjm1, Value imj, Value buffer) { 1043 Value t = builder.create<memref::LoadOp>(loc, buffer, imjm1); 1044 builder.create<memref::StoreOp>(loc, t, buffer, imj); 1045 }); 1046 1047 // Store the value at data[i] to data[p]. 1048 builder.setInsertionPointAfter(forOpJ); 1049 operands[0] = operands[1] = p; 1050 forEachIJPairInAllBuffers( 1051 builder, loc, operands, nx, ny, isCoo, 1052 [&](uint64_t k, Value p, Value usused, Value buffer) { 1053 builder.create<memref::StoreOp>(loc, d[k], buffer, p); 1054 }); 1055 1056 builder.setInsertionPointAfter(forOpI); 1057 builder.create<func::ReturnOp>(loc); 1058 } 1059 1060 /// Creates a function to perform quick sort or a hybrid quick sort on the 1061 /// values in the range of index [lo, hi). 1062 // 1063 // 1064 // When nTrailingP == 0, the generated IR corresponds to this C like algorithm: 1065 // void quickSort(lo, hi, data) { 1066 // while (lo + 1 < hi) { 1067 // p = partition(low, high, data); 1068 // if (len(lo, p) < len(p+1, hi)) { 1069 // quickSort(lo, p, data); 1070 // lo = p+1; 1071 // } else { 1072 // quickSort(p + 1, hi, data); 1073 // hi = p; 1074 // } 1075 // } 1076 // } 1077 // 1078 // When nTrailingP == 1, the generated IR corresponds to this C like algorithm: 1079 // void hybridQuickSort(lo, hi, data, depthLimit) { 1080 // while (lo + 1 < hi) { 1081 // len = hi - lo; 1082 // if (len <= limit) { 1083 // insertionSort(lo, hi, data); 1084 // } else { 1085 // depthLimit --; 1086 // if (depthLimit <= 0) { 1087 // heapSort(lo, hi, data); 1088 // } else { 1089 // p = partition(low, high, data); 1090 // if (len(lo, p) < len(p+1, hi)) { 1091 // quickSort(lo, p, data, depthLimit); 1092 // lo = p+1; 1093 // } else { 1094 // quickSort(p + 1, hi, data, depthLimit); 1095 // hi = p; 1096 // } 1097 // } 1098 // } 1099 // } 1100 // } 1101 // 1102 static void createQuickSortFunc(OpBuilder &builder, ModuleOp module, 1103 func::FuncOp func, uint64_t nx, uint64_t ny, 1104 bool isCoo, uint32_t nTrailingP) { 1105 assert(nTrailingP == 1 || nTrailingP == 0); 1106 bool isHybrid = (nTrailingP == 1); 1107 OpBuilder::InsertionGuard insertionGuard(builder); 1108 Block *entryBlock = func.addEntryBlock(); 1109 builder.setInsertionPointToStart(entryBlock); 1110 1111 Location loc = func.getLoc(); 1112 SmallVector<Value> args; 1113 args.append(entryBlock->getArguments().begin(), 1114 entryBlock->getArguments().end()); 1115 Value lo = args[loIdx]; 1116 Value hi = args[hiIdx]; 1117 SmallVector<Type, 2> types(2, lo.getType()); // Only two types. 1118 scf::WhileOp whileOp = 1119 builder.create<scf::WhileOp>(loc, types, SmallVector<Value, 2>{lo, hi}); 1120 1121 // The before-region of the WhileOp. 1122 Block *before = 1123 builder.createBlock(&whileOp.getBefore(), {}, types, {loc, loc}); 1124 builder.setInsertionPointToEnd(before); 1125 lo = before->getArgument(0); 1126 hi = before->getArgument(1); 1127 Value loP1 = 1128 builder.create<arith::AddIOp>(loc, lo, constantIndex(builder, loc, 1)); 1129 Value needSort = 1130 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, loP1, hi); 1131 builder.create<scf::ConditionOp>(loc, needSort, before->getArguments()); 1132 1133 // The after-region of the WhileOp. 1134 Block *after = 1135 builder.createBlock(&whileOp.getAfter(), {}, types, {loc, loc}); 1136 builder.setInsertionPointToEnd(after); 1137 lo = after->getArgument(0); 1138 hi = after->getArgument(1); 1139 args[0] = lo; 1140 args[1] = hi; 1141 1142 if (isHybrid) { 1143 Value len = builder.create<arith::SubIOp>(loc, hi, lo); 1144 Value lenLimit = constantIndex(builder, loc, 30); 1145 Value lenCond = builder.create<arith::CmpIOp>( 1146 loc, arith::CmpIPredicate::ule, len, lenLimit); 1147 scf::IfOp lenIf = 1148 builder.create<scf::IfOp>(loc, types, lenCond, /*else=*/true); 1149 1150 // When len <= limit. 1151 builder.setInsertionPointToStart(&lenIf.getThenRegion().front()); 1152 FlatSymbolRefAttr insertionSortFunc = getMangledSortHelperFunc( 1153 builder, func, TypeRange(), kSortStableFuncNamePrefix, nx, ny, isCoo, 1154 ValueRange(args).drop_back(nTrailingP), createSortStableFunc); 1155 builder.create<func::CallOp>(loc, insertionSortFunc, TypeRange(), 1156 ValueRange(args).drop_back(nTrailingP)); 1157 builder.create<scf::YieldOp>(loc, ValueRange{lo, lo}); 1158 1159 // When len > limit. 1160 builder.setInsertionPointToStart(&lenIf.getElseRegion().front()); 1161 Value depthLimit = args.back(); 1162 depthLimit = builder.create<arith::SubIOp>(loc, depthLimit, 1163 constantI64(builder, loc, 1)); 1164 Value depthCond = 1165 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ule, 1166 depthLimit, constantI64(builder, loc, 0)); 1167 scf::IfOp depthIf = 1168 builder.create<scf::IfOp>(loc, types, depthCond, /*else=*/true); 1169 1170 // When depth exceeds limit. 1171 builder.setInsertionPointToStart(&depthIf.getThenRegion().front()); 1172 FlatSymbolRefAttr heapSortFunc = getMangledSortHelperFunc( 1173 builder, func, TypeRange(), kHeapSortFuncNamePrefix, nx, ny, isCoo, 1174 ValueRange(args).drop_back(nTrailingP), createHeapSortFunc); 1175 builder.create<func::CallOp>(loc, heapSortFunc, TypeRange(), 1176 ValueRange(args).drop_back(nTrailingP)); 1177 builder.create<scf::YieldOp>(loc, ValueRange{lo, lo}); 1178 1179 // When depth doesn't exceed limit. 1180 builder.setInsertionPointToStart(&depthIf.getElseRegion().front()); 1181 args.back() = depthLimit; 1182 std::tie(lo, hi) = 1183 createQuickSort(builder, module, func, args, nx, ny, isCoo, nTrailingP); 1184 builder.create<scf::YieldOp>(loc, ValueRange{lo, hi}); 1185 1186 builder.setInsertionPointAfter(depthIf); 1187 lo = depthIf.getResult(0); 1188 hi = depthIf.getResult(1); 1189 builder.create<scf::YieldOp>(loc, ValueRange{lo, hi}); 1190 1191 builder.setInsertionPointAfter(lenIf); 1192 lo = lenIf.getResult(0); 1193 hi = lenIf.getResult(1); 1194 } else { 1195 std::tie(lo, hi) = 1196 createQuickSort(builder, module, func, args, nx, ny, isCoo, nTrailingP); 1197 } 1198 1199 // New [lo, hi) for the next while-loop iteration. 1200 builder.create<scf::YieldOp>(loc, ValueRange{lo, hi}); 1201 1202 // After the while-loop. 1203 builder.setInsertionPointAfter(whileOp); 1204 builder.create<func::ReturnOp>(loc); 1205 } 1206 1207 /// Implements the rewriting for operator sort and sort_coo. 1208 template <typename OpTy> 1209 LogicalResult matchAndRewriteSortOp(OpTy op, ValueRange xys, uint64_t nx, 1210 uint64_t ny, bool isCoo, 1211 PatternRewriter &rewriter) { 1212 Location loc = op.getLoc(); 1213 SmallVector<Value> operands{constantIndex(rewriter, loc, 0), op.getN()}; 1214 1215 // Convert `values` to have dynamic shape and append them to `operands`. 1216 for (Value v : xys) { 1217 auto mtp = getMemRefType(v); 1218 if (!mtp.isDynamicDim(0)) { 1219 auto newMtp = 1220 MemRefType::get({ShapedType::kDynamic}, mtp.getElementType()); 1221 v = rewriter.create<memref::CastOp>(loc, newMtp, v); 1222 } 1223 operands.push_back(v); 1224 } 1225 1226 auto insertPoint = op->template getParentOfType<func::FuncOp>(); 1227 if (!insertPoint) 1228 return failure(); 1229 1230 SmallString<32> funcName; 1231 FuncGeneratorType funcGenerator; 1232 uint32_t nTrailingP = 0; 1233 switch (op.getAlgorithm()) { 1234 case SparseTensorSortKind::HybridQuickSort: { 1235 funcName = kHybridQuickSortFuncNamePrefix; 1236 funcGenerator = createQuickSortFunc; 1237 nTrailingP = 1; 1238 // As a heuristics, set depthLimit = 2 * log2(n). 1239 Value lo = operands[loIdx]; 1240 Value hi = operands[hiIdx]; 1241 Value len = rewriter.create<arith::IndexCastOp>( 1242 loc, rewriter.getI64Type(), 1243 rewriter.create<arith::SubIOp>(loc, hi, lo)); 1244 Value depthLimit = rewriter.create<arith::SubIOp>( 1245 loc, constantI64(rewriter, loc, 64), 1246 rewriter.create<math::CountLeadingZerosOp>(loc, len)); 1247 operands.push_back(depthLimit); 1248 break; 1249 } 1250 case SparseTensorSortKind::QuickSort: 1251 funcName = kQuickSortFuncNamePrefix; 1252 funcGenerator = createQuickSortFunc; 1253 break; 1254 case SparseTensorSortKind::InsertionSortStable: 1255 funcName = kSortStableFuncNamePrefix; 1256 funcGenerator = createSortStableFunc; 1257 break; 1258 case SparseTensorSortKind::HeapSort: 1259 funcName = kHeapSortFuncNamePrefix; 1260 funcGenerator = createHeapSortFunc; 1261 break; 1262 } 1263 1264 FlatSymbolRefAttr func = 1265 getMangledSortHelperFunc(rewriter, insertPoint, TypeRange(), funcName, nx, 1266 ny, isCoo, operands, funcGenerator, nTrailingP); 1267 rewriter.replaceOpWithNewOp<func::CallOp>(op, func, TypeRange(), operands); 1268 return success(); 1269 } 1270 1271 //===---------------------------------------------------------------------===// 1272 // The actual sparse buffer rewriting rules. 1273 //===---------------------------------------------------------------------===// 1274 1275 namespace { 1276 1277 /// Sparse rewriting rule for the push_back operator. 1278 struct PushBackRewriter : OpRewritePattern<PushBackOp> { 1279 public: 1280 using OpRewritePattern<PushBackOp>::OpRewritePattern; 1281 PushBackRewriter(MLIRContext *context, bool enableInit) 1282 : OpRewritePattern(context), enableBufferInitialization(enableInit) {} 1283 LogicalResult matchAndRewrite(PushBackOp op, 1284 PatternRewriter &rewriter) const override { 1285 // Rewrite push_back(buffer, value, n) to: 1286 // new_size = size(buffer) + n 1287 // if (new_size > capacity(buffer)) 1288 // while new_size > new_capacity 1289 // new_capacity = new_capacity*2 1290 // new_buffer = realloc(buffer, new_capacity) 1291 // buffer = new_buffer 1292 // subBuffer = subviewof(buffer) 1293 // linalg.fill subBuffer value 1294 // 1295 // size(buffer) += n 1296 // 1297 // The capacity check is skipped when the attribute inbounds is presented. 1298 Location loc = op->getLoc(); 1299 Value c0 = constantIndex(rewriter, loc, 0); 1300 Value buffer = op.getInBuffer(); 1301 Value capacity = rewriter.create<memref::DimOp>(loc, buffer, c0); 1302 Value size = op.getCurSize(); 1303 Value value = op.getValue(); 1304 1305 Value n = op.getN() ? op.getN() : constantIndex(rewriter, loc, 1); 1306 Value newSize = rewriter.create<arith::AddIOp>(loc, size, n); 1307 auto nValue = dyn_cast_or_null<arith::ConstantIndexOp>(n.getDefiningOp()); 1308 bool nIsOne = (nValue && nValue.value() == 1); 1309 1310 if (!op.getInbounds()) { 1311 Value cond = rewriter.create<arith::CmpIOp>( 1312 loc, arith::CmpIPredicate::ugt, newSize, capacity); 1313 1314 Value c2 = constantIndex(rewriter, loc, 2); 1315 auto bufferType = 1316 MemRefType::get({ShapedType::kDynamic}, value.getType()); 1317 scf::IfOp ifOp = rewriter.create<scf::IfOp>(loc, bufferType, cond, 1318 /*else=*/true); 1319 // True branch. 1320 rewriter.setInsertionPointToStart(&ifOp.getThenRegion().front()); 1321 if (nIsOne) { 1322 capacity = rewriter.create<arith::MulIOp>(loc, capacity, c2); 1323 } else { 1324 // Use a do-while loop to calculate the new capacity as follows: 1325 // do { new_capacity *= 2 } while (size > new_capacity) 1326 scf::WhileOp whileOp = 1327 rewriter.create<scf::WhileOp>(loc, capacity.getType(), capacity); 1328 1329 // The before-region of the WhileOp. 1330 Block *before = rewriter.createBlock(&whileOp.getBefore(), {}, 1331 {capacity.getType()}, {loc}); 1332 rewriter.setInsertionPointToEnd(before); 1333 1334 capacity = 1335 rewriter.create<arith::MulIOp>(loc, before->getArgument(0), c2); 1336 cond = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ugt, 1337 newSize, capacity); 1338 rewriter.create<scf::ConditionOp>(loc, cond, ValueRange{capacity}); 1339 // The after-region of the WhileOp. 1340 Block *after = rewriter.createBlock(&whileOp.getAfter(), {}, 1341 {capacity.getType()}, {loc}); 1342 rewriter.setInsertionPointToEnd(after); 1343 rewriter.create<scf::YieldOp>(loc, after->getArguments()); 1344 1345 rewriter.setInsertionPointAfter(whileOp); 1346 capacity = whileOp.getResult(0); 1347 } 1348 1349 Value newBuffer = 1350 rewriter.create<memref::ReallocOp>(loc, bufferType, buffer, capacity); 1351 if (enableBufferInitialization) { 1352 Value fillSize = rewriter.create<arith::SubIOp>(loc, capacity, newSize); 1353 Value fillValue = constantZero(rewriter, loc, value.getType()); 1354 Value subBuffer = rewriter.create<memref::SubViewOp>( 1355 loc, newBuffer, /*offset=*/ValueRange{newSize}, 1356 /*size=*/ValueRange{fillSize}, 1357 /*step=*/ValueRange{constantIndex(rewriter, loc, 1)}); 1358 rewriter.create<linalg::FillOp>(loc, fillValue, subBuffer); 1359 } 1360 rewriter.create<scf::YieldOp>(loc, newBuffer); 1361 1362 // False branch. 1363 rewriter.setInsertionPointToStart(&ifOp.getElseRegion().front()); 1364 rewriter.create<scf::YieldOp>(loc, buffer); 1365 1366 // Prepare for adding the value to the end of the buffer. 1367 rewriter.setInsertionPointAfter(ifOp); 1368 buffer = ifOp.getResult(0); 1369 } 1370 1371 // Add the value to the end of the buffer. 1372 if (nIsOne) { 1373 rewriter.create<memref::StoreOp>(loc, value, buffer, size); 1374 } else { 1375 Value subBuffer = rewriter.create<memref::SubViewOp>( 1376 loc, buffer, /*offset=*/ValueRange{size}, /*size=*/ValueRange{n}, 1377 /*step=*/ValueRange{constantIndex(rewriter, loc, 1)}); 1378 rewriter.create<linalg::FillOp>(loc, value, subBuffer); 1379 } 1380 1381 // Update the buffer size. 1382 rewriter.replaceOp(op, {buffer, newSize}); 1383 return success(); 1384 } 1385 1386 private: 1387 bool enableBufferInitialization; 1388 }; 1389 1390 /// Sparse rewriting rule for the sort operator. 1391 struct SortRewriter : public OpRewritePattern<SortOp> { 1392 public: 1393 using OpRewritePattern<SortOp>::OpRewritePattern; 1394 1395 LogicalResult matchAndRewrite(SortOp op, 1396 PatternRewriter &rewriter) const override { 1397 SmallVector<Value> xys(op.getXs()); 1398 xys.append(op.getYs().begin(), op.getYs().end()); 1399 return matchAndRewriteSortOp(op, xys, op.getXs().size(), /*ny=*/0, 1400 /*isCoo=*/false, rewriter); 1401 } 1402 }; 1403 1404 /// Sparse rewriting rule for the sort_coo operator. 1405 struct SortCooRewriter : public OpRewritePattern<SortCooOp> { 1406 public: 1407 using OpRewritePattern<SortCooOp>::OpRewritePattern; 1408 1409 LogicalResult matchAndRewrite(SortCooOp op, 1410 PatternRewriter &rewriter) const override { 1411 SmallVector<Value> xys; 1412 xys.push_back(op.getXy()); 1413 xys.append(op.getYs().begin(), op.getYs().end()); 1414 uint64_t nx = 1; 1415 if (auto nxAttr = op.getNxAttr()) 1416 nx = nxAttr.getInt(); 1417 1418 uint64_t ny = 0; 1419 if (auto nyAttr = op.getNyAttr()) 1420 ny = nyAttr.getInt(); 1421 1422 return matchAndRewriteSortOp(op, xys, nx, ny, 1423 /*isCoo=*/true, rewriter); 1424 } 1425 }; 1426 1427 } // namespace 1428 1429 //===---------------------------------------------------------------------===// 1430 // Methods that add patterns described in this file to a pattern list. 1431 //===---------------------------------------------------------------------===// 1432 1433 void mlir::populateSparseBufferRewriting(RewritePatternSet &patterns, 1434 bool enableBufferInitialization) { 1435 patterns.add<PushBackRewriter>(patterns.getContext(), 1436 enableBufferInitialization); 1437 patterns.add<SortRewriter, SortCooRewriter>(patterns.getContext()); 1438 } 1439