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