Clang `unused-but-set-variable` warnings should not apply to `__attribute__((objc_pre...
authorMichael Wyman <michael@mwyman.com>
Wed, 23 Feb 2022 18:47:16 +0000 (10:47 -0800)
committerMichael Wyman <michael@mwyman.com>
Thu, 24 Feb 2022 22:26:05 +0000 (14:26 -0800)
The `objc_precise_lifetime` attribute is applied to Objective-C pointers to ensure the optimizer does not prematurely release an object under Automatic Reference Counting (ARC). It is a common enough pattern to assign values to these variables but not reference them otherwise, and annotating them with `__unused` is not really correct as they are being used to ensure an object's lifetime.

Differential Revision: https://reviews.llvm.org/D120372

clang/lib/Sema/SemaDecl.cpp
clang/test/SemaObjC/objc-precise-lifetime-unused-variable.m [new file with mode: 0644]

index 52d9a23..671aeb7 100644 (file)
@@ -2016,6 +2016,12 @@ void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
     return;
 
+  // Don't warn about Objective-C pointer variables with precise lifetime
+  // semantics; they can be used to ensure ARC releases the object at a known
+  // time, which may mean assignment but no other references.
+  if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
+    return;
+
   auto iter = RefsMinusAssignments.find(VD);
   if (iter == RefsMinusAssignments.end())
     return;
diff --git a/clang/test/SemaObjC/objc-precise-lifetime-unused-variable.m b/clang/test/SemaObjC/objc-precise-lifetime-unused-variable.m
new file mode 100644 (file)
index 0000000..2a140a8
--- /dev/null
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macos11 -fsyntax-only -fobjc-arc -fblocks -verify -Wunused-but-set-variable -Wno-objc-root-class %s
+
+id getFoo(void);
+
+void test() {
+  // no diagnostics for objects with precise lifetime semantics.
+  __attribute__((objc_precise_lifetime)) id x;
+  x = getFoo();
+
+  id x2; // expected-warning {{variable 'x2' set but not used}}
+  x2 = getFoo();
+
+  do {
+    __attribute__((objc_precise_lifetime)) id y;
+    y = getFoo();
+
+    id y2; // expected-warning {{variable 'y2' set but not used}}
+    y2 = getFoo();
+  } while(0);
+
+  x = ((void *)0);
+}