[clang][dataflow] Fix MapLattice::insert() to not drop return value
authorEric Li <li.zhe.hua@gmail.com>
Mon, 25 Jul 2022 16:18:53 +0000 (12:18 -0400)
committerEric Li <li.zhe.hua@gmail.com>
Mon, 25 Jul 2022 18:24:33 +0000 (14:24 -0400)
Fix `MapLattice` API to return `std::pair<iterator, bool>`,
allowing users to detect when an element has been inserted without
performing a redundant map lookup.

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

clang/include/clang/Analysis/FlowSensitive/MapLattice.h
clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp

index 014cd60..16b0c97 100644 (file)
@@ -54,10 +54,13 @@ public:
   // The `bottom` element is the empty map.
   static MapLattice bottom() { return MapLattice(); }
 
-  void insert(const std::pair<const key_type, mapped_type> &P) { C.insert(P); }
+  std::pair<iterator, bool>
+  insert(const std::pair<const key_type, mapped_type> &P) {
+    return C.insert(P);
+  }
 
-  void insert(std::pair<const key_type, mapped_type> &&P) {
-    C.insert(std::move(P));
+  std::pair<iterator, bool> insert(std::pair<const key_type, mapped_type> &&P) {
+    return C.insert(std::move(P));
   }
 
   unsigned size() const { return C.size(); }
index d3436e8..f6fe81e 100644 (file)
@@ -50,13 +50,18 @@ static constexpr int Key1 = 0;
 static constexpr int Key2 = 1;
 
 namespace {
+using ::testing::_;
 using ::testing::Pair;
 using ::testing::UnorderedElementsAre;
 
 TEST(MapLatticeTest, InsertWorks) {
   MapLattice<int, BooleanLattice> Lattice;
-  Lattice.insert({Key1, BooleanLattice(false)});
-  Lattice.insert({Key2, BooleanLattice(false)});
+  EXPECT_THAT(Lattice.insert({Key1, BooleanLattice(false)}), Pair(_, true));
+  EXPECT_THAT(Lattice.insert({Key2, BooleanLattice(false)}), Pair(_, true));
+
+  // Insertion fails on collision.
+  EXPECT_THAT(Lattice.insert({Key1, BooleanLattice(false)}), Pair(_, false));
+  EXPECT_THAT(Lattice.insert({Key2, BooleanLattice(false)}), Pair(_, false));
 
   EXPECT_THAT(Lattice, UnorderedElementsAre(Pair(Key1, BooleanLattice(false)),
                                             Pair(Key2, BooleanLattice(false))));