[Mlir-commits] [mlir] [mlir][spirv] Add gpu printf op lowering to spirv.CL.printf op (PR #78510)

Jakub Kuderski llvmlistbot at llvm.org
Wed Sep 18 06:50:46 PDT 2024


================
@@ -597,6 +606,120 @@ class GPUSubgroupReduceConversion final
   }
 };
 
+/// Pattern to convert a gpu.printf op into a SPIR-V CLPrintf op.
+
+LogicalResult GPUPrintfConversion::matchAndRewrite(
+    gpu::PrintfOp gpuPrintfOp, OpAdaptor adaptor,
+    ConversionPatternRewriter &rewriter) const {
+
+  Location loc = gpuPrintfOp.getLoc();
+
+  auto moduleOp = gpuPrintfOp->getParentOfType<spirv::ModuleOp>();
+
+  if (!moduleOp) {
+    return success();
+  }
+
+  const char formatStringPrefix[] = "printfMsg";
+  unsigned stringNumber = 0;
+  SmallString<16> globalVarName;
+  spirv::GlobalVariableOp globalVar;
+
+  // SPIR-V global variable is used to initialize printf
+  // format string value, if there are multiple printf messages,
+  // each global var needs to be created with a unique name.
+  // like printfMsg0, printfMsg1, ...
+  // Formulate unique global variable name after
+  // searching in the module for existing global variable names.
+  // This is to avoid name collision with existing global variables.
+  do {
+    globalVarName.clear();
+    (formatStringPrefix + llvm::Twine(stringNumber++))
+        .toStringRef(globalVarName);
+  } while (moduleOp.lookupSymbol(globalVarName));
+
+  IntegerType i8Type = rewriter.getI8Type();
+  IntegerType i32Type = rewriter.getI32Type();
+
+  // Each character of printf format string is
+  // stored as a spec constant. We need to create
+  // unique name for this spec constant like
+  // @printfMsg0_sc0, @printfMsg0_sc1, ... by searching in the module
+  // for existing spec constant names.
+  unsigned specConstantNum = 0;
+  auto createSpecConstant = [&](unsigned value) {
+    auto attr = rewriter.getI8IntegerAttr(value);
+    SmallString<16> specCstName;
+    (llvm::Twine(globalVarName) + "_sc" + llvm::Twine(specConstantNum++))
+        .toStringRef(specCstName);
+
+    return rewriter.create<spirv::SpecConstantOp>(
+        loc, rewriter.getStringAttr(specCstName), attr);
+  };
----------------
kuhar wrote:

Similar here: could we outline this code to a helper function?

https://github.com/llvm/llvm-project/pull/78510


More information about the Mlir-commits mailing list