[clang] [CIR][CUDA] Support device-side surface reference arguments and returns (PR #249349)

via cfe-commits cfe-commits at lists.llvm.org
Sat Dec 5 22:31:23 PST 2026


https://github.com/Siya-05 created https://github.com/llvm/llvm-project/pull/249349

Related: #179278

This patch adds support for passing and returning CUDA built-in surface references in device-side CIR code generation, preserving their semantic CIR type and NVPTX device-handle representation (`i64`).

## Changes

- Handle `CUDADeviceSurfaceType` in call argument emission
- Add a target-specific hook for device-side surface copies in NVPTX
- Preserve alignment in parameter stores and return loads
- Add regression tests with shared LLVM IR checks against original Clang CodeGen

Global surface handle extraction is left for a follow-up patch.

## Testing

- `clang/test/CIR/CodeGenCUDA/surface-abi.cu`
- `clang/test/CIR/CodeGenCUDA/surface.cu`
- Full `clang/test/CIR` suite: 1488 passed, 53 unsupported, 1 expected failure, 0 unexpected failures

>From 534112a4e3679cf978b8715b4a85c9384374c054 Mon Sep 17 00:00:00 2001
From: Sivapriya <sivapriyaofficial2005 at gmail.com>
Date: Sun, 6 Dec 2026 10:01:48 +0400
Subject: [PATCH] [CIR][CUDA] Support device-side surface reference arguments
 and returns

---
 clang/lib/CIR/CodeGen/CIRGenCall.cpp          |  3 +-
 clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp |  7 +-
 clang/lib/CIR/CodeGen/CIRGenFunction.cpp      | 17 +++--
 clang/lib/CIR/CodeGen/CIRGenStmt.cpp          | 15 +++--
 clang/lib/CIR/CodeGen/TargetInfo.h            |  8 +++
 clang/lib/CIR/CodeGen/Targets/NVPTX.cpp       | 33 ++++++++++
 clang/test/CIR/CodeGenCUDA/surface-abi.cu     | 66 +++++++++++++++++++
 7 files changed, 139 insertions(+), 10 deletions(-)
 create mode 100644 clang/test/CIR/CodeGenCUDA/surface-abi.cu

diff --git a/clang/lib/CIR/CodeGen/CIRGenCall.cpp b/clang/lib/CIR/CodeGen/CIRGenCall.cpp
index 26e055256739bc..dc5af3a7cfc554 100644
--- a/clang/lib/CIR/CodeGen/CIRGenCall.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenCall.cpp
@@ -1300,7 +1300,8 @@ RValue CIRGenFunction::emitCall(const CIRGenFunctionInfo &funcInfo,
 
     mlir::Type argType = convertType(canQualArgType);
     if (!mlir::isa<cir::RecordType>(argType) &&
-        !mlir::isa<cir::ComplexType>(argType)) {
+        !mlir::isa<cir::ComplexType>(argType) &&
+        !mlir::isa<cir::CUDADeviceSurfaceType>(argType)) {
       mlir::Value v;
       if (arg.isAggregate())
         cgm.errorNYI(loc, "emitCall: aggregate call argument");
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp b/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
index 02a47fb27a93c1..c0d2b07612eedc 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
@@ -1391,8 +1391,13 @@ void CIRGenFunction::emitAggregateCopy(LValue dest, LValue src, QualType ty,
     }
   }
 
-  assert(!cir::MissingFeatures::cudaSupport());
+  if (getLangOpts().CUDAIsDevice && ty->isCUDADeviceBuiltinSurfaceType()) {
+    if (getTargetHooks().emitCUDADeviceBuiltinSurfaceDeviceCopy(*this, dest,
+                                                                src))
+      return;
+  }
 
+  assert(!cir::MissingFeatures::cudaSupport());
   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
   // C99 6.5.16.1p3, which states "If the value being stored in an object is
   // read from another object that overlaps in anyway the storage of the first
diff --git a/clang/lib/CIR/CodeGen/CIRGenFunction.cpp b/clang/lib/CIR/CodeGen/CIRGenFunction.cpp
index ad85d2b42509f6..d5a5612921cf79 100644
--- a/clang/lib/CIR/CodeGen/CIRGenFunction.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenFunction.cpp
@@ -386,8 +386,14 @@ cir::ReturnOp CIRGenFunction::LexicalScope::emitReturn(mlir::Location loc) {
     // Load the value from the return slot and return it. Like classic
     // codegen's EmitFunctionEpilog, the cir-forward-return-slot pass later
     // returns the stored value directly and drops the slot.
-    auto value = cir::LoadOp::create(
-        builder, loc, fn.getFunctionType().getReturnType(), *cgf.fnRetAlloca);
+    auto value =
+        mlir::isa<cir::CUDADeviceSurfaceType>(
+            fn.getFunctionType().getReturnType())
+            ? builder.createLoad(loc, Address(*cgf.fnRetAlloca,
+                                              cgf.returnValue.getAlignment()))
+            : cir::LoadOp::create(builder, loc,
+                                  fn.getFunctionType().getReturnType(),
+                                  *cgf.fnRetAlloca);
     return cir::ReturnOp::create(builder, loc,
                                  llvm::ArrayRef(value.getResult()));
   }
@@ -547,8 +553,11 @@ void CIRGenFunction::emitFunctionProlog(const FunctionArgList &args,
     // Location of the store to the param storage tracked as beginning of
     // the function body.
     mlir::Location fnBodyBegin = getLoc(bodyBeginLoc);
-    cir::StoreOp store = builder.CIRBaseBuilderTy::createStore(
-        fnBodyBegin, paramVal, addr.getPointer());
+    cir::StoreOp store =
+        mlir::isa<cir::CUDADeviceSurfaceType>(paramVal.getType())
+            ? builder.createStore(fnBodyBegin, paramVal, addr)
+            : builder.CIRBaseBuilderTy::createStore(fnBodyBegin, paramVal,
+                                                    addr.getPointer());
     if (hasScalarEvaluationKind(paramVar->getType()))
       decorateOperationWithTBAA(store,
                                 cgm.getTBAAAccessInfo(paramVar->getType()));
diff --git a/clang/lib/CIR/CodeGen/CIRGenStmt.cpp b/clang/lib/CIR/CodeGen/CIRGenStmt.cpp
index 7d5a65ead461fb..e1268152eee4e2 100644
--- a/clang/lib/CIR/CodeGen/CIRGenStmt.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenStmt.cpp
@@ -761,8 +761,12 @@ mlir::LogicalResult CIRGenFunction::emitReturnStmt(const ReturnStmt &s) {
     // returns the stored value directly and drops the slot.
     cir::AllocaOp retAlloca =
         mlir::cast<cir::AllocaOp>(fnRetAlloca->getDefiningOp());
-    auto value = cir::LoadOp::create(builder, loc, retAlloca.getAllocaType(),
-                                     *fnRetAlloca);
+    auto value =
+        mlir::isa<cir::CUDADeviceSurfaceType>(retAlloca.getAllocaType())
+            ? builder.createLoad(
+                  loc, Address(*fnRetAlloca, returnValue.getAlignment()))
+            : cir::LoadOp::create(builder, loc, retAlloca.getAllocaType(),
+                                  *fnRetAlloca);
 
     cir::ReturnOp::create(builder, loc, {value});
   } else {
@@ -1663,8 +1667,11 @@ void CIRGenFunction::emitReturnOfRValue(mlir::Location loc, RValue rv,
   // returns the stored value directly and drops the slot.
   cir::AllocaOp retAlloca =
       mlir::cast<cir::AllocaOp>(fnRetAlloca->getDefiningOp());
-  auto value = cir::LoadOp::create(builder, loc, retAlloca.getAllocaType(),
-                                   *fnRetAlloca);
+  auto value = mlir::isa<cir::CUDADeviceSurfaceType>(retAlloca.getAllocaType())
+                   ? builder.createLoad(
+                         loc, Address(*fnRetAlloca, returnValue.getAlignment()))
+                   : cir::LoadOp::create(
+                         builder, loc, retAlloca.getAllocaType(), *fnRetAlloca);
 
   cir::ReturnOp::create(builder, loc, {value});
 }
diff --git a/clang/lib/CIR/CodeGen/TargetInfo.h b/clang/lib/CIR/CodeGen/TargetInfo.h
index 62acf0afa80020..e8b03967b87c83 100644
--- a/clang/lib/CIR/CodeGen/TargetInfo.h
+++ b/clang/lib/CIR/CodeGen/TargetInfo.h
@@ -42,6 +42,7 @@ bool isEmptyFieldForABI(const ASTContext &context, const FieldDecl *fd);
 bool isEmptyRecordForABI(const ASTContext &context, QualType t);
 
 class CIRGenFunction;
+class LValue;
 
 class TargetCIRGenInfo {
   std::unique_ptr<ABIInfo> info;
@@ -86,6 +87,13 @@ class TargetCIRGenInfo {
     return nullptr;
   }
 
+  /// Emit the device-side copy of the builtin surface type.
+  virtual bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CIRGenFunction &cgf,
+                                                      const LValue &dest,
+                                                      const LValue &src) const {
+    return false;
+  }
+
   virtual mlir::Type getCUDADeviceBuiltinTextureDeviceType() const {
     return nullptr;
   }
diff --git a/clang/lib/CIR/CodeGen/Targets/NVPTX.cpp b/clang/lib/CIR/CodeGen/Targets/NVPTX.cpp
index 4cf8bc18ee478c..4b5817ffe31bc9 100644
--- a/clang/lib/CIR/CodeGen/Targets/NVPTX.cpp
+++ b/clang/lib/CIR/CodeGen/Targets/NVPTX.cpp
@@ -11,6 +11,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "../ABIInfo.h"
+#include "../CIRGenFunction.h"
 #include "../CIRGenModule.h"
 #include "../TargetInfo.h"
 
@@ -117,6 +118,38 @@ class NVPTXTargetCIRGenInfo : public TargetCIRGenInfo {
     return cir::CUDADeviceSurfaceType::get(&getABIInfo().cgt.getMLIRContext());
   }
 
+  bool
+  emitCUDADeviceBuiltinSurfaceDeviceCopy(CIRGenFunction &cgf,
+                                         const LValue &dest,
+                                         const LValue &src) const override {
+    Address destPtr = dest.getAddress();
+    Address srcPtr = src.getAddress();
+
+    if (!mlir::isa<cir::CUDADeviceSurfaceType>(srcPtr.getElementType()))
+      return false;
+
+    mlir::Location loc = srcPtr.getPointer().getLoc();
+
+    // Look through address space casts to identify global surfaces.
+    mlir::Value ptr = srcPtr.getPointer();
+    while (auto castOp = ptr.getDefiningOp<cir::CastOp>()) {
+      if (castOp.getKind() != cir::CastKind::address_space)
+        break;
+      ptr = castOp.getSrc();
+    }
+
+    // Global surfaces require target-specific handle extraction.
+    if (ptr.getDefiningOp<cir::GetGlobalOp>()) {
+      cgf.cgm.errorNYI(loc, "CUDA device global surface copy");
+      return true;
+    }
+
+    CIRGenBuilderTy &builder = cgf.cgm.getBuilder();
+    mlir::Value handle = builder.createLoad(loc, srcPtr, src.isVolatile());
+    builder.createStore(loc, handle, destPtr, dest.isVolatile());
+    return true;
+  }
+
   mlir::Type getCUDADeviceBuiltinTextureDeviceType() const override {
     return cir::CUDADeviceTextureType::get(&getABIInfo().cgt.getMLIRContext());
   }
diff --git a/clang/test/CIR/CodeGenCUDA/surface-abi.cu b/clang/test/CIR/CodeGenCUDA/surface-abi.cu
new file mode 100644
index 00000000000000..36cca4e9d1ce90
--- /dev/null
+++ b/clang/test/CIR/CodeGenCUDA/surface-abi.cu
@@ -0,0 +1,66 @@
+// REQUIRES: nvptx-registered-target
+
+// RUN: %clang_cc1 -fclangir -std=c++11 -fcuda-is-device -triple nvptx64-nvidia-cuda -emit-cir -o - %s | FileCheck --check-prefix=CIR %s
+// RUN: %clang_cc1 -fclangir -std=c++11 -fcuda-is-device -triple nvptx64-nvidia-cuda -emit-llvm -o - %s | FileCheck --check-prefix=LLVM %s
+// RUN: %clang_cc1 -std=c++11 -fcuda-is-device -triple nvptx64-nvidia-cuda -emit-llvm -o - %s | FileCheck --check-prefix=LLVM %s
+
+template <typename T, int dim>
+struct __attribute__((device_builtin_surface_type)) surface {
+  int desc[2];
+};
+
+using Surface = surface<void, 2>;
+
+// CIR-LABEL: cir.func {{.*}} @_Z14accept_surface7surfaceIvLi2EE
+// CIR-SAME: (%[[ARG:.*]]: !cir.cuda_surface
+// CIR: %[[ADDR:.*]] = cir.alloca "s" align(4)
+// CIR: cir.store align(4) %[[ARG]], %[[ADDR]]
+
+// LLVM-LABEL: define {{.*}}void @_Z14accept_surface7surfaceIvLi2EE
+// LLVM-SAME: (i64 %[[ARG:.*]])
+// LLVM: %[[ADDR:.*]] = alloca i64, align 4
+// LLVM: store i64 %[[ARG]], ptr %[[ADDR]], align 4
+
+__attribute__((device))
+void accept_surface(Surface s) {}
+
+// CIR-LABEL: cir.func {{.*}} @_Z14return_surface7surfaceIvLi2EE
+// CIR-SAME: -> !cir.cuda_surface
+// CIR: cir.load align(4)
+// CIR: cir.store align(4)
+// CIR: cir.return %{{.*}} : !cir.cuda_surface
+
+// LLVM-LABEL: define {{.*}}i64 @_Z14return_surface7surfaceIvLi2EE
+// LLVM: %[[HANDLE:.*]] = load i64, ptr %{{.*}}, align 4
+// LLVM: ret i64 %[[HANDLE]]
+
+__attribute__((device))
+Surface return_surface(Surface s) {
+  return s;
+}
+
+// CIR-LABEL: cir.func {{.*}} @_Z12call_surface7surfaceIvLi2EE
+// CIR: cir.call @_Z14accept_surface7surfaceIvLi2EE
+// CIR-SAME: (!cir.cuda_surface) -> ()
+
+// LLVM-LABEL: define {{.*}}void @_Z12call_surface7surfaceIvLi2EE
+// LLVM: call void @_Z14accept_surface7surfaceIvLi2EE(i64
+
+__attribute__((device))
+void call_surface(Surface s) {
+  accept_surface(s);
+}
+
+// CIR-LABEL: cir.func {{.*}} @_Z19call_return_surface7surfaceIvLi2EE
+// CIR: cir.call @_Z14return_surface7surfaceIvLi2EE
+// CIR-SAME: (!cir.cuda_surface) -> !cir.cuda_surface
+// CIR: cir.return %{{.*}} : !cir.cuda_surface
+
+// LLVM-LABEL: define {{.*}}i64 @_Z19call_return_surface7surfaceIvLi2EE
+// LLVM: %[[RESULT:.*]] = call i64 @_Z14return_surface7surfaceIvLi2EE(i64
+// LLVM-NEXT: ret i64 %[[RESULT]]
+
+__attribute__((device))
+Surface call_return_surface(Surface s) {
+  return return_surface(s);
+}



More information about the cfe-commits mailing list