[clang] [CIR] Implement local 'cleanup' attribute (PR #238501)

Erich Keane via cfe-commits cfe-commits at lists.llvm.org
Tue Nov 3 13:57:23 PST 2026


================
@@ -32,6 +32,42 @@
 using namespace clang;
 using namespace clang::CIRGen;
 
+namespace {
+/// Call the function named by a variable's `cleanup` attribute with the
+/// variable's address when it goes out of scope.
+struct CallCleanupFunction final : EHScopeStack::Cleanup {
+  const CIRGenFunctionInfo &fnInfo;
+  Address addr;
+  QualType varType;
+  CIRGenCallee callee;
+  SourceRange attrRange;
+
+  CallCleanupFunction(cir::FuncOp cleanupFn, const CIRGenFunctionInfo *info,
+                      Address addr, QualType varType, const CleanupAttr *attr)
+      : fnInfo(*info), addr(addr), varType(varType),
+        callee(CIRGenCallee::forDirect(
+            cleanupFn, CIRGenCalleeInfo(attr->getFunctionDecl()))),
+        attrRange(attr->getRange()) {}
+
+  void emit(CIRGenFunction &cgf, Flags flags) override {
+    QualType argTy = fnInfo.arguments()[0];
+    // Sema only guarantees that these are assignable/convertible pointers (that
+    // is, the address-of the cleanup variable and the function parameter type),
+    // which don't necessarily match. Thus, we need a bitcast.
+    // For example: address-of-g is void**, but the function takes void*.
+    // void f(void* arg);
+    // __attribute__((cleanup(f))) void *g;
+    mlir::Value arg = cgf.getBuilder().createBitcast(
+        addr.getPointer().getLoc(), addr.getPointer(), cgf.convertType(argTy));
----------------
erichkeane wrote:

TBH, I didn't realize we were paying attention to AS cast yet.  Do we have a 'helper' function to do what this is doing that I should be using instead? 

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


More information about the cfe-commits mailing list