]> git.ipfire.org Git - thirdparty/gcc.git/blob - libstdc++-v3/include/ext/bitmap_allocator.h
doxygroups.cc: Add std::tr1 namespace.
[thirdparty/gcc.git] / libstdc++-v3 / include / ext / bitmap_allocator.h
1 // Bitmap Allocator. -*- C++ -*-
2
3 // Copyright (C) 2004 Free Software Foundation, Inc.
4 //
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 2, or (at your option)
9 // any later version.
10
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15
16 // You should have received a copy of the GNU General Public License along
17 // with this library; see the file COPYING. If not, write to the Free
18 // Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
19 // USA.
20
21 // As a special exception, you may use this file as part of a free software
22 // library without restriction. Specifically, if other files instantiate
23 // templates or use macros or inline functions from this file, or you compile
24 // this file and link it with other files to produce an executable, this
25 // file does not by itself cause the resulting executable to be covered by
26 // the GNU General Public License. This exception does not however
27 // invalidate any other reasons why the executable file might be covered by
28 // the GNU General Public License.
29
30 /** @file ext/bitmap_allocator.h
31 * This file is a GNU extension to the Standard C++ Library.
32 */
33
34 #ifndef _BITMAP_ALLOCATOR_H
35 #define _BITMAP_ALLOCATOR_H 1
36
37 // For std::size_t, and ptrdiff_t.
38 #include <cstddef>
39
40 // For __throw_bad_alloc().
41 #include <bits/functexcept.h>
42
43 // For std::pair.
44 #include <utility>
45
46 // For greater_equal, and less_equal.
47 #include <functional>
48
49 // For operator new.
50 #include <new>
51
52 // For __gthread_mutex_t, __gthread_mutex_lock and __gthread_mutex_unlock.
53 #include <bits/gthr.h>
54
55 // Define this to enable error checking withing the allocator
56 // itself(to debug the allocator itself).
57 //#define _BALLOC_SANITY_CHECK
58
59 // The constant in the expression below is the alignment required in
60 // bytes.
61 #define _BALLOC_ALIGN_BYTES 8
62
63 #if defined _BALLOC_SANITY_CHECK
64 #include <cassert>
65 #define _BALLOC_ASSERT(_EXPR) assert(_EXPR)
66 #else
67 #define _BALLOC_ASSERT(_EXPR)
68 #endif
69
70
71 namespace __gnu_cxx
72 {
73 #if defined __GTHREADS
74 namespace
75 {
76 // If true, then the application being compiled will be using
77 // threads, so use mutexes as a synchronization primitive, else do
78 // no use any synchronization primitives.
79 bool const __threads_enabled = __gthread_active_p();
80 }
81 #endif
82
83 #if defined __GTHREADS
84 // _Mutex is an OO-Wrapper for __gthread_mutex_t. It does not allow
85 // you to copy or assign an already initialized mutex. This is used
86 // merely as a convenience for the locking classes.
87 class _Mutex
88 {
89 __gthread_mutex_t _M_mut;
90
91 // Prevent Copying and assignment.
92 _Mutex(_Mutex const&);
93 _Mutex& operator=(_Mutex const&);
94
95 public:
96 _Mutex()
97 {
98 if (__threads_enabled)
99 {
100 #if !defined __GTHREAD_MUTEX_INIT
101 __GTHREAD_MUTEX_INIT_FUNCTION(&_M_mut);
102 #else
103 __gthread_mutex_t __mtemp = __GTHREAD_MUTEX_INIT;
104 _M_mut = __mtemp;
105 #endif
106 }
107 }
108
109 ~_Mutex()
110 {
111 // Gthreads does not define a Mutex Destruction Function.
112 }
113
114 __gthread_mutex_t*
115 _M_get() { return &_M_mut; }
116 };
117
118 // _Lock is a simple manual lokcing class which allows you to
119 // manually lock and unlock a mutex associated with the lock. There
120 // is not automatic locking or unlocking happening without the
121 // programmer's explicit instructions. This class unlocks the mutex
122 // ONLY if it has not been locked. However, this check does not
123 // apply for lokcing, and wayward use may cause dead-locks.
124 class _Lock
125 {
126 _Mutex* _M_pmt;
127 bool _M_locked;
128
129 // Prevent Copying and assignment.
130 _Lock(_Lock const&);
131 _Lock& operator=(_Lock const&);
132
133 public:
134 _Lock(_Mutex* __mptr)
135 : _M_pmt(__mptr), _M_locked(false)
136 { }
137
138 void
139 _M_lock()
140 {
141 if (__threads_enabled)
142 {
143 _M_locked = true;
144 __gthread_mutex_lock(_M_pmt->_M_get());
145 }
146 }
147
148 void
149 _M_unlock()
150 {
151 if (__threads_enabled)
152 {
153 if (__builtin_expect(_M_locked, true))
154 {
155 __gthread_mutex_unlock(_M_pmt->_M_get());
156 _M_locked = false;
157 }
158 }
159 }
160
161 ~_Lock() { }
162 };
163
164 // _Auto_Lock locks the associated mutex on construction, and
165 // unlocks on it's destruction. There are no checks performed, and
166 // this calss follows the RAII principle.
167 class _Auto_Lock
168 {
169 _Mutex* _M_pmt;
170 // Prevent Copying and assignment.
171 _Auto_Lock(_Auto_Lock const&);
172 _Auto_Lock& operator=(_Auto_Lock const&);
173
174 void
175 _M_lock()
176 {
177 if (__threads_enabled)
178 __gthread_mutex_lock(_M_pmt->_M_get());
179 }
180
181 void
182 _M_unlock()
183 {
184 if (__threads_enabled)
185 __gthread_mutex_unlock(_M_pmt->_M_get());
186 }
187
188 public:
189 _Auto_Lock(_Mutex* __mptr) : _M_pmt(__mptr)
190 { this->_M_lock(); }
191
192 ~_Auto_Lock() { this->_M_unlock(); }
193 };
194 #endif
195
196 namespace balloc
197 {
198 // __mini_vector<> is to be used only for built-in types or
199 // PODs. It is a stripped down version of the full-fledged
200 // std::vector<>. Noteable differences are:
201 //
202 // 1. Not all accessor functions are present.
203 // 2. Used ONLY for PODs.
204 // 3. No Allocator template argument. Uses ::operator new() to get
205 // memory, and ::operator delete() to free it.
206 template<typename _Tp>
207 class __mini_vector
208 {
209 __mini_vector(const __mini_vector&);
210 __mini_vector& operator=(const __mini_vector&);
211
212 public:
213 typedef _Tp value_type;
214 typedef _Tp* pointer;
215 typedef _Tp& reference;
216 typedef const _Tp& const_reference;
217 typedef std::size_t size_type;
218 typedef std::ptrdiff_t difference_type;
219 typedef pointer iterator;
220
221 private:
222 pointer _M_start;
223 pointer _M_finish;
224 pointer _M_end_of_storage;
225
226 size_type
227 _M_space_left() const throw()
228 { return _M_end_of_storage - _M_finish; }
229
230 pointer
231 allocate(size_type __n)
232 { return static_cast<pointer>(::operator new(__n * sizeof(_Tp))); }
233
234 void
235 deallocate(pointer __p, size_type)
236 { ::operator delete(__p); }
237
238 public:
239 // Members used: size(), push_back(), pop_back(),
240 // insert(iterator, const_reference), erase(iterator),
241 // begin(), end(), back(), operator[].
242
243 __mini_vector() : _M_start(0), _M_finish(0),
244 _M_end_of_storage(0)
245 { }
246
247 #if 0
248 ~__mini_vector()
249 {
250 if (this->_M_start)
251 {
252 this->deallocate(this->_M_start, this->_M_end_of_storage
253 - this->_M_start);
254 }
255 }
256 #endif
257
258 size_type
259 size() const throw()
260 { return _M_finish - _M_start; }
261
262 iterator
263 begin() const throw()
264 { return this->_M_start; }
265
266 iterator
267 end() const throw()
268 { return this->_M_finish; }
269
270 reference
271 back() const throw()
272 { return *(this->end() - 1); }
273
274 reference
275 operator[](const size_type __pos) const throw()
276 { return this->_M_start[__pos]; }
277
278 void
279 insert(iterator __pos, const_reference __x);
280
281 void
282 push_back(const_reference __x)
283 {
284 if (this->_M_space_left())
285 {
286 *this->end() = __x;
287 ++this->_M_finish;
288 }
289 else
290 this->insert(this->end(), __x);
291 }
292
293 void
294 pop_back() throw()
295 { --this->_M_finish; }
296
297 void
298 erase(iterator __pos) throw();
299
300 void
301 clear() throw()
302 { this->_M_finish = this->_M_start; }
303 };
304
305 // Out of line function definitions.
306 template<typename _Tp>
307 void __mini_vector<_Tp>::
308 insert(iterator __pos, const_reference __x)
309 {
310 if (this->_M_space_left())
311 {
312 size_type __to_move = this->_M_finish - __pos;
313 iterator __dest = this->end();
314 iterator __src = this->end() - 1;
315
316 ++this->_M_finish;
317 while (__to_move)
318 {
319 *__dest = *__src;
320 --__dest; --__src; --__to_move;
321 }
322 *__pos = __x;
323 }
324 else
325 {
326 size_type __new_size = this->size() ? this->size() * 2 : 1;
327 iterator __new_start = this->allocate(__new_size);
328 iterator __first = this->begin();
329 iterator __start = __new_start;
330 while (__first != __pos)
331 {
332 *__start = *__first;
333 ++__start; ++__first;
334 }
335 *__start = __x;
336 ++__start;
337 while (__first != this->end())
338 {
339 *__start = *__first;
340 ++__start; ++__first;
341 }
342 if (this->_M_start)
343 this->deallocate(this->_M_start, this->size());
344
345 this->_M_start = __new_start;
346 this->_M_finish = __start;
347 this->_M_end_of_storage = this->_M_start + __new_size;
348 }
349 }
350
351 template<typename _Tp>
352 void __mini_vector<_Tp>::
353 erase(iterator __pos) throw()
354 {
355 while (__pos + 1 != this->end())
356 {
357 *__pos = __pos[1];
358 ++__pos;
359 }
360 --this->_M_finish;
361 }
362
363
364 template<typename _Tp>
365 struct __mv_iter_traits
366 {
367 typedef typename _Tp::value_type value_type;
368 typedef typename _Tp::difference_type difference_type;
369 };
370
371 template<typename _Tp>
372 struct __mv_iter_traits<_Tp*>
373 {
374 typedef _Tp value_type;
375 typedef std::ptrdiff_t difference_type;
376 };
377
378 enum
379 {
380 bits_per_byte = 8,
381 bits_per_block = sizeof(size_t) * bits_per_byte
382 };
383
384 template<typename _ForwardIterator, typename _Tp, typename _Compare>
385 _ForwardIterator
386 __lower_bound(_ForwardIterator __first, _ForwardIterator __last,
387 const _Tp& __val, _Compare __comp)
388 {
389 typedef typename __mv_iter_traits<_ForwardIterator>::value_type
390 _ValueType;
391 typedef typename __mv_iter_traits<_ForwardIterator>::difference_type
392 _DistanceType;
393
394 _DistanceType __len = __last - __first;
395 _DistanceType __half;
396 _ForwardIterator __middle;
397
398 while (__len > 0)
399 {
400 __half = __len >> 1;
401 __middle = __first;
402 __middle += __half;
403 if (__comp(*__middle, __val))
404 {
405 __first = __middle;
406 ++__first;
407 __len = __len - __half - 1;
408 }
409 else
410 __len = __half;
411 }
412 return __first;
413 }
414
415 template<typename _InputIterator, typename _Predicate>
416 inline _InputIterator
417 __find_if(_InputIterator __first, _InputIterator __last, _Predicate __p)
418 {
419 while (__first != __last && !__p(*__first))
420 ++__first;
421 return __first;
422 }
423
424 template<typename _AddrPair>
425 inline size_t
426 __num_blocks(_AddrPair __ap)
427 { return (__ap.second - __ap.first) + 1; }
428
429 template<typename _AddrPair>
430 inline size_t
431 __num_bitmaps(_AddrPair __ap)
432 { return __num_blocks(__ap) / bits_per_block; }
433
434 // _Tp should be a pointer type.
435 template<typename _Tp>
436 class _Inclusive_between
437 : public std::unary_function<typename std::pair<_Tp, _Tp>, bool>
438 {
439 typedef _Tp pointer;
440 pointer _M_ptr_value;
441 typedef typename std::pair<_Tp, _Tp> _Block_pair;
442
443 public:
444 _Inclusive_between(pointer __ptr) : _M_ptr_value(__ptr)
445 { }
446
447 bool
448 operator()(_Block_pair __bp) const throw()
449 {
450 if (std::less_equal<pointer>()(_M_ptr_value, __bp.second)
451 && std::greater_equal<pointer>()(_M_ptr_value, __bp.first))
452 return true;
453 else
454 return false;
455 }
456 };
457
458 // Used to pass a Functor to functions by reference.
459 template<typename _Functor>
460 class _Functor_Ref
461 : public std::unary_function<typename _Functor::argument_type,
462 typename _Functor::result_type>
463 {
464 _Functor& _M_fref;
465
466 public:
467 typedef typename _Functor::argument_type argument_type;
468 typedef typename _Functor::result_type result_type;
469
470 _Functor_Ref(_Functor& __fref) : _M_fref(__fref)
471 { }
472
473 result_type
474 operator()(argument_type __arg)
475 { return _M_fref(__arg); }
476 };
477
478 // _Tp should be a pointer type, and _Alloc is the Allocator for
479 // the vector.
480 template<typename _Tp>
481 class _Ffit_finder
482 : public std::unary_function<typename std::pair<_Tp, _Tp>, bool>
483 {
484 typedef typename std::pair<_Tp, _Tp> _Block_pair;
485 typedef typename balloc::__mini_vector<_Block_pair> _BPVector;
486 typedef typename _BPVector::difference_type _Counter_type;
487
488 size_t* _M_pbitmap;
489 _Counter_type _M_data_offset;
490
491 public:
492 _Ffit_finder() : _M_pbitmap(0), _M_data_offset(0)
493 { }
494
495 bool
496 operator()(_Block_pair __bp) throw()
497 {
498 // Set the _rover to the last physical location bitmap,
499 // which is the bitmap which belongs to the first free
500 // block. Thus, the bitmaps are in exact reverse order of
501 // the actual memory layout. So, we count down the bimaps,
502 // which is the same as moving up the memory.
503
504 // If the used count stored at the start of the Bit Map headers
505 // is equal to the number of Objects that the current Block can
506 // store, then there is definitely no space for another single
507 // object, so just return false.
508 _Counter_type __diff =
509 __gnu_cxx::balloc::__num_bitmaps(__bp);
510
511 if (*(reinterpret_cast<size_t*>
512 (__bp.first) - (__diff + 1))
513 == __gnu_cxx::balloc::__num_blocks(__bp))
514 return false;
515
516 size_t* __rover = reinterpret_cast<size_t*>(__bp.first) - 1;
517
518 for (_Counter_type __i = 0; __i < __diff; ++__i)
519 {
520 _M_data_offset = __i;
521 if (*__rover)
522 {
523 _M_pbitmap = __rover;
524 return true;
525 }
526 --__rover;
527 }
528 return false;
529 }
530
531
532 size_t*
533 _M_get() const throw()
534 { return _M_pbitmap; }
535
536 _Counter_type
537 _M_offset() const throw()
538 { return _M_data_offset * bits_per_block; }
539 };
540
541
542
543 // _Tp should be a pointer type.
544 template<typename _Tp>
545 class _Bitmap_counter
546 {
547 typedef typename balloc::__mini_vector<typename std::pair<_Tp, _Tp> >
548 _BPVector;
549 typedef typename _BPVector::size_type _Index_type;
550 typedef _Tp pointer;
551
552 _BPVector& _M_vbp;
553 size_t* _M_curr_bmap;
554 size_t* _M_last_bmap_in_block;
555 _Index_type _M_curr_index;
556
557 public:
558 // Use the 2nd parameter with care. Make sure that such an
559 // entry exists in the vector before passing that particular
560 // index to this ctor.
561 _Bitmap_counter(_BPVector& Rvbp, long __index = -1) : _M_vbp(Rvbp)
562 { this->_M_reset(__index); }
563
564 void
565 _M_reset(long __index = -1) throw()
566 {
567 if (__index == -1)
568 {
569 _M_curr_bmap = 0;
570 _M_curr_index = static_cast<_Index_type>(-1);
571 return;
572 }
573
574 _M_curr_index = __index;
575 _M_curr_bmap = reinterpret_cast<size_t*>
576 (_M_vbp[_M_curr_index].first) - 1;
577
578 _BALLOC_ASSERT(__index <= (long)_M_vbp.size() - 1);
579
580 _M_last_bmap_in_block = _M_curr_bmap
581 - ((_M_vbp[_M_curr_index].second
582 - _M_vbp[_M_curr_index].first + 1)
583 / bits_per_block - 1);
584 }
585
586 // Dangerous Function! Use with extreme care. Pass to this
587 // function ONLY those values that are known to be correct,
588 // otherwise this will mess up big time.
589 void
590 _M_set_internal_bitmap(size_t* __new_internal_marker) throw()
591 { _M_curr_bmap = __new_internal_marker; }
592
593 bool
594 _M_finished() const throw()
595 { return(_M_curr_bmap == 0); }
596
597 _Bitmap_counter&
598 operator++() throw()
599 {
600 if (_M_curr_bmap == _M_last_bmap_in_block)
601 {
602 if (++_M_curr_index == _M_vbp.size())
603 _M_curr_bmap = 0;
604 else
605 this->_M_reset(_M_curr_index);
606 }
607 else
608 --_M_curr_bmap;
609 return *this;
610 }
611
612 size_t*
613 _M_get() const throw()
614 { return _M_curr_bmap; }
615
616 pointer
617 _M_base() const throw()
618 { return _M_vbp[_M_curr_index].first; }
619
620 _Index_type
621 _M_offset() const throw()
622 {
623 return bits_per_block
624 * ((reinterpret_cast<size_t*>(this->_M_base())
625 - _M_curr_bmap) - 1);
626 }
627
628 _Index_type
629 _M_where() const throw()
630 { return _M_curr_index; }
631 };
632
633 inline void
634 __bit_allocate(size_t* __pbmap, size_t __pos) throw()
635 {
636 size_t __mask = 1 << __pos;
637 __mask = ~__mask;
638 *__pbmap &= __mask;
639 }
640
641 inline void
642 __bit_free(size_t* __pbmap, size_t __pos) throw()
643 {
644 size_t __mask = 1 << __pos;
645 *__pbmap |= __mask;
646 }
647 } // namespace balloc
648
649 // Generic Version of the bsf instruction.
650 inline size_t
651 _Bit_scan_forward(size_t __num)
652 { return static_cast<size_t>(__builtin_ctzl(__num)); }
653
654 class free_list
655 {
656 typedef size_t* value_type;
657 typedef balloc::__mini_vector<value_type> vector_type;
658 typedef vector_type::iterator iterator;
659
660 struct _LT_pointer_compare
661 {
662 bool
663 operator()(const size_t* __pui,
664 const size_t __cui) const throw()
665 { return *__pui < __cui; }
666 };
667
668 #if defined __GTHREADS
669 static _Mutex _S_bfl_mutex;
670 #endif
671 static vector_type _S_free_list;
672
673 void
674 _M_validate(size_t* __addr) throw()
675 {
676 const vector_type::size_type __max_size = 64;
677 if (_S_free_list.size() >= __max_size)
678 {
679 // Ok, the threshold value has been reached. We determine
680 // which block to remove from the list of free blocks.
681 if (*__addr >= *_S_free_list.back())
682 {
683 // Ok, the new block is greater than or equal to the
684 // last block in the list of free blocks. We just free
685 // the new block.
686 ::operator delete(static_cast<void*>(__addr));
687 return;
688 }
689 else
690 {
691 // Deallocate the last block in the list of free lists,
692 // and insert the new one in it's correct position.
693 ::operator delete(static_cast<void*>(_S_free_list.back()));
694 _S_free_list.pop_back();
695 }
696 }
697
698 // Just add the block to the list of free lists unconditionally.
699 iterator __temp = __gnu_cxx::balloc::__lower_bound
700 (_S_free_list.begin(), _S_free_list.end(),
701 *__addr, _LT_pointer_compare());
702
703 // We may insert the new free list before _temp;
704 _S_free_list.insert(__temp, __addr);
705 }
706
707 bool
708 _M_should_i_give(size_t __block_size,
709 size_t __required_size) throw()
710 {
711 const size_t __max_wastage_percentage = 36;
712 if (__block_size >= __required_size &&
713 (((__block_size - __required_size) * 100 / __block_size)
714 < __max_wastage_percentage))
715 return true;
716 else
717 return false;
718 }
719
720 public:
721 inline void
722 _M_insert(size_t* __addr) throw()
723 {
724 #if defined __GTHREADS
725 _Auto_Lock __bfl_lock(&_S_bfl_mutex);
726 #endif
727 // Call _M_validate to decide what should be done with
728 // this particular free list.
729 this->_M_validate(reinterpret_cast<size_t*>(__addr) - 1);
730 // See discussion as to why this is 1!
731 }
732
733 size_t*
734 _M_get(size_t __sz) throw(std::bad_alloc);
735
736 // This function just clears the internal Free List, and gives back
737 // all the memory to the OS.
738 void
739 _M_clear();
740 };
741
742
743 // Forward declare the class.
744 template<typename _Tp>
745 class bitmap_allocator;
746
747 // Specialize for void:
748 template<>
749 class bitmap_allocator<void>
750 {
751 public:
752 typedef void* pointer;
753 typedef const void* const_pointer;
754
755 // Reference-to-void members are impossible.
756 typedef void value_type;
757 template<typename _Tp1>
758 struct rebind
759 {
760 typedef bitmap_allocator<_Tp1> other;
761 };
762 };
763
764 template<typename _Tp>
765 class bitmap_allocator : private free_list
766 {
767 public:
768 typedef std::size_t size_type;
769 typedef std::ptrdiff_t difference_type;
770 typedef _Tp* pointer;
771 typedef const _Tp* const_pointer;
772 typedef _Tp& reference;
773 typedef const _Tp& const_reference;
774 typedef _Tp value_type;
775 template<typename _Tp1>
776 struct rebind
777 {
778 typedef bitmap_allocator<_Tp1> other;
779 };
780
781 private:
782 template<size_t _BSize, size_t _AlignSize>
783 struct aligned_size
784 {
785 enum
786 {
787 modulus = _BSize % _AlignSize,
788 value = _BSize + (modulus ? _AlignSize - (modulus) : 0)
789 };
790 };
791
792 struct _Alloc_block
793 {
794 char __M_unused[aligned_size<sizeof(value_type),
795 _BALLOC_ALIGN_BYTES>::value];
796 };
797
798
799 typedef typename std::pair<_Alloc_block*, _Alloc_block*> _Block_pair;
800
801 typedef typename
802 balloc::__mini_vector<_Block_pair> _BPVector;
803
804 #if defined _BALLOC_SANITY_CHECK
805 // Complexity: O(lg(N)). Where, N is the number of block of size
806 // sizeof(value_type).
807 void
808 _S_check_for_free_blocks() throw()
809 {
810 typedef typename
811 __gnu_cxx::balloc::_Ffit_finder<_Alloc_block*> _FFF;
812 _FFF __fff;
813 typedef typename _BPVector::iterator _BPiter;
814 _BPiter __bpi =
815 __gnu_cxx::balloc::__find_if
816 (_S_mem_blocks.begin(), _S_mem_blocks.end(),
817 __gnu_cxx::balloc::_Functor_Ref<_FFF>(__fff));
818
819 _BALLOC_ASSERT(__bpi == _S_mem_blocks.end());
820 }
821 #endif
822
823 // Complexity: O(1), but internally depends upon the complexity
824 // of the function free_list::_M_get. The
825 // part where the bitmap headers are written is of worst case
826 // complexity: O(X),where X is the number of blocks of size
827 // sizeof(value_type) within the newly acquired block. Having a
828 // tight bound.
829 void
830 _S_refill_pool() throw(std::bad_alloc)
831 {
832 #if defined _BALLOC_SANITY_CHECK
833 _S_check_for_free_blocks();
834 #endif
835
836 const size_t __num_bitmaps = _S_block_size / balloc::bits_per_block;
837 const size_t __size_to_allocate = sizeof(size_t)
838 + _S_block_size * sizeof(_Alloc_block)
839 + __num_bitmaps * sizeof(size_t);
840
841 size_t* __temp =
842 reinterpret_cast<size_t*>
843 (this->_M_get(__size_to_allocate));
844 *__temp = 0;
845 ++__temp;
846
847 // The Header information goes at the Beginning of the Block.
848 _Block_pair __bp =
849 std::make_pair(reinterpret_cast<_Alloc_block*>
850 (__temp + __num_bitmaps),
851 reinterpret_cast<_Alloc_block*>
852 (__temp + __num_bitmaps)
853 + _S_block_size - 1);
854
855 // Fill the Vector with this information.
856 _S_mem_blocks.push_back(__bp);
857
858 size_t __bit_mask = 0; // 0 Indicates all Allocated.
859 __bit_mask = ~__bit_mask; // 1 Indicates all Free.
860
861 for (size_t __i = 0; __i < __num_bitmaps; ++__i)
862 __temp[__i] = __bit_mask;
863
864 _S_block_size *= 2;
865 }
866
867
868 static _BPVector _S_mem_blocks;
869 static size_t _S_block_size;
870 static __gnu_cxx::balloc::
871 _Bitmap_counter<_Alloc_block*> _S_last_request;
872 static typename _BPVector::size_type _S_last_dealloc_index;
873 #if defined __GTHREADS
874 static _Mutex _S_mut;
875 #endif
876
877 public:
878
879 // Complexity: Worst case complexity is O(N), but that is hardly
880 // ever hit. if and when this particular case is encountered,
881 // the next few cases are guaranteed to have a worst case
882 // complexity of O(1)! That's why this function performs very
883 // well on the average. you can consider this function to be
884 // having a complexity referred to commonly as: Amortized
885 // Constant time.
886 pointer
887 _M_allocate_single_object() throw(std::bad_alloc)
888 {
889 #if defined __GTHREADS
890 _Auto_Lock __bit_lock(&_S_mut);
891 #endif
892
893 // The algorithm is something like this: The last_request
894 // variable points to the last accessed Bit Map. When such a
895 // condition occurs, we try to find a free block in the
896 // current bitmap, or succeeding bitmaps until the last bitmap
897 // is reached. If no free block turns up, we resort to First
898 // Fit method.
899
900 // WARNING: Do not re-order the condition in the while
901 // statement below, because it relies on C++'s short-circuit
902 // evaluation. The return from _S_last_request->_M_get() will
903 // NOT be dereference able if _S_last_request->_M_finished()
904 // returns true. This would inevitably lead to a NULL pointer
905 // dereference if tinkered with.
906 while (_S_last_request._M_finished() == false
907 && (*(_S_last_request._M_get()) == 0))
908 {
909 _S_last_request.operator++();
910 }
911
912 if (__builtin_expect(_S_last_request._M_finished() == true, false))
913 {
914 // Fall Back to First Fit algorithm.
915 typedef typename
916 __gnu_cxx::balloc::_Ffit_finder<_Alloc_block*> _FFF;
917 _FFF __fff;
918 typedef typename _BPVector::iterator _BPiter;
919 _BPiter __bpi =
920 __gnu_cxx::balloc::__find_if
921 (_S_mem_blocks.begin(), _S_mem_blocks.end(),
922 __gnu_cxx::balloc::_Functor_Ref<_FFF>(__fff));
923
924 if (__bpi != _S_mem_blocks.end())
925 {
926 // Search was successful. Ok, now mark the first bit from
927 // the right as 0, meaning Allocated. This bit is obtained
928 // by calling _M_get() on __fff.
929 size_t __nz_bit = _Bit_scan_forward(*__fff._M_get());
930 balloc::__bit_allocate(__fff._M_get(), __nz_bit);
931
932 _S_last_request._M_reset(__bpi - _S_mem_blocks.begin());
933
934 // Now, get the address of the bit we marked as allocated.
935 pointer __ret = reinterpret_cast<pointer>
936 (__bpi->first + __fff._M_offset() + __nz_bit);
937 size_t* __puse_count =
938 reinterpret_cast<size_t*>
939 (__bpi->first)
940 - (__gnu_cxx::balloc::__num_bitmaps(*__bpi) + 1);
941
942 ++(*__puse_count);
943 return __ret;
944 }
945 else
946 {
947 // Search was unsuccessful. We Add more memory to the
948 // pool by calling _S_refill_pool().
949 _S_refill_pool();
950
951 // _M_Reset the _S_last_request structure to the first
952 // free block's bit map.
953 _S_last_request._M_reset(_S_mem_blocks.size() - 1);
954
955 // Now, mark that bit as allocated.
956 }
957 }
958
959 // _S_last_request holds a pointer to a valid bit map, that
960 // points to a free block in memory.
961 size_t __nz_bit = _Bit_scan_forward(*_S_last_request._M_get());
962 balloc::__bit_allocate(_S_last_request._M_get(), __nz_bit);
963
964 pointer __ret = reinterpret_cast<pointer>
965 (_S_last_request._M_base() + _S_last_request._M_offset() + __nz_bit);
966
967 size_t* __puse_count = reinterpret_cast<size_t*>
968 (_S_mem_blocks[_S_last_request._M_where()].first)
969 - (__gnu_cxx::balloc::
970 __num_bitmaps(_S_mem_blocks[_S_last_request._M_where()]) + 1);
971
972 ++(*__puse_count);
973 return __ret;
974 }
975
976 // Complexity: O(lg(N)), but the worst case is hit quite often!
977 // I need to do something about this. I'll be able to work on
978 // it, only when I have some solid figures from a few real apps.
979 void
980 _M_deallocate_single_object(pointer __p) throw()
981 {
982 #if defined __GTHREADS
983 _Auto_Lock __bit_lock(&_S_mut);
984 #endif
985 _Alloc_block* __real_p = reinterpret_cast<_Alloc_block*>(__p);
986
987 typedef typename _BPVector::iterator _Iterator;
988 typedef typename _BPVector::difference_type _Difference_type;
989
990 _Difference_type __diff;
991 long __displacement;
992
993 _BALLOC_ASSERT(_S_last_dealloc_index >= 0);
994
995
996 if (__gnu_cxx::balloc::_Inclusive_between<_Alloc_block*>
997 (__real_p)
998 (_S_mem_blocks[_S_last_dealloc_index]))
999 {
1000 _BALLOC_ASSERT(_S_last_dealloc_index <= _S_mem_blocks.size() - 1);
1001
1002 // Initial Assumption was correct!
1003 __diff = _S_last_dealloc_index;
1004 __displacement = __real_p - _S_mem_blocks[__diff].first;
1005 }
1006 else
1007 {
1008 _Iterator _iter =
1009 __gnu_cxx::balloc::
1010 __find_if(_S_mem_blocks.begin(),
1011 _S_mem_blocks.end(),
1012 __gnu_cxx::balloc::
1013 _Inclusive_between<_Alloc_block*>(__real_p));
1014
1015 _BALLOC_ASSERT(_iter != _S_mem_blocks.end());
1016
1017 __diff = _iter - _S_mem_blocks.begin();
1018 __displacement = __real_p - _S_mem_blocks[__diff].first;
1019 _S_last_dealloc_index = __diff;
1020 }
1021
1022 // Get the position of the iterator that has been found.
1023 const size_t __rotate = __displacement % balloc::bits_per_block;
1024 size_t* __bitmapC =
1025 reinterpret_cast<size_t*>
1026 (_S_mem_blocks[__diff].first) - 1;
1027 __bitmapC -= (__displacement / balloc::bits_per_block);
1028
1029 balloc::__bit_free(__bitmapC, __rotate);
1030 size_t* __puse_count = reinterpret_cast<size_t*>
1031 (_S_mem_blocks[__diff].first)
1032 - (__gnu_cxx::balloc::__num_bitmaps(_S_mem_blocks[__diff]) + 1);
1033
1034 _BALLOC_ASSERT(*__puse_count != 0);
1035
1036 --(*__puse_count);
1037
1038 if (__builtin_expect(*__puse_count == 0, false))
1039 {
1040 _S_block_size /= 2;
1041
1042 // We can safely remove this block.
1043 // _Block_pair __bp = _S_mem_blocks[__diff];
1044 this->_M_insert(__puse_count);
1045 _S_mem_blocks.erase(_S_mem_blocks.begin() + __diff);
1046
1047 // Reset the _S_last_request variable to reflect the
1048 // erased block. We do this to protect future requests
1049 // after the last block has been removed from a particular
1050 // memory Chunk, which in turn has been returned to the
1051 // free list, and hence had been erased from the vector,
1052 // so the size of the vector gets reduced by 1.
1053 if ((_Difference_type)_S_last_request._M_where() >= __diff--)
1054 _S_last_request._M_reset(__diff);
1055
1056 // If the Index into the vector of the region of memory
1057 // that might hold the next address that will be passed to
1058 // deallocated may have been invalidated due to the above
1059 // erase procedure being called on the vector, hence we
1060 // try to restore this invariant too.
1061 if (_S_last_dealloc_index >= _S_mem_blocks.size())
1062 {
1063 _S_last_dealloc_index =(__diff != -1 ? __diff : 0);
1064 _BALLOC_ASSERT(_S_last_dealloc_index >= 0);
1065 }
1066 }
1067 }
1068
1069 public:
1070 bitmap_allocator() throw()
1071 { }
1072
1073 bitmap_allocator(const bitmap_allocator&)
1074 { }
1075
1076 template<typename _Tp1>
1077 bitmap_allocator(const bitmap_allocator<_Tp1>&) throw()
1078 { }
1079
1080 ~bitmap_allocator() throw()
1081 { }
1082
1083 // Complexity: O(1), but internally the complexity depends upon the
1084 // complexity of the function(s) _S_allocate_single_object and
1085 // operator new.
1086 pointer
1087 allocate(size_type __n)
1088 {
1089 if (__builtin_expect(__n > this->max_size(), false))
1090 std::__throw_bad_alloc();
1091
1092 if (__builtin_expect(__n == 1, true))
1093 return this->_M_allocate_single_object();
1094 else
1095 {
1096 const size_type __b = __n * sizeof(value_type);
1097 return reinterpret_cast<pointer>(::operator new(__b));
1098 }
1099 }
1100
1101 pointer
1102 allocate(size_type __n, typename bitmap_allocator<void>::const_pointer)
1103 { return allocate(__n); }
1104
1105 void
1106 deallocate(pointer __p, size_type __n) throw()
1107 {
1108 if (__builtin_expect(__p != 0, true))
1109 {
1110 if (__builtin_expect(__n == 1, true))
1111 this->_M_deallocate_single_object(__p);
1112 else
1113 ::operator delete(__p);
1114 }
1115 }
1116
1117 pointer
1118 address(reference __r) const
1119 { return &__r; }
1120
1121 const_pointer
1122 address(const_reference __r) const
1123 { return &__r; }
1124
1125 size_type
1126 max_size() const throw()
1127 { return size_type(-1) / sizeof(value_type); }
1128
1129 void
1130 construct(pointer __p, const_reference __data)
1131 { ::new(__p) value_type(__data); }
1132
1133 void
1134 destroy(pointer __p)
1135 { __p->~value_type(); }
1136 };
1137
1138 template<typename _Tp1, typename _Tp2>
1139 bool
1140 operator==(const bitmap_allocator<_Tp1>&,
1141 const bitmap_allocator<_Tp2>&) throw()
1142 { return true; }
1143
1144 template<typename _Tp1, typename _Tp2>
1145 bool
1146 operator!=(const bitmap_allocator<_Tp1>&,
1147 const bitmap_allocator<_Tp2>&) throw()
1148 { return false; }
1149
1150 // Static member definitions.
1151 template<typename _Tp>
1152 typename bitmap_allocator<_Tp>::_BPVector
1153 bitmap_allocator<_Tp>::_S_mem_blocks;
1154
1155 template<typename _Tp>
1156 size_t bitmap_allocator<_Tp>::_S_block_size =
1157 2 * balloc::bits_per_block;
1158
1159 template<typename _Tp>
1160 typename __gnu_cxx::bitmap_allocator<_Tp>::_BPVector::size_type
1161 bitmap_allocator<_Tp>::_S_last_dealloc_index = 0;
1162
1163 template<typename _Tp>
1164 __gnu_cxx::balloc::_Bitmap_counter
1165 <typename bitmap_allocator<_Tp>::_Alloc_block*>
1166 bitmap_allocator<_Tp>::_S_last_request(_S_mem_blocks);
1167
1168 #if defined __GTHREADS
1169 template<typename _Tp>
1170 __gnu_cxx::_Mutex
1171 bitmap_allocator<_Tp>::_S_mut;
1172 #endif
1173
1174
1175 }
1176
1177 #endif
1178
1179 // LocalWords: namespace GTHREADS bool const gthread endif Mutex mutex