[PATCH] D30608: Make SmallPtrSet count and find able to take const PtrType's

Daniel Berlin via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Sat Mar 4 06:37:06 PST 2017


dberlin created this revision.

For our set/map types, count/find normally take const references.
This works well for non-pointer types, but can suck for pointer
types.

DenseSet<int *> foo;
const int *b = nullptr;
foo.count(b) does not work

but the equivalent reference version does work
(patch to fix DenseSet/DenseMap coming up)
For SmallPtrSet, you have no such option.

The following will not work right now:
SmallPtrSet<int *> foo;
const int *b = nullptr;
foo.count(b);

This makes const correctness hard in some cases.
Example:
SmallPtrSet<Instruction *> InstructionsToErase;

You can't make this SmallPtrSet<const Instruction *> because then you
can't erase the instruction.  If I want to see if something is in the
set, I may only have a const Instruction *.  Given that count and find
are non-mutating, this should just work.

The places in our code base that do this resort to const_cast :(.

This patch makes count and find able to be used with const Instruction

- in the above SmallPtrSet examples.

This is a bit annoying because of where C++ applies the const, so we
have to remove the pointer type from the passed-in-type and rebuild it
with const.


https://reviews.llvm.org/D30608

Files:
  include/llvm/ADT/SmallPtrSet.h


Index: include/llvm/ADT/SmallPtrSet.h
===================================================================
--- include/llvm/ADT/SmallPtrSet.h
+++ include/llvm/ADT/SmallPtrSet.h
@@ -343,7 +343,9 @@
 /// to avoid encoding a particular small size in the interface boundary.
 template <typename PtrType>
 class SmallPtrSetImpl : public SmallPtrSetImplBase {
+  using ConstPtrType = const typename std::remove_pointer<PtrType>::type *;
   typedef PointerLikeTypeTraits<PtrType> PtrTraits;
+  typedef PointerLikeTypeTraits<ConstPtrType> ConstPtrTraits;
 
 protected:
   // Constructors that forward to the base.
@@ -375,13 +377,12 @@
   bool erase(PtrType Ptr) {
     return erase_imp(PtrTraits::getAsVoidPointer(Ptr));
   }
-
   /// count - Return 1 if the specified pointer is in the set, 0 otherwise.
-  size_type count(PtrType Ptr) const {
+  size_type count(ConstPtrType Ptr) const {
     return find(Ptr) != endPtr() ? 1 : 0;
   }
-  iterator find(PtrType Ptr) const {
-    auto *P = find_imp(PtrTraits::getAsVoidPointer(Ptr));
+  iterator find(ConstPtrType Ptr) const {
+    auto *P = find_imp(ConstPtrTraits::getAsVoidPointer(Ptr));
     return iterator(P, EndPointer());
   }
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D30608.90578.patch
Type: text/x-patch
Size: 1180 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20170304/62b8454e/attachment.bin>


More information about the llvm-commits mailing list