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