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

via cfe-commits cfe-commits at lists.llvm.org
Fri Sep 15 05:31:14 PDT 2023


Author: martinboehme
Date: 2023-09-15T14:31:10+02:00
New Revision: 0069004856dd216ffed48a860a38b986dfe3e871

URL: https://github.com/llvm/llvm-project/commit/0069004856dd216ffed48a860a38b986dfe3e871
DIFF: https://github.com/llvm/llvm-project/commit/0069004856dd216ffed48a860a38b986dfe3e871.diff

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

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.

Added: 
    

Modified: 
    clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 
    


################################################################################
diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index e0e3b71503d2176..cdb1bc3cd16ac7b 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -5481,6 +5481,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"(
+    class MyClass {
+    public:
+      MyClass() : Self(this) {}
+      MyClass *Self;
+    };
+
+    void target() {
+      MyClass MyObj;
+      MyClass *SelfPtr = MyObj.Self;
+      // [[p]]
+    }
+  )";
+  runDataflow(
+      Code,
+      [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
+         ASTContext &ASTCtx) {
+        ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
+
+        const ValueDecl *MyObjDecl = findValueDecl(ASTCtx, "MyObj");
+        ASSERT_THAT(MyObjDecl, NotNull());
+
+        const ValueDecl *SelfDecl = findValueDecl(ASTCtx, "SelfPtr");
+        ASSERT_THAT(SelfDecl, NotNull());
+
+        const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
+        auto &SelfVal = *cast<PointerValue>(Env.getValue(*SelfDecl));
+        EXPECT_EQ(Env.getStorageLocation(*MyObjDecl), &SelfVal.getPointeeLoc());
+      },
+      {BuiltinOptions{ContextSensitiveOptions{}}});
+}
+
 TEST(TransferTest, UnnamedBitfieldInitializer) {
   std::string Code = R"(
     struct B {};


        


More information about the cfe-commits mailing list