1 //===- MemoryPromotion.cpp - Utilities for moving data across GPU memories ===// 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 utilities that allow one to create IR moving the data 10 // across different levels of the GPU memory hierarchy. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "mlir/Dialect/GPU/MemoryPromotion.h" 15 #include "mlir/Dialect/GPU/GPUDialect.h" 16 #include "mlir/Dialect/LoopOps/EDSC/Builders.h" 17 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h" 18 #include "mlir/Pass/Pass.h" 19 #include "mlir/Transforms/LoopUtils.h" 20 21 using namespace mlir; 22 using namespace mlir::edsc; 23 using namespace mlir::edsc::intrinsics; 24 using namespace mlir::gpu; 25 26 /// Returns the textual name of a GPU dimension. 27 static StringRef getDimName(unsigned dim) { 28 if (dim == 0) 29 return "x"; 30 if (dim == 1) 31 return "y"; 32 if (dim == 2) 33 return "z"; 34 35 llvm_unreachable("dimension ID overflow"); 36 } 37 38 /// Emits the (imperfect) loop nest performing the copy between "from" and "to" 39 /// values using the bounds derived from the "from" value. Emits at least 40 /// GPUDialect::getNumWorkgroupDimensions() loops, completing the nest with 41 /// single-iteration loops. Maps the innermost loops to thread dimensions, in 42 /// reverse order to enable access coalescing in the innermost loop. 43 static void insertCopyLoops(OpBuilder &builder, Location loc, 44 MemRefBoundsCapture &bounds, Value from, Value to) { 45 // Create EDSC handles for bounds. 46 unsigned rank = bounds.rank(); 47 SmallVector<Value, 4> lbs, ubs, steps; 48 49 // Make sure we have enough loops to use all thread dimensions, these trivial 50 // loops should be outermost and therefore inserted first. 51 if (rank < GPUDialect::getNumWorkgroupDimensions()) { 52 unsigned extraLoops = GPUDialect::getNumWorkgroupDimensions() - rank; 53 Value zero = std_constant_index(0); 54 Value one = std_constant_index(1); 55 lbs.resize(extraLoops, zero); 56 ubs.resize(extraLoops, one); 57 steps.resize(extraLoops, one); 58 } 59 60 // Add existing bounds. 61 lbs.append(bounds.getLbs().begin(), bounds.getLbs().end()); 62 ubs.append(bounds.getUbs().begin(), bounds.getUbs().end()); 63 64 // Emit constant operations for steps. 65 steps.reserve(lbs.size()); 66 llvm::transform(bounds.getSteps(), std::back_inserter(steps), 67 [](int64_t step) { return std_constant_index(step); }); 68 69 // Obtain thread identifiers and block sizes, necessary to map to them. 70 auto indexType = builder.getIndexType(); 71 SmallVector<Value, 3> threadIds, blockDims; 72 for (unsigned i = 0; i < 3; ++i) { 73 auto dimName = builder.getStringAttr(getDimName(i)); 74 threadIds.push_back( 75 builder.create<gpu::ThreadIdOp>(loc, indexType, dimName)); 76 blockDims.push_back( 77 builder.create<gpu::BlockDimOp>(loc, indexType, dimName)); 78 } 79 80 // Produce the loop nest with copies. 81 SmallVector<Value, 8> ivs(lbs.size()); 82 LoopNestBuilder(ivs, lbs, ubs, steps)([&]() { 83 auto activeIvs = llvm::makeArrayRef(ivs).take_back(rank); 84 StdIndexedValue fromHandle(from), toHandle(to); 85 toHandle(activeIvs) = fromHandle(activeIvs); 86 }); 87 88 // Map the innermost loops to threads in reverse order. 89 for (auto en : 90 llvm::enumerate(llvm::reverse(llvm::makeArrayRef(ivs).take_back( 91 GPUDialect::getNumWorkgroupDimensions())))) { 92 Value v = en.value(); 93 auto loop = cast<loop::ForOp>(v.getParentRegion()->getParentOp()); 94 mapLoopToProcessorIds(loop, {threadIds[en.index()]}, 95 {blockDims[en.index()]}); 96 } 97 } 98 99 /// Emits the loop nests performing the copy to the designated location in the 100 /// beginning of the region, and from the designated location immediately before 101 /// the terminator of the first block of the region. The region is expected to 102 /// have one block. This boils down to the following structure 103 /// 104 /// ^bb(...): 105 /// <loop-bound-computation> 106 /// for %arg0 = ... to ... step ... { 107 /// ... 108 /// for %argN = <thread-id-x> to ... step <block-dim-x> { 109 /// %0 = load %from[%arg0, ..., %argN] 110 /// store %0, %to[%arg0, ..., %argN] 111 /// } 112 /// ... 113 /// } 114 /// gpu.barrier 115 /// <... original body ...> 116 /// gpu.barrier 117 /// for %arg0 = ... to ... step ... { 118 /// ... 119 /// for %argN = <thread-id-x> to ... step <block-dim-x> { 120 /// %1 = load %to[%arg0, ..., %argN] 121 /// store %1, %from[%arg0, ..., %argN] 122 /// } 123 /// ... 124 /// } 125 /// 126 /// Inserts the barriers unconditionally since different threads may be copying 127 /// values and reading them. An analysis would be required to eliminate barriers 128 /// in case where value is only used by the thread that copies it. Both copies 129 /// are inserted unconditionally, an analysis would be required to only copy 130 /// live-in and live-out values when necessary. This copies the entire memref 131 /// pointed to by "from". In case a smaller block would be sufficient, the 132 /// caller can create a subview of the memref and promote it instead. 133 static void insertCopies(Region ®ion, Location loc, Value from, Value to) { 134 auto fromType = from.getType().cast<MemRefType>(); 135 auto toType = to.getType().cast<MemRefType>(); 136 (void)fromType; 137 (void)toType; 138 assert(fromType.getShape() == toType.getShape()); 139 assert(fromType.getRank() != 0); 140 assert(llvm::hasSingleElement(region) && 141 "unstructured control flow not supported"); 142 143 OpBuilder builder(region.getContext()); 144 builder.setInsertionPointToStart(®ion.front()); 145 146 ScopedContext edscContext(builder, loc); 147 MemRefBoundsCapture fromBoundsCapture(from); 148 insertCopyLoops(builder, loc, fromBoundsCapture, from, to); 149 builder.create<gpu::BarrierOp>(loc); 150 151 builder.setInsertionPoint(®ion.front().back()); 152 builder.create<gpu::BarrierOp>(loc); 153 insertCopyLoops(builder, loc, fromBoundsCapture, to, from); 154 } 155 156 /// Promotes a function argument to workgroup memory in the given function. The 157 /// copies will be inserted in the beginning and in the end of the function. 158 void mlir::promoteToWorkgroupMemory(GPUFuncOp op, unsigned arg) { 159 Value value = op.getArgument(arg); 160 auto type = value.getType().dyn_cast<MemRefType>(); 161 assert(type && type.hasStaticShape() && "can only promote memrefs"); 162 163 Value attribution = 164 op.addWorkgroupAttribution(type.getShape(), type.getElementType()); 165 166 // Replace the uses first since only the original uses are currently present. 167 // Then insert the copies. 168 value.replaceAllUsesWith(attribution); 169 insertCopies(op.getBody(), op.getLoc(), value, attribution); 170 } 171