Skip to content

Commit 0069004

Browse files
authored
[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.
1 parent c0a64ec commit 0069004

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5481,6 +5481,41 @@ TEST(TransferTest, ContextSensitiveConstructorDefault) {
54815481
{BuiltinOptions{ContextSensitiveOptions{}}});
54825482
}
54835483

5484+
TEST(TransferTest, ContextSensitiveSelfReferentialClass) {
5485+
// Test that the `this` pointer seen in the constructor has the same value
5486+
// as the address of the variable the object is constructed into.
5487+
std::string Code = R"(
5488+
class MyClass {
5489+
public:
5490+
MyClass() : Self(this) {}
5491+
MyClass *Self;
5492+
};
5493+
5494+
void target() {
5495+
MyClass MyObj;
5496+
MyClass *SelfPtr = MyObj.Self;
5497+
// [[p]]
5498+
}
5499+
)";
5500+
runDataflow(
5501+
Code,
5502+
[](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
5503+
ASTContext &ASTCtx) {
5504+
ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
5505+
5506+
const ValueDecl *MyObjDecl = findValueDecl(ASTCtx, "MyObj");
5507+
ASSERT_THAT(MyObjDecl, NotNull());
5508+
5509+
const ValueDecl *SelfDecl = findValueDecl(ASTCtx, "SelfPtr");
5510+
ASSERT_THAT(SelfDecl, NotNull());
5511+
5512+
const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
5513+
auto &SelfVal = *cast<PointerValue>(Env.getValue(*SelfDecl));
5514+
EXPECT_EQ(Env.getStorageLocation(*MyObjDecl), &SelfVal.getPointeeLoc());
5515+
},
5516+
{BuiltinOptions{ContextSensitiveOptions{}}});
5517+
}
5518+
54845519
TEST(TransferTest, UnnamedBitfieldInitializer) {
54855520
std::string Code = R"(
54865521
struct B {};

0 commit comments

Comments
 (0)