OSDN Git Service

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