OSDN Git Service

* ggc-page.c (alloc_page): Round up allocation size to one page.
[pf3gnuchains/gcc-fork.git] / gcc / ggc-page.c
1 /* "Bag-of-pages" garbage collector for the GNU compiler.
2    Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.
3
4 This file is part of GNU CC.
5
6 GNU CC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU CC 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
17 along with GNU CC; see the file COPYING.  If not, write to
18 the Free Software Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "tree.h"
24 #include "rtl.h"
25 #include "tm_p.h"
26 #include "toplev.h"
27 #include "varray.h"
28 #include "flags.h"
29 #include "ggc.h"
30 #include "timevar.h"
31
32 /* Prefer MAP_ANON(YMOUS) to /dev/zero, since we don't need to keep a
33    file open.  Prefer either to valloc.  */
34 #ifdef HAVE_MMAP_ANON
35 # undef HAVE_MMAP_DEV_ZERO
36 # undef HAVE_VALLOC
37
38 # include <sys/mman.h>
39 # ifndef MAP_FAILED
40 #  define MAP_FAILED -1
41 # endif
42 # if !defined (MAP_ANONYMOUS) && defined (MAP_ANON)
43 #  define MAP_ANONYMOUS MAP_ANON
44 # endif
45 # define USING_MMAP
46
47 #endif
48
49 #ifdef HAVE_MMAP_DEV_ZERO
50 # undef HAVE_VALLOC
51
52 # include <sys/mman.h>
53 # ifndef MAP_FAILED
54 #  define MAP_FAILED -1
55 # endif
56 # define USING_MMAP
57
58 #endif
59
60 #ifdef HAVE_VALLOC
61 # undef MAP_FAILED
62 # define MAP_FAILED 0
63 #endif
64
65 /* Stategy: 
66
67    This garbage-collecting allocator allocates objects on one of a set
68    of pages.  Each page can allocate objects of a single size only;
69    available sizes are powers of two starting at four bytes.  The size
70    of an allocation request is rounded up to the next power of two
71    (`order'), and satisfied from the appropriate page.
72
73    Each page is recorded in a page-entry, which also maintains an
74    in-use bitmap of object positions on the page.  This allows the
75    allocation state of a particular object to be flipped without
76    touching the page itself.
77
78    Each page-entry also has a context depth, which is used to track
79    pushing and popping of allocation contexts.  Only objects allocated
80    in the current (highest-numbered) context may be collected.  
81
82    Page entries are arranged in an array of singly-linked lists.  The
83    array is indexed by the allocation size, in bits, of the pages on
84    it; i.e. all pages on a list allocate objects of the same size.
85    Pages are ordered on the list such that all non-full pages precede
86    all full pages, with non-full pages arranged in order of decreasing
87    context depth.
88
89    Empty pages (of all orders) are kept on a single page cache list,
90    and are considered first when new pages are required; they are
91    deallocated at the start of the next collection if they haven't
92    been recycled by then.  */
93
94
95 /* Define GGC_POISON to poison memory marked unused by the collector.  */
96 #undef GGC_POISON
97
98 /* Define GGC_ALWAYS_COLLECT to perform collection every time
99    ggc_collect is invoked.  Otherwise, collection is performed only
100    when a significant amount of memory has been allocated since the
101    last collection.  */
102 #undef GGC_ALWAYS_COLLECT
103
104 #ifdef ENABLE_GC_CHECKING
105 #define GGC_POISON
106 #endif
107 #ifdef ENABLE_GC_ALWAYS_COLLECT
108 #define GGC_ALWAYS_COLLECT
109 #endif
110
111 /* Define GGC_DEBUG_LEVEL to print debugging information.
112      0: No debugging output.
113      1: GC statistics only.
114      2: Page-entry allocations/deallocations as well.
115      3: Object allocations as well.
116      4: Object marks as well.   */
117 #define GGC_DEBUG_LEVEL (0)
118 \f
119 #ifndef HOST_BITS_PER_PTR
120 #define HOST_BITS_PER_PTR  HOST_BITS_PER_LONG
121 #endif
122
123 \f
124 /* A two-level tree is used to look up the page-entry for a given
125    pointer.  Two chunks of the pointer's bits are extracted to index
126    the first and second levels of the tree, as follows:
127
128                                    HOST_PAGE_SIZE_BITS
129                            32           |      |
130        msb +----------------+----+------+------+ lsb
131                             |    |      |
132                          PAGE_L1_BITS   |
133                                  |      |
134                                PAGE_L2_BITS
135
136    The bottommost HOST_PAGE_SIZE_BITS are ignored, since page-entry
137    pages are aligned on system page boundaries.  The next most
138    significant PAGE_L2_BITS and PAGE_L1_BITS are the second and first
139    index values in the lookup table, respectively.  
140
141    For 32-bit architectures and the settings below, there are no
142    leftover bits.  For architectures with wider pointers, the lookup
143    tree points to a list of pages, which must be scanned to find the
144    correct one.  */
145
146 #define PAGE_L1_BITS    (8)
147 #define PAGE_L2_BITS    (32 - PAGE_L1_BITS - G.lg_pagesize)
148 #define PAGE_L1_SIZE    ((size_t) 1 << PAGE_L1_BITS)
149 #define PAGE_L2_SIZE    ((size_t) 1 << PAGE_L2_BITS)
150
151 #define LOOKUP_L1(p) \
152   (((size_t) (p) >> (32 - PAGE_L1_BITS)) & ((1 << PAGE_L1_BITS) - 1))
153
154 #define LOOKUP_L2(p) \
155   (((size_t) (p) >> G.lg_pagesize) & ((1 << PAGE_L2_BITS) - 1))
156
157 /* The number of objects per allocation page, for objects on a page of
158    the indicated ORDER.  */
159 #define OBJECTS_PER_PAGE(ORDER) objects_per_page_table[ORDER]
160
161 /* The size of an object on a page of the indicated ORDER.  */
162 #define OBJECT_SIZE(ORDER) object_size_table[ORDER]
163
164 /* The number of extra orders, not corresponding to power-of-two sized
165    objects.  */
166
167 #define NUM_EXTRA_ORDERS \
168   (sizeof (extra_order_size_table) / sizeof (extra_order_size_table[0]))
169
170 /* The Ith entry is the maximum size of an object to be stored in the
171    Ith extra order.  Adding a new entry to this array is the *only*
172    thing you need to do to add a new special allocation size.  */
173
174 static const size_t extra_order_size_table[] = {
175   sizeof (struct tree_decl),
176   sizeof (struct tree_list)
177 };
178
179 /* The total number of orders.  */
180
181 #define NUM_ORDERS (HOST_BITS_PER_PTR + NUM_EXTRA_ORDERS)
182
183 /* We use this structure to determine the alignment required for
184    allocations.  For power-of-two sized allocations, that's not a
185    problem, but it does matter for odd-sized allocations.  */
186
187 struct max_alignment {
188   char c;
189   union {
190     HOST_WIDEST_INT i;
191 #ifdef HAVE_LONG_DOUBLE
192     long double d;
193 #else
194     double d;
195 #endif
196   } u;
197 };
198
199 /* The biggest alignment required.  */
200
201 #define MAX_ALIGNMENT (offsetof (struct max_alignment, u))
202
203 /* The Ith entry is the number of objects on a page or order I.  */
204
205 static unsigned objects_per_page_table[NUM_ORDERS];
206
207 /* The Ith entry is the size of an object on a page of order I.  */
208
209 static size_t object_size_table[NUM_ORDERS];
210
211 /* A page_entry records the status of an allocation page.  This
212    structure is dynamically sized to fit the bitmap in_use_p.  */
213 typedef struct page_entry 
214 {
215   /* The next page-entry with objects of the same size, or NULL if
216      this is the last page-entry.  */
217   struct page_entry *next;
218
219   /* The number of bytes allocated.  (This will always be a multiple
220      of the host system page size.)  */
221   size_t bytes;
222
223   /* The address at which the memory is allocated.  */
224   char *page;
225
226   /* Saved in-use bit vector for pages that aren't in the topmost
227      context during collection.  */
228   unsigned long *save_in_use_p;
229
230   /* Context depth of this page.  */
231   unsigned short context_depth;
232
233   /* The number of free objects remaining on this page.  */
234   unsigned short num_free_objects;
235
236   /* A likely candidate for the bit position of a free object for the
237      next allocation from this page.  */
238   unsigned short next_bit_hint;
239
240   /* The lg of size of objects allocated from this page.  */
241   unsigned char order;
242
243   /* A bit vector indicating whether or not objects are in use.  The
244      Nth bit is one if the Nth object on this page is allocated.  This
245      array is dynamically sized.  */
246   unsigned long in_use_p[1];
247 } page_entry;
248
249
250 #if HOST_BITS_PER_PTR <= 32
251
252 /* On 32-bit hosts, we use a two level page table, as pictured above.  */
253 typedef page_entry **page_table[PAGE_L1_SIZE];
254
255 #else
256
257 /* On 64-bit hosts, we use the same two level page tables plus a linked
258    list that disambiguates the top 32-bits.  There will almost always be
259    exactly one entry in the list.  */
260 typedef struct page_table_chain
261 {
262   struct page_table_chain *next;
263   size_t high_bits;
264   page_entry **table[PAGE_L1_SIZE];
265 } *page_table;
266
267 #endif
268
269 /* The rest of the global variables.  */
270 static struct globals
271 {
272   /* The Nth element in this array is a page with objects of size 2^N.
273      If there are any pages with free objects, they will be at the
274      head of the list.  NULL if there are no page-entries for this
275      object size.  */
276   page_entry *pages[NUM_ORDERS];
277
278   /* The Nth element in this array is the last page with objects of
279      size 2^N.  NULL if there are no page-entries for this object
280      size.  */
281   page_entry *page_tails[NUM_ORDERS];
282
283   /* Lookup table for associating allocation pages with object addresses.  */
284   page_table lookup;
285
286   /* The system's page size.  */
287   size_t pagesize;
288   size_t lg_pagesize;
289
290   /* Bytes currently allocated.  */
291   size_t allocated;
292
293   /* Bytes currently allocated at the end of the last collection.  */
294   size_t allocated_last_gc;
295
296   /* Total amount of memory mapped.  */
297   size_t bytes_mapped;
298
299   /* The current depth in the context stack.  */
300   unsigned short context_depth;
301
302   /* A file descriptor open to /dev/zero for reading.  */
303 #if defined (HAVE_MMAP_DEV_ZERO)
304   int dev_zero_fd;
305 #endif
306
307   /* A cache of free system pages.  */
308   page_entry *free_pages;
309
310   /* The file descriptor for debugging output.  */
311   FILE *debug_file;
312 } G;
313
314 /* The size in bytes required to maintain a bitmap for the objects
315    on a page-entry.  */
316 #define BITMAP_SIZE(Num_objects) \
317   (CEIL ((Num_objects), HOST_BITS_PER_LONG) * sizeof(long))
318
319 /* Skip garbage collection if the current allocation is not at least
320    this factor times the allocation at the end of the last collection.
321    In other words, total allocation must expand by (this factor minus
322    one) before collection is performed.  */
323 #define GGC_MIN_EXPAND_FOR_GC (1.3)
324
325 /* Bound `allocated_last_gc' to 4MB, to prevent the memory expansion
326    test from triggering too often when the heap is small.  */
327 #define GGC_MIN_LAST_ALLOCATED (4 * 1024 * 1024)
328
329 /* Allocate pages in chunks of this size, to throttle calls to mmap.
330    The first page is used, the rest go onto the free list.  */
331 #define GGC_QUIRE_SIZE 16
332
333 \f
334 static int ggc_allocated_p PARAMS ((const void *));
335 static page_entry *lookup_page_table_entry PARAMS ((const void *));
336 static void set_page_table_entry PARAMS ((void *, page_entry *));
337 static char *alloc_anon PARAMS ((char *, size_t));
338 static struct page_entry * alloc_page PARAMS ((unsigned));
339 static void free_page PARAMS ((struct page_entry *));
340 static void release_pages PARAMS ((void));
341 static void clear_marks PARAMS ((void));
342 static void sweep_pages PARAMS ((void));
343 static void ggc_recalculate_in_use_p PARAMS ((page_entry *));
344
345 #ifdef GGC_POISON
346 static void poison_pages PARAMS ((void));
347 #endif
348
349 void debug_print_page_list PARAMS ((int));
350 \f
351 /* Returns non-zero if P was allocated in GC'able memory.  */
352
353 static inline int
354 ggc_allocated_p (p)
355      const void *p;
356 {
357   page_entry ***base;
358   size_t L1, L2;
359
360 #if HOST_BITS_PER_PTR <= 32
361   base = &G.lookup[0];
362 #else
363   page_table table = G.lookup;
364   size_t high_bits = (size_t) p & ~ (size_t) 0xffffffff;
365   while (1)
366     {
367       if (table == NULL)
368         return 0;
369       if (table->high_bits == high_bits)
370         break;
371       table = table->next;
372     }
373   base = &table->table[0];
374 #endif
375
376   /* Extract the level 1 and 2 indicies.  */
377   L1 = LOOKUP_L1 (p);
378   L2 = LOOKUP_L2 (p);
379
380   return base[L1] && base[L1][L2];
381 }
382
383 /* Traverse the page table and find the entry for a page. 
384    Die (probably) if the object wasn't allocated via GC.  */
385
386 static inline page_entry *
387 lookup_page_table_entry(p)
388      const void *p;
389 {
390   page_entry ***base;
391   size_t L1, L2;
392
393 #if HOST_BITS_PER_PTR <= 32
394   base = &G.lookup[0];
395 #else
396   page_table table = G.lookup;
397   size_t high_bits = (size_t) p & ~ (size_t) 0xffffffff;
398   while (table->high_bits != high_bits)
399     table = table->next;
400   base = &table->table[0];
401 #endif
402
403   /* Extract the level 1 and 2 indicies.  */
404   L1 = LOOKUP_L1 (p);
405   L2 = LOOKUP_L2 (p);
406
407   return base[L1][L2];
408 }
409
410 /* Set the page table entry for a page.  */
411
412 static void
413 set_page_table_entry(p, entry)
414      void *p;
415      page_entry *entry;
416 {
417   page_entry ***base;
418   size_t L1, L2;
419
420 #if HOST_BITS_PER_PTR <= 32
421   base = &G.lookup[0];
422 #else
423   page_table table;
424   size_t high_bits = (size_t) p & ~ (size_t) 0xffffffff;
425   for (table = G.lookup; table; table = table->next)
426     if (table->high_bits == high_bits)
427       goto found;
428
429   /* Not found -- allocate a new table.  */
430   table = (page_table) xcalloc (1, sizeof(*table));
431   table->next = G.lookup;
432   table->high_bits = high_bits;
433   G.lookup = table;
434 found:
435   base = &table->table[0];
436 #endif
437
438   /* Extract the level 1 and 2 indicies.  */
439   L1 = LOOKUP_L1 (p);
440   L2 = LOOKUP_L2 (p);
441
442   if (base[L1] == NULL)
443     base[L1] = (page_entry **) xcalloc (PAGE_L2_SIZE, sizeof (page_entry *));
444
445   base[L1][L2] = entry;
446 }
447
448 /* Prints the page-entry for object size ORDER, for debugging.  */
449
450 void
451 debug_print_page_list (order)
452      int order;
453 {
454   page_entry *p;
455   printf ("Head=%p, Tail=%p:\n", (PTR) G.pages[order],
456           (PTR) G.page_tails[order]);
457   p = G.pages[order];
458   while (p != NULL)
459     {
460       printf ("%p(%1d|%3d) -> ", (PTR) p, p->context_depth,
461               p->num_free_objects);
462       p = p->next;
463     }
464   printf ("NULL\n");
465   fflush (stdout);
466 }
467
468 /* Allocate SIZE bytes of anonymous memory, preferably near PREF,
469    (if non-null).  The ifdef structure here is intended to cause a
470    compile error unless exactly one of the HAVE_* is defined.  */
471
472 static inline char *
473 alloc_anon (pref, size)
474      char *pref ATTRIBUTE_UNUSED;
475      size_t size;
476 {
477 #ifdef HAVE_MMAP_ANON
478   char *page = (char *) mmap (pref, size, PROT_READ | PROT_WRITE,
479                               MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
480 #endif
481 #ifdef HAVE_MMAP_DEV_ZERO
482   char *page = (char *) mmap (pref, size, PROT_READ | PROT_WRITE,
483                               MAP_PRIVATE, G.dev_zero_fd, 0);
484 #endif
485 #ifdef HAVE_VALLOC
486   char *page = (char *) valloc (size);
487 #endif
488
489   if (page == (char *) MAP_FAILED)
490     {
491       fputs ("Virtual memory exhausted!\n", stderr);
492       exit(1);
493     }
494
495   /* Remember that we allocated this memory.  */
496   G.bytes_mapped += size;
497
498   return page;
499 }
500
501 /* Allocate a new page for allocating objects of size 2^ORDER,
502    and return an entry for it.  The entry is not added to the
503    appropriate page_table list.  */
504
505 static inline struct page_entry *
506 alloc_page (order)
507      unsigned order;
508 {
509   struct page_entry *entry, *p, **pp;
510   char *page;
511   size_t num_objects;
512   size_t bitmap_size;
513   size_t page_entry_size;
514   size_t entry_size;
515
516   num_objects = OBJECTS_PER_PAGE (order);
517   bitmap_size = BITMAP_SIZE (num_objects + 1);
518   page_entry_size = sizeof (page_entry) - sizeof (long) + bitmap_size;
519   entry_size = num_objects * OBJECT_SIZE (order);
520   if (entry_size < G.pagesize)
521     entry_size = G.pagesize;
522
523   entry = NULL;
524   page = NULL;
525
526   /* Check the list of free pages for one we can use.  */
527   for (pp = &G.free_pages, p = *pp; p ; pp = &p->next, p = *pp)
528     if (p->bytes == entry_size)
529       break;
530
531   if (p != NULL)
532     {
533       /* Recycle the allocated memory from this page ... */
534       *pp = p->next;
535       page = p->page;
536       /* ... and, if possible, the page entry itself.  */
537       if (p->order == order)
538         {
539           entry = p;
540           memset (entry, 0, page_entry_size);
541         }
542       else
543         free (p);
544     }
545 #ifdef USING_MMAP
546   else if (entry_size == G.pagesize)
547     {
548       /* We want just one page.  Allocate a bunch of them and put the
549          extras on the freelist.  (Can only do this optimization with
550          mmap for backing store.)  */
551       struct page_entry *e, *f = G.free_pages;
552       int i;
553
554       page = alloc_anon (NULL, G.pagesize * GGC_QUIRE_SIZE);
555       /* This loop counts down so that the chain will be in ascending
556          memory order.  */
557       for (i = GGC_QUIRE_SIZE - 1; i >= 1; i--)
558         {
559           e = (struct page_entry *) xcalloc (1, page_entry_size);
560           e->order = order;
561           e->bytes = G.pagesize;
562           e->page = page + (i << G.lg_pagesize);
563           e->next = f;
564           f = e;
565         }
566       G.free_pages = f;
567     }
568 #endif
569   else
570     page = alloc_anon (NULL, entry_size);
571
572   if (entry == NULL)
573     entry = (struct page_entry *) xcalloc (1, page_entry_size);
574
575   entry->bytes = entry_size;
576   entry->page = page;
577   entry->context_depth = G.context_depth;
578   entry->order = order;
579   entry->num_free_objects = num_objects;
580   entry->next_bit_hint = 1;
581
582   /* Set the one-past-the-end in-use bit.  This acts as a sentry as we
583      increment the hint.  */
584   entry->in_use_p[num_objects / HOST_BITS_PER_LONG]
585     = (unsigned long) 1 << (num_objects % HOST_BITS_PER_LONG);
586
587   set_page_table_entry (page, entry);
588
589   if (GGC_DEBUG_LEVEL >= 2)
590     fprintf (G.debug_file, 
591              "Allocating page at %p, object size=%d, data %p-%p\n",
592              (PTR) entry, OBJECT_SIZE (order), page, page + entry_size - 1);
593
594   return entry;
595 }
596
597 /* For a page that is no longer needed, put it on the free page list.  */
598
599 static inline void
600 free_page (entry)
601      page_entry *entry;
602 {
603   if (GGC_DEBUG_LEVEL >= 2)
604     fprintf (G.debug_file, 
605              "Deallocating page at %p, data %p-%p\n", (PTR) entry,
606              entry->page, entry->page + entry->bytes - 1);
607
608   set_page_table_entry (entry->page, NULL);
609
610   entry->next = G.free_pages;
611   G.free_pages = entry;
612 }
613
614 /* Release the free page cache to the system.  */
615
616 static void
617 release_pages ()
618 {
619   page_entry *p, *next;
620
621 #ifdef USING_MMAP
622   char *start;
623   size_t len;
624
625   /* Gather up adjacent pages so they are unmapped together.  */
626   p = G.free_pages;
627
628   while (p)
629     {
630       start = p->page;
631       next = p->next;
632       len = p->bytes;
633       free (p);
634       p = next;
635
636       while (p && p->page == start + len)
637         {
638           next = p->next;
639           len += p->bytes;
640           free (p);
641           p = next;
642         }
643
644       munmap (start, len);
645       G.bytes_mapped -= len;
646     }
647 #else
648   for (p = G.free_pages; p; p = next)
649     {
650       next = p->next;
651       free (p->page);
652       G.bytes_mapped -= p->bytes;
653       free (p);
654     }
655 #endif /* USING_MMAP */
656
657   G.free_pages = NULL;
658 }
659
660 /* This table provides a fast way to determine ceil(log_2(size)) for
661    allocation requests.  The minimum allocation size is four bytes.  */
662
663 static unsigned char size_lookup[257] = 
664
665   2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 
666   4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 
667   5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 
668   6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 
669   6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 
670   7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 
671   7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
672   7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 
673   7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
674   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
675   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
676   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
677   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
678   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
679   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
680   8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
681   8
682 };
683
684 /* Allocate a chunk of memory of SIZE bytes.  If ZERO is non-zero, the
685    memory is zeroed; otherwise, its contents are undefined.  */
686
687 void *
688 ggc_alloc (size)
689      size_t size;
690 {
691   unsigned order, word, bit, object_offset;
692   struct page_entry *entry;
693   void *result;
694
695   if (size <= 256)
696     order = size_lookup[size];
697   else
698     {
699       order = 9;
700       while (size > OBJECT_SIZE (order))
701         order++;
702     }
703
704   /* If there are non-full pages for this size allocation, they are at
705      the head of the list.  */
706   entry = G.pages[order];
707
708   /* If there is no page for this object size, or all pages in this
709      context are full, allocate a new page.  */
710   if (entry == NULL || entry->num_free_objects == 0)
711     {
712       struct page_entry *new_entry;
713       new_entry = alloc_page (order);
714       
715       /* If this is the only entry, it's also the tail.  */
716       if (entry == NULL)
717         G.page_tails[order] = new_entry;
718      
719       /* Put new pages at the head of the page list.  */
720       new_entry->next = entry;
721       entry = new_entry;
722       G.pages[order] = new_entry;
723
724       /* For a new page, we know the word and bit positions (in the
725          in_use bitmap) of the first available object -- they're zero.  */
726       new_entry->next_bit_hint = 1;
727       word = 0;
728       bit = 0;
729       object_offset = 0;
730     }
731   else
732     {
733       /* First try to use the hint left from the previous allocation
734          to locate a clear bit in the in-use bitmap.  We've made sure
735          that the one-past-the-end bit is always set, so if the hint
736          has run over, this test will fail.  */
737       unsigned hint = entry->next_bit_hint;
738       word = hint / HOST_BITS_PER_LONG;
739       bit = hint % HOST_BITS_PER_LONG;
740       
741       /* If the hint didn't work, scan the bitmap from the beginning.  */
742       if ((entry->in_use_p[word] >> bit) & 1)
743         {
744           word = bit = 0;
745           while (~entry->in_use_p[word] == 0)
746             ++word;
747           while ((entry->in_use_p[word] >> bit) & 1)
748             ++bit;
749           hint = word * HOST_BITS_PER_LONG + bit;
750         }
751
752       /* Next time, try the next bit.  */
753       entry->next_bit_hint = hint + 1;
754
755       object_offset = hint * OBJECT_SIZE (order);
756     }
757
758   /* Set the in-use bit.  */
759   entry->in_use_p[word] |= ((unsigned long) 1 << bit);
760
761   /* Keep a running total of the number of free objects.  If this page
762      fills up, we may have to move it to the end of the list if the
763      next page isn't full.  If the next page is full, all subsequent
764      pages are full, so there's no need to move it.  */
765   if (--entry->num_free_objects == 0
766       && entry->next != NULL
767       && entry->next->num_free_objects > 0)
768     {
769       G.pages[order] = entry->next;
770       entry->next = NULL;
771       G.page_tails[order]->next = entry;
772       G.page_tails[order] = entry;
773     }
774
775   /* Calculate the object's address.  */
776   result = entry->page + object_offset;
777
778 #ifdef GGC_POISON
779   /* `Poison' the entire allocated object, including any padding at
780      the end.  */
781   memset (result, 0xaf, OBJECT_SIZE (order));
782 #endif
783
784   /* Keep track of how many bytes are being allocated.  This
785      information is used in deciding when to collect.  */
786   G.allocated += OBJECT_SIZE (order);
787
788   if (GGC_DEBUG_LEVEL >= 3)
789     fprintf (G.debug_file, 
790              "Allocating object, requested size=%d, actual=%d at %p on %p\n",
791              (int) size, OBJECT_SIZE (order), result, (PTR) entry);
792
793   return result;
794 }
795
796 /* If P is not marked, marks it and return false.  Otherwise return true.
797    P must have been allocated by the GC allocator; it mustn't point to
798    static objects, stack variables, or memory allocated with malloc.  */
799
800 int
801 ggc_set_mark (p)
802      const void *p;
803 {
804   page_entry *entry;
805   unsigned bit, word;
806   unsigned long mask;
807
808   /* Look up the page on which the object is alloced.  If the object
809      wasn't allocated by the collector, we'll probably die.  */
810   entry = lookup_page_table_entry (p);
811 #ifdef ENABLE_CHECKING
812   if (entry == NULL)
813     abort ();
814 #endif
815
816   /* Calculate the index of the object on the page; this is its bit
817      position in the in_use_p bitmap.  */
818   bit = (((const char *) p) - entry->page) / OBJECT_SIZE (entry->order);
819   word = bit / HOST_BITS_PER_LONG;
820   mask = (unsigned long) 1 << (bit % HOST_BITS_PER_LONG);
821   
822   /* If the bit was previously set, skip it. */
823   if (entry->in_use_p[word] & mask)
824     return 1;
825
826   /* Otherwise set it, and decrement the free object count.  */
827   entry->in_use_p[word] |= mask;
828   entry->num_free_objects -= 1;
829
830   if (GGC_DEBUG_LEVEL >= 4)
831     fprintf (G.debug_file, "Marking %p\n", p);
832
833   return 0;
834 }
835
836 /* Mark P, but check first that it was allocated by the collector.  */
837
838 void
839 ggc_mark_if_gcable (p)
840      const void *p;
841 {
842   if (p && ggc_allocated_p (p))
843     ggc_set_mark (p);
844 }
845
846 /* Return the size of the gc-able object P.  */
847
848 size_t
849 ggc_get_size (p)
850      const void *p;
851 {
852   page_entry *pe = lookup_page_table_entry (p);
853   return OBJECT_SIZE (pe->order);
854 }
855 \f
856 /* Initialize the ggc-mmap allocator.  */
857
858 void
859 init_ggc ()
860 {
861   unsigned order;
862
863   G.pagesize = getpagesize();
864   G.lg_pagesize = exact_log2 (G.pagesize);
865
866 #ifdef HAVE_MMAP_DEV_ZERO
867   G.dev_zero_fd = open ("/dev/zero", O_RDONLY);
868   if (G.dev_zero_fd == -1)
869     abort ();
870 #endif
871
872 #if 0
873   G.debug_file = fopen ("ggc-mmap.debug", "w");
874 #else
875   G.debug_file = stdout;
876 #endif
877
878   G.allocated_last_gc = GGC_MIN_LAST_ALLOCATED;
879
880 #ifdef USING_MMAP
881   /* StunOS has an amazing off-by-one error for the first mmap allocation
882      after fiddling with RLIMIT_STACK.  The result, as hard as it is to
883      believe, is an unaligned page allocation, which would cause us to
884      hork badly if we tried to use it.  */
885   {
886     char *p = alloc_anon (NULL, G.pagesize);
887     struct page_entry *e;
888     if ((size_t)p & (G.pagesize - 1))
889       {
890         /* How losing.  Discard this one and try another.  If we still
891            can't get something useful, give up.  */
892
893         p = alloc_anon (NULL, G.pagesize);
894         if ((size_t)p & (G.pagesize - 1))
895           abort ();
896       }
897
898     /* We have a good page, might as well hold onto it... */
899     e = (struct page_entry *) xcalloc (1, sizeof (struct page_entry));
900     e->bytes = G.pagesize;
901     e->page = p;
902     e->next = G.free_pages;
903     G.free_pages = e;
904   }
905 #endif
906
907   /* Initialize the object size table.  */
908   for (order = 0; order < HOST_BITS_PER_PTR; ++order)
909     object_size_table[order] = (size_t) 1 << order;
910   for (order = HOST_BITS_PER_PTR; order < NUM_ORDERS; ++order)
911     {
912       size_t s = extra_order_size_table[order - HOST_BITS_PER_PTR];
913
914       /* If S is not a multiple of the MAX_ALIGNMENT, then round it up
915          so that we're sure of getting aligned memory.  */
916       s = CEIL (s, MAX_ALIGNMENT) * MAX_ALIGNMENT;
917       object_size_table[order] = s;
918     }
919
920   /* Initialize the objects-per-page table.  */
921   for (order = 0; order < NUM_ORDERS; ++order)
922     {
923       objects_per_page_table[order] = G.pagesize / OBJECT_SIZE (order);
924       if (objects_per_page_table[order] == 0)
925         objects_per_page_table[order] = 1;
926     }
927
928   /* Reset the size_lookup array to put appropriately sized objects in
929      the special orders.  All objects bigger than the previous power
930      of two, but no greater than the special size, should go in the
931      new order.  */
932   for (order = HOST_BITS_PER_PTR; order < NUM_ORDERS; ++order)
933     {
934       int o;
935       int i;
936
937       o = size_lookup[OBJECT_SIZE (order)];
938       for (i = OBJECT_SIZE (order); size_lookup [i] == o; --i)
939         size_lookup[i] = order;
940     }
941 }
942
943 /* Increment the `GC context'.  Objects allocated in an outer context
944    are never freed, eliminating the need to register their roots.  */
945
946 void
947 ggc_push_context ()
948 {
949   ++G.context_depth;
950
951   /* Die on wrap.  */
952   if (G.context_depth == 0)
953     abort ();
954 }
955
956 /* Merge the SAVE_IN_USE_P and IN_USE_P arrays in P so that IN_USE_P
957    reflects reality.  Recalculate NUM_FREE_OBJECTS as well.  */
958
959 static void
960 ggc_recalculate_in_use_p (p)
961      page_entry *p;
962 {
963   unsigned int i;
964   size_t num_objects;
965
966   /* Because the past-the-end bit in in_use_p is always set, we 
967      pretend there is one additional object.  */
968   num_objects = OBJECTS_PER_PAGE (p->order) + 1;
969
970   /* Reset the free object count.  */
971   p->num_free_objects = num_objects;
972
973   /* Combine the IN_USE_P and SAVE_IN_USE_P arrays.  */
974   for (i = 0; 
975        i < CEIL (BITMAP_SIZE (num_objects),
976                  sizeof (*p->in_use_p));
977        ++i)
978     {
979       unsigned long j;
980
981       /* Something is in use if it is marked, or if it was in use in a
982          context further down the context stack.  */
983       p->in_use_p[i] |= p->save_in_use_p[i];
984
985       /* Decrement the free object count for every object allocated.  */
986       for (j = p->in_use_p[i]; j; j >>= 1)
987         p->num_free_objects -= (j & 1);
988     }
989
990   if (p->num_free_objects >= num_objects)
991     abort ();
992 }
993
994 /* Decrement the `GC context'.  All objects allocated since the 
995    previous ggc_push_context are migrated to the outer context.  */
996
997 void
998 ggc_pop_context ()
999 {
1000   unsigned order, depth;
1001
1002   depth = --G.context_depth;
1003
1004   /* Any remaining pages in the popped context are lowered to the new
1005      current context; i.e. objects allocated in the popped context and
1006      left over are imported into the previous context.  */
1007   for (order = 2; order < NUM_ORDERS; order++)
1008     {
1009       page_entry *p;
1010
1011       for (p = G.pages[order]; p != NULL; p = p->next)
1012         {
1013           if (p->context_depth > depth)
1014             p->context_depth = depth;
1015
1016           /* If this page is now in the topmost context, and we'd
1017              saved its allocation state, restore it.  */
1018           else if (p->context_depth == depth && p->save_in_use_p)
1019             {
1020               ggc_recalculate_in_use_p (p);
1021               free (p->save_in_use_p);
1022               p->save_in_use_p = 0;
1023             }
1024         }
1025     }
1026 }
1027 \f
1028 /* Unmark all objects.  */
1029
1030 static inline void
1031 clear_marks ()
1032 {
1033   unsigned order;
1034
1035   for (order = 2; order < NUM_ORDERS; order++)
1036     {
1037       size_t num_objects = OBJECTS_PER_PAGE (order);
1038       size_t bitmap_size = BITMAP_SIZE (num_objects + 1);
1039       page_entry *p;
1040
1041       for (p = G.pages[order]; p != NULL; p = p->next)
1042         {
1043 #ifdef ENABLE_CHECKING
1044           /* The data should be page-aligned.  */
1045           if ((size_t) p->page & (G.pagesize - 1))
1046             abort ();
1047 #endif
1048
1049           /* Pages that aren't in the topmost context are not collected;
1050              nevertheless, we need their in-use bit vectors to store GC
1051              marks.  So, back them up first.  */
1052           if (p->context_depth < G.context_depth)
1053             {
1054               if (! p->save_in_use_p)
1055                 p->save_in_use_p = xmalloc (bitmap_size);
1056               memcpy (p->save_in_use_p, p->in_use_p, bitmap_size);
1057             }
1058
1059           /* Reset reset the number of free objects and clear the
1060              in-use bits.  These will be adjusted by mark_obj.  */
1061           p->num_free_objects = num_objects;
1062           memset (p->in_use_p, 0, bitmap_size);
1063
1064           /* Make sure the one-past-the-end bit is always set.  */
1065           p->in_use_p[num_objects / HOST_BITS_PER_LONG] 
1066             = ((unsigned long) 1 << (num_objects % HOST_BITS_PER_LONG));
1067         }
1068     }
1069 }
1070
1071 /* Free all empty pages.  Partially empty pages need no attention
1072    because the `mark' bit doubles as an `unused' bit.  */
1073
1074 static inline void
1075 sweep_pages ()
1076 {
1077   unsigned order;
1078
1079   for (order = 2; order < NUM_ORDERS; order++)
1080     {
1081       /* The last page-entry to consider, regardless of entries
1082          placed at the end of the list.  */
1083       page_entry * const last = G.page_tails[order];
1084
1085       size_t num_objects = OBJECTS_PER_PAGE (order);
1086       size_t live_objects;
1087       page_entry *p, *previous;
1088       int done;
1089         
1090       p = G.pages[order];
1091       if (p == NULL)
1092         continue;
1093
1094       previous = NULL;
1095       do
1096         {
1097           page_entry *next = p->next;
1098
1099           /* Loop until all entries have been examined.  */
1100           done = (p == last);
1101
1102           /* Add all live objects on this page to the count of
1103              allocated memory.  */
1104           live_objects = num_objects - p->num_free_objects;
1105
1106           G.allocated += OBJECT_SIZE (order) * live_objects;
1107
1108           /* Only objects on pages in the topmost context should get
1109              collected.  */
1110           if (p->context_depth < G.context_depth)
1111             ;
1112
1113           /* Remove the page if it's empty.  */
1114           else if (live_objects == 0)
1115             {
1116               if (! previous)
1117                 G.pages[order] = next;
1118               else
1119                 previous->next = next;
1120
1121               /* Are we removing the last element?  */
1122               if (p == G.page_tails[order])
1123                 G.page_tails[order] = previous;
1124               free_page (p);
1125               p = previous;
1126             }
1127
1128           /* If the page is full, move it to the end.  */
1129           else if (p->num_free_objects == 0)
1130             {
1131               /* Don't move it if it's already at the end.  */
1132               if (p != G.page_tails[order])
1133                 {
1134                   /* Move p to the end of the list.  */
1135                   p->next = NULL;
1136                   G.page_tails[order]->next = p;
1137
1138                   /* Update the tail pointer...  */
1139                   G.page_tails[order] = p;
1140
1141                   /* ... and the head pointer, if necessary.  */
1142                   if (! previous)
1143                     G.pages[order] = next;
1144                   else
1145                     previous->next = next;
1146                   p = previous;
1147                 }
1148             }
1149
1150           /* If we've fallen through to here, it's a page in the
1151              topmost context that is neither full nor empty.  Such a
1152              page must precede pages at lesser context depth in the
1153              list, so move it to the head.  */
1154           else if (p != G.pages[order])
1155             {
1156               previous->next = p->next;
1157               p->next = G.pages[order];
1158               G.pages[order] = p;
1159               /* Are we moving the last element?  */
1160               if (G.page_tails[order] == p)
1161                 G.page_tails[order] = previous;
1162               p = previous;
1163             }
1164
1165           previous = p;
1166           p = next;
1167         } 
1168       while (! done);
1169
1170       /* Now, restore the in_use_p vectors for any pages from contexts
1171          other than the current one.  */
1172       for (p = G.pages[order]; p; p = p->next)
1173         if (p->context_depth != G.context_depth)
1174           ggc_recalculate_in_use_p (p);
1175     }
1176 }
1177
1178 #ifdef GGC_POISON
1179 /* Clobber all free objects.  */
1180
1181 static inline void
1182 poison_pages ()
1183 {
1184   unsigned order;
1185
1186   for (order = 2; order < NUM_ORDERS; order++)
1187     {
1188       size_t num_objects = OBJECTS_PER_PAGE (order);
1189       size_t size = OBJECT_SIZE (order);
1190       page_entry *p;
1191
1192       for (p = G.pages[order]; p != NULL; p = p->next)
1193         {
1194           size_t i;
1195
1196           if (p->context_depth != G.context_depth)
1197             /* Since we don't do any collection for pages in pushed
1198                contexts, there's no need to do any poisoning.  And
1199                besides, the IN_USE_P array isn't valid until we pop
1200                contexts.  */
1201             continue;
1202
1203           for (i = 0; i < num_objects; i++)
1204             {
1205               size_t word, bit;
1206               word = i / HOST_BITS_PER_LONG;
1207               bit = i % HOST_BITS_PER_LONG;
1208               if (((p->in_use_p[word] >> bit) & 1) == 0)
1209                 memset (p->page + i * size, 0xa5, size);
1210             }
1211         }
1212     }
1213 }
1214 #endif
1215
1216 /* Top level mark-and-sweep routine.  */
1217
1218 void
1219 ggc_collect ()
1220 {
1221   /* Avoid frequent unnecessary work by skipping collection if the
1222      total allocations haven't expanded much since the last
1223      collection.  */
1224 #ifndef GGC_ALWAYS_COLLECT
1225   if (G.allocated < GGC_MIN_EXPAND_FOR_GC * G.allocated_last_gc)
1226     return;
1227 #endif
1228
1229   timevar_push (TV_GC);
1230   if (!quiet_flag)
1231     fprintf (stderr, " {GC %luk -> ", (unsigned long) G.allocated / 1024);
1232
1233   /* Zero the total allocated bytes.  This will be recalculated in the
1234      sweep phase.  */
1235   G.allocated = 0;
1236
1237   /* Release the pages we freed the last time we collected, but didn't 
1238      reuse in the interim.  */
1239   release_pages ();
1240
1241   clear_marks ();
1242   ggc_mark_roots ();
1243   
1244 #ifdef GGC_POISON
1245   poison_pages ();
1246 #endif
1247
1248   sweep_pages ();
1249
1250   G.allocated_last_gc = G.allocated;
1251   if (G.allocated_last_gc < GGC_MIN_LAST_ALLOCATED)
1252     G.allocated_last_gc = GGC_MIN_LAST_ALLOCATED;
1253
1254   timevar_pop (TV_GC);
1255
1256   if (!quiet_flag)
1257     fprintf (stderr, "%luk}", (unsigned long) G.allocated / 1024);
1258 }
1259
1260 /* Print allocation statistics.  */
1261 #define SCALE(x) ((unsigned long) ((x) < 1024*10 \
1262                   ? (x) \
1263                   : ((x) < 1024*1024*10 \
1264                      ? (x) / 1024 \
1265                      : (x) / (1024*1024))))
1266 #define LABEL(x) ((x) < 1024*10 ? ' ' : ((x) < 1024*1024*10 ? 'k' : 'M'))
1267
1268 void
1269 ggc_print_statistics ()
1270 {
1271   struct ggc_statistics stats;
1272   unsigned int i;
1273   size_t total_overhead = 0;
1274
1275   /* Clear the statistics.  */
1276   memset (&stats, 0, sizeof (stats));
1277   
1278   /* Make sure collection will really occur.  */
1279   G.allocated_last_gc = 0;
1280
1281   /* Collect and print the statistics common across collectors.  */
1282   ggc_print_common_statistics (stderr, &stats);
1283
1284   /* Release free pages so that we will not count the bytes allocated
1285      there as part of the total allocated memory.  */
1286   release_pages ();
1287
1288   /* Collect some information about the various sizes of 
1289      allocation.  */
1290   fprintf (stderr, "\n%-5s %10s  %10s  %10s\n",
1291            "Log", "Allocated", "Used", "Overhead");
1292   for (i = 0; i < NUM_ORDERS; ++i)
1293     {
1294       page_entry *p;
1295       size_t allocated;
1296       size_t in_use;
1297       size_t overhead;
1298
1299       /* Skip empty entries.  */
1300       if (!G.pages[i])
1301         continue;
1302
1303       overhead = allocated = in_use = 0;
1304
1305       /* Figure out the total number of bytes allocated for objects of
1306          this size, and how many of them are actually in use.  Also figure
1307          out how much memory the page table is using.  */
1308       for (p = G.pages[i]; p; p = p->next)
1309         {
1310           allocated += p->bytes;
1311           in_use += 
1312             (OBJECTS_PER_PAGE (i) - p->num_free_objects) * OBJECT_SIZE (i);
1313
1314           overhead += (sizeof (page_entry) - sizeof (long)
1315                        + BITMAP_SIZE (OBJECTS_PER_PAGE (i) + 1));
1316         }
1317       fprintf (stderr, "%-5d %10ld%c %10ld%c %10ld%c\n", i,
1318                SCALE (allocated), LABEL (allocated),
1319                SCALE (in_use), LABEL (in_use),
1320                SCALE (overhead), LABEL (overhead));
1321       total_overhead += overhead;
1322     }
1323   fprintf (stderr, "%-5s %10ld%c %10ld%c %10ld%c\n", "Total",
1324            SCALE (G.bytes_mapped), LABEL (G.bytes_mapped),
1325            SCALE (G.allocated), LABEL(G.allocated),
1326            SCALE (total_overhead), LABEL (total_overhead));
1327 }