OSDN Git Service

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