OSDN Git Service

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