[clang] [clang][dataflow] Add a test for context-sensitive analysis on a self-referential class. (PR #66359)

via cfe-commits cfe-commits at lists.llvm.org
Thu Sep 14 04:08:09 PDT 2023


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang
            
<details>
<summary>Changes</summary>
The test demonstrates that the `this` pointer seen in the constructor has the
same value as the address of the variable the object is constructed into.

--
Full diff: https://github.com/llvm/llvm-project/pull/66359.diff

1 Files Affected:

- (modified) clang/unittests/Analysis/FlowSensitive/TransferTest.cpp (+35) 


<pre>
diff --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index 05ee5df0e95a433..e29dc86d7aaffb3 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -5457,6 +5457,41 @@ TEST(TransferTest, ContextSensitiveConstructorDefault) {
       {BuiltinOptions{ContextSensitiveOptions{}}});
 }
 
+TEST(TransferTest, ContextSensitiveSelfReferentialClass) {
+  // Test that the `this` pointer seen in the constructor has the same value
+  // as the address of the variable the object is constructed into.
+  std::string Code = R&quot;(
+    class MyClass {
+    public:
+      MyClass() : Self(this) {}
+      MyClass *Self;
+    };
+
+    void target() {
+      MyClass MyObj;
+      MyClass *SelfPtr = MyObj.Self;
+      // [[p]]
+    }
+  )&quot;;
+  runDataflow(
+      Code,
+      [](const llvm::StringMap&lt;DataflowAnalysisState&lt;NoopLattice&gt;&gt; &amp;Results,
+         ASTContext &amp;ASTCtx) {
+        ASSERT_THAT(Results.keys(), UnorderedElementsAre(&quot;p&quot;));
+
+        const ValueDecl *MyObjDecl = findValueDecl(ASTCtx, &quot;MyObj&quot;);
+        ASSERT_THAT(MyObjDecl, NotNull());
+
+        const ValueDecl *SelfDecl = findValueDecl(ASTCtx, &quot;SelfPtr&quot;);
+        ASSERT_THAT(SelfDecl, NotNull());
+
+        const Environment &amp;Env = getEnvironmentAtAnnotation(Results, &quot;p&quot;);
+        auto &amp;SelfVal = *cast&lt;PointerValue&gt;(Env.getValue(*SelfDecl));
+        EXPECT_EQ(Env.getStorageLocation(*MyObjDecl), &amp;SelfVal.getPointeeLoc());
+      },
+      {BuiltinOptions{ContextSensitiveOptions{}}});
+}
+
 TEST(TransferTest, UnnamedBitfieldInitializer) {
   std::string Code = R&quot;(
     struct B {};
</pre>
</details>


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


More information about the cfe-commits mailing list