1 /*
   2  * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #ifndef SHARE_UTILITIES_BITMAP_HPP
  26 #define SHARE_UTILITIES_BITMAP_HPP
  27 
  28 #include "memory/allocation.hpp"
  29 
  30 // Forward decl;
  31 class BitMapClosure;
  32 
  33 // Operations for bitmaps represented as arrays of unsigned integers.
  34 // Bit offsets are numbered from 0 to size-1.
  35 
  36 // The "abstract" base BitMap class.
  37 //
  38 // The constructor and destructor are protected to prevent
  39 // creation of BitMap instances outside of the BitMap class.
  40 //
  41 // The BitMap class doesn't use virtual calls on purpose,
  42 // this ensures that we don't get a vtable unnecessarily.
  43 //
  44 // The allocation of the backing storage for the BitMap are handled by
  45 // the subclasses. BitMap doesn't allocate or delete backing storage.
  46 class BitMap {
  47   friend class BitMap2D;
  48 
  49  public:
  50   typedef size_t idx_t;         // Type used for bit and word indices.
  51   typedef uintptr_t bm_word_t;  // Element type of array that represents
  52                                 // the bitmap.  BitsPerWord bits per element.
  53 
  54   // Hints for range sizes.
  55   typedef enum {
  56     unknown_range, small_range, large_range
  57   } RangeSizeHint;
  58 
  59  private:
  60   bm_word_t* _map;     // First word in bitmap
  61   idx_t      _size;    // Size of bitmap (in bits)
  62 
  63   // Limit max_size_in_bits so roundup in calc_size_in_words can't overflow.
  64   static idx_t max_size_in_words() { return word_index(~idx_t(0)); }
  65   static idx_t max_size_in_bits() { return max_size_in_words() * BitsPerWord; }
  66 
  67   // Helper for get_next_{zero,one}_bit variants.
  68   // - flip designates whether searching for 1s or 0s.  Must be one of
  69   //   find_{zeros,ones}_flip.
  70   // - aligned_right is true if r_index is a priori on a bm_word_t boundary.
  71   template<bm_word_t flip, bool aligned_right>
  72   inline idx_t get_next_bit_impl(idx_t l_index, idx_t r_index) const;
  73 
  74   // Values for get_next_bit_impl flip parameter.
  75   static const bm_word_t find_ones_flip = 0;
  76   static const bm_word_t find_zeros_flip = ~(bm_word_t)0;
  77 
  78   // Threshold for performing small range operation, even when large range
  79   // operation was requested. Measured in words.
  80   static const size_t small_range_words = 32;
  81 
  82  protected:
  83   // Return the position of bit within the word that contains it (e.g., if
  84   // bitmap words are 32 bits, return a number 0 <= n <= 31).
  85   static idx_t bit_in_word(idx_t bit) { return bit & (BitsPerWord - 1); }
  86 
  87   // Return a mask that will select the specified bit, when applied to the word
  88   // containing the bit.
  89   static bm_word_t bit_mask(idx_t bit) { return (bm_word_t)1 << bit_in_word(bit); }
  90 
  91   // Return the index of the word containing the specified bit.
  92   static idx_t word_index(idx_t bit)  { return bit >> LogBitsPerWord; }
  93 
  94   // Return the bit number of the first bit in the specified word.
  95   static idx_t bit_index(idx_t word)  { return word << LogBitsPerWord; }
  96 
  97   // Return the array of bitmap words, or a specific word from it.
  98   bm_word_t* map()                 { return _map; }
  99   const bm_word_t* map() const     { return _map; }
 100   bm_word_t  map(idx_t word) const { return _map[word]; }
 101 
 102   // Return a pointer to the word containing the specified bit.
 103   bm_word_t* word_addr(idx_t bit)             { return map() + word_index(bit); }
 104   const bm_word_t* word_addr(idx_t bit) const { return map() + word_index(bit); }
 105 
 106   // Set a word to a specified value or to all ones; clear a word.
 107   void set_word  (idx_t word, bm_word_t val) { _map[word] = val; }
 108   void set_word  (idx_t word)            { set_word(word, ~(bm_word_t)0); }
 109   void clear_word(idx_t word)            { _map[word] = 0; }
 110 
 111   // Utilities for ranges of bits.  Ranges are half-open [beg, end).
 112 
 113   // Ranges within a single word.
 114   bm_word_t inverted_bit_mask_for_range(idx_t beg, idx_t end) const;
 115   void  set_range_within_word      (idx_t beg, idx_t end);
 116   void  clear_range_within_word    (idx_t beg, idx_t end);
 117   void  par_put_range_within_word  (idx_t beg, idx_t end, bool value);
 118 
 119   // Ranges spanning entire words.
 120   void      set_range_of_words         (idx_t beg, idx_t end);
 121   void      clear_range_of_words       (idx_t beg, idx_t end);
 122   void      set_large_range_of_words   (idx_t beg, idx_t end);
 123   void      clear_large_range_of_words (idx_t beg, idx_t end);
 124 
 125   static void clear_range_of_words(bm_word_t* map, idx_t beg, idx_t end);
 126 
 127   static bool is_small_range_of_words(idx_t beg_full_word, idx_t end_full_word);
 128 
 129   // The index of the first full word in a range.
 130   idx_t word_index_round_up(idx_t bit) const;
 131 
 132   // Verification.
 133   static void verify_max_size_limited(idx_t bit) NOT_DEBUG_RETURN;
 134   void verify_index(idx_t index) const NOT_DEBUG_RETURN;
 135   void verify_range(idx_t beg_index, idx_t end_index) const NOT_DEBUG_RETURN;
 136 
 137   // Statistics.
 138   static const idx_t* _pop_count_table;
 139   static void init_pop_count_table();
 140   static idx_t num_set_bits(bm_word_t w);
 141   static idx_t num_set_bits_from_table(unsigned char c);
 142 
 143   // Allocation Helpers.
 144 
 145   // Allocates and clears the bitmap memory.
 146   template <class Allocator>
 147   static bm_word_t* allocate(const Allocator&, idx_t size_in_bits, bool clear = true);
 148 
 149   // Reallocates and clears the new bitmap memory.
 150   template <class Allocator>
 151   static bm_word_t* reallocate(const Allocator&, bm_word_t* map, idx_t old_size_in_bits, idx_t new_size_in_bits, bool clear = true);
 152 
 153   // Free the bitmap memory.
 154   template <class Allocator>
 155   static void free(const Allocator&, bm_word_t* map, idx_t size_in_bits);
 156 
 157   // Protected functions, that are used by BitMap sub-classes that support them.
 158 
 159   // Resize the backing bitmap memory.
 160   //
 161   // Old bits are transfered to the new memory
 162   // and the extended memory is cleared.
 163   template <class Allocator>
 164   void resize(const Allocator& allocator, idx_t new_size_in_bits, bool clear);
 165 
 166   // Set up and clear the bitmap memory.
 167   //
 168   // Precondition: The bitmap was default constructed and has
 169   // not yet had memory allocated via resize or (re)initialize.
 170   template <class Allocator>
 171   void initialize(const Allocator& allocator, idx_t size_in_bits, bool clear);
 172 
 173   // Set up and clear the bitmap memory.
 174   //
 175   // Can be called on previously initialized bitmaps.
 176   template <class Allocator>
 177   void reinitialize(const Allocator& allocator, idx_t new_size_in_bits, bool clear);
 178 
 179   // Set the map and size.
 180   void update(bm_word_t* map, idx_t size) {
 181     _map = map;
 182     _size = size;
 183   }
 184 
 185   // Protected constructor and destructor.
 186   BitMap(bm_word_t* map, idx_t size_in_bits) : _map(map), _size(size_in_bits) {}
 187   ~BitMap() {}
 188 
 189  public:
 190   // Pretouch the entire range of memory this BitMap covers.
 191   void pretouch();
 192 
 193   static idx_t calc_size_in_words(idx_t size_in_bits) {
 194     verify_max_size_limited(size_in_bits);
 195     return word_index(size_in_bits + (BitsPerWord - 1));
 196   }
 197 
 198   idx_t size() const          { return _size; }
 199   idx_t size_in_words() const { return calc_size_in_words(size()); }
 200   idx_t size_in_bytes() const { return size_in_words() * BytesPerWord; }
 201 
 202   bool at(idx_t index) const {
 203     verify_index(index);
 204     return (*word_addr(index) & bit_mask(index)) != 0;
 205   }
 206 
 207   // Set or clear the specified bit.
 208   inline void set_bit(idx_t bit);
 209   inline void clear_bit(idx_t bit);
 210 
 211   // Atomically set or clear the specified bit.
 212   inline bool par_set_bit(idx_t bit);
 213   inline bool par_clear_bit(idx_t bit);
 214 
 215   // Put the given value at the given offset. The parallel version
 216   // will CAS the value into the bitmap and is quite a bit slower.
 217   // The parallel version also returns a value indicating if the
 218   // calling thread was the one that changed the value of the bit.
 219   void at_put(idx_t index, bool value);
 220   bool par_at_put(idx_t index, bool value);
 221 
 222   // Update a range of bits.  Ranges are half-open [beg, end).
 223   void set_range   (idx_t beg, idx_t end);
 224   void clear_range (idx_t beg, idx_t end);
 225   void set_large_range   (idx_t beg, idx_t end);
 226   void clear_large_range (idx_t beg, idx_t end);
 227   void at_put_range(idx_t beg, idx_t end, bool value);
 228   void par_at_put_range(idx_t beg, idx_t end, bool value);
 229   void at_put_large_range(idx_t beg, idx_t end, bool value);
 230   void par_at_put_large_range(idx_t beg, idx_t end, bool value);
 231 
 232   // Update a range of bits, using a hint about the size.  Currently only
 233   // inlines the predominant case of a 1-bit range.  Works best when hint is a
 234   // compile-time constant.
 235   void set_range(idx_t beg, idx_t end, RangeSizeHint hint);
 236   void clear_range(idx_t beg, idx_t end, RangeSizeHint hint);
 237   void par_set_range(idx_t beg, idx_t end, RangeSizeHint hint);
 238   void par_clear_range  (idx_t beg, idx_t end, RangeSizeHint hint);
 239 
 240   // Clearing
 241   void clear_large();
 242   inline void clear();
 243 
 244   // Iteration support.  Returns "true" if the iteration completed, false
 245   // if the iteration terminated early (because the closure "blk" returned
 246   // false).
 247   bool iterate(BitMapClosure* blk, idx_t leftIndex, idx_t rightIndex);
 248   bool iterate(BitMapClosure* blk) {
 249     // call the version that takes an interval
 250     return iterate(blk, 0, size());
 251   }
 252 
 253   // Looking for 1's and 0's at indices equal to or greater than "l_index",
 254   // stopping if none has been found before "r_index", and returning
 255   // "r_index" (which must be at most "size") in that case.
 256   idx_t get_next_one_offset (idx_t l_index, idx_t r_index) const;
 257   idx_t get_next_zero_offset(idx_t l_index, idx_t r_index) const;
 258 
 259   idx_t get_next_one_offset(idx_t offset) const {
 260     return get_next_one_offset(offset, size());
 261   }
 262   idx_t get_next_zero_offset(idx_t offset) const {
 263     return get_next_zero_offset(offset, size());
 264   }
 265 
 266   // Like "get_next_one_offset", except requires that "r_index" is
 267   // aligned to bitsizeof(bm_word_t).
 268   idx_t get_next_one_offset_aligned_right(idx_t l_index, idx_t r_index) const;
 269 
 270   // Returns the number of bits set in the bitmap.
 271   idx_t count_one_bits() const;
 272 
 273   // Set operations.
 274   void set_union(const BitMap& bits);
 275   void set_difference(const BitMap& bits);
 276   void set_intersection(const BitMap& bits);
 277   // Returns true iff "this" is a superset of "bits".
 278   bool contains(const BitMap& bits) const;
 279   // Returns true iff "this and "bits" have a non-empty intersection.
 280   bool intersects(const BitMap& bits) const;
 281 
 282   // Returns result of whether this map changed
 283   // during the operation
 284   bool set_union_with_result(const BitMap& bits);
 285   bool set_difference_with_result(const BitMap& bits);
 286   bool set_intersection_with_result(const BitMap& bits);
 287 
 288   void set_from(const BitMap& bits);
 289 
 290   bool is_same(const BitMap& bits) const;
 291 
 292   // Test if all bits are set or cleared
 293   bool is_full() const;
 294   bool is_empty() const;
 295 
 296   void write_to(bm_word_t* buffer, size_t buffer_size_in_bytes) const;
 297   void print_on_error(outputStream* st, const char* prefix) const;
 298 
 299 #ifndef PRODUCT
 300  public:
 301   // Printing
 302   void print_on(outputStream* st) const;
 303 #endif
 304 };
 305 
 306 // A concrete implementation of the the "abstract" BitMap class.
 307 //
 308 // The BitMapView is used when the backing storage is managed externally.
 309 class BitMapView : public BitMap {
 310  public:
 311   BitMapView() : BitMap(NULL, 0) {}
 312   BitMapView(bm_word_t* map, idx_t size_in_bits) : BitMap(map, size_in_bits) {}
 313 };
 314 
 315 // A BitMap with storage in a ResourceArea.
 316 class ResourceBitMap : public BitMap {
 317 
 318  public:
 319   ResourceBitMap() : BitMap(NULL, 0) {}
 320   // Clears the bitmap memory.
 321   ResourceBitMap(idx_t size_in_bits);
 322 
 323   // Resize the backing bitmap memory.
 324   //
 325   // Old bits are transfered to the new memory
 326   // and the extended memory is cleared.
 327   void resize(idx_t new_size_in_bits);
 328 
 329   // Set up and clear the bitmap memory.
 330   //
 331   // Precondition: The bitmap was default constructed and has
 332   // not yet had memory allocated via resize or initialize.
 333   void initialize(idx_t size_in_bits);
 334 
 335   // Set up and clear the bitmap memory.
 336   //
 337   // Can be called on previously initialized bitmaps.
 338   void reinitialize(idx_t size_in_bits);
 339 };
 340 
 341 // A BitMap with storage in a specific Arena.
 342 class ArenaBitMap : public BitMap {
 343  public:
 344   // Clears the bitmap memory.
 345   ArenaBitMap(Arena* arena, idx_t size_in_bits);
 346 
 347  private:
 348   // Don't allow copy or assignment.
 349   ArenaBitMap(const ArenaBitMap&);
 350   ArenaBitMap& operator=(const ArenaBitMap&);
 351 };
 352 
 353 // A BitMap with storage in the CHeap.
 354 class CHeapBitMap : public BitMap {
 355 
 356  private:
 357   // Don't allow copy or assignment, to prevent the
 358   // allocated memory from leaking out to other instances.
 359   CHeapBitMap(const CHeapBitMap&);
 360   CHeapBitMap& operator=(const CHeapBitMap&);
 361 
 362   // NMT memory type
 363   MEMFLAGS _flags;
 364 
 365  public:
 366   CHeapBitMap(MEMFLAGS flags = mtInternal) : BitMap(NULL, 0), _flags(flags) {}
 367   // Clears the bitmap memory.
 368   CHeapBitMap(idx_t size_in_bits, MEMFLAGS flags = mtInternal, bool clear = true);
 369   ~CHeapBitMap();
 370 
 371   // Resize the backing bitmap memory.
 372   //
 373   // Old bits are transfered to the new memory
 374   // and the extended memory is cleared.
 375   void resize(idx_t new_size_in_bits, bool clear = true);
 376 
 377   // Set up and clear the bitmap memory.
 378   //
 379   // Precondition: The bitmap was default constructed and has
 380   // not yet had memory allocated via resize or initialize.
 381   void initialize(idx_t size_in_bits, bool clear = true);
 382 
 383   // Set up and clear the bitmap memory.
 384   //
 385   // Can be called on previously initialized bitmaps.
 386   void reinitialize(idx_t size_in_bits, bool clear = true);
 387 };
 388 
 389 // Convenience class wrapping BitMap which provides multiple bits per slot.
 390 class BitMap2D {
 391  public:
 392   typedef BitMap::idx_t idx_t;          // Type used for bit and word indices.
 393   typedef BitMap::bm_word_t bm_word_t;  // Element type of array that
 394                                         // represents the bitmap.
 395  private:
 396   ResourceBitMap _map;
 397   idx_t          _bits_per_slot;
 398 
 399   idx_t bit_index(idx_t slot_index, idx_t bit_within_slot_index) const {
 400     return slot_index * _bits_per_slot + bit_within_slot_index;
 401   }
 402 
 403   void verify_bit_within_slot_index(idx_t index) const {
 404     assert(index < _bits_per_slot, "bit_within_slot index out of bounds");
 405   }
 406 
 407  public:
 408   // Construction. bits_per_slot must be greater than 0.
 409   BitMap2D(idx_t bits_per_slot) :
 410       _map(), _bits_per_slot(bits_per_slot) {}
 411 
 412   // Allocates necessary data structure in resource area. bits_per_slot must be greater than 0.
 413   BitMap2D(idx_t size_in_slots, idx_t bits_per_slot) :
 414       _map(size_in_slots * bits_per_slot), _bits_per_slot(bits_per_slot) {}
 415 
 416   idx_t size_in_bits() {
 417     return _map.size();
 418   }
 419 
 420   bool is_valid_index(idx_t slot_index, idx_t bit_within_slot_index);
 421   bool at(idx_t slot_index, idx_t bit_within_slot_index) const;
 422   void set_bit(idx_t slot_index, idx_t bit_within_slot_index);
 423   void clear_bit(idx_t slot_index, idx_t bit_within_slot_index);
 424   void at_put(idx_t slot_index, idx_t bit_within_slot_index, bool value);
 425   void at_put_grow(idx_t slot_index, idx_t bit_within_slot_index, bool value);
 426 };
 427 
 428 // Closure for iterating over BitMaps
 429 
 430 class BitMapClosure {
 431  public:
 432   // Callback when bit in map is set.  Should normally return "true";
 433   // return of false indicates that the bitmap iteration should terminate.
 434   virtual bool do_bit(BitMap::idx_t offset) = 0;
 435 };
 436 
 437 #endif // SHARE_UTILITIES_BITMAP_HPP