OSDN Git Service

2009-08-04 David Daney <ddaney@caviumnetworks.com>
[pf3gnuchains/gcc-fork.git] / gcc / ggc-common.c
1 /* Simple garbage collection for the GNU compiler.
2    Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
3    Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 /* Generic garbage collection (GC) functions and data, not specific to
22    any particular GC implementation.  */
23
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "hashtab.h"
28 #include "ggc.h"
29 #include "toplev.h"
30 #include "params.h"
31 #include "hosthooks.h"
32 #include "hosthooks-def.h"
33 #include "plugin.h"
34 #include "vec.h"
35
36 #ifdef HAVE_SYS_RESOURCE_H
37 # include <sys/resource.h>
38 #endif
39
40 #ifdef HAVE_MMAP_FILE
41 # include <sys/mman.h>
42 # ifdef HAVE_MINCORE
43 /* This is on Solaris.  */
44 #  include <sys/types.h> 
45 # endif
46 #endif
47
48 #ifndef MAP_FAILED
49 # define MAP_FAILED ((void *)-1)
50 #endif
51
52 /* When set, ggc_collect will do collection.  */
53 bool ggc_force_collect;
54
55 /* When true, protect the contents of the identifier hash table.  */
56 bool ggc_protect_identifiers = true;
57
58 /* Statistics about the allocation.  */
59 static ggc_statistics *ggc_stats;
60
61 struct traversal_state;
62
63 static int ggc_htab_delete (void **, void *);
64 static hashval_t saving_htab_hash (const void *);
65 static int saving_htab_eq (const void *, const void *);
66 static int call_count (void **, void *);
67 static int call_alloc (void **, void *);
68 static int compare_ptr_data (const void *, const void *);
69 static void relocate_ptrs (void *, void *);
70 static void write_pch_globals (const struct ggc_root_tab * const *tab,
71                                struct traversal_state *state);
72 static double ggc_rlimit_bound (double);
73
74 /* Maintain global roots that are preserved during GC.  */
75
76 /* Process a slot of an htab by deleting it if it has not been marked.  */
77
78 static int
79 ggc_htab_delete (void **slot, void *info)
80 {
81   const struct ggc_cache_tab *r = (const struct ggc_cache_tab *) info;
82
83   if (! (*r->marked_p) (*slot))
84     htab_clear_slot (*r->base, slot);
85   else
86     (*r->cb) (*slot);
87
88   return 1;
89 }
90
91
92 /* This extra vector of dynamically registered root_tab-s is used by
93    ggc_mark_roots and gives the ability to dynamically add new GGC root
94    tables, for instance from some plugins; this vector is a heap one
95    [since it is used by GGC internally!] */
96 typedef const struct ggc_root_tab* const_ggc_root_tab_t;
97 DEF_VEC_P(const_ggc_root_tab_t);
98 DEF_VEC_ALLOC_P(const_ggc_root_tab_t, heap);
99 static VEC(const_ggc_root_tab_t, heap) *extra_root_vec;
100
101
102 /* Dynamically register a new GGC root table RT. This is useful for
103    plugins. */
104
105 void 
106 ggc_register_root_tab (const struct ggc_root_tab* rt)
107 {
108   if (!rt)
109     return;
110   if (!extra_root_vec) 
111     {
112       int vlen = 32;
113       extra_root_vec = VEC_alloc (const_ggc_root_tab_t, heap, vlen);
114     }
115   VEC_safe_push (const_ggc_root_tab_t, heap, extra_root_vec, rt);
116 }
117
118
119 /* Iterate through all registered roots and mark each element.  */
120
121 void
122 ggc_mark_roots (void)
123 {
124   const struct ggc_root_tab *const *rt;
125   const struct ggc_root_tab *rti;
126   const struct ggc_cache_tab *const *ct;
127   const struct ggc_cache_tab *cti;
128   size_t i;
129
130   for (rt = gt_ggc_deletable_rtab; *rt; rt++)
131     for (rti = *rt; rti->base != NULL; rti++)
132       memset (rti->base, 0, rti->stride);
133
134   for (rt = gt_ggc_rtab; *rt; rt++)
135     for (rti = *rt; rti->base != NULL; rti++)
136       for (i = 0; i < rti->nelt; i++)
137         (*rti->cb) (*(void **)((char *)rti->base + rti->stride * i));
138
139   if (extra_root_vec 
140       && VEC_length(const_ggc_root_tab_t,extra_root_vec) > 0)
141     {
142       const_ggc_root_tab_t rtp = NULL;
143       for (i=0; 
144            VEC_iterate(const_ggc_root_tab_t, extra_root_vec, i, rtp); 
145            i++) 
146         {
147           for (rti = rtp; rti->base != NULL; rti++)
148             for (i = 0; i < rti->nelt; i++)
149               (*rti->cb) (*(void **) ((char *)rti->base + rti->stride * i));
150         }
151     }
152
153   if (ggc_protect_identifiers)
154     ggc_mark_stringpool ();
155
156   /* Now scan all hash tables that have objects which are to be deleted if
157      they are not already marked.  */
158   for (ct = gt_ggc_cache_rtab; *ct; ct++)
159     for (cti = *ct; cti->base != NULL; cti++)
160       if (*cti->base)
161         {
162           ggc_set_mark (*cti->base);
163           htab_traverse_noresize (*cti->base, ggc_htab_delete,
164                                   CONST_CAST (void *, (const void *)cti));
165           ggc_set_mark ((*cti->base)->entries);
166         }
167
168   if (! ggc_protect_identifiers)
169     ggc_purge_stringpool ();
170
171   /* Some plugins may call ggc_set_mark from here.  */
172   invoke_plugin_callbacks (PLUGIN_GGC_MARKING, NULL);
173 }
174
175 /* Allocate a block of memory, then clear it.  */
176 void *
177 ggc_alloc_cleared_stat (size_t size MEM_STAT_DECL)
178 {
179   void *buf = ggc_alloc_stat (size PASS_MEM_STAT);
180   memset (buf, 0, size);
181   return buf;
182 }
183
184 /* Resize a block of memory, possibly re-allocating it.  */
185 void *
186 ggc_realloc_stat (void *x, size_t size MEM_STAT_DECL)
187 {
188   void *r;
189   size_t old_size;
190
191   if (x == NULL)
192     return ggc_alloc_stat (size PASS_MEM_STAT);
193
194   old_size = ggc_get_size (x);
195
196   if (size <= old_size)
197     {
198       /* Mark the unwanted memory as unaccessible.  We also need to make
199          the "new" size accessible, since ggc_get_size returns the size of
200          the pool, not the size of the individually allocated object, the
201          size which was previously made accessible.  Unfortunately, we
202          don't know that previously allocated size.  Without that
203          knowledge we have to lose some initialization-tracking for the
204          old parts of the object.  An alternative is to mark the whole
205          old_size as reachable, but that would lose tracking of writes
206          after the end of the object (by small offsets).  Discard the
207          handle to avoid handle leak.  */
208       VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS ((char *) x + size,
209                                                     old_size - size));
210       VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (x, size));
211       return x;
212     }
213
214   r = ggc_alloc_stat (size PASS_MEM_STAT);
215
216   /* Since ggc_get_size returns the size of the pool, not the size of the
217      individually allocated object, we'd access parts of the old object
218      that were marked invalid with the memcpy below.  We lose a bit of the
219      initialization-tracking since some of it may be uninitialized.  */
220   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (x, old_size));
221
222   memcpy (r, x, old_size);
223
224   /* The old object is not supposed to be used anymore.  */
225   ggc_free (x);
226
227   return r;
228 }
229
230 /* Like ggc_alloc_cleared, but performs a multiplication.  */
231 void *
232 ggc_calloc (size_t s1, size_t s2)
233 {
234   return ggc_alloc_cleared (s1 * s2);
235 }
236
237 /* These are for splay_tree_new_ggc.  */
238 void *
239 ggc_splay_alloc (int sz, void *nl)
240 {
241   gcc_assert (!nl);
242   return ggc_alloc (sz);
243 }
244
245 void
246 ggc_splay_dont_free (void * x ATTRIBUTE_UNUSED, void *nl)
247 {
248   gcc_assert (!nl);
249 }
250
251 /* Print statistics that are independent of the collector in use.  */
252 #define SCALE(x) ((unsigned long) ((x) < 1024*10 \
253                   ? (x) \
254                   : ((x) < 1024*1024*10 \
255                      ? (x) / 1024 \
256                      : (x) / (1024*1024))))
257 #define LABEL(x) ((x) < 1024*10 ? ' ' : ((x) < 1024*1024*10 ? 'k' : 'M'))
258
259 void
260 ggc_print_common_statistics (FILE *stream ATTRIBUTE_UNUSED,
261                              ggc_statistics *stats)
262 {
263   /* Set the pointer so that during collection we will actually gather
264      the statistics.  */
265   ggc_stats = stats;
266
267   /* Then do one collection to fill in the statistics.  */
268   ggc_collect ();
269
270   /* At present, we don't really gather any interesting statistics.  */
271
272   /* Don't gather statistics any more.  */
273   ggc_stats = NULL;
274 }
275 \f
276 /* Functions for saving and restoring GCable memory to disk.  */
277
278 static htab_t saving_htab;
279
280 struct ptr_data
281 {
282   void *obj;
283   void *note_ptr_cookie;
284   gt_note_pointers note_ptr_fn;
285   gt_handle_reorder reorder_fn;
286   size_t size;
287   void *new_addr;
288   enum gt_types_enum type;
289 };
290
291 #define POINTER_HASH(x) (hashval_t)((long)x >> 3)
292
293 /* Register an object in the hash table.  */
294
295 int
296 gt_pch_note_object (void *obj, void *note_ptr_cookie,
297                     gt_note_pointers note_ptr_fn,
298                     enum gt_types_enum type)
299 {
300   struct ptr_data **slot;
301
302   if (obj == NULL || obj == (void *) 1)
303     return 0;
304
305   slot = (struct ptr_data **)
306     htab_find_slot_with_hash (saving_htab, obj, POINTER_HASH (obj),
307                               INSERT);
308   if (*slot != NULL)
309     {
310       gcc_assert ((*slot)->note_ptr_fn == note_ptr_fn
311                   && (*slot)->note_ptr_cookie == note_ptr_cookie);
312       return 0;
313     }
314
315   *slot = XCNEW (struct ptr_data);
316   (*slot)->obj = obj;
317   (*slot)->note_ptr_fn = note_ptr_fn;
318   (*slot)->note_ptr_cookie = note_ptr_cookie;
319   if (note_ptr_fn == gt_pch_p_S)
320     (*slot)->size = strlen ((const char *)obj) + 1;
321   else
322     (*slot)->size = ggc_get_size (obj);
323   (*slot)->type = type;
324   return 1;
325 }
326
327 /* Register an object in the hash table.  */
328
329 void
330 gt_pch_note_reorder (void *obj, void *note_ptr_cookie,
331                      gt_handle_reorder reorder_fn)
332 {
333   struct ptr_data *data;
334
335   if (obj == NULL || obj == (void *) 1)
336     return;
337
338   data = (struct ptr_data *)
339     htab_find_with_hash (saving_htab, obj, POINTER_HASH (obj));
340   gcc_assert (data && data->note_ptr_cookie == note_ptr_cookie);
341
342   data->reorder_fn = reorder_fn;
343 }
344
345 /* Hash and equality functions for saving_htab, callbacks for htab_create.  */
346
347 static hashval_t
348 saving_htab_hash (const void *p)
349 {
350   return POINTER_HASH (((const struct ptr_data *)p)->obj);
351 }
352
353 static int
354 saving_htab_eq (const void *p1, const void *p2)
355 {
356   return ((const struct ptr_data *)p1)->obj == p2;
357 }
358
359 /* Handy state for the traversal functions.  */
360
361 struct traversal_state
362 {
363   FILE *f;
364   struct ggc_pch_data *d;
365   size_t count;
366   struct ptr_data **ptrs;
367   size_t ptrs_i;
368 };
369
370 /* Callbacks for htab_traverse.  */
371
372 static int
373 call_count (void **slot, void *state_p)
374 {
375   struct ptr_data *d = (struct ptr_data *)*slot;
376   struct traversal_state *state = (struct traversal_state *)state_p;
377
378   ggc_pch_count_object (state->d, d->obj, d->size,
379                         d->note_ptr_fn == gt_pch_p_S,
380                         d->type);
381   state->count++;
382   return 1;
383 }
384
385 static int
386 call_alloc (void **slot, void *state_p)
387 {
388   struct ptr_data *d = (struct ptr_data *)*slot;
389   struct traversal_state *state = (struct traversal_state *)state_p;
390
391   d->new_addr = ggc_pch_alloc_object (state->d, d->obj, d->size,
392                                       d->note_ptr_fn == gt_pch_p_S,
393                                       d->type);
394   state->ptrs[state->ptrs_i++] = d;
395   return 1;
396 }
397
398 /* Callback for qsort.  */
399
400 static int
401 compare_ptr_data (const void *p1_p, const void *p2_p)
402 {
403   const struct ptr_data *const p1 = *(const struct ptr_data *const *)p1_p;
404   const struct ptr_data *const p2 = *(const struct ptr_data *const *)p2_p;
405   return (((size_t)p1->new_addr > (size_t)p2->new_addr)
406           - ((size_t)p1->new_addr < (size_t)p2->new_addr));
407 }
408
409 /* Callbacks for note_ptr_fn.  */
410
411 static void
412 relocate_ptrs (void *ptr_p, void *state_p)
413 {
414   void **ptr = (void **)ptr_p;
415   struct traversal_state *state ATTRIBUTE_UNUSED
416     = (struct traversal_state *)state_p;
417   struct ptr_data *result;
418
419   if (*ptr == NULL || *ptr == (void *)1)
420     return;
421
422   result = (struct ptr_data *)
423     htab_find_with_hash (saving_htab, *ptr, POINTER_HASH (*ptr));
424   gcc_assert (result);
425   *ptr = result->new_addr;
426 }
427
428 /* Write out, after relocation, the pointers in TAB.  */
429 static void
430 write_pch_globals (const struct ggc_root_tab * const *tab,
431                    struct traversal_state *state)
432 {
433   const struct ggc_root_tab *const *rt;
434   const struct ggc_root_tab *rti;
435   size_t i;
436
437   for (rt = tab; *rt; rt++)
438     for (rti = *rt; rti->base != NULL; rti++)
439       for (i = 0; i < rti->nelt; i++)
440         {
441           void *ptr = *(void **)((char *)rti->base + rti->stride * i);
442           struct ptr_data *new_ptr;
443           if (ptr == NULL || ptr == (void *)1)
444             {
445               if (fwrite (&ptr, sizeof (void *), 1, state->f)
446                   != 1)
447                 fatal_error ("can't write PCH file: %m");
448             }
449           else
450             {
451               new_ptr = (struct ptr_data *)
452                 htab_find_with_hash (saving_htab, ptr, POINTER_HASH (ptr));
453               if (fwrite (&new_ptr->new_addr, sizeof (void *), 1, state->f)
454                   != 1)
455                 fatal_error ("can't write PCH file: %m");
456             }
457         }
458 }
459
460 /* Hold the information we need to mmap the file back in.  */
461
462 struct mmap_info
463 {
464   size_t offset;
465   size_t size;
466   void *preferred_base;
467 };
468
469 /* Write out the state of the compiler to F.  */
470
471 void
472 gt_pch_save (FILE *f)
473 {
474   const struct ggc_root_tab *const *rt;
475   const struct ggc_root_tab *rti;
476   size_t i;
477   struct traversal_state state;
478   char *this_object = NULL;
479   size_t this_object_size = 0;
480   struct mmap_info mmi;
481   const size_t mmap_offset_alignment = host_hooks.gt_pch_alloc_granularity();
482
483   gt_pch_save_stringpool ();
484
485   saving_htab = htab_create (50000, saving_htab_hash, saving_htab_eq, free);
486
487   for (rt = gt_ggc_rtab; *rt; rt++)
488     for (rti = *rt; rti->base != NULL; rti++)
489       for (i = 0; i < rti->nelt; i++)
490         (*rti->pchw)(*(void **)((char *)rti->base + rti->stride * i));
491
492   for (rt = gt_pch_cache_rtab; *rt; rt++)
493     for (rti = *rt; rti->base != NULL; rti++)
494       for (i = 0; i < rti->nelt; i++)
495         (*rti->pchw)(*(void **)((char *)rti->base + rti->stride * i));
496
497   /* Prepare the objects for writing, determine addresses and such.  */
498   state.f = f;
499   state.d = init_ggc_pch();
500   state.count = 0;
501   htab_traverse (saving_htab, call_count, &state);
502
503   mmi.size = ggc_pch_total_size (state.d);
504
505   /* Try to arrange things so that no relocation is necessary, but
506      don't try very hard.  On most platforms, this will always work,
507      and on the rest it's a lot of work to do better.  
508      (The extra work goes in HOST_HOOKS_GT_PCH_GET_ADDRESS and
509      HOST_HOOKS_GT_PCH_USE_ADDRESS.)  */
510   mmi.preferred_base = host_hooks.gt_pch_get_address (mmi.size, fileno (f));
511       
512   ggc_pch_this_base (state.d, mmi.preferred_base);
513
514   state.ptrs = XNEWVEC (struct ptr_data *, state.count);
515   state.ptrs_i = 0;
516   htab_traverse (saving_htab, call_alloc, &state);
517   qsort (state.ptrs, state.count, sizeof (*state.ptrs), compare_ptr_data);
518
519   /* Write out all the scalar variables.  */
520   for (rt = gt_pch_scalar_rtab; *rt; rt++)
521     for (rti = *rt; rti->base != NULL; rti++)
522       if (fwrite (rti->base, rti->stride, 1, f) != 1)
523         fatal_error ("can't write PCH file: %m");
524
525   /* Write out all the global pointers, after translation.  */
526   write_pch_globals (gt_ggc_rtab, &state);
527   write_pch_globals (gt_pch_cache_rtab, &state);
528
529   /* Pad the PCH file so that the mmapped area starts on an allocation
530      granularity (usually page) boundary.  */
531   {
532     long o;
533     o = ftell (state.f) + sizeof (mmi);
534     if (o == -1)
535       fatal_error ("can't get position in PCH file: %m");
536     mmi.offset = mmap_offset_alignment - o % mmap_offset_alignment;
537     if (mmi.offset == mmap_offset_alignment)
538       mmi.offset = 0;
539     mmi.offset += o;
540   }
541   if (fwrite (&mmi, sizeof (mmi), 1, state.f) != 1)
542     fatal_error ("can't write PCH file: %m");
543   if (mmi.offset != 0
544       && fseek (state.f, mmi.offset, SEEK_SET) != 0)
545     fatal_error ("can't write padding to PCH file: %m");
546
547   ggc_pch_prepare_write (state.d, state.f);
548
549   /* Actually write out the objects.  */
550   for (i = 0; i < state.count; i++)
551     {
552       if (this_object_size < state.ptrs[i]->size)
553         {
554           this_object_size = state.ptrs[i]->size;
555           this_object = XRESIZEVAR (char, this_object, this_object_size);
556         }
557       memcpy (this_object, state.ptrs[i]->obj, state.ptrs[i]->size);
558       if (state.ptrs[i]->reorder_fn != NULL)
559         state.ptrs[i]->reorder_fn (state.ptrs[i]->obj,
560                                    state.ptrs[i]->note_ptr_cookie,
561                                    relocate_ptrs, &state);
562       state.ptrs[i]->note_ptr_fn (state.ptrs[i]->obj,
563                                   state.ptrs[i]->note_ptr_cookie,
564                                   relocate_ptrs, &state);
565       ggc_pch_write_object (state.d, state.f, state.ptrs[i]->obj,
566                             state.ptrs[i]->new_addr, state.ptrs[i]->size,
567                             state.ptrs[i]->note_ptr_fn == gt_pch_p_S);
568       if (state.ptrs[i]->note_ptr_fn != gt_pch_p_S)
569         memcpy (state.ptrs[i]->obj, this_object, state.ptrs[i]->size);
570     }
571   ggc_pch_finish (state.d, state.f);
572   gt_pch_fixup_stringpool ();
573
574   free (state.ptrs);
575   htab_delete (saving_htab);
576 }
577
578 /* Read the state of the compiler back in from F.  */
579
580 void
581 gt_pch_restore (FILE *f)
582 {
583   const struct ggc_root_tab *const *rt;
584   const struct ggc_root_tab *rti;
585   size_t i;
586   struct mmap_info mmi;
587   int result;
588
589   /* Delete any deletable objects.  This makes ggc_pch_read much
590      faster, as it can be sure that no GCable objects remain other
591      than the ones just read in.  */
592   for (rt = gt_ggc_deletable_rtab; *rt; rt++)
593     for (rti = *rt; rti->base != NULL; rti++)
594       memset (rti->base, 0, rti->stride);
595
596   /* Read in all the scalar variables.  */
597   for (rt = gt_pch_scalar_rtab; *rt; rt++)
598     for (rti = *rt; rti->base != NULL; rti++)
599       if (fread (rti->base, rti->stride, 1, f) != 1)
600         fatal_error ("can't read PCH file: %m");
601
602   /* Read in all the global pointers, in 6 easy loops.  */
603   for (rt = gt_ggc_rtab; *rt; rt++)
604     for (rti = *rt; rti->base != NULL; rti++)
605       for (i = 0; i < rti->nelt; i++)
606         if (fread ((char *)rti->base + rti->stride * i,
607                    sizeof (void *), 1, f) != 1)
608           fatal_error ("can't read PCH file: %m");
609
610   for (rt = gt_pch_cache_rtab; *rt; rt++)
611     for (rti = *rt; rti->base != NULL; rti++)
612       for (i = 0; i < rti->nelt; i++)
613         if (fread ((char *)rti->base + rti->stride * i,
614                    sizeof (void *), 1, f) != 1)
615           fatal_error ("can't read PCH file: %m");
616
617   if (fread (&mmi, sizeof (mmi), 1, f) != 1)
618     fatal_error ("can't read PCH file: %m");
619
620   result = host_hooks.gt_pch_use_address (mmi.preferred_base, mmi.size,
621                                           fileno (f), mmi.offset);
622   if (result < 0)
623     fatal_error ("had to relocate PCH");
624   if (result == 0)
625     {
626       if (fseek (f, mmi.offset, SEEK_SET) != 0
627           || fread (mmi.preferred_base, mmi.size, 1, f) != 1)
628         fatal_error ("can't read PCH file: %m");
629     }
630   else if (fseek (f, mmi.offset + mmi.size, SEEK_SET) != 0)
631     fatal_error ("can't read PCH file: %m");
632
633   ggc_pch_read (f, mmi.preferred_base);
634
635   gt_pch_restore_stringpool ();
636 }
637
638 /* Default version of HOST_HOOKS_GT_PCH_GET_ADDRESS when mmap is not present.
639    Select no address whatsoever, and let gt_pch_save choose what it will with
640    malloc, presumably.  */
641
642 void *
643 default_gt_pch_get_address (size_t size ATTRIBUTE_UNUSED,
644                             int fd ATTRIBUTE_UNUSED)
645 {
646   return NULL;
647 }
648
649 /* Default version of HOST_HOOKS_GT_PCH_USE_ADDRESS when mmap is not present.
650    Allocate SIZE bytes with malloc.  Return 0 if the address we got is the
651    same as base, indicating that the memory has been allocated but needs to
652    be read in from the file.  Return -1 if the address differs, to relocation
653    of the PCH file would be required.  */
654
655 int
656 default_gt_pch_use_address (void *base, size_t size, int fd ATTRIBUTE_UNUSED,
657                             size_t offset ATTRIBUTE_UNUSED)
658 {
659   void *addr = xmalloc (size);
660   return (addr == base) - 1;
661 }
662
663 /* Default version of HOST_HOOKS_GT_PCH_GET_ADDRESS.   Return the
664    alignment required for allocating virtual memory. Usually this is the
665    same as pagesize.  */
666
667 size_t
668 default_gt_pch_alloc_granularity (void)
669 {
670   return getpagesize();
671 }
672
673 #if HAVE_MMAP_FILE
674 /* Default version of HOST_HOOKS_GT_PCH_GET_ADDRESS when mmap is present.
675    We temporarily allocate SIZE bytes, and let the kernel place the data
676    wherever it will.  If it worked, that's our spot, if not we're likely
677    to be in trouble.  */
678
679 void *
680 mmap_gt_pch_get_address (size_t size, int fd)
681 {
682   void *ret;
683
684   ret = mmap (NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
685   if (ret == (void *) MAP_FAILED)
686     ret = NULL;
687   else
688     munmap ((caddr_t) ret, size);
689
690   return ret;
691 }
692
693 /* Default version of HOST_HOOKS_GT_PCH_USE_ADDRESS when mmap is present.
694    Map SIZE bytes of FD+OFFSET at BASE.  Return 1 if we succeeded at 
695    mapping the data at BASE, -1 if we couldn't.
696
697    This version assumes that the kernel honors the START operand of mmap
698    even without MAP_FIXED if START through START+SIZE are not currently
699    mapped with something.  */
700
701 int
702 mmap_gt_pch_use_address (void *base, size_t size, int fd, size_t offset)
703 {
704   void *addr;
705
706   /* We're called with size == 0 if we're not planning to load a PCH
707      file at all.  This allows the hook to free any static space that
708      we might have allocated at link time.  */
709   if (size == 0)
710     return -1;
711
712   addr = mmap ((caddr_t) base, size, PROT_READ | PROT_WRITE, MAP_PRIVATE,
713                fd, offset);
714
715   return addr == base ? 1 : -1;
716 }
717 #endif /* HAVE_MMAP_FILE */
718
719 /* Modify the bound based on rlimits.  */
720 static double
721 ggc_rlimit_bound (double limit)
722 {
723 #if defined(HAVE_GETRLIMIT)
724   struct rlimit rlim;
725 # if defined (RLIMIT_AS)
726   /* RLIMIT_AS is what POSIX says is the limit on mmap.  Presumably
727      any OS which has RLIMIT_AS also has a working mmap that GCC will use.  */
728   if (getrlimit (RLIMIT_AS, &rlim) == 0
729       && rlim.rlim_cur != (rlim_t) RLIM_INFINITY
730       && rlim.rlim_cur < limit)
731     limit = rlim.rlim_cur;
732 # elif defined (RLIMIT_DATA)
733   /* ... but some older OSs bound mmap based on RLIMIT_DATA, or we
734      might be on an OS that has a broken mmap.  (Others don't bound
735      mmap at all, apparently.)  */
736   if (getrlimit (RLIMIT_DATA, &rlim) == 0
737       && rlim.rlim_cur != (rlim_t) RLIM_INFINITY
738       && rlim.rlim_cur < limit
739       /* Darwin has this horribly bogus default setting of
740          RLIMIT_DATA, to 6144Kb.  No-one notices because RLIMIT_DATA
741          appears to be ignored.  Ignore such silliness.  If a limit
742          this small was actually effective for mmap, GCC wouldn't even
743          start up.  */
744       && rlim.rlim_cur >= 8 * 1024 * 1024)
745     limit = rlim.rlim_cur;
746 # endif /* RLIMIT_AS or RLIMIT_DATA */
747 #endif /* HAVE_GETRLIMIT */
748
749   return limit;
750 }
751
752 /* Heuristic to set a default for GGC_MIN_EXPAND.  */
753 int
754 ggc_min_expand_heuristic (void)
755 {
756   double min_expand = physmem_total();
757
758   /* Adjust for rlimits.  */
759   min_expand = ggc_rlimit_bound (min_expand);
760
761   /* The heuristic is a percentage equal to 30% + 70%*(RAM/1GB), yielding
762      a lower bound of 30% and an upper bound of 100% (when RAM >= 1GB).  */
763   min_expand /= 1024*1024*1024;
764   min_expand *= 70;
765   min_expand = MIN (min_expand, 70);
766   min_expand += 30;
767
768   return min_expand;
769 }
770
771 /* Heuristic to set a default for GGC_MIN_HEAPSIZE.  */
772 int
773 ggc_min_heapsize_heuristic (void)
774 {
775   double phys_kbytes = physmem_total();
776   double limit_kbytes = ggc_rlimit_bound (phys_kbytes * 2);
777
778   phys_kbytes /= 1024; /* Convert to Kbytes.  */
779   limit_kbytes /= 1024;
780
781   /* The heuristic is RAM/8, with a lower bound of 4M and an upper
782      bound of 128M (when RAM >= 1GB).  */
783   phys_kbytes /= 8;
784
785 #if defined(HAVE_GETRLIMIT) && defined (RLIMIT_RSS)
786   /* Try not to overrun the RSS limit while doing garbage collection.  
787      The RSS limit is only advisory, so no margin is subtracted.  */
788  {
789    struct rlimit rlim;
790    if (getrlimit (RLIMIT_RSS, &rlim) == 0
791        && rlim.rlim_cur != (rlim_t) RLIM_INFINITY)
792      phys_kbytes = MIN (phys_kbytes, rlim.rlim_cur / 1024);
793  }
794 # endif
795
796   /* Don't blindly run over our data limit; do GC at least when the
797      *next* GC would be within 20Mb of the limit or within a quarter of
798      the limit, whichever is larger.  If GCC does hit the data limit,
799      compilation will fail, so this tries to be conservative.  */
800   limit_kbytes = MAX (0, limit_kbytes - MAX (limit_kbytes / 4, 20 * 1024));
801   limit_kbytes = (limit_kbytes * 100) / (110 + ggc_min_expand_heuristic());
802   phys_kbytes = MIN (phys_kbytes, limit_kbytes);
803
804   phys_kbytes = MAX (phys_kbytes, 4 * 1024);
805   phys_kbytes = MIN (phys_kbytes, 128 * 1024);
806
807   return phys_kbytes;
808 }
809
810 void
811 init_ggc_heuristics (void)
812 {
813 #if !defined ENABLE_GC_CHECKING && !defined ENABLE_GC_ALWAYS_COLLECT
814   set_param_value ("ggc-min-expand", ggc_min_expand_heuristic());
815   set_param_value ("ggc-min-heapsize", ggc_min_heapsize_heuristic());
816 #endif
817 }
818
819 #ifdef GATHER_STATISTICS
820
821 /* Datastructure used to store per-call-site statistics.  */
822 struct loc_descriptor
823 {
824   const char *file;
825   int line;
826   const char *function;
827   int times;
828   size_t allocated;
829   size_t overhead;
830   size_t freed;
831   size_t collected;
832 };
833
834 /* Hashtable used for statistics.  */
835 static htab_t loc_hash;
836
837 /* Hash table helpers functions.  */
838 static hashval_t
839 hash_descriptor (const void *p)
840 {
841   const struct loc_descriptor *const d = (const struct loc_descriptor *) p;
842
843   return htab_hash_pointer (d->function) | d->line;
844 }
845
846 static int
847 eq_descriptor (const void *p1, const void *p2)
848 {
849   const struct loc_descriptor *const d = (const struct loc_descriptor *) p1;
850   const struct loc_descriptor *const d2 = (const struct loc_descriptor *) p2;
851
852   return (d->file == d2->file && d->line == d2->line
853           && d->function == d2->function);
854 }
855
856 /* Hashtable converting address of allocated field to loc descriptor.  */
857 static htab_t ptr_hash;
858 struct ptr_hash_entry
859 {
860   void *ptr;
861   struct loc_descriptor *loc;
862   size_t size;
863 };
864
865 /* Hash table helpers functions.  */
866 static hashval_t
867 hash_ptr (const void *p)
868 {
869   const struct ptr_hash_entry *const d = (const struct ptr_hash_entry *) p;
870
871   return htab_hash_pointer (d->ptr);
872 }
873
874 static int
875 eq_ptr (const void *p1, const void *p2)
876 {
877   const struct ptr_hash_entry *const p = (const struct ptr_hash_entry *) p1;
878
879   return (p->ptr == p2);
880 }
881
882 /* Return descriptor for given call site, create new one if needed.  */
883 static struct loc_descriptor *
884 loc_descriptor (const char *name, int line, const char *function)
885 {
886   struct loc_descriptor loc;
887   struct loc_descriptor **slot;
888
889   loc.file = name;
890   loc.line = line;
891   loc.function = function;
892   if (!loc_hash)
893     loc_hash = htab_create (10, hash_descriptor, eq_descriptor, NULL);
894
895   slot = (struct loc_descriptor **) htab_find_slot (loc_hash, &loc, INSERT);
896   if (*slot)
897     return *slot;
898   *slot = XCNEW (struct loc_descriptor);
899   (*slot)->file = name;
900   (*slot)->line = line;
901   (*slot)->function = function;
902   return *slot;
903 }
904
905 /* Record ALLOCATED and OVERHEAD bytes to descriptor NAME:LINE (FUNCTION).  */
906 void
907 ggc_record_overhead (size_t allocated, size_t overhead, void *ptr,
908                      const char *name, int line, const char *function)
909 {
910   struct loc_descriptor *loc = loc_descriptor (name, line, function);
911   struct ptr_hash_entry *p = XNEW (struct ptr_hash_entry);
912   PTR *slot;
913
914   p->ptr = ptr;
915   p->loc = loc;
916   p->size = allocated + overhead;
917   if (!ptr_hash)
918     ptr_hash = htab_create (10, hash_ptr, eq_ptr, NULL);
919   slot = htab_find_slot_with_hash (ptr_hash, ptr, htab_hash_pointer (ptr), INSERT);
920   gcc_assert (!*slot);
921   *slot = p;
922
923   loc->times++;
924   loc->allocated+=allocated;
925   loc->overhead+=overhead;
926 }
927
928 /* Helper function for prune_overhead_list.  See if SLOT is still marked and
929    remove it from hashtable if it is not.  */
930 static int
931 ggc_prune_ptr (void **slot, void *b ATTRIBUTE_UNUSED)
932 {
933   struct ptr_hash_entry *p = (struct ptr_hash_entry *) *slot;
934   if (!ggc_marked_p (p->ptr))
935     {
936       p->loc->collected += p->size;
937       htab_clear_slot (ptr_hash, slot);
938       free (p);
939     }
940   return 1;
941 }
942
943 /* After live values has been marked, walk all recorded pointers and see if
944    they are still live.  */
945 void
946 ggc_prune_overhead_list (void)
947 {
948   htab_traverse (ptr_hash, ggc_prune_ptr, NULL);
949 }
950
951 /* Notice that the pointer has been freed.  */
952 void
953 ggc_free_overhead (void *ptr)
954 {
955   PTR *slot = htab_find_slot_with_hash (ptr_hash, ptr, htab_hash_pointer (ptr),
956                                         NO_INSERT);
957   struct ptr_hash_entry *p = (struct ptr_hash_entry *) *slot;
958   p->loc->freed += p->size;
959   htab_clear_slot (ptr_hash, slot);
960   free (p);
961 }
962
963 /* Helper for qsort; sort descriptors by amount of memory consumed.  */
964 static int
965 final_cmp_statistic (const void *loc1, const void *loc2)
966 {
967   const struct loc_descriptor *const l1 =
968     *(const struct loc_descriptor *const *) loc1;
969   const struct loc_descriptor *const l2 =
970     *(const struct loc_descriptor *const *) loc2;
971   long diff;
972   diff = ((long)(l1->allocated + l1->overhead - l1->freed) -
973           (l2->allocated + l2->overhead - l2->freed));
974   return diff > 0 ? 1 : diff < 0 ? -1 : 0;
975 }
976
977 /* Helper for qsort; sort descriptors by amount of memory consumed.  */
978 static int
979 cmp_statistic (const void *loc1, const void *loc2)
980 {
981   const struct loc_descriptor *const l1 =
982     *(const struct loc_descriptor *const *) loc1;
983   const struct loc_descriptor *const l2 =
984     *(const struct loc_descriptor *const *) loc2;
985   long diff;
986
987   diff = ((long)(l1->allocated + l1->overhead - l1->freed - l1->collected) -
988           (l2->allocated + l2->overhead - l2->freed - l2->collected));
989   if (diff)
990     return diff > 0 ? 1 : diff < 0 ? -1 : 0;
991   diff =  ((long)(l1->allocated + l1->overhead - l1->freed) -
992            (l2->allocated + l2->overhead - l2->freed));
993   return diff > 0 ? 1 : diff < 0 ? -1 : 0;
994 }
995
996 /* Collect array of the descriptors from hashtable.  */
997 static struct loc_descriptor **loc_array;
998 static int
999 add_statistics (void **slot, void *b)
1000 {
1001   int *n = (int *)b;
1002   loc_array[*n] = (struct loc_descriptor *) *slot;
1003   (*n)++;
1004   return 1;
1005 }
1006
1007 /* Dump per-site memory statistics.  */
1008 #endif
1009 void
1010 dump_ggc_loc_statistics (bool final ATTRIBUTE_UNUSED)
1011 {
1012 #ifdef GATHER_STATISTICS
1013   int nentries = 0;
1014   char s[4096];
1015   size_t collected = 0, freed = 0, allocated = 0, overhead = 0, times = 0;
1016   int i;
1017
1018   ggc_force_collect = true;
1019   ggc_collect ();
1020
1021   loc_array = XCNEWVEC (struct loc_descriptor *, loc_hash->n_elements);
1022   fprintf (stderr, "-------------------------------------------------------\n");
1023   fprintf (stderr, "\n%-48s %10s       %10s       %10s       %10s       %10s\n",
1024            "source location", "Garbage", "Freed", "Leak", "Overhead", "Times");
1025   fprintf (stderr, "-------------------------------------------------------\n");
1026   htab_traverse (loc_hash, add_statistics, &nentries);
1027   qsort (loc_array, nentries, sizeof (*loc_array),
1028          final ? final_cmp_statistic : cmp_statistic);
1029   for (i = 0; i < nentries; i++)
1030     {
1031       struct loc_descriptor *d = loc_array[i];
1032       allocated += d->allocated;
1033       times += d->times;
1034       freed += d->freed;
1035       collected += d->collected;
1036       overhead += d->overhead;
1037     }
1038   for (i = 0; i < nentries; i++)
1039     {
1040       struct loc_descriptor *d = loc_array[i];
1041       if (d->allocated)
1042         {
1043           const char *s1 = d->file;
1044           const char *s2;
1045           while ((s2 = strstr (s1, "gcc/")))
1046             s1 = s2 + 4;
1047           sprintf (s, "%s:%i (%s)", s1, d->line, d->function);
1048           s[48] = 0;
1049           fprintf (stderr, "%-48s %10li:%4.1f%% %10li:%4.1f%% %10li:%4.1f%% %10li:%4.1f%% %10li\n", s,
1050                    (long)d->collected,
1051                    (d->collected) * 100.0 / collected,
1052                    (long)d->freed,
1053                    (d->freed) * 100.0 / freed,
1054                    (long)(d->allocated + d->overhead - d->freed - d->collected),
1055                    (d->allocated + d->overhead - d->freed - d->collected) * 100.0
1056                    / (allocated + overhead - freed - collected),
1057                    (long)d->overhead,
1058                    d->overhead * 100.0 / overhead,
1059                    (long)d->times);
1060         }
1061     }
1062   fprintf (stderr, "%-48s %10ld       %10ld       %10ld       %10ld       %10ld\n",
1063            "Total", (long)collected, (long)freed,
1064            (long)(allocated + overhead - freed - collected), (long)overhead,
1065            (long)times);
1066   fprintf (stderr, "%-48s %10s       %10s       %10s       %10s       %10s\n",
1067            "source location", "Garbage", "Freed", "Leak", "Overhead", "Times");
1068   fprintf (stderr, "-------------------------------------------------------\n");
1069   ggc_force_collect = false;
1070 #endif
1071 }