Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:10

0001 //===- StringMap.h - String Hash table map interface ------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 ///
0009 /// \file
0010 /// This file defines the StringMap class.
0011 ///
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_ADT_STRINGMAP_H
0015 #define LLVM_ADT_STRINGMAP_H
0016 
0017 #include "llvm/ADT/StringMapEntry.h"
0018 #include "llvm/ADT/iterator.h"
0019 #include "llvm/Support/AllocatorBase.h"
0020 #include "llvm/Support/PointerLikeTypeTraits.h"
0021 #include <initializer_list>
0022 #include <iterator>
0023 
0024 namespace llvm {
0025 
0026 template <typename ValueTy> class StringMapConstIterator;
0027 template <typename ValueTy> class StringMapIterator;
0028 template <typename ValueTy> class StringMapKeyIterator;
0029 
0030 /// StringMapImpl - This is the base class of StringMap that is shared among
0031 /// all of its instantiations.
0032 class StringMapImpl {
0033 protected:
0034   // Array of NumBuckets pointers to entries, null pointers are holes.
0035   // TheTable[NumBuckets] contains a sentinel value for easy iteration. Followed
0036   // by an array of the actual hash values as unsigned integers.
0037   StringMapEntryBase **TheTable = nullptr;
0038   unsigned NumBuckets = 0;
0039   unsigned NumItems = 0;
0040   unsigned NumTombstones = 0;
0041   unsigned ItemSize;
0042 
0043 protected:
0044   explicit StringMapImpl(unsigned itemSize) : ItemSize(itemSize) {}
0045   StringMapImpl(StringMapImpl &&RHS)
0046       : TheTable(RHS.TheTable), NumBuckets(RHS.NumBuckets),
0047         NumItems(RHS.NumItems), NumTombstones(RHS.NumTombstones),
0048         ItemSize(RHS.ItemSize) {
0049     RHS.TheTable = nullptr;
0050     RHS.NumBuckets = 0;
0051     RHS.NumItems = 0;
0052     RHS.NumTombstones = 0;
0053   }
0054 
0055   StringMapImpl(unsigned InitSize, unsigned ItemSize);
0056   ~StringMapImpl() { free(TheTable); }
0057   unsigned RehashTable(unsigned BucketNo = 0);
0058 
0059   /// LookupBucketFor - Look up the bucket that the specified string should end
0060   /// up in.  If it already exists as a key in the map, the Item pointer for the
0061   /// specified bucket will be non-null.  Otherwise, it will be null.  In either
0062   /// case, the FullHashValue field of the bucket will be set to the hash value
0063   /// of the string.
0064   unsigned LookupBucketFor(StringRef Key) {
0065     return LookupBucketFor(Key, hash(Key));
0066   }
0067 
0068   /// Overload that explicitly takes precomputed hash(Key).
0069   unsigned LookupBucketFor(StringRef Key, uint32_t FullHashValue);
0070 
0071   /// FindKey - Look up the bucket that contains the specified key. If it exists
0072   /// in the map, return the bucket number of the key.  Otherwise return -1.
0073   /// This does not modify the map.
0074   int FindKey(StringRef Key) const { return FindKey(Key, hash(Key)); }
0075 
0076   /// Overload that explicitly takes precomputed hash(Key).
0077   int FindKey(StringRef Key, uint32_t FullHashValue) const;
0078 
0079   /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
0080   /// delete it.  This aborts if the value isn't in the table.
0081   void RemoveKey(StringMapEntryBase *V);
0082 
0083   /// RemoveKey - Remove the StringMapEntry for the specified key from the
0084   /// table, returning it.  If the key is not in the table, this returns null.
0085   StringMapEntryBase *RemoveKey(StringRef Key);
0086 
0087   /// Allocate the table with the specified number of buckets and otherwise
0088   /// setup the map as empty.
0089   void init(unsigned Size);
0090 
0091 public:
0092   static constexpr uintptr_t TombstoneIntVal =
0093       static_cast<uintptr_t>(-1)
0094       << PointerLikeTypeTraits<StringMapEntryBase *>::NumLowBitsAvailable;
0095 
0096   static StringMapEntryBase *getTombstoneVal() {
0097     return reinterpret_cast<StringMapEntryBase *>(TombstoneIntVal);
0098   }
0099 
0100   unsigned getNumBuckets() const { return NumBuckets; }
0101   unsigned getNumItems() const { return NumItems; }
0102 
0103   bool empty() const { return NumItems == 0; }
0104   unsigned size() const { return NumItems; }
0105 
0106   /// Returns the hash value that will be used for the given string.
0107   /// This allows precomputing the value and passing it explicitly
0108   /// to some of the functions.
0109   /// The implementation of this function is not guaranteed to be stable
0110   /// and may change.
0111   static uint32_t hash(StringRef Key);
0112 
0113   void swap(StringMapImpl &Other) {
0114     std::swap(TheTable, Other.TheTable);
0115     std::swap(NumBuckets, Other.NumBuckets);
0116     std::swap(NumItems, Other.NumItems);
0117     std::swap(NumTombstones, Other.NumTombstones);
0118   }
0119 };
0120 
0121 /// StringMap - This is an unconventional map that is specialized for handling
0122 /// keys that are "strings", which are basically ranges of bytes. This does some
0123 /// funky memory allocation and hashing things to make it extremely efficient,
0124 /// storing the string data *after* the value in the map.
0125 template <typename ValueTy, typename AllocatorTy = MallocAllocator>
0126 class LLVM_ALLOCATORHOLDER_EMPTYBASE StringMap
0127     : public StringMapImpl,
0128       private detail::AllocatorHolder<AllocatorTy> {
0129   using AllocTy = detail::AllocatorHolder<AllocatorTy>;
0130 
0131 public:
0132   using MapEntryTy = StringMapEntry<ValueTy>;
0133 
0134   StringMap() : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {}
0135 
0136   explicit StringMap(unsigned InitialSize)
0137       : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))) {}
0138 
0139   explicit StringMap(AllocatorTy A)
0140       : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))), AllocTy(A) {}
0141 
0142   StringMap(unsigned InitialSize, AllocatorTy A)
0143       : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))),
0144         AllocTy(A) {}
0145 
0146   StringMap(std::initializer_list<std::pair<StringRef, ValueTy>> List)
0147       : StringMapImpl(List.size(), static_cast<unsigned>(sizeof(MapEntryTy))) {
0148     insert(List);
0149   }
0150 
0151   StringMap(StringMap &&RHS)
0152       : StringMapImpl(std::move(RHS)), AllocTy(std::move(RHS.getAllocator())) {}
0153 
0154   StringMap(const StringMap &RHS)
0155       : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))),
0156         AllocTy(RHS.getAllocator()) {
0157     if (RHS.empty())
0158       return;
0159 
0160     // Allocate TheTable of the same size as RHS's TheTable, and set the
0161     // sentinel appropriately (and NumBuckets).
0162     init(RHS.NumBuckets);
0163     unsigned *HashTable = (unsigned *)(TheTable + NumBuckets + 1),
0164              *RHSHashTable = (unsigned *)(RHS.TheTable + NumBuckets + 1);
0165 
0166     NumItems = RHS.NumItems;
0167     NumTombstones = RHS.NumTombstones;
0168     for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
0169       StringMapEntryBase *Bucket = RHS.TheTable[I];
0170       if (!Bucket || Bucket == getTombstoneVal()) {
0171         TheTable[I] = Bucket;
0172         continue;
0173       }
0174 
0175       TheTable[I] = MapEntryTy::create(
0176           static_cast<MapEntryTy *>(Bucket)->getKey(), getAllocator(),
0177           static_cast<MapEntryTy *>(Bucket)->getValue());
0178       HashTable[I] = RHSHashTable[I];
0179     }
0180 
0181     // Note that here we've copied everything from the RHS into this object,
0182     // tombstones included. We could, instead, have re-probed for each key to
0183     // instantiate this new object without any tombstone buckets. The
0184     // assumption here is that items are rarely deleted from most StringMaps,
0185     // and so tombstones are rare, so the cost of re-probing for all inputs is
0186     // not worthwhile.
0187   }
0188 
0189   StringMap &operator=(StringMap RHS) {
0190     StringMapImpl::swap(RHS);
0191     std::swap(getAllocator(), RHS.getAllocator());
0192     return *this;
0193   }
0194 
0195   ~StringMap() {
0196     // Delete all the elements in the map, but don't reset the elements
0197     // to default values.  This is a copy of clear(), but avoids unnecessary
0198     // work not required in the destructor.
0199     if (!empty()) {
0200       for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
0201         StringMapEntryBase *Bucket = TheTable[I];
0202         if (Bucket && Bucket != getTombstoneVal()) {
0203           static_cast<MapEntryTy *>(Bucket)->Destroy(getAllocator());
0204         }
0205       }
0206     }
0207   }
0208 
0209   using AllocTy::getAllocator;
0210 
0211   using key_type = const char *;
0212   using mapped_type = ValueTy;
0213   using value_type = StringMapEntry<ValueTy>;
0214   using size_type = size_t;
0215 
0216   using const_iterator = StringMapConstIterator<ValueTy>;
0217   using iterator = StringMapIterator<ValueTy>;
0218 
0219   iterator begin() { return iterator(TheTable, NumBuckets == 0); }
0220   iterator end() { return iterator(TheTable + NumBuckets, true); }
0221   const_iterator begin() const {
0222     return const_iterator(TheTable, NumBuckets == 0);
0223   }
0224   const_iterator end() const {
0225     return const_iterator(TheTable + NumBuckets, true);
0226   }
0227 
0228   iterator_range<StringMapKeyIterator<ValueTy>> keys() const {
0229     return make_range(StringMapKeyIterator<ValueTy>(begin()),
0230                       StringMapKeyIterator<ValueTy>(end()));
0231   }
0232 
0233   iterator find(StringRef Key) { return find(Key, hash(Key)); }
0234 
0235   iterator find(StringRef Key, uint32_t FullHashValue) {
0236     int Bucket = FindKey(Key, FullHashValue);
0237     if (Bucket == -1)
0238       return end();
0239     return iterator(TheTable + Bucket, true);
0240   }
0241 
0242   const_iterator find(StringRef Key) const { return find(Key, hash(Key)); }
0243 
0244   const_iterator find(StringRef Key, uint32_t FullHashValue) const {
0245     int Bucket = FindKey(Key, FullHashValue);
0246     if (Bucket == -1)
0247       return end();
0248     return const_iterator(TheTable + Bucket, true);
0249   }
0250 
0251   /// lookup - Return the entry for the specified key, or a default
0252   /// constructed value if no such entry exists.
0253   ValueTy lookup(StringRef Key) const {
0254     const_iterator Iter = find(Key);
0255     if (Iter != end())
0256       return Iter->second;
0257     return ValueTy();
0258   }
0259 
0260   /// at - Return the entry for the specified key, or abort if no such
0261   /// entry exists.
0262   const ValueTy &at(StringRef Val) const {
0263     auto Iter = this->find(std::move(Val));
0264     assert(Iter != this->end() && "StringMap::at failed due to a missing key");
0265     return Iter->second;
0266   }
0267 
0268   /// Lookup the ValueTy for the \p Key, or create a default constructed value
0269   /// if the key is not in the map.
0270   ValueTy &operator[](StringRef Key) { return try_emplace(Key).first->second; }
0271 
0272   /// contains - Return true if the element is in the map, false otherwise.
0273   bool contains(StringRef Key) const { return find(Key) != end(); }
0274 
0275   /// count - Return 1 if the element is in the map, 0 otherwise.
0276   size_type count(StringRef Key) const { return contains(Key) ? 1 : 0; }
0277 
0278   template <typename InputTy>
0279   size_type count(const StringMapEntry<InputTy> &MapEntry) const {
0280     return count(MapEntry.getKey());
0281   }
0282 
0283   /// equal - check whether both of the containers are equal.
0284   bool operator==(const StringMap &RHS) const {
0285     if (size() != RHS.size())
0286       return false;
0287 
0288     for (const auto &KeyValue : *this) {
0289       auto FindInRHS = RHS.find(KeyValue.getKey());
0290 
0291       if (FindInRHS == RHS.end())
0292         return false;
0293 
0294       if constexpr (!std::is_same_v<ValueTy, std::nullopt_t>) {
0295         if (!(KeyValue.getValue() == FindInRHS->getValue()))
0296           return false;
0297       }
0298     }
0299 
0300     return true;
0301   }
0302 
0303   bool operator!=(const StringMap &RHS) const { return !(*this == RHS); }
0304 
0305   /// insert - Insert the specified key/value pair into the map.  If the key
0306   /// already exists in the map, return false and ignore the request, otherwise
0307   /// insert it and return true.
0308   bool insert(MapEntryTy *KeyValue) {
0309     unsigned BucketNo = LookupBucketFor(KeyValue->getKey());
0310     StringMapEntryBase *&Bucket = TheTable[BucketNo];
0311     if (Bucket && Bucket != getTombstoneVal())
0312       return false; // Already exists in map.
0313 
0314     if (Bucket == getTombstoneVal())
0315       --NumTombstones;
0316     Bucket = KeyValue;
0317     ++NumItems;
0318     assert(NumItems + NumTombstones <= NumBuckets);
0319 
0320     RehashTable();
0321     return true;
0322   }
0323 
0324   /// insert - Inserts the specified key/value pair into the map if the key
0325   /// isn't already in the map. The bool component of the returned pair is true
0326   /// if and only if the insertion takes place, and the iterator component of
0327   /// the pair points to the element with key equivalent to the key of the pair.
0328   std::pair<iterator, bool> insert(std::pair<StringRef, ValueTy> KV) {
0329     return try_emplace_with_hash(KV.first, hash(KV.first),
0330                                  std::move(KV.second));
0331   }
0332 
0333   std::pair<iterator, bool> insert(std::pair<StringRef, ValueTy> KV,
0334                                    uint32_t FullHashValue) {
0335     return try_emplace_with_hash(KV.first, FullHashValue, std::move(KV.second));
0336   }
0337 
0338   /// Inserts elements from range [first, last). If multiple elements in the
0339   /// range have keys that compare equivalent, it is unspecified which element
0340   /// is inserted .
0341   template <typename InputIt> void insert(InputIt First, InputIt Last) {
0342     for (InputIt It = First; It != Last; ++It)
0343       insert(*It);
0344   }
0345 
0346   ///  Inserts elements from initializer list ilist. If multiple elements in
0347   /// the range have keys that compare equivalent, it is unspecified which
0348   /// element is inserted
0349   void insert(std::initializer_list<std::pair<StringRef, ValueTy>> List) {
0350     insert(List.begin(), List.end());
0351   }
0352 
0353   /// Inserts an element or assigns to the current element if the key already
0354   /// exists. The return type is the same as try_emplace.
0355   template <typename V>
0356   std::pair<iterator, bool> insert_or_assign(StringRef Key, V &&Val) {
0357     auto Ret = try_emplace(Key, std::forward<V>(Val));
0358     if (!Ret.second)
0359       Ret.first->second = std::forward<V>(Val);
0360     return Ret;
0361   }
0362 
0363   /// Emplace a new element for the specified key into the map if the key isn't
0364   /// already in the map. The bool component of the returned pair is true
0365   /// if and only if the insertion takes place, and the iterator component of
0366   /// the pair points to the element with key equivalent to the key of the pair.
0367   template <typename... ArgsTy>
0368   std::pair<iterator, bool> try_emplace(StringRef Key, ArgsTy &&...Args) {
0369     return try_emplace_with_hash(Key, hash(Key), std::forward<ArgsTy>(Args)...);
0370   }
0371 
0372   template <typename... ArgsTy>
0373   std::pair<iterator, bool> try_emplace_with_hash(StringRef Key,
0374                                                   uint32_t FullHashValue,
0375                                                   ArgsTy &&...Args) {
0376     unsigned BucketNo = LookupBucketFor(Key, FullHashValue);
0377     StringMapEntryBase *&Bucket = TheTable[BucketNo];
0378     if (Bucket && Bucket != getTombstoneVal())
0379       return std::make_pair(iterator(TheTable + BucketNo, false),
0380                             false); // Already exists in map.
0381 
0382     if (Bucket == getTombstoneVal())
0383       --NumTombstones;
0384     Bucket =
0385         MapEntryTy::create(Key, getAllocator(), std::forward<ArgsTy>(Args)...);
0386     ++NumItems;
0387     assert(NumItems + NumTombstones <= NumBuckets);
0388 
0389     BucketNo = RehashTable(BucketNo);
0390     return std::make_pair(iterator(TheTable + BucketNo, false), true);
0391   }
0392 
0393   // clear - Empties out the StringMap
0394   void clear() {
0395     if (empty())
0396       return;
0397 
0398     // Zap all values, resetting the keys back to non-present (not tombstone),
0399     // which is safe because we're removing all elements.
0400     for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
0401       StringMapEntryBase *&Bucket = TheTable[I];
0402       if (Bucket && Bucket != getTombstoneVal()) {
0403         static_cast<MapEntryTy *>(Bucket)->Destroy(getAllocator());
0404       }
0405       Bucket = nullptr;
0406     }
0407 
0408     NumItems = 0;
0409     NumTombstones = 0;
0410   }
0411 
0412   /// remove - Remove the specified key/value pair from the map, but do not
0413   /// erase it.  This aborts if the key is not in the map.
0414   void remove(MapEntryTy *KeyValue) { RemoveKey(KeyValue); }
0415 
0416   void erase(iterator I) {
0417     MapEntryTy &V = *I;
0418     remove(&V);
0419     V.Destroy(getAllocator());
0420   }
0421 
0422   bool erase(StringRef Key) {
0423     iterator I = find(Key);
0424     if (I == end())
0425       return false;
0426     erase(I);
0427     return true;
0428   }
0429 };
0430 
0431 template <typename DerivedTy, typename ValueTy>
0432 class StringMapIterBase
0433     : public iterator_facade_base<DerivedTy, std::forward_iterator_tag,
0434                                   ValueTy> {
0435 protected:
0436   StringMapEntryBase **Ptr = nullptr;
0437 
0438 public:
0439   StringMapIterBase() = default;
0440 
0441   explicit StringMapIterBase(StringMapEntryBase **Bucket,
0442                              bool NoAdvance = false)
0443       : Ptr(Bucket) {
0444     if (!NoAdvance)
0445       AdvancePastEmptyBuckets();
0446   }
0447 
0448   DerivedTy &operator=(const DerivedTy &Other) {
0449     Ptr = Other.Ptr;
0450     return static_cast<DerivedTy &>(*this);
0451   }
0452 
0453   friend bool operator==(const DerivedTy &LHS, const DerivedTy &RHS) {
0454     return LHS.Ptr == RHS.Ptr;
0455   }
0456 
0457   DerivedTy &operator++() { // Preincrement
0458     ++Ptr;
0459     AdvancePastEmptyBuckets();
0460     return static_cast<DerivedTy &>(*this);
0461   }
0462 
0463   DerivedTy operator++(int) { // Post-increment
0464     DerivedTy Tmp(Ptr);
0465     ++*this;
0466     return Tmp;
0467   }
0468 
0469 private:
0470   void AdvancePastEmptyBuckets() {
0471     while (*Ptr == nullptr || *Ptr == StringMapImpl::getTombstoneVal())
0472       ++Ptr;
0473   }
0474 };
0475 
0476 template <typename ValueTy>
0477 class StringMapConstIterator
0478     : public StringMapIterBase<StringMapConstIterator<ValueTy>,
0479                                const StringMapEntry<ValueTy>> {
0480   using base = StringMapIterBase<StringMapConstIterator<ValueTy>,
0481                                  const StringMapEntry<ValueTy>>;
0482 
0483 public:
0484   StringMapConstIterator() = default;
0485   explicit StringMapConstIterator(StringMapEntryBase **Bucket,
0486                                   bool NoAdvance = false)
0487       : base(Bucket, NoAdvance) {}
0488 
0489   const StringMapEntry<ValueTy> &operator*() const {
0490     return *static_cast<const StringMapEntry<ValueTy> *>(*this->Ptr);
0491   }
0492 };
0493 
0494 template <typename ValueTy>
0495 class StringMapIterator : public StringMapIterBase<StringMapIterator<ValueTy>,
0496                                                    StringMapEntry<ValueTy>> {
0497   using base =
0498       StringMapIterBase<StringMapIterator<ValueTy>, StringMapEntry<ValueTy>>;
0499 
0500 public:
0501   StringMapIterator() = default;
0502   explicit StringMapIterator(StringMapEntryBase **Bucket,
0503                              bool NoAdvance = false)
0504       : base(Bucket, NoAdvance) {}
0505 
0506   StringMapEntry<ValueTy> &operator*() const {
0507     return *static_cast<StringMapEntry<ValueTy> *>(*this->Ptr);
0508   }
0509 
0510   operator StringMapConstIterator<ValueTy>() const {
0511     return StringMapConstIterator<ValueTy>(this->Ptr, true);
0512   }
0513 };
0514 
0515 template <typename ValueTy>
0516 class StringMapKeyIterator
0517     : public iterator_adaptor_base<StringMapKeyIterator<ValueTy>,
0518                                    StringMapConstIterator<ValueTy>,
0519                                    std::forward_iterator_tag, StringRef> {
0520   using base = iterator_adaptor_base<StringMapKeyIterator<ValueTy>,
0521                                      StringMapConstIterator<ValueTy>,
0522                                      std::forward_iterator_tag, StringRef>;
0523 
0524 public:
0525   StringMapKeyIterator() = default;
0526   explicit StringMapKeyIterator(StringMapConstIterator<ValueTy> Iter)
0527       : base(std::move(Iter)) {}
0528 
0529   StringRef operator*() const { return this->wrapped()->getKey(); }
0530 };
0531 
0532 } // end namespace llvm
0533 
0534 #endif // LLVM_ADT_STRINGMAP_H